<commit_before>package SGN::Controller::JavaScript;
use Moose;
use namespace::autoclean;

use File::Spec;

use Carp;
use Digest::MD5 'md5_hex';
use JSAN::ServerSide;
use List::MoreUtils qw/uniq/;
use Storable qw/ nfreeze /;

BEGIN { extends 'Catalyst::Controller' }
with 'Catalyst::Component::ApplicationAttribute';

__PACKAGE__->config(
    namespace => 'js',
   );


has '_package_defs' => (
    is => 'ro',
    lazy_build => 1,
   ); sub _build__package_defs {
       my $self = shift;

       my $cache = Cache::File->new(
           cache_root       => $self->_app->path_to( $self->_app->tempfiles_subdir('cache','js_packs') ),

           default_expires  => 'never',
           size_limit       => 1_000_000,
           removal_strategy => 'Cache::RemovalStrategy::LRU',
          );
   }

=head1 ACTIONS

=head2 js_package

Serve a minified, concatenated package of javascript, assembled and
stored on the previous request.

Args: package identifier (32-character hex)

=cut

sub js_package :Path('pack') :Args(1) {
    my ( $self, $c, $key ) = @_;

    # NOTE: you might think that we should cache the minified
    # javascript too, but it turns out to not be much faster!

    $c->stash->{js} = $self->_package_defs->thaw( $key );

    $c->log->debug(
         "serving JS pack $key = ("
        .(join ', ', @{ $c->stash->{js} || [] })
        .')'
       ) if $c->debug;

}

=head2 default

Serve a single (minified) javascript file from our js path.

=cut

sub default :Path {
    my ( $self, $c, @args ) = @_;

    $c->stash->{js} = [  File::Spec->catfile( @args ) ];
}

=head2 end

forwards to View::JavaScript

=cut

sub end :Private {
    my ( $self, $c ) = @_;

    # all of the actions in this controller will use View::Javascript
    # for rendering
    $c->forward('View::JavaScript');

    # handle missing JS with a 404
    if( @{ $c->error } == 1 && $c->error->[0] =~ /^Can't open '/ ) {

        $c->clear_errors;

        $c->res->status( 404 );
        $c->res->content_type( 'text/html' );

        $c->stash->{template} = "/site/error/404.mas";
        $c->stash->{message}  = "Javascript not found";
        $c->forward('View::Mason');
    }
}

=head2 insert_js_pack_html

Scans the current $c->res->body and inserts <script> includes for the
current set of javascript includes in the $c->stash->{pack_js}
arrayref.

Replaces comments like:

  <!-- INSERT_JS_PACK -->

with:

  <script src="(uri for js pack)" type="text/javascript">
  </script>

=cut


sub insert_js_pack_html :Private {
  my ( $self, $c ) = @_;

  my $js = $c->stash->{pack_js};
  return unless $js && @$js;

  my $b = $c->res->body;

  $c->log->debug("inserting js pack with @$js into body of size ".length($b));

  my $url_cache;
  if( $b =~ s{<!-- \s* INSERT_JS_PACK \s* -->} {'<script src="'.($url_cache ||= $c->uri_for( $self->action_for_js_package( $js ))).qq|" type="text/javascript">\n</script>|}ex ) {
      $c->res->body( $b );
      delete $c->stash->{pack_js};
  }
}

=head1 REGULAR METHODS

=head2 action_for_js_package

  Usage: $controller->action_for_js_package([ 'sgn', 'jquery' ])
  Desc : get a list of (action,arguments) for getting a minified,
         concatenated set of javascript containing the given libraries.
  Args : arrayref of of JS libraries to include in the package
  Ret  : list of ( $action, @arguments )
  Side Effects: saves the list of js libs in a cache for subsequent
                requests
  Example:

      $c->uri_for( $c->controller('JavaScript')->action_for_js_package([ 'sgn', 'jquery' ]))

=cut

sub action_for_js_package {
    my ( $self, $files ) = @_;
    @_ == 2 && ref $files && ref $files eq 'ARRAY' && @$files
        or croak "action_for_js_package takes a single param, an arrayref of files";<commit_msg>only insert js pack includes into html documents, only print debugging output if debug is on<commit_after>package SGN::Controller::JavaScript;
use Moose;
use namespace::autoclean;

use File::Spec;

use Carp;
use Digest::MD5 'md5_hex';
use JSAN::ServerSide;
use List::MoreUtils qw/uniq/;
use Storable qw/ nfreeze /;

BEGIN { extends 'Catalyst::Controller' }
with 'Catalyst::Component::ApplicationAttribute';

__PACKAGE__->config(
    namespace => 'js',
   );


has '_package_defs' => (
    is => 'ro',
    lazy_build => 1,
   ); sub _build__package_defs {
       my $self = shift;

       my $cache = Cache::File->new(
           cache_root       => $self->_app->path_to( $self->_app->tempfiles_subdir('cache','js_packs') ),

           default_expires  => 'never',
           size_limit       => 1_000_000,
           removal_strategy => 'Cache::RemovalStrategy::LRU',
          );
   }

=head1 ACTIONS

=head2 js_package

Serve a minified, concatenated package of javascript, assembled and
stored on the previous request.

Args: package identifier (32-character hex)

=cut

sub js_package :Path('pack') :Args(1) {
    my ( $self, $c, $key ) = @_;

    # NOTE: you might think that we should cache the minified
    # javascript too, but it turns out to not be much faster!

    $c->stash->{js} = $self->_package_defs->thaw( $key );

    $c->log->debug(
         "serving JS pack $key = ("
        .(join ', ', @{ $c->stash->{js} || [] })
        .')'
       ) if $c->debug;

}

=head2 default

Serve a single (minified) javascript file from our js path.

=cut

sub default :Path {
    my ( $self, $c, @args ) = @_;

    $c->stash->{js} = [  File::Spec->catfile( @args ) ];
}

=head2 end

forwards to View::JavaScript

=cut

sub end :Private {
    my ( $self, $c ) = @_;

    # all of the actions in this controller will use View::Javascript
    # for rendering
    $c->forward('View::JavaScript');

    # handle missing JS with a 404
    if( @{ $c->error } == 1 && $c->error->[0] =~ /^Can't open '/ ) {

        $c->clear_errors;

        $c->res->status( 404 );
        $c->res->content_type( 'text/html' );

        $c->stash->{template} = "/site/error/404.mas";
        $c->stash->{message}  = "Javascript not found";
        $c->forward('View::Mason');
    }
}

=head2 insert_js_pack_html

Scans the current $c->res->body and inserts <script> includes for the
current set of javascript includes in the $c->stash->{pack_js}
arrayref.

Replaces comments like:

  <!-- INSERT_JS_PACK -->

with:

  <script src="(uri for js pack)" type="text/javascript">
  </script>

=cut


sub insert_js_pack_html :Private {
  my ( $self, $c ) = @_;

  my $js = $c->stash->{pack_js};
  return unless $js && @$js && $c->res->content_type eq 'text/html';

  my $b = $c->res->body;

  $c->log->debug("inserting js pack containing (@$js) into body of size ".length($b)) if $c->debug;

  my $url_cache;
  if( $b =~ s{<!-- \s* INSERT_JS_PACK \s* -->} {'<script src="'.($url_cache ||= $c->uri_for( $self->action_for_js_package( $js ))).qq|" type="text/javascript">\n</script>|}ex ) {
      $c->res->body( $b );
      delete $c->stash->{pack_js};
  }
}

=head1 REGULAR METHODS

=head2 action_for_js_package

  Usage: $controller->action_for_js_package([ 'sgn', 'jquery' ])
  Desc : get a list of (action,arguments) for getting a minified,
         concatenated set of javascript containing the given libraries.
  Args : arrayref of of JS libraries to include in the package
  Ret  : list of ( $action, @arguments )
  Side Effects: saves the list of js libs in a cache for subsequent
                requests
  Example:

      $c->uri_for( $c->controller('JavaScript')->action_for_js_package([ 'sgn', 'jquery' ]))

=cut

sub action_for_js_package {
    my ( $self, $files ) = @_;
    @_ == 2 && ref $files && ref $files eq 'ARRAY' && @$files
        or croak "action_for_js_package takes a single param, an arrayref of files";
{'fraction_non_alphanumeric': 0.16362212943632568, 'fraction_numerical': 0.008350730688935281, 'mean_word_length': 3.0427215189873418, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 140, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5194567', 'n_tokens_mistral': 2787, 'n_tokens_neox': 2637, 'n_words': 731}