#!/usr/bin/perl

use strict;

use JavaScript;

my $document;
my $depth_watchdog;

sub js_extract
{
	my ($html) = @_;

	my $runtime = new JavaScript::Runtime;
	my $context = $runtime->create_context();

	$context->bind_function(name => 'document_write', func => sub {

		js_document_write($context, join '', @_);
	});

	$context->eval(qq|

		function Document()
		{
			this.write = document_write
			this.all = function () {}
		}

		document = new Document()

		function items()
		{
		}

		function priv()
		{
		}

		function w2()
		{
		}
	|);

	$document = '';
	$depth_watchdog = 0;

	js_document_write($context, $html);

	return $document;
}

sub js_document_write
{
	my ($context, $data) = @_;
	
	return if ++$depth_watchdog > 10000;

	$data =~ s/<!--.*?-->//gs;

	while ($data =~ /^(.*?)<script[^>]*>(.*?)<\/script>(.*)$/si) {

		my $before = $1;
		my $script = $2;
		my $after = $3;

		$document .= $before;
		$context->eval($script);
		$data = $after;
	}

	$document .= $data;
}

print js_extract(join '', <>);
