md2essay/js/markdowntoapa.js

28213 lines
1.6 MiB
JavaScript
Raw Normal View History

2015-04-07 04:49:22 -04:00
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var essay, refreshTimer;
window.markdowntoapa = require('./markdowntoapa.coffee');
window.md = require('markdown').markdown;
window._ = require('underscore');
window.extractMetadata = markdowntoapa.extractMetadata;
window.createMLADocument = markdowntoapa.createAPADocument;
window.blobStream = require('blob-stream');
window.editor = ace.edit("editor");
editor.setTheme("ace/theme/textmate");
editor.getSession().setMode("ace/mode/markdown");
editor.getSession().setUseWrapMode(true);
editor.renderer.setShowPrintMargin(false);
if (essay = typeof localStorage !== "undefined" && localStorage !== null ? localStorage.getItem('APA_paper') : void 0) {
editor.getSession().setValue(essay);
}
refreshTimer = null;
editor.getSession().on('change', function() {
clearTimeout(refreshTimer);
return refreshTimer = setTimeout(function() {
refresh();
return typeof localStorage !== "undefined" && localStorage !== null ? localStorage.setItem('APA_paper', editor.getSession().getValue()) : void 0;
}, 1000);
});
window.refresh = function() {
var body, content, doc, metadata, stream;
content = editor.getSession().getValue();
content = extractMetadata(content);
body = content.body;
metadata = content.metadata;
doc = createMLADocument(body, metadata);
stream = blobStream();
doc.pipe(stream);
return stream.on('finish', function() {
var url;
url = stream.toBlobURL('application/pdf');
document.getElementById('preview').src = url;
return document.title = metadata.title + " - MarkdownToAPA.com";
});
};
refresh();
},{"./markdowntoapa.coffee":2,"blob-stream":3,"markdown":14,"underscore":57}],2:[function(require,module,exports){
var Node, PDFDocument, _, addAPAHeader, base, base1, coffee, createAPADocument, extractMetadata, md, render, styles;
_ = require('underscore');
md = require('markdown').markdown;
coffee = require('coffee-script');
PDFDocument = require('pdfkit');
if ((base = Array.prototype).first == null) {
base.first = function() {
return this[0];
};
}
if ((base1 = Array.prototype).last == null) {
base1.last = function() {
return this[this.length - 1];
};
}
styles = {
"default": {
font: 'Times-Roman',
fontSize: 12,
lineGap: 14,
align: 'left'
},
meta: {
indent: 0
},
title: {
align: 'center'
},
para: {
indent: 72 / 2
},
blockquote: {
indent: 0,
marginLeft: 72 / 2,
font: 'Times-Italic'
},
em: {
font: 'Times-Italic'
},
strong: {
font: 'Times-Bold'
},
h1: {
align: 'center',
font: 'Times-Bold'
},
h2: {
font: 'Times-Bold'
},
h3: {
font: 'Times-Bold',
inline: true,
indent: 72 / 2
},
citationHeader: {
align: 'center'
},
citation: {
indent: -72 / 2,
marginLeft: 72 / 2
}
};
Node = (function() {
function Node(tree) {
var child, code;
if (typeof tree === 'string') {
this.type = 'text';
this.text = tree;
return;
}
this.type = tree.shift();
this.attrs = {};
if (typeof tree[0] === 'object' && !Array.isArray(tree[0])) {
this.attrs = tree.shift();
}
switch (this.type) {
case 'header':
this.type = 'h' + this.attrs.level;
break;
case 'img':
this.type = 'example';
code = codeBlocks[this.attrs.alt];
if (code) {
this.code = coffee.compile(code);
}
this.height = +this.attrs.title || 0;
}
this.style = _.extend({}, styles["default"], styles[this.type]);
this.content = (function() {
var ref, results;
results = [];
while (tree.length) {
child = new Node(tree.shift());
if (this.style.indent != null) {
if ((ref = child.style) != null) {
ref.indent = this.style.indent;
}
}
results.push(child);
}
return results;
}).call(this);
}
Node.prototype.setStyle = function(doc) {
if (this.style.font) {
doc.font(this.style.font);
}
if (this.style.fontSize) {
doc.fontSize(this.style.fontSize);
}
if (this.style.color) {
return doc.fillColor(this.style.color);
} else {
return doc.fillColor('black');
}
};
Node.prototype.render = function(doc, continued) {
var fragment, index, j, len, ref, text;
if (continued == null) {
continued = false;
}
if (this.style.marginLeft) {
doc.x += this.style.marginLeft;
}
switch (this.type) {
case 'hr':
doc.addPage();
break;
default:
ref = this.content;
for (index = j = 0, len = ref.length; j < len; index = ++j) {
fragment = ref[index];
if (fragment.type === 'text') {
this.setStyle(doc);
text = fragment.text;
if (this.style.inline) {
text = text + " ";
}
doc.text(text, _.extend({}, this.style, {
continued: continued || index < this.content.length - 1 || this.style.inline
}));
} else {
fragment.render(doc, index < this.content.length - 1 && this.type !== 'bulletlist');
}
}
}
if (this.style.marginBottom) {
doc.y += this.style.marginBottom;
}
if (this.style.marginLeft) {
return doc.x -= this.style.marginLeft;
}
};
return Node;
})();
addAPAHeader = function(doc, runningHead) {
var head, i, j, range, ref, ref1, results;
range = doc.bufferedPageRange();
doc.font(styles["default"].font);
results = [];
for (i = j = ref = range.start, ref1 = range.start + range.count; ref <= ref1 ? j < ref1 : j > ref1; i = ref <= ref1 ? ++j : --j) {
doc.switchToPage(i);
doc.y = 72 / 2;
doc.x = 72;
head = runningHead;
if (i === 0) {
head = "Running head: " + head;
}
doc.text(head, _.extend({}, styles["default"], {}));
doc.y = 72 / 2;
doc.x = 72;
results.push(doc.text("" + (i + 1), _.extend({}, styles["default"], {
align: 'right'
})));
}
return results;
};
render = function(doc, tree) {
var codeBlocks, node, onWorksCited, ref, ref1, ref2;
doc.font('Times-Roman');
doc.fontSize(12);
codeBlocks = [];
onWorksCited = false;
while (tree.length) {
node = new Node(tree.shift());
if (node.type === "h1" && ((ref = node.content) != null ? (ref1 = ref.first()) != null ? (ref2 = ref1.text) != null ? ref2.toLowerCase() : void 0 : void 0 : void 0) === "references") {
onWorksCited = true;
node.style = _.extend({}, styles["default"], styles.citationHeader);
}
if (onWorksCited && node.type === "para") {
node.style = _.extend({}, styles["default"], styles.citation);
}
node.render(doc);
}
return doc;
};
extractMetadata = function(text) {
var body, j, key, len, line, meta, metadata, metadata_pattern, ref, value;
body = "";
metadata = {};
metadata_pattern = /^([\w.-]+)\: \s*(.+)$/;
ref = text.split("\n");
for (j = 0, len = ref.length; j < len; j++) {
line = ref[j];
if (meta = line.match(metadata_pattern)) {
key = meta[1];
value = meta[2].replace(/\\n/, "\n");
metadata[key] = value;
} else {
body += line + "\n";
}
}
return {
metadata: metadata,
body: body
};
};
createAPADocument = function(body, metadata, stream) {
var doc, ref, tree;
tree = md.parse(body);
tree.shift();
metadata.lastName || (metadata.lastName = (ref = metadata.author) != null ? ref.split(" ").last() : void 0);
doc = new PDFDocument({
bufferPages: true
});
doc.info.Title = metadata.title.replace("\n", " ");
doc.info.Author = metadata.author;
doc.info.Creator = "markdowntoapa by christian.gen.co";
doc.y = 72 * 3;
doc.font('Times-Roman');
doc.fontSize(12);
doc.text(metadata.title, _.extend({}, styles["default"], styles.title));
doc.text(metadata.author, _.extend({}, styles["default"], styles.title));
doc.text(metadata.institution, _.extend({}, styles["default"], styles.title));
doc.addPage();
doc.text("Abstract", _.extend({}, styles["default"], styles.citationHeader));
doc.text(metadata.abstract, _.extend({}, styles["default"], {}));
if (metadata.keywords) {
doc.font(styles.em.font);
doc.text("Keywords: ", _.extend({
continued: true
}, styles["default"], styles.para));
doc.font(styles["default"].font);
doc.text(metadata.keywords, _.extend({}, styles["default"], styles.para));
}
doc.addPage();
doc.text(metadata.title, _.extend({}, styles["default"], styles.title));
render(doc, tree);
addAPAHeader(doc, metadata.runninghead);
doc.end();
return doc;
};
exports.extractMetadata = extractMetadata;
exports.createAPADocument = createAPADocument;
},{"coffee-script":5,"markdown":14,"pdfkit":17,"underscore":57}],3:[function(require,module,exports){
(function (global){
var WritableStream = require('stream').Writable;
var util = require('util');
var Blob = require('blob');
var URL = global.URL || global.webkitURL || global.mozURL;
function BlobStream() {
if (!(this instanceof BlobStream))
return new BlobStream;
WritableStream.call(this);
this._chunks = [];
this._blob = null;
this.length = 0;
}
util.inherits(BlobStream, WritableStream);
BlobStream.prototype._write = function(chunk, encoding, callback) {
// convert chunks to Uint8Arrays (e.g. Buffer when array fallback is being used)
if (!(chunk instanceof Uint8Array))
chunk = new Uint8Array(chunk);
this.length += chunk.length;
this._chunks.push(chunk);
callback();
};
BlobStream.prototype.toBlob = function(type) {
type = type || 'application/octet-stream';
// cache the blob if needed
if (!this._blob) {
this._blob = new Blob(this._chunks, {
type: type
});
this._chunks = []; // free memory
}
// if the cached blob's type doesn't match the requested type, make a new blob
if (this._blob.type !== type)
this._blob = new Blob([this._blob], { type: type });
return this._blob;
};
BlobStream.prototype.toBlobURL = function(type) {
return URL.createObjectURL(this.toBlob(type));
};
module.exports = BlobStream;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"blob":4,"stream":94,"util":97}],4:[function(require,module,exports){
(function (global){
/**
* Create a blob builder even when vendor prefixes exist
*/
var BlobBuilder = global.BlobBuilder
|| global.WebKitBlobBuilder
|| global.MSBlobBuilder
|| global.MozBlobBuilder;
/**
* Check if Blob constructor is supported
*/
var blobSupported = (function() {
try {
var a = new Blob(['hi']);
return a.size === 2;
} catch(e) {
return false;
}
})();
/**
* Check if Blob constructor supports ArrayBufferViews
* Fails in Safari 6, so we need to map to ArrayBuffers there.
*/
var blobSupportsArrayBufferView = blobSupported && (function() {
try {
var b = new Blob([new Uint8Array([1,2])]);
return b.size === 2;
} catch(e) {
return false;
}
})();
/**
* Check if BlobBuilder is supported
*/
var blobBuilderSupported = BlobBuilder
&& BlobBuilder.prototype.append
&& BlobBuilder.prototype.getBlob;
/**
* Helper function that maps ArrayBufferViews to ArrayBuffers
* Used by BlobBuilder constructor and old browsers that didn't
* support it in the Blob constructor.
*/
function mapArrayBufferViews(ary) {
for (var i = 0; i < ary.length; i++) {
var chunk = ary[i];
if (chunk.buffer instanceof ArrayBuffer) {
var buf = chunk.buffer;
// if this is a subarray, make a copy so we only
// include the subarray region from the underlying buffer
if (chunk.byteLength !== buf.byteLength) {
var copy = new Uint8Array(chunk.byteLength);
copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
buf = copy.buffer;
}
ary[i] = buf;
}
}
}
function BlobBuilderConstructor(ary, options) {
options = options || {};
var bb = new BlobBuilder();
mapArrayBufferViews(ary);
for (var i = 0; i < ary.length; i++) {
bb.append(ary[i]);
}
return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
};
function BlobConstructor(ary, options) {
mapArrayBufferViews(ary);
return new Blob(ary, options || {});
};
module.exports = (function() {
if (blobSupported) {
return blobSupportsArrayBufferView ? global.Blob : BlobConstructor;
} else if (blobBuilderSupported) {
return BlobBuilderConstructor;
} else {
return undefined;
}
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],5:[function(require,module,exports){
(function (process,global){
// Generated by CoffeeScript 1.9.1
(function() {
var Lexer, SourceMap, base, compile, ext, formatSourcePosition, fs, getSourceMap, helpers, i, len, lexer, parser, path, ref, sourceMaps, vm, withPrettyErrors,
hasProp = {}.hasOwnProperty,
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
fs = require('fs');
vm = require('vm');
path = require('path');
Lexer = require('./lexer').Lexer;
parser = require('./parser').parser;
helpers = require('./helpers');
SourceMap = require('./sourcemap');
exports.VERSION = '1.9.1';
exports.FILE_EXTENSIONS = ['.coffee', '.litcoffee', '.coffee.md'];
exports.helpers = helpers;
withPrettyErrors = function(fn) {
return function(code, options) {
var err;
if (options == null) {
options = {};
}
try {
return fn.call(this, code, options);
} catch (_error) {
err = _error;
throw helpers.updateSyntaxError(err, code, options.filename);
}
};
};
exports.compile = compile = withPrettyErrors(function(code, options) {
var answer, currentColumn, currentLine, extend, fragment, fragments, header, i, js, len, map, merge, newLines, token, tokens;
merge = helpers.merge, extend = helpers.extend;
options = extend({}, options);
if (options.sourceMap) {
map = new SourceMap;
}
tokens = lexer.tokenize(code, options);
options.referencedVars = (function() {
var i, len, results;
results = [];
for (i = 0, len = tokens.length; i < len; i++) {
token = tokens[i];
if (token.variable) {
results.push(token[1]);
}
}
return results;
})();
fragments = parser.parse(tokens).compileToFragments(options);
currentLine = 0;
if (options.header) {
currentLine += 1;
}
if (options.shiftLine) {
currentLine += 1;
}
currentColumn = 0;
js = "";
for (i = 0, len = fragments.length; i < len; i++) {
fragment = fragments[i];
if (options.sourceMap) {
if (fragment.locationData) {
map.add([fragment.locationData.first_line, fragment.locationData.first_column], [currentLine, currentColumn], {
noReplace: true
});
}
newLines = helpers.count(fragment.code, "\n");
currentLine += newLines;
if (newLines) {
currentColumn = fragment.code.length - (fragment.code.lastIndexOf("\n") + 1);
} else {
currentColumn += fragment.code.length;
}
}
js += fragment.code;
}
if (options.header) {
header = "Generated by CoffeeScript " + this.VERSION;
js = "// " + header + "\n" + js;
}
if (options.sourceMap) {
answer = {
js: js
};
answer.sourceMap = map;
answer.v3SourceMap = map.generate(options, code);
return answer;
} else {
return js;
}
});
exports.tokens = withPrettyErrors(function(code, options) {
return lexer.tokenize(code, options);
});
exports.nodes = withPrettyErrors(function(source, options) {
if (typeof source === 'string') {
return parser.parse(lexer.tokenize(source, options));
} else {
return parser.parse(source);
}
});
exports.run = function(code, options) {
var answer, dir, mainModule, ref;
if (options == null) {
options = {};
}
mainModule = require.main;
mainModule.filename = process.argv[1] = options.filename ? fs.realpathSync(options.filename) : '.';
mainModule.moduleCache && (mainModule.moduleCache = {});
dir = options.filename ? path.dirname(fs.realpathSync(options.filename)) : fs.realpathSync('.');
mainModule.paths = require('module')._nodeModulePaths(dir);
if (!helpers.isCoffee(mainModule.filename) || require.extensions) {
answer = compile(code, options);
code = (ref = answer.js) != null ? ref : answer;
}
return mainModule._compile(code, mainModule.filename);
};
exports["eval"] = function(code, options) {
var Module, _module, _require, createContext, i, isContext, js, k, len, o, r, ref, ref1, ref2, ref3, sandbox, v;
if (options == null) {
options = {};
}
if (!(code = code.trim())) {
return;
}
createContext = (ref = vm.Script.createContext) != null ? ref : vm.createContext;
isContext = (ref1 = vm.isContext) != null ? ref1 : function(ctx) {
return options.sandbox instanceof createContext().constructor;
};
if (createContext) {
if (options.sandbox != null) {
if (isContext(options.sandbox)) {
sandbox = options.sandbox;
} else {
sandbox = createContext();
ref2 = options.sandbox;
for (k in ref2) {
if (!hasProp.call(ref2, k)) continue;
v = ref2[k];
sandbox[k] = v;
}
}
sandbox.global = sandbox.root = sandbox.GLOBAL = sandbox;
} else {
sandbox = global;
}
sandbox.__filename = options.filename || 'eval';
sandbox.__dirname = path.dirname(sandbox.__filename);
if (!(sandbox !== global || sandbox.module || sandbox.require)) {
Module = require('module');
sandbox.module = _module = new Module(options.modulename || 'eval');
sandbox.require = _require = function(path) {
return Module._load(path, _module, true);
};
_module.filename = sandbox.__filename;
ref3 = Object.getOwnPropertyNames(require);
for (i = 0, len = ref3.length; i < len; i++) {
r = ref3[i];
if (r !== 'paths') {
_require[r] = require[r];
}
}
_require.paths = _module.paths = Module._nodeModulePaths(process.cwd());
_require.resolve = function(request) {
return Module._resolveFilename(request, _module);
};
}
}
o = {};
for (k in options) {
if (!hasProp.call(options, k)) continue;
v = options[k];
o[k] = v;
}
o.bare = true;
js = compile(code, o);
if (sandbox === global) {
return vm.runInThisContext(js);
} else {
return vm.runInContext(js, sandbox);
}
};
exports.register = function() {
return require('./register');
};
if (require.extensions) {
ref = this.FILE_EXTENSIONS;
for (i = 0, len = ref.length; i < len; i++) {
ext = ref[i];
if ((base = require.extensions)[ext] == null) {
base[ext] = function() {
throw new Error("Use CoffeeScript.register() or require the coffee-script/register module to require " + ext + " files.");
};
}
}
}
exports._compileFile = function(filename, sourceMap) {
var answer, err, raw, stripped;
if (sourceMap == null) {
sourceMap = false;
}
raw = fs.readFileSync(filename, 'utf8');
stripped = raw.charCodeAt(0) === 0xFEFF ? raw.substring(1) : raw;
try {
answer = compile(stripped, {
filename: filename,
sourceMap: sourceMap,
literate: helpers.isLiterate(filename)
});
} catch (_error) {
err = _error;
throw helpers.updateSyntaxError(err, stripped, filename);
}
return answer;
};
lexer = new Lexer;
parser.lexer = {
lex: function() {
var tag, token;
token = parser.tokens[this.pos++];
if (token) {
tag = token[0], this.yytext = token[1], this.yylloc = token[2];
parser.errorToken = token.origin || token;
this.yylineno = this.yylloc.first_line;
} else {
tag = '';
}
return tag;
},
setInput: function(tokens) {
parser.tokens = tokens;
return this.pos = 0;
},
upcomingInput: function() {
return "";
}
};
parser.yy = require('./nodes');
parser.yy.parseError = function(message, arg) {
var errorLoc, errorTag, errorText, errorToken, token, tokens;
token = arg.token;
errorToken = parser.errorToken, tokens = parser.tokens;
errorTag = errorToken[0], errorText = errorToken[1], errorLoc = errorToken[2];
errorText = (function() {
switch (false) {
case errorToken !== tokens[tokens.length - 1]:
return 'end of input';
case errorTag !== 'INDENT' && errorTag !== 'OUTDENT':
return 'indentation';
case errorTag !== 'IDENTIFIER' && errorTag !== 'NUMBER' && errorTag !== 'STRING' && errorTag !== 'STRING_START' && errorTag !== 'REGEX' && errorTag !== 'REGEX_START':
return errorTag.replace(/_START$/, '').toLowerCase();
default:
return helpers.nameWhitespaceCharacter(errorText);
}
})();
return helpers.throwSyntaxError("unexpected " + errorText, errorLoc);
};
formatSourcePosition = function(frame, getSourceMapping) {
var as, column, fileLocation, fileName, functionName, isConstructor, isMethodCall, line, methodName, source, tp, typeName;
fileName = void 0;
fileLocation = '';
if (frame.isNative()) {
fileLocation = "native";
} else {
if (frame.isEval()) {
fileName = frame.getScriptNameOrSourceURL();
if (!fileName) {
fileLocation = (frame.getEvalOrigin()) + ", ";
}
} else {
fileName = frame.getFileName();
}
fileName || (fileName = "<anonymous>");
line = frame.getLineNumber();
column = frame.getColumnNumber();
source = getSourceMapping(fileName, line, column);
fileLocation = source ? fileName + ":" + source[0] + ":" + source[1] : fileName + ":" + line + ":" + column;
}
functionName = frame.getFunctionName();
isConstructor = frame.isConstructor();
isMethodCall = !(frame.isToplevel() || isConstructor);
if (isMethodCall) {
methodName = frame.getMethodName();
typeName = frame.getTypeName();
if (functionName) {
tp = as = '';
if (typeName && functionName.indexOf(typeName)) {
tp = typeName + ".";
}
if (methodName && functionName.indexOf("." + methodName) !== functionName.length - methodName.length - 1) {
as = " [as " + methodName + "]";
}
return "" + tp + functionName + as + " (" + fileLocation + ")";
} else {
return typeName + "." + (methodName || '<anonymous>') + " (" + fileLocation + ")";
}
} else if (isConstructor) {
return "new " + (functionName || '<anonymous>') + " (" + fileLocation + ")";
} else if (functionName) {
return functionName + " (" + fileLocation + ")";
} else {
return fileLocation;
}
};
sourceMaps = {};
getSourceMap = function(filename) {
var answer, ref1;
if (sourceMaps[filename]) {
return sourceMaps[filename];
}
if (ref1 = path != null ? path.extname(filename) : void 0, indexOf.call(exports.FILE_EXTENSIONS, ref1) < 0) {
return;
}
answer = exports._compileFile(filename, true);
return sourceMaps[filename] = answer.sourceMap;
};
Error.prepareStackTrace = function(err, stack) {
var frame, frames, getSourceMapping;
getSourceMapping = function(filename, line, column) {
var answer, sourceMap;
sourceMap = getSourceMap(filename);
if (sourceMap) {
answer = sourceMap.sourceLocation([line - 1, column - 1]);
}
if (answer) {
return [answer[0] + 1, answer[1] + 1];
} else {
return null;
}
};
frames = (function() {
var j, len1, results;
results = [];
for (j = 0, len1 = stack.length; j < len1; j++) {
frame = stack[j];
if (frame.getFunction() === exports.run) {
break;
}
results.push(" at " + (formatSourcePosition(frame, getSourceMapping)));
}
return results;
})();
return (err.toString()) + "\n" + (frames.join('\n')) + "\n";
};
}).call(this);
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./helpers":6,"./lexer":7,"./nodes":8,"./parser":9,"./register":10,"./sourcemap":13,"_process":82,"fs":58,"module":58,"path":81,"vm":98}],6:[function(require,module,exports){
(function (process){
// Generated by CoffeeScript 1.9.1
(function() {
var buildLocationData, extend, flatten, ref, repeat, syntaxErrorToString;
exports.starts = function(string, literal, start) {
return literal === string.substr(start, literal.length);
};
exports.ends = function(string, literal, back) {
var len;
len = literal.length;
return literal === string.substr(string.length - len - (back || 0), len);
};
exports.repeat = repeat = function(str, n) {
var res;
res = '';
while (n > 0) {
if (n & 1) {
res += str;
}
n >>>= 1;
str += str;
}
return res;
};
exports.compact = function(array) {
var i, item, len1, results;
results = [];
for (i = 0, len1 = array.length; i < len1; i++) {
item = array[i];
if (item) {
results.push(item);
}
}
return results;
};
exports.count = function(string, substr) {
var num, pos;
num = pos = 0;
if (!substr.length) {
return 1 / 0;
}
while (pos = 1 + string.indexOf(substr, pos)) {
num++;
}
return num;
};
exports.merge = function(options, overrides) {
return extend(extend({}, options), overrides);
};
extend = exports.extend = function(object, properties) {
var key, val;
for (key in properties) {
val = properties[key];
object[key] = val;
}
return object;
};
exports.flatten = flatten = function(array) {
var element, flattened, i, len1;
flattened = [];
for (i = 0, len1 = array.length; i < len1; i++) {
element = array[i];
if (element instanceof Array) {
flattened = flattened.concat(flatten(element));
} else {
flattened.push(element);
}
}
return flattened;
};
exports.del = function(obj, key) {
var val;
val = obj[key];
delete obj[key];
return val;
};
exports.some = (ref = Array.prototype.some) != null ? ref : function(fn) {
var e, i, len1;
for (i = 0, len1 = this.length; i < len1; i++) {
e = this[i];
if (fn(e)) {
return true;
}
}
return false;
};
exports.invertLiterate = function(code) {
var line, lines, maybe_code;
maybe_code = true;
lines = (function() {
var i, len1, ref1, results;
ref1 = code.split('\n');
results = [];
for (i = 0, len1 = ref1.length; i < len1; i++) {
line = ref1[i];
if (maybe_code && /^([ ]{4}|[ ]{0,3}\t)/.test(line)) {
results.push(line);
} else if (maybe_code = /^\s*$/.test(line)) {
results.push(line);
} else {
results.push('# ' + line);
}
}
return results;
})();
return lines.join('\n');
};
buildLocationData = function(first, last) {
if (!last) {
return first;
} else {
return {
first_line: first.first_line,
first_column: first.first_column,
last_line: last.last_line,
last_column: last.last_column
};
}
};
exports.addLocationDataFn = function(first, last) {
return function(obj) {
if (((typeof obj) === 'object') && (!!obj['updateLocationDataIfMissing'])) {
obj.updateLocationDataIfMissing(buildLocationData(first, last));
}
return obj;
};
};
exports.locationDataToString = function(obj) {
var locationData;
if (("2" in obj) && ("first_line" in obj[2])) {
locationData = obj[2];
} else if ("first_line" in obj) {
locationData = obj;
}
if (locationData) {
return ((locationData.first_line + 1) + ":" + (locationData.first_column + 1) + "-") + ((locationData.last_line + 1) + ":" + (locationData.last_column + 1));
} else {
return "No location data";
}
};
exports.baseFileName = function(file, stripExt, useWinPathSep) {
var parts, pathSep;
if (stripExt == null) {
stripExt = false;
}
if (useWinPathSep == null) {
useWinPathSep = false;
}
pathSep = useWinPathSep ? /\\|\// : /\//;
parts = file.split(pathSep);
file = parts[parts.length - 1];
if (!(stripExt && file.indexOf('.') >= 0)) {
return file;
}
parts = file.split('.');
parts.pop();
if (parts[parts.length - 1] === 'coffee' && parts.length > 1) {
parts.pop();
}
return parts.join('.');
};
exports.isCoffee = function(file) {
return /\.((lit)?coffee|coffee\.md)$/.test(file);
};
exports.isLiterate = function(file) {
return /\.(litcoffee|coffee\.md)$/.test(file);
};
exports.throwSyntaxError = function(message, location) {
var error;
error = new SyntaxError(message);
error.location = location;
error.toString = syntaxErrorToString;
error.stack = error.toString();
throw error;
};
exports.updateSyntaxError = function(error, code, filename) {
if (error.toString === syntaxErrorToString) {
error.code || (error.code = code);
error.filename || (error.filename = filename);
error.stack = error.toString();
}
return error;
};
syntaxErrorToString = function() {
var codeLine, colorize, colorsEnabled, end, filename, first_column, first_line, last_column, last_line, marker, ref1, ref2, start;
if (!(this.code && this.location)) {
return Error.prototype.toString.call(this);
}
ref1 = this.location, first_line = ref1.first_line, first_column = ref1.first_column, last_line = ref1.last_line, last_column = ref1.last_column;
if (last_line == null) {
last_line = first_line;
}
if (last_column == null) {
last_column = first_column;
}
filename = this.filename || '[stdin]';
codeLine = this.code.split('\n')[first_line];
start = first_column;
end = first_line === last_line ? last_column + 1 : codeLine.length;
marker = codeLine.slice(0, start).replace(/[^\s]/g, ' ') + repeat('^', end - start);
if (typeof process !== "undefined" && process !== null) {
colorsEnabled = process.stdout.isTTY && !process.env.NODE_DISABLE_COLORS;
}
if ((ref2 = this.colorful) != null ? ref2 : colorsEnabled) {
colorize = function(str) {
return "\x1B[1;31m" + str + "\x1B[0m";
};
codeLine = codeLine.slice(0, start) + colorize(codeLine.slice(start, end)) + codeLine.slice(end);
marker = colorize(marker);
}
return filename + ":" + (first_line + 1) + ":" + (first_column + 1) + ": error: " + this.message + "\n" + codeLine + "\n" + marker;
};
exports.nameWhitespaceCharacter = function(string) {
switch (string) {
case ' ':
return 'space';
case '\n':
return 'newline';
case '\r':
return 'carriage return';
case '\t':
return 'tab';
default:
return string;
}
};
}).call(this);
}).call(this,require('_process'))
},{"_process":82}],7:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var BOM, BOOL, CALLABLE, CODE, COFFEE_ALIASES, COFFEE_ALIAS_MAP, COFFEE_KEYWORDS, COMMENT, COMPARE, COMPOUND_ASSIGN, HERECOMMENT_ILLEGAL, HEREDOC_DOUBLE, HEREDOC_INDENT, HEREDOC_SINGLE, HEREGEX, HEREGEX_OMIT, IDENTIFIER, INDENTABLE_CLOSERS, INDEXABLE, INVALID_ESCAPE, INVERSES, JSTOKEN, JS_FORBIDDEN, JS_KEYWORDS, LEADING_BLANK_LINE, LINE_BREAK, LINE_CONTINUER, LOGIC, Lexer, MATH, MULTI_DENT, NOT_REGEX, NUMBER, OPERATOR, POSSIBLY_DIVISION, REGEX, REGEX_FLAGS, REGEX_ILLEGAL, RELATION, RESERVED, Rewriter, SHIFT, SIMPLE_STRING_OMIT, STRICT_PROSCRIBED, STRING_DOUBLE, STRING_OMIT, STRING_SINGLE, STRING_START, TRAILING_BLANK_LINE, TRAILING_SPACES, UNARY, UNARY_MATH, VALID_FLAGS, WHITESPACE, compact, count, invertLiterate, key, locationDataToString, ref, ref1, repeat, starts, throwSyntaxError,
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
ref = require('./rewriter'), Rewriter = ref.Rewriter, INVERSES = ref.INVERSES;
ref1 = require('./helpers'), count = ref1.count, starts = ref1.starts, compact = ref1.compact, repeat = ref1.repeat, invertLiterate = ref1.invertLiterate, locationDataToString = ref1.locationDataToString, throwSyntaxError = ref1.throwSyntaxError;
exports.Lexer = Lexer = (function() {
function Lexer() {}
Lexer.prototype.tokenize = function(code, opts) {
var consumed, end, i, ref2;
if (opts == null) {
opts = {};
}
this.literate = opts.literate;
this.indent = 0;
this.baseIndent = 0;
this.indebt = 0;
this.outdebt = 0;
this.indents = [];
this.ends = [];
this.tokens = [];
this.chunkLine = opts.line || 0;
this.chunkColumn = opts.column || 0;
code = this.clean(code);
i = 0;
while (this.chunk = code.slice(i)) {
consumed = this.identifierToken() || this.commentToken() || this.whitespaceToken() || this.lineToken() || this.stringToken() || this.numberToken() || this.regexToken() || this.jsToken() || this.literalToken();
ref2 = this.getLineAndColumnFromChunk(consumed), this.chunkLine = ref2[0], this.chunkColumn = ref2[1];
i += consumed;
if (opts.untilBalanced && this.ends.length === 0) {
return {
tokens: this.tokens,
index: i
};
}
}
this.closeIndentation();
if (end = this.ends.pop()) {
this.error("missing " + end.tag, end.origin[2]);
}
if (opts.rewrite === false) {
return this.tokens;
}
return (new Rewriter).rewrite(this.tokens);
};
Lexer.prototype.clean = function(code) {
if (code.charCodeAt(0) === BOM) {
code = code.slice(1);
}
code = code.replace(/\r/g, '').replace(TRAILING_SPACES, '');
if (WHITESPACE.test(code)) {
code = "\n" + code;
this.chunkLine--;
}
if (this.literate) {
code = invertLiterate(code);
}
return code;
};
Lexer.prototype.identifierToken = function() {
var colon, colonOffset, forcedIdentifier, id, idLength, input, match, poppedToken, prev, ref2, ref3, ref4, ref5, tag, tagToken;
if (!(match = IDENTIFIER.exec(this.chunk))) {
return 0;
}
input = match[0], id = match[1], colon = match[2];
idLength = id.length;
poppedToken = void 0;
if (id === 'own' && this.tag() === 'FOR') {
this.token('OWN', id);
return id.length;
}
if (id === 'from' && this.tag() === 'YIELD') {
this.token('FROM', id);
return id.length;
}
ref2 = this.tokens, prev = ref2[ref2.length - 1];
forcedIdentifier = colon || (prev != null) && (((ref3 = prev[0]) === '.' || ref3 === '?.' || ref3 === '::' || ref3 === '?::') || !prev.spaced && prev[0] === '@');
tag = 'IDENTIFIER';
if (!forcedIdentifier && (indexOf.call(JS_KEYWORDS, id) >= 0 || indexOf.call(COFFEE_KEYWORDS, id) >= 0)) {
tag = id.toUpperCase();
if (tag === 'WHEN' && (ref4 = this.tag(), indexOf.call(LINE_BREAK, ref4) >= 0)) {
tag = 'LEADING_WHEN';
} else if (tag === 'FOR') {
this.seenFor = true;
} else if (tag === 'UNLESS') {
tag = 'IF';
} else if (indexOf.call(UNARY, tag) >= 0) {
tag = 'UNARY';
} else if (indexOf.call(RELATION, tag) >= 0) {
if (tag !== 'INSTANCEOF' && this.seenFor) {
tag = 'FOR' + tag;
this.seenFor = false;
} else {
tag = 'RELATION';
if (this.value() === '!') {
poppedToken = this.tokens.pop();
id = '!' + id;
}
}
}
}
if (indexOf.call(JS_FORBIDDEN, id) >= 0) {
if (forcedIdentifier) {
tag = 'IDENTIFIER';
id = new String(id);
id.reserved = true;
} else if (indexOf.call(RESERVED, id) >= 0) {
this.error("reserved word '" + id + "'", {
length: id.length
});
}
}
if (!forcedIdentifier) {
if (indexOf.call(COFFEE_ALIASES, id) >= 0) {
id = COFFEE_ALIAS_MAP[id];
}
tag = (function() {
switch (id) {
case '!':
return 'UNARY';
case '==':
case '!=':
return 'COMPARE';
case '&&':
case '||':
return 'LOGIC';
case 'true':
case 'false':
return 'BOOL';
case 'break':
case 'continue':
return 'STATEMENT';
default:
return tag;
}
})();
}
tagToken = this.token(tag, id, 0, idLength);
tagToken.variable = !forcedIdentifier;
if (poppedToken) {
ref5 = [poppedToken[2].first_line, poppedToken[2].first_column], tagToken[2].first_line = ref5[0], tagToken[2].first_column = ref5[1];
}
if (colon) {
colonOffset = input.lastIndexOf(':');
this.token(':', ':', colonOffset, colon.length);
}
return input.length;
};
Lexer.prototype.numberToken = function() {
var binaryLiteral, lexedLength, match, number, octalLiteral;
if (!(match = NUMBER.exec(this.chunk))) {
return 0;
}
number = match[0];
lexedLength = number.length;
if (/^0[BOX]/.test(number)) {
this.error("radix prefix in '" + number + "' must be lowercase", {
offset: 1
});
} else if (/E/.test(number) && !/^0x/.test(number)) {
this.error("exponential notation in '" + number + "' must be indicated with a lowercase 'e'", {
offset: number.indexOf('E')
});
} else if (/^0\d*[89]/.test(number)) {
this.error("decimal literal '" + number + "' must not be prefixed with '0'", {
length: lexedLength
});
} else if (/^0\d+/.test(number)) {
this.error("octal literal '" + number + "' must be prefixed with '0o'", {
length: lexedLength
});
}
if (octalLiteral = /^0o([0-7]+)/.exec(number)) {
number = '0x' + parseInt(octalLiteral[1], 8).toString(16);
}
if (binaryLiteral = /^0b([01]+)/.exec(number)) {
number = '0x' + parseInt(binaryLiteral[1], 2).toString(16);
}
this.token('NUMBER', number, 0, lexedLength);
return lexedLength;
};
Lexer.prototype.stringToken = function() {
var $, attempt, delimiter, doc, end, heredoc, i, indent, indentRegex, match, quote, ref2, ref3, regex, token, tokens;
quote = (STRING_START.exec(this.chunk) || [])[0];
if (!quote) {
return 0;
}
regex = (function() {
switch (quote) {
case "'":
return STRING_SINGLE;
case '"':
return STRING_DOUBLE;
case "'''":
return HEREDOC_SINGLE;
case '"""':
return HEREDOC_DOUBLE;
}
})();
heredoc = quote.length === 3;
ref2 = this.matchWithInterpolations(regex, quote), tokens = ref2.tokens, end = ref2.index;
$ = tokens.length - 1;
delimiter = quote[0];
if (heredoc) {
indent = null;
doc = ((function() {
var j, len, results;
results = [];
for (i = j = 0, len = tokens.length; j < len; i = ++j) {
token = tokens[i];
if (token[0] === 'NEOSTRING') {
results.push(token[1]);
}
}
return results;
})()).join('#{}');
while (match = HEREDOC_INDENT.exec(doc)) {
attempt = match[1];
if (indent === null || (0 < (ref3 = attempt.length) && ref3 < indent.length)) {
indent = attempt;
}
}
if (indent) {
indentRegex = RegExp("^" + indent, "gm");
}
this.mergeInterpolationTokens(tokens, {
delimiter: delimiter
}, (function(_this) {
return function(value, i) {
value = _this.formatString(value);
if (i === 0) {
value = value.replace(LEADING_BLANK_LINE, '');
}
if (i === $) {
value = value.replace(TRAILING_BLANK_LINE, '');
}
if (indentRegex) {
value = value.replace(indentRegex, '');
}
return value;
};
})(this));
} else {
this.mergeInterpolationTokens(tokens, {
delimiter: delimiter
}, (function(_this) {
return function(value, i) {
value = _this.formatString(value);
value = value.replace(SIMPLE_STRING_OMIT, function(match, offset) {
if ((i === 0 && offset === 0) || (i === $ && offset + match.length === value.length)) {
return '';
} else {
return ' ';
}
});
return value;
};
})(this));
}
return end;
};
Lexer.prototype.commentToken = function() {
var comment, here, match;
if (!(match = this.chunk.match(COMMENT))) {
return 0;
}
comment = match[0], here = match[1];
if (here) {
if (match = HERECOMMENT_ILLEGAL.exec(comment)) {
this.error("block comments cannot contain " + match[0], {
offset: match.index,
length: match[0].length
});
}
if (here.indexOf('\n') >= 0) {
here = here.replace(RegExp("\\n" + (repeat(' ', this.indent)), "g"), '\n');
}
this.token('HERECOMMENT', here, 0, comment.length);
}
return comment.length;
};
Lexer.prototype.jsToken = function() {
var match, script;
if (!(this.chunk.charAt(0) === '`' && (match = JSTOKEN.exec(this.chunk)))) {
return 0;
}
this.token('JS', (script = match[0]).slice(1, -1), 0, script.length);
return script.length;
};
Lexer.prototype.regexToken = function() {
var body, closed, end, flags, index, match, origin, prev, ref2, ref3, ref4, regex, tokens;
switch (false) {
case !(match = REGEX_ILLEGAL.exec(this.chunk)):
this.error("regular expressions cannot begin with " + match[2], {
offset: match.index + match[1].length
});
break;
case !(match = this.matchWithInterpolations(HEREGEX, '///')):
tokens = match.tokens, index = match.index;
break;
case !(match = REGEX.exec(this.chunk)):
regex = match[0], body = match[1], closed = match[2];
this.validateEscapes(body, {
isRegex: true,
offsetInChunk: 1
});
index = regex.length;
ref2 = this.tokens, prev = ref2[ref2.length - 1];
if (prev) {
if (prev.spaced && (ref3 = prev[0], indexOf.call(CALLABLE, ref3) >= 0)) {
if (!closed || POSSIBLY_DIVISION.test(regex)) {
return 0;
}
} else if (ref4 = prev[0], indexOf.call(NOT_REGEX, ref4) >= 0) {
return 0;
}
}
if (!closed) {
this.error('missing / (unclosed regex)');
}
break;
default:
return 0;
}
flags = REGEX_FLAGS.exec(this.chunk.slice(index))[0];
end = index + flags.length;
origin = this.makeToken('REGEX', null, 0, end);
switch (false) {
case !!VALID_FLAGS.test(flags):
this.error("invalid regular expression flags " + flags, {
offset: index,
length: flags.length
});
break;
case !(regex || tokens.length === 1):
if (body == null) {
body = this.formatHeregex(tokens[0][1]);
}
this.token('REGEX', "" + (this.makeDelimitedLiteral(body, {
delimiter: '/'
})) + flags, 0, end, origin);
break;
default:
this.token('REGEX_START', '(', 0, 0, origin);
this.token('IDENTIFIER', 'RegExp', 0, 0);
this.token('CALL_START', '(', 0, 0);
this.mergeInterpolationTokens(tokens, {
delimiter: '"',
double: true
}, this.formatHeregex);
if (flags) {
this.token(',', ',', index, 0);
this.token('STRING', '"' + flags + '"', index, flags.length);
}
this.token(')', ')', end, 0);
this.token('REGEX_END', ')', end, 0);
}
return end;
};
Lexer.prototype.lineToken = function() {
var diff, indent, match, noNewlines, size;
if (!(match = MULTI_DENT.exec(this.chunk))) {
return 0;
}
indent = match[0];
this.seenFor = false;
size = indent.length - 1 - indent.lastIndexOf('\n');
noNewlines = this.unfinished();
if (size - this.indebt === this.indent) {
if (noNewlines) {
this.suppressNewlines();
} else {
this.newlineToken(0);
}
return indent.length;
}
if (size > this.indent) {
if (noNewlines) {
this.indebt = size - this.indent;
this.suppressNewlines();
return indent.length;
}
if (!this.tokens.length) {
this.baseIndent = this.indent = size;
return indent.length;
}
diff = size - this.indent + this.outdebt;
this.token('INDENT', diff, indent.length - size, size);
this.indents.push(diff);
this.ends.push({
tag: 'OUTDENT'
});
this.outdebt = this.indebt = 0;
this.indent = size;
} else if (size < this.baseIndent) {
this.error('missing indentation', {
offset: indent.length
});
} else {
this.indebt = 0;
this.outdentToken(this.indent - size, noNewlines, indent.length);
}
return indent.length;
};
Lexer.prototype.outdentToken = function(moveOut, noNewlines, outdentLength) {
var decreasedIndent, dent, lastIndent, ref2;
decreasedIndent = this.indent - moveOut;
while (moveOut > 0) {
lastIndent = this.indents[this.indents.length - 1];
if (!lastIndent) {
moveOut = 0;
} else if (lastIndent === this.outdebt) {
moveOut -= this.outdebt;
this.outdebt = 0;
} else if (lastIndent < this.outdebt) {
this.outdebt -= lastIndent;
moveOut -= lastIndent;
} else {
dent = this.indents.pop() + this.outdebt;
if (outdentLength && (ref2 = this.chunk[outdentLength], indexOf.call(INDENTABLE_CLOSERS, ref2) >= 0)) {
decreasedIndent -= dent - moveOut;
moveOut = dent;
}
this.outdebt = 0;
this.pair('OUTDENT');
this.token('OUTDENT', moveOut, 0, outdentLength);
moveOut -= dent;
}
}
if (dent) {
this.outdebt -= moveOut;
}
while (this.value() === ';') {
this.tokens.pop();
}
if (!(this.tag() === 'TERMINATOR' || noNewlines)) {
this.token('TERMINATOR', '\n', outdentLength, 0);
}
this.indent = decreasedIndent;
return this;
};
Lexer.prototype.whitespaceToken = function() {
var match, nline, prev, ref2;
if (!((match = WHITESPACE.exec(this.chunk)) || (nline = this.chunk.charAt(0) === '\n'))) {
return 0;
}
ref2 = this.tokens, prev = ref2[ref2.length - 1];
if (prev) {
prev[match ? 'spaced' : 'newLine'] = true;
}
if (match) {
return match[0].length;
} else {
return 0;
}
};
Lexer.prototype.newlineToken = function(offset) {
while (this.value() === ';') {
this.tokens.pop();
}
if (this.tag() !== 'TERMINATOR') {
this.token('TERMINATOR', '\n', offset, 0);
}
return this;
};
Lexer.prototype.suppressNewlines = function() {
if (this.value() === '\\') {
this.tokens.pop();
}
return this;
};
Lexer.prototype.literalToken = function() {
var match, prev, ref2, ref3, ref4, ref5, ref6, tag, token, value;
if (match = OPERATOR.exec(this.chunk)) {
value = match[0];
if (CODE.test(value)) {
this.tagParameters();
}
} else {
value = this.chunk.charAt(0);
}
tag = value;
ref2 = this.tokens, prev = ref2[ref2.length - 1];
if (value === '=' && prev) {
if (!prev[1].reserved && (ref3 = prev[1], indexOf.call(JS_FORBIDDEN, ref3) >= 0)) {
this.error("reserved word '" + prev[1] + "' can't be assigned", prev[2]);
}
if ((ref4 = prev[1]) === '||' || ref4 === '&&') {
prev[0] = 'COMPOUND_ASSIGN';
prev[1] += '=';
return value.length;
}
}
if (value === ';') {
this.seenFor = false;
tag = 'TERMINATOR';
} else if (indexOf.call(MATH, value) >= 0) {
tag = 'MATH';
} else if (indexOf.call(COMPARE, value) >= 0) {
tag = 'COMPARE';
} else if (indexOf.call(COMPOUND_ASSIGN, value) >= 0) {
tag = 'COMPOUND_ASSIGN';
} else if (indexOf.call(UNARY, value) >= 0) {
tag = 'UNARY';
} else if (indexOf.call(UNARY_MATH, value) >= 0) {
tag = 'UNARY_MATH';
} else if (indexOf.call(SHIFT, value) >= 0) {
tag = 'SHIFT';
} else if (indexOf.call(LOGIC, value) >= 0 || value === '?' && (prev != null ? prev.spaced : void 0)) {
tag = 'LOGIC';
} else if (prev && !prev.spaced) {
if (value === '(' && (ref5 = prev[0], indexOf.call(CALLABLE, ref5) >= 0)) {
if (prev[0] === '?') {
prev[0] = 'FUNC_EXIST';
}
tag = 'CALL_START';
} else if (value === '[' && (ref6 = prev[0], indexOf.call(INDEXABLE, ref6) >= 0)) {
tag = 'INDEX_START';
switch (prev[0]) {
case '?':
prev[0] = 'INDEX_SOAK';
}
}
}
token = this.makeToken(tag, value);
switch (value) {
case '(':
case '{':
case '[':
this.ends.push({
tag: INVERSES[value],
origin: token
});
break;
case ')':
case '}':
case ']':
this.pair(value);
}
this.tokens.push(token);
return value.length;
};
Lexer.prototype.tagParameters = function() {
var i, stack, tok, tokens;
if (this.tag() !== ')') {
return this;
}
stack = [];
tokens = this.tokens;
i = tokens.length;
tokens[--i][0] = 'PARAM_END';
while (tok = tokens[--i]) {
switch (tok[0]) {
case ')':
stack.push(tok);
break;
case '(':
case 'CALL_START':
if (stack.length) {
stack.pop();
} else if (tok[0] === '(') {
tok[0] = 'PARAM_START';
return this;
} else {
return this;
}
}
}
return this;
};
Lexer.prototype.closeIndentation = function() {
return this.outdentToken(this.indent);
};
Lexer.prototype.matchWithInterpolations = function(regex, delimiter) {
var close, column, firstToken, index, lastToken, line, nested, offsetInChunk, open, ref2, ref3, ref4, str, strPart, tokens;
tokens = [];
offsetInChunk = delimiter.length;
if (this.chunk.slice(0, offsetInChunk) !== delimiter) {
return null;
}
str = this.chunk.slice(offsetInChunk);
while (true) {
strPart = regex.exec(str)[0];
this.validateEscapes(strPart, {
isRegex: delimiter.charAt(0) === '/',
offsetInChunk: offsetInChunk
});
tokens.push(this.makeToken('NEOSTRING', strPart, offsetInChunk));
str = str.slice(strPart.length);
offsetInChunk += strPart.length;
if (str.slice(0, 2) !== '#{') {
break;
}
ref2 = this.getLineAndColumnFromChunk(offsetInChunk + 1), line = ref2[0], column = ref2[1];
ref3 = new Lexer().tokenize(str.slice(1), {
line: line,
column: column,
untilBalanced: true
}), nested = ref3.tokens, index = ref3.index;
index += 1;
open = nested[0], close = nested[nested.length - 1];
open[0] = open[1] = '(';
close[0] = close[1] = ')';
close.origin = ['', 'end of interpolation', close[2]];
if (((ref4 = nested[1]) != null ? ref4[0] : void 0) === 'TERMINATOR') {
nested.splice(1, 1);
}
tokens.push(['TOKENS', nested]);
str = str.slice(index);
offsetInChunk += index;
}
if (str.slice(0, delimiter.length) !== delimiter) {
this.error("missing " + delimiter, {
length: delimiter.length
});
}
firstToken = tokens[0], lastToken = tokens[tokens.length - 1];
firstToken[2].first_column -= delimiter.length;
lastToken[2].last_column += delimiter.length;
if (lastToken[1].length === 0) {
lastToken[2].last_column -= 1;
}
return {
tokens: tokens,
index: offsetInChunk + delimiter.length
};
};
Lexer.prototype.mergeInterpolationTokens = function(tokens, options, fn) {
var converted, firstEmptyStringIndex, firstIndex, i, j, lastToken, len, locationToken, lparen, plusToken, ref2, rparen, tag, token, tokensToPush, value;
if (tokens.length > 1) {
lparen = this.token('STRING_START', '(', 0, 0);
}
firstIndex = this.tokens.length;
for (i = j = 0, len = tokens.length; j < len; i = ++j) {
token = tokens[i];
tag = token[0], value = token[1];
switch (tag) {
case 'TOKENS':
if (value.length === 2) {
continue;
}
locationToken = value[0];
tokensToPush = value;
break;
case 'NEOSTRING':
converted = fn(token[1], i);
if (converted.length === 0) {
if (i === 0) {
firstEmptyStringIndex = this.tokens.length;
} else {
continue;
}
}
if (i === 2 && (firstEmptyStringIndex != null)) {
this.tokens.splice(firstEmptyStringIndex, 2);
}
token[0] = 'STRING';
token[1] = this.makeDelimitedLiteral(converted, options);
locationToken = token;
tokensToPush = [token];
}
if (this.tokens.length > firstIndex) {
plusToken = this.token('+', '+');
plusToken[2] = {
first_line: locationToken[2].first_line,
first_column: locationToken[2].first_column,
last_line: locationToken[2].first_line,
last_column: locationToken[2].first_column
};
}
(ref2 = this.tokens).push.apply(ref2, tokensToPush);
}
if (lparen) {
lastToken = tokens[tokens.length - 1];
lparen.origin = [
'STRING', null, {
first_line: lparen[2].first_line,
first_column: lparen[2].first_column,
last_line: lastToken[2].last_line,
last_column: lastToken[2].last_column
}
];
rparen = this.token('STRING_END', ')');
return rparen[2] = {
first_line: lastToken[2].last_line,
first_column: lastToken[2].last_column,
last_line: lastToken[2].last_line,
last_column: lastToken[2].last_column
};
}
};
Lexer.prototype.pair = function(tag) {
var lastIndent, prev, ref2, ref3, wanted;
ref2 = this.ends, prev = ref2[ref2.length - 1];
if (tag !== (wanted = prev != null ? prev.tag : void 0)) {
if ('OUTDENT' !== wanted) {
this.error("unmatched " + tag);
}
ref3 = this.indents, lastIndent = ref3[ref3.length - 1];
this.outdentToken(lastIndent, true);
return this.pair(tag);
}
return this.ends.pop();
};
Lexer.prototype.getLineAndColumnFromChunk = function(offset) {
var column, lastLine, lineCount, ref2, string;
if (offset === 0) {
return [this.chunkLine, this.chunkColumn];
}
if (offset >= this.chunk.length) {
string = this.chunk;
} else {
string = this.chunk.slice(0, +(offset - 1) + 1 || 9e9);
}
lineCount = count(string, '\n');
column = this.chunkColumn;
if (lineCount > 0) {
ref2 = string.split('\n'), lastLine = ref2[ref2.length - 1];
column = lastLine.length;
} else {
column += string.length;
}
return [this.chunkLine + lineCount, column];
};
Lexer.prototype.makeToken = function(tag, value, offsetInChunk, length) {
var lastCharacter, locationData, ref2, ref3, token;
if (offsetInChunk == null) {
offsetInChunk = 0;
}
if (length == null) {
length = value.length;
}
locationData = {};
ref2 = this.getLineAndColumnFromChunk(offsetInChunk), locationData.first_line = ref2[0], locationData.first_column = ref2[1];
lastCharacter = Math.max(0, length - 1);
ref3 = this.getLineAndColumnFromChunk(offsetInChunk + lastCharacter), locationData.last_line = ref3[0], locationData.last_column = ref3[1];
token = [tag, value, locationData];
return token;
};
Lexer.prototype.token = function(tag, value, offsetInChunk, length, origin) {
var token;
token = this.makeToken(tag, value, offsetInChunk, length);
if (origin) {
token.origin = origin;
}
this.tokens.push(token);
return token;
};
Lexer.prototype.tag = function() {
var ref2, token;
ref2 = this.tokens, token = ref2[ref2.length - 1];
return token != null ? token[0] : void 0;
};
Lexer.prototype.value = function() {
var ref2, token;
ref2 = this.tokens, token = ref2[ref2.length - 1];
return token != null ? token[1] : void 0;
};
Lexer.prototype.unfinished = function() {
var ref2;
return LINE_CONTINUER.test(this.chunk) || ((ref2 = this.tag()) === '\\' || ref2 === '.' || ref2 === '?.' || ref2 === '?::' || ref2 === 'UNARY' || ref2 === 'MATH' || ref2 === 'UNARY_MATH' || ref2 === '+' || ref2 === '-' || ref2 === 'YIELD' || ref2 === '**' || ref2 === 'SHIFT' || ref2 === 'RELATION' || ref2 === 'COMPARE' || ref2 === 'LOGIC' || ref2 === 'THROW' || ref2 === 'EXTENDS');
};
Lexer.prototype.formatString = function(str) {
return str.replace(STRING_OMIT, '$1');
};
Lexer.prototype.formatHeregex = function(str) {
return str.replace(HEREGEX_OMIT, '$1$2');
};
Lexer.prototype.validateEscapes = function(str, options) {
var before, hex, invalidEscape, match, message, octal, ref2, unicode;
if (options == null) {
options = {};
}
match = INVALID_ESCAPE.exec(str);
if (!match) {
return;
}
match[0], before = match[1], octal = match[2], hex = match[3], unicode = match[4];
if (options.isRegex && octal && octal.charAt(0) !== '0') {
return;
}
message = octal ? "octal escape sequences are not allowed" : "invalid escape sequence";
invalidEscape = "\\" + (octal || hex || unicode);
return this.error(message + " " + invalidEscape, {
offset: ((ref2 = options.offsetInChunk) != null ? ref2 : 0) + match.index + before.length,
length: invalidEscape.length
});
};
Lexer.prototype.makeDelimitedLiteral = function(body, options) {
var regex;
if (options == null) {
options = {};
}
if (body === '' && options.delimiter === '/') {
body = '(?:)';
}
regex = RegExp("(\\\\\\\\)|(\\\\0(?=[1-7]))|\\\\?(" + options.delimiter + ")|\\\\?(?:(\\n)|(\\r)|(\\u2028)|(\\u2029))|(\\\\.)", "g");
body = body.replace(regex, function(match, backslash, nul, delimiter, lf, cr, ls, ps, other) {
switch (false) {
case !backslash:
if (options.double) {
return backslash + backslash;
} else {
return backslash;
}
case !nul:
return '\\x00';
case !delimiter:
return "\\" + delimiter;
case !lf:
return '\\n';
case !cr:
return '\\r';
case !ls:
return '\\u2028';
case !ps:
return '\\u2029';
case !other:
if (options.double) {
return "\\" + other;
} else {
return other;
}
}
});
return "" + options.delimiter + body + options.delimiter;
};
Lexer.prototype.error = function(message, options) {
var first_column, first_line, location, ref2, ref3, ref4;
if (options == null) {
options = {};
}
location = 'first_line' in options ? options : ((ref3 = this.getLineAndColumnFromChunk((ref2 = options.offset) != null ? ref2 : 0), first_line = ref3[0], first_column = ref3[1], ref3), {
first_line: first_line,
first_column: first_column,
last_column: first_column + ((ref4 = options.length) != null ? ref4 : 1) - 1
});
return throwSyntaxError(message, location);
};
return Lexer;
})();
JS_KEYWORDS = ['true', 'false', 'null', 'this', 'new', 'delete', 'typeof', 'in', 'instanceof', 'return', 'throw', 'break', 'continue', 'debugger', 'yield', 'if', 'else', 'switch', 'for', 'while', 'do', 'try', 'catch', 'finally', 'class', 'extends', 'super'];
COFFEE_KEYWORDS = ['undefined', 'then', 'unless', 'until', 'loop', 'of', 'by', 'when'];
COFFEE_ALIAS_MAP = {
and: '&&',
or: '||',
is: '==',
isnt: '!=',
not: '!',
yes: 'true',
no: 'false',
on: 'true',
off: 'false'
};
COFFEE_ALIASES = (function() {
var results;
results = [];
for (key in COFFEE_ALIAS_MAP) {
results.push(key);
}
return results;
})();
COFFEE_KEYWORDS = COFFEE_KEYWORDS.concat(COFFEE_ALIASES);
RESERVED = ['case', 'default', 'function', 'var', 'void', 'with', 'const', 'let', 'enum', 'export', 'import', 'native', 'implements', 'interface', 'package', 'private', 'protected', 'public', 'static'];
STRICT_PROSCRIBED = ['arguments', 'eval', 'yield*'];
JS_FORBIDDEN = JS_KEYWORDS.concat(RESERVED).concat(STRICT_PROSCRIBED);
exports.RESERVED = RESERVED.concat(JS_KEYWORDS).concat(COFFEE_KEYWORDS).concat(STRICT_PROSCRIBED);
exports.STRICT_PROSCRIBED = STRICT_PROSCRIBED;
BOM = 65279;
IDENTIFIER = /^(?!\d)((?:(?!\s)[$\w\x7f-\uffff])+)([^\n\S]*:(?!:))?/;
NUMBER = /^0b[01]+|^0o[0-7]+|^0x[\da-f]+|^\d*\.?\d+(?:e[+-]?\d+)?/i;
OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>*\/%])\2=?|\?(\.|::)|\.{2,3})/;
WHITESPACE = /^[^\n\S]+/;
COMMENT = /^###([^#][\s\S]*?)(?:###[^\n\S]*|###$)|^(?:\s*#(?!##[^#]).*)+/;
CODE = /^[-=]>/;
MULTI_DENT = /^(?:\n[^\n\S]*)+/;
JSTOKEN = /^`[^\\`]*(?:\\.[^\\`]*)*`/;
STRING_START = /^(?:'''|"""|'|")/;
STRING_SINGLE = /^(?:[^\\']|\\[\s\S])*/;
STRING_DOUBLE = /^(?:[^\\"#]|\\[\s\S]|\#(?!\{))*/;
HEREDOC_SINGLE = /^(?:[^\\']|\\[\s\S]|'(?!''))*/;
HEREDOC_DOUBLE = /^(?:[^\\"#]|\\[\s\S]|"(?!"")|\#(?!\{))*/;
STRING_OMIT = /((?:\\\\)+)|\\[^\S\n]*\n\s*/g;
SIMPLE_STRING_OMIT = /\s*\n\s*/g;
HEREDOC_INDENT = /\n+([^\n\S]*)(?=\S)/g;
REGEX = /^\/(?!\/)((?:[^[\/\n\\]|\\[^\n]|\[(?:\\[^\n]|[^\]\n\\])*])*)(\/)?/;
REGEX_FLAGS = /^\w*/;
VALID_FLAGS = /^(?!.*(.).*\1)[imgy]*$/;
HEREGEX = /^(?:[^\\\/#]|\\[\s\S]|\/(?!\/\/)|\#(?!\{))*/;
HEREGEX_OMIT = /((?:\\\\)+)|\\(\s)|\s+(?:#.*)?/g;
REGEX_ILLEGAL = /^(\/|\/{3}\s*)(\*)/;
POSSIBLY_DIVISION = /^\/=?\s/;
HERECOMMENT_ILLEGAL = /\*\//;
LINE_CONTINUER = /^\s*(?:,|\??\.(?![.\d])|::)/;
INVALID_ESCAPE = /((?:^|[^\\])(?:\\\\)*)\\(?:(0[0-7]|[1-7])|(x(?![\da-fA-F]{2}).{0,2})|(u(?![\da-fA-F]{4}).{0,4}))/;
LEADING_BLANK_LINE = /^[^\n\S]*\n/;
TRAILING_BLANK_LINE = /\n[^\n\S]*$/;
TRAILING_SPACES = /\s+$/;
COMPOUND_ASSIGN = ['-=', '+=', '/=', '*=', '%=', '||=', '&&=', '?=', '<<=', '>>=', '>>>=', '&=', '^=', '|=', '**=', '//=', '%%='];
UNARY = ['NEW', 'TYPEOF', 'DELETE', 'DO'];
UNARY_MATH = ['!', '~'];
LOGIC = ['&&', '||', '&', '|', '^'];
SHIFT = ['<<', '>>', '>>>'];
COMPARE = ['==', '!=', '<', '>', '<=', '>='];
MATH = ['*', '/', '%', '//', '%%'];
RELATION = ['IN', 'OF', 'INSTANCEOF'];
BOOL = ['TRUE', 'FALSE'];
CALLABLE = ['IDENTIFIER', ')', ']', '?', '@', 'THIS', 'SUPER'];
INDEXABLE = CALLABLE.concat(['NUMBER', 'STRING', 'STRING_END', 'REGEX', 'REGEX_END', 'BOOL', 'NULL', 'UNDEFINED', '}', '::']);
NOT_REGEX = INDEXABLE.concat(['++', '--']);
LINE_BREAK = ['INDENT', 'OUTDENT', 'TERMINATOR'];
INDENTABLE_CLOSERS = [')', '}', ']'];
}).call(this);
},{"./helpers":6,"./rewriter":11}],8:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var Access, Arr, Assign, Base, Block, Call, Class, Code, CodeFragment, Comment, Existence, Expansion, Extends, For, HEXNUM, IDENTIFIER, IS_REGEX, IS_STRING, If, In, Index, LEVEL_ACCESS, LEVEL_COND, LEVEL_LIST, LEVEL_OP, LEVEL_PAREN, LEVEL_TOP, Literal, NEGATE, NO, NUMBER, Obj, Op, Param, Parens, RESERVED, Range, Return, SIMPLENUM, STRICT_PROSCRIBED, Scope, Slice, Splat, Switch, TAB, THIS, Throw, Try, UTILITIES, Value, While, YES, addLocationDataFn, compact, del, ends, extend, flatten, fragmentsToText, isComplexOrAssignable, isLiteralArguments, isLiteralThis, locationDataToString, merge, multident, parseNum, ref1, ref2, some, starts, throwSyntaxError, unfoldSoak, utility,
extend1 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty,
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
slice = [].slice;
Error.stackTraceLimit = Infinity;
Scope = require('./scope').Scope;
ref1 = require('./lexer'), RESERVED = ref1.RESERVED, STRICT_PROSCRIBED = ref1.STRICT_PROSCRIBED;
ref2 = require('./helpers'), compact = ref2.compact, flatten = ref2.flatten, extend = ref2.extend, merge = ref2.merge, del = ref2.del, starts = ref2.starts, ends = ref2.ends, some = ref2.some, addLocationDataFn = ref2.addLocationDataFn, locationDataToString = ref2.locationDataToString, throwSyntaxError = ref2.throwSyntaxError;
exports.extend = extend;
exports.addLocationDataFn = addLocationDataFn;
YES = function() {
return true;
};
NO = function() {
return false;
};
THIS = function() {
return this;
};
NEGATE = function() {
this.negated = !this.negated;
return this;
};
exports.CodeFragment = CodeFragment = (function() {
function CodeFragment(parent, code) {
var ref3;
this.code = "" + code;
this.locationData = parent != null ? parent.locationData : void 0;
this.type = (parent != null ? (ref3 = parent.constructor) != null ? ref3.name : void 0 : void 0) || 'unknown';
}
CodeFragment.prototype.toString = function() {
return "" + this.code + (this.locationData ? ": " + locationDataToString(this.locationData) : '');
};
return CodeFragment;
})();
fragmentsToText = function(fragments) {
var fragment;
return ((function() {
var j, len1, results;
results = [];
for (j = 0, len1 = fragments.length; j < len1; j++) {
fragment = fragments[j];
results.push(fragment.code);
}
return results;
})()).join('');
};
exports.Base = Base = (function() {
function Base() {}
Base.prototype.compile = function(o, lvl) {
return fragmentsToText(this.compileToFragments(o, lvl));
};
Base.prototype.compileToFragments = function(o, lvl) {
var node;
o = extend({}, o);
if (lvl) {
o.level = lvl;
}
node = this.unfoldSoak(o) || this;
node.tab = o.indent;
if (o.level === LEVEL_TOP || !node.isStatement(o)) {
return node.compileNode(o);
} else {
return node.compileClosure(o);
}
};
Base.prototype.compileClosure = function(o) {
var args, argumentsNode, func, jumpNode, meth, parts;
if (jumpNode = this.jumps()) {
jumpNode.error('cannot use a pure statement in an expression');
}
o.sharedScope = true;
func = new Code([], Block.wrap([this]));
args = [];
if ((argumentsNode = this.contains(isLiteralArguments)) || this.contains(isLiteralThis)) {
args = [new Literal('this')];
if (argumentsNode) {
meth = 'apply';
args.push(new Literal('arguments'));
} else {
meth = 'call';
}
func = new Value(func, [new Access(new Literal(meth))]);
}
parts = (new Call(func, args)).compileNode(o);
if (func.isGenerator) {
parts.unshift(this.makeCode("(yield* "));
parts.push(this.makeCode(")"));
}
return parts;
};
Base.prototype.cache = function(o, level, isComplex) {
var complex, ref, sub;
complex = isComplex != null ? isComplex(this) : this.isComplex();
if (complex) {
ref = new Literal(o.scope.freeVariable('ref'));
sub = new Assign(ref, this);
if (level) {
return [sub.compileToFragments(o, level), [this.makeCode(ref.value)]];
} else {
return [sub, ref];
}
} else {
ref = level ? this.compileToFragments(o, level) : this;
return [ref, ref];
}
};
Base.prototype.cacheToCodeFragments = function(cacheValues) {
return [fragmentsToText(cacheValues[0]), fragmentsToText(cacheValues[1])];
};
Base.prototype.makeReturn = function(res) {
var me;
me = this.unwrapAll();
if (res) {
return new Call(new Literal(res + ".push"), [me]);
} else {
return new Return(me);
}
};
Base.prototype.contains = function(pred) {
var node;
node = void 0;
this.traverseChildren(false, function(n) {
if (pred(n)) {
node = n;
return false;
}
});
return node;
};
Base.prototype.lastNonComment = function(list) {
var i;
i = list.length;
while (i--) {
if (!(list[i] instanceof Comment)) {
return list[i];
}
}
return null;
};
Base.prototype.toString = function(idt, name) {
var tree;
if (idt == null) {
idt = '';
}
if (name == null) {
name = this.constructor.name;
}
tree = '\n' + idt + name;
if (this.soak) {
tree += '?';
}
this.eachChild(function(node) {
return tree += node.toString(idt + TAB);
});
return tree;
};
Base.prototype.eachChild = function(func) {
var attr, child, j, k, len1, len2, ref3, ref4;
if (!this.children) {
return this;
}
ref3 = this.children;
for (j = 0, len1 = ref3.length; j < len1; j++) {
attr = ref3[j];
if (this[attr]) {
ref4 = flatten([this[attr]]);
for (k = 0, len2 = ref4.length; k < len2; k++) {
child = ref4[k];
if (func(child) === false) {
return this;
}
}
}
}
return this;
};
Base.prototype.traverseChildren = function(crossScope, func) {
return this.eachChild(function(child) {
var recur;
recur = func(child);
if (recur !== false) {
return child.traverseChildren(crossScope, func);
}
});
};
Base.prototype.invert = function() {
return new Op('!', this);
};
Base.prototype.unwrapAll = function() {
var node;
node = this;
while (node !== (node = node.unwrap())) {
continue;
}
return node;
};
Base.prototype.children = [];
Base.prototype.isStatement = NO;
Base.prototype.jumps = NO;
Base.prototype.isComplex = YES;
Base.prototype.isChainable = NO;
Base.prototype.isAssignable = NO;
Base.prototype.unwrap = THIS;
Base.prototype.unfoldSoak = NO;
Base.prototype.assigns = NO;
Base.prototype.updateLocationDataIfMissing = function(locationData) {
if (this.locationData) {
return this;
}
this.locationData = locationData;
return this.eachChild(function(child) {
return child.updateLocationDataIfMissing(locationData);
});
};
Base.prototype.error = function(message) {
return throwSyntaxError(message, this.locationData);
};
Base.prototype.makeCode = function(code) {
return new CodeFragment(this, code);
};
Base.prototype.wrapInBraces = function(fragments) {
return [].concat(this.makeCode('('), fragments, this.makeCode(')'));
};
Base.prototype.joinFragmentArrays = function(fragmentsList, joinStr) {
var answer, fragments, i, j, len1;
answer = [];
for (i = j = 0, len1 = fragmentsList.length; j < len1; i = ++j) {
fragments = fragmentsList[i];
if (i) {
answer.push(this.makeCode(joinStr));
}
answer = answer.concat(fragments);
}
return answer;
};
return Base;
})();
exports.Block = Block = (function(superClass1) {
extend1(Block, superClass1);
function Block(nodes) {
this.expressions = compact(flatten(nodes || []));
}
Block.prototype.children = ['expressions'];
Block.prototype.push = function(node) {
this.expressions.push(node);
return this;
};
Block.prototype.pop = function() {
return this.expressions.pop();
};
Block.prototype.unshift = function(node) {
this.expressions.unshift(node);
return this;
};
Block.prototype.unwrap = function() {
if (this.expressions.length === 1) {
return this.expressions[0];
} else {
return this;
}
};
Block.prototype.isEmpty = function() {
return !this.expressions.length;
};
Block.prototype.isStatement = function(o) {
var exp, j, len1, ref3;
ref3 = this.expressions;
for (j = 0, len1 = ref3.length; j < len1; j++) {
exp = ref3[j];
if (exp.isStatement(o)) {
return true;
}
}
return false;
};
Block.prototype.jumps = function(o) {
var exp, j, jumpNode, len1, ref3;
ref3 = this.expressions;
for (j = 0, len1 = ref3.length; j < len1; j++) {
exp = ref3[j];
if (jumpNode = exp.jumps(o)) {
return jumpNode;
}
}
};
Block.prototype.makeReturn = function(res) {
var expr, len;
len = this.expressions.length;
while (len--) {
expr = this.expressions[len];
if (!(expr instanceof Comment)) {
this.expressions[len] = expr.makeReturn(res);
if (expr instanceof Return && !expr.expression) {
this.expressions.splice(len, 1);
}
break;
}
}
return this;
};
Block.prototype.compileToFragments = function(o, level) {
if (o == null) {
o = {};
}
if (o.scope) {
return Block.__super__.compileToFragments.call(this, o, level);
} else {
return this.compileRoot(o);
}
};
Block.prototype.compileNode = function(o) {
var answer, compiledNodes, fragments, index, j, len1, node, ref3, top;
this.tab = o.indent;
top = o.level === LEVEL_TOP;
compiledNodes = [];
ref3 = this.expressions;
for (index = j = 0, len1 = ref3.length; j < len1; index = ++j) {
node = ref3[index];
node = node.unwrapAll();
node = node.unfoldSoak(o) || node;
if (node instanceof Block) {
compiledNodes.push(node.compileNode(o));
} else if (top) {
node.front = true;
fragments = node.compileToFragments(o);
if (!node.isStatement(o)) {
fragments.unshift(this.makeCode("" + this.tab));
fragments.push(this.makeCode(";"));
}
compiledNodes.push(fragments);
} else {
compiledNodes.push(node.compileToFragments(o, LEVEL_LIST));
}
}
if (top) {
if (this.spaced) {
return [].concat(this.joinFragmentArrays(compiledNodes, '\n\n'), this.makeCode("\n"));
} else {
return this.joinFragmentArrays(compiledNodes, '\n');
}
}
if (compiledNodes.length) {
answer = this.joinFragmentArrays(compiledNodes, ', ');
} else {
answer = [this.makeCode("void 0")];
}
if (compiledNodes.length > 1 && o.level >= LEVEL_LIST) {
return this.wrapInBraces(answer);
} else {
return answer;
}
};
Block.prototype.compileRoot = function(o) {
var exp, fragments, i, j, len1, name, prelude, preludeExps, ref3, ref4, rest;
o.indent = o.bare ? '' : TAB;
o.level = LEVEL_TOP;
this.spaced = true;
o.scope = new Scope(null, this, null, (ref3 = o.referencedVars) != null ? ref3 : []);
ref4 = o.locals || [];
for (j = 0, len1 = ref4.length; j < len1; j++) {
name = ref4[j];
o.scope.parameter(name);
}
prelude = [];
if (!o.bare) {
preludeExps = (function() {
var k, len2, ref5, results;
ref5 = this.expressions;
results = [];
for (i = k = 0, len2 = ref5.length; k < len2; i = ++k) {
exp = ref5[i];
if (!(exp.unwrap() instanceof Comment)) {
break;
}
results.push(exp);
}
return results;
}).call(this);
rest = this.expressions.slice(preludeExps.length);
this.expressions = preludeExps;
if (preludeExps.length) {
prelude = this.compileNode(merge(o, {
indent: ''
}));
prelude.push(this.makeCode("\n"));
}
this.expressions = rest;
}
fragments = this.compileWithDeclarations(o);
if (o.bare) {
return fragments;
}
return [].concat(prelude, this.makeCode("(function() {\n"), fragments, this.makeCode("\n}).call(this);\n"));
};
Block.prototype.compileWithDeclarations = function(o) {
var assigns, declars, exp, fragments, i, j, len1, post, ref3, ref4, ref5, rest, scope, spaced;
fragments = [];
post = [];
ref3 = this.expressions;
for (i = j = 0, len1 = ref3.length; j < len1; i = ++j) {
exp = ref3[i];
exp = exp.unwrap();
if (!(exp instanceof Comment || exp instanceof Literal)) {
break;
}
}
o = merge(o, {
level: LEVEL_TOP
});
if (i) {
rest = this.expressions.splice(i, 9e9);
ref4 = [this.spaced, false], spaced = ref4[0], this.spaced = ref4[1];
ref5 = [this.compileNode(o), spaced], fragments = ref5[0], this.spaced = ref5[1];
this.expressions = rest;
}
post = this.compileNode(o);
scope = o.scope;
if (scope.expressions === this) {
declars = o.scope.hasDeclarations();
assigns = scope.hasAssignments;
if (declars || assigns) {
if (i) {
fragments.push(this.makeCode('\n'));
}
fragments.push(this.makeCode(this.tab + "var "));
if (declars) {
fragments.push(this.makeCode(scope.declaredVariables().join(', ')));
}
if (assigns) {
if (declars) {
fragments.push(this.makeCode(",\n" + (this.tab + TAB)));
}
fragments.push(this.makeCode(scope.assignedVariables().join(",\n" + (this.tab + TAB))));
}
fragments.push(this.makeCode(";\n" + (this.spaced ? '\n' : '')));
} else if (fragments.length && post.length) {
fragments.push(this.makeCode("\n"));
}
}
return fragments.concat(post);
};
Block.wrap = function(nodes) {
if (nodes.length === 1 && nodes[0] instanceof Block) {
return nodes[0];
}
return new Block(nodes);
};
return Block;
})(Base);
exports.Literal = Literal = (function(superClass1) {
extend1(Literal, superClass1);
function Literal(value1) {
this.value = value1;
}
Literal.prototype.makeReturn = function() {
if (this.isStatement()) {
return this;
} else {
return Literal.__super__.makeReturn.apply(this, arguments);
}
};
Literal.prototype.isAssignable = function() {
return IDENTIFIER.test(this.value);
};
Literal.prototype.isStatement = function() {
var ref3;
return (ref3 = this.value) === 'break' || ref3 === 'continue' || ref3 === 'debugger';
};
Literal.prototype.isComplex = NO;
Literal.prototype.assigns = function(name) {
return name === this.value;
};
Literal.prototype.jumps = function(o) {
if (this.value === 'break' && !((o != null ? o.loop : void 0) || (o != null ? o.block : void 0))) {
return this;
}
if (this.value === 'continue' && !(o != null ? o.loop : void 0)) {
return this;
}
};
Literal.prototype.compileNode = function(o) {
var answer, code, ref3;
code = this.value === 'this' ? ((ref3 = o.scope.method) != null ? ref3.bound : void 0) ? o.scope.method.context : this.value : this.value.reserved ? "\"" + this.value + "\"" : this.value;
answer = this.isStatement() ? "" + this.tab + code + ";" : code;
return [this.makeCode(answer)];
};
Literal.prototype.toString = function() {
return ' "' + this.value + '"';
};
return Literal;
})(Base);
exports.Undefined = (function(superClass1) {
extend1(Undefined, superClass1);
function Undefined() {
return Undefined.__super__.constructor.apply(this, arguments);
}
Undefined.prototype.isAssignable = NO;
Undefined.prototype.isComplex = NO;
Undefined.prototype.compileNode = function(o) {
return [this.makeCode(o.level >= LEVEL_ACCESS ? '(void 0)' : 'void 0')];
};
return Undefined;
})(Base);
exports.Null = (function(superClass1) {
extend1(Null, superClass1);
function Null() {
return Null.__super__.constructor.apply(this, arguments);
}
Null.prototype.isAssignable = NO;
Null.prototype.isComplex = NO;
Null.prototype.compileNode = function() {
return [this.makeCode("null")];
};
return Null;
})(Base);
exports.Bool = (function(superClass1) {
extend1(Bool, superClass1);
Bool.prototype.isAssignable = NO;
Bool.prototype.isComplex = NO;
Bool.prototype.compileNode = function() {
return [this.makeCode(this.val)];
};
function Bool(val1) {
this.val = val1;
}
return Bool;
})(Base);
exports.Return = Return = (function(superClass1) {
extend1(Return, superClass1);
function Return(expression) {
this.expression = expression;
}
Return.prototype.children = ['expression'];
Return.prototype.isStatement = YES;
Return.prototype.makeReturn = THIS;
Return.prototype.jumps = THIS;
Return.prototype.compileToFragments = function(o, level) {
var expr, ref3;
expr = (ref3 = this.expression) != null ? ref3.makeReturn() : void 0;
if (expr && !(expr instanceof Return)) {
return expr.compileToFragments(o, level);
} else {
return Return.__super__.compileToFragments.call(this, o, level);
}
};
Return.prototype.compileNode = function(o) {
var answer, exprIsYieldReturn, ref3;
answer = [];
exprIsYieldReturn = (ref3 = this.expression) != null ? typeof ref3.isYieldReturn === "function" ? ref3.isYieldReturn() : void 0 : void 0;
if (!exprIsYieldReturn) {
answer.push(this.makeCode(this.tab + ("return" + (this.expression ? " " : ""))));
}
if (this.expression) {
answer = answer.concat(this.expression.compileToFragments(o, LEVEL_PAREN));
}
if (!exprIsYieldReturn) {
answer.push(this.makeCode(";"));
}
return answer;
};
return Return;
})(Base);
exports.Value = Value = (function(superClass1) {
extend1(Value, superClass1);
function Value(base, props, tag) {
if (!props && base instanceof Value) {
return base;
}
this.base = base;
this.properties = props || [];
if (tag) {
this[tag] = true;
}
return this;
}
Value.prototype.children = ['base', 'properties'];
Value.prototype.add = function(props) {
this.properties = this.properties.concat(props);
return this;
};
Value.prototype.hasProperties = function() {
return !!this.properties.length;
};
Value.prototype.bareLiteral = function(type) {
return !this.properties.length && this.base instanceof type;
};
Value.prototype.isArray = function() {
return this.bareLiteral(Arr);
};
Value.prototype.isRange = function() {
return this.bareLiteral(Range);
};
Value.prototype.isComplex = function() {
return this.hasProperties() || this.base.isComplex();
};
Value.prototype.isAssignable = function() {
return this.hasProperties() || this.base.isAssignable();
};
Value.prototype.isSimpleNumber = function() {
return this.bareLiteral(Literal) && SIMPLENUM.test(this.base.value);
};
Value.prototype.isString = function() {
return this.bareLiteral(Literal) && IS_STRING.test(this.base.value);
};
Value.prototype.isRegex = function() {
return this.bareLiteral(Literal) && IS_REGEX.test(this.base.value);
};
Value.prototype.isAtomic = function() {
var j, len1, node, ref3;
ref3 = this.properties.concat(this.base);
for (j = 0, len1 = ref3.length; j < len1; j++) {
node = ref3[j];
if (node.soak || node instanceof Call) {
return false;
}
}
return true;
};
Value.prototype.isNotCallable = function() {
return this.isSimpleNumber() || this.isString() || this.isRegex() || this.isArray() || this.isRange() || this.isSplice() || this.isObject();
};
Value.prototype.isStatement = function(o) {
return !this.properties.length && this.base.isStatement(o);
};
Value.prototype.assigns = function(name) {
return !this.properties.length && this.base.assigns(name);
};
Value.prototype.jumps = function(o) {
return !this.properties.length && this.base.jumps(o);
};
Value.prototype.isObject = function(onlyGenerated) {
if (this.properties.length) {
return false;
}
return (this.base instanceof Obj) && (!onlyGenerated || this.base.generated);
};
Value.prototype.isSplice = function() {
var lastProp, ref3;
ref3 = this.properties, lastProp = ref3[ref3.length - 1];
return lastProp instanceof Slice;
};
Value.prototype.looksStatic = function(className) {
var ref3;
return this.base.value === className && this.properties.length === 1 && ((ref3 = this.properties[0].name) != null ? ref3.value : void 0) !== 'prototype';
};
Value.prototype.unwrap = function() {
if (this.properties.length) {
return this;
} else {
return this.base;
}
};
Value.prototype.cacheReference = function(o) {
var base, bref, name, nref, ref3;
ref3 = this.properties, name = ref3[ref3.length - 1];
if (this.properties.length < 2 && !this.base.isComplex() && !(name != null ? name.isComplex() : void 0)) {
return [this, this];
}
base = new Value(this.base, this.properties.slice(0, -1));
if (base.isComplex()) {
bref = new Literal(o.scope.freeVariable('base'));
base = new Value(new Parens(new Assign(bref, base)));
}
if (!name) {
return [base, bref];
}
if (name.isComplex()) {
nref = new Literal(o.scope.freeVariable('name'));
name = new Index(new Assign(nref, name.index));
nref = new Index(nref);
}
return [base.add(name), new Value(bref || base.base, [nref || name])];
};
Value.prototype.compileNode = function(o) {
var fragments, j, len1, prop, props;
this.base.front = this.front;
props = this.properties;
fragments = this.base.compileToFragments(o, (props.length ? LEVEL_ACCESS : null));
if ((this.base instanceof Parens || props.length) && SIMPLENUM.test(fragmentsToText(fragments))) {
fragments.push(this.makeCode('.'));
}
for (j = 0, len1 = props.length; j < len1; j++) {
prop = props[j];
fragments.push.apply(fragments, prop.compileToFragments(o));
}
return fragments;
};
Value.prototype.unfoldSoak = function(o) {
return this.unfoldedSoak != null ? this.unfoldedSoak : this.unfoldedSoak = (function(_this) {
return function() {
var fst, i, ifn, j, len1, prop, ref, ref3, ref4, snd;
if (ifn = _this.base.unfoldSoak(o)) {
(ref3 = ifn.body.properties).push.apply(ref3, _this.properties);
return ifn;
}
ref4 = _this.properties;
for (i = j = 0, len1 = ref4.length; j < len1; i = ++j) {
prop = ref4[i];
if (!prop.soak) {
continue;
}
prop.soak = false;
fst = new Value(_this.base, _this.properties.slice(0, i));
snd = new Value(_this.base, _this.properties.slice(i));
if (fst.isComplex()) {
ref = new Literal(o.scope.freeVariable('ref'));
fst = new Parens(new Assign(ref, fst));
snd.base = ref;
}
return new If(new Existence(fst), snd, {
soak: true
});
}
return false;
};
})(this)();
};
return Value;
})(Base);
exports.Comment = Comment = (function(superClass1) {
extend1(Comment, superClass1);
function Comment(comment1) {
this.comment = comment1;
}
Comment.prototype.isStatement = YES;
Comment.prototype.makeReturn = THIS;
Comment.prototype.compileNode = function(o, level) {
var code, comment;
comment = this.comment.replace(/^(\s*)# /gm, "$1 * ");
code = "/*" + (multident(comment, this.tab)) + (indexOf.call(comment, '\n') >= 0 ? "\n" + this.tab : '') + " */";
if ((level || o.level) === LEVEL_TOP) {
code = o.indent + code;
}
return [this.makeCode("\n"), this.makeCode(code)];
};
return Comment;
})(Base);
exports.Call = Call = (function(superClass1) {
extend1(Call, superClass1);
function Call(variable, args1, soak) {
this.args = args1 != null ? args1 : [];
this.soak = soak;
this.isNew = false;
this.isSuper = variable === 'super';
this.variable = this.isSuper ? null : variable;
if (variable instanceof Value && variable.isNotCallable()) {
variable.error("literal is not a function");
}
}
Call.prototype.children = ['variable', 'args'];
Call.prototype.newInstance = function() {
var base, ref3;
base = ((ref3 = this.variable) != null ? ref3.base : void 0) || this.variable;
if (base instanceof Call && !base.isNew) {
base.newInstance();
} else {
this.isNew = true;
}
return this;
};
Call.prototype.superReference = function(o) {
var accesses, base, bref, klass, method, name, nref, variable;
method = o.scope.namedMethod();
if (method != null ? method.klass : void 0) {
klass = method.klass, name = method.name, variable = method.variable;
if (klass.isComplex()) {
bref = new Literal(o.scope.parent.freeVariable('base'));
base = new Value(new Parens(new Assign(bref, klass)));
variable.base = base;
variable.properties.splice(0, klass.properties.length);
}
if (name.isComplex() || (name instanceof Index && name.index.isAssignable())) {
nref = new Literal(o.scope.parent.freeVariable('name'));
name = new Index(new Assign(nref, name.index));
variable.properties.pop();
variable.properties.push(name);
}
accesses = [new Access(new Literal('__super__'))];
if (method["static"]) {
accesses.push(new Access(new Literal('constructor')));
}
accesses.push(nref != null ? new Index(nref) : name);
return (new Value(bref != null ? bref : klass, accesses)).compile(o);
} else if (method != null ? method.ctor : void 0) {
return method.name + ".__super__.constructor";
} else {
return this.error('cannot call super outside of an instance method.');
}
};
Call.prototype.superThis = function(o) {
var method;
method = o.scope.method;
return (method && !method.klass && method.context) || "this";
};
Call.prototype.unfoldSoak = function(o) {
var call, ifn, j, left, len1, list, ref3, ref4, rite;
if (this.soak) {
if (this.variable) {
if (ifn = unfoldSoak(o, this, 'variable')) {
return ifn;
}
ref3 = new Value(this.variable).cacheReference(o), left = ref3[0], rite = ref3[1];
} else {
left = new Literal(this.superReference(o));
rite = new Value(left);
}
rite = new Call(rite, this.args);
rite.isNew = this.isNew;
left = new Literal("typeof " + (left.compile(o)) + " === \"function\"");
return new If(left, new Value(rite), {
soak: true
});
}
call = this;
list = [];
while (true) {
if (call.variable instanceof Call) {
list.push(call);
call = call.variable;
continue;
}
if (!(call.variable instanceof Value)) {
break;
}
list.push(call);
if (!((call = call.variable.base) instanceof Call)) {
break;
}
}
ref4 = list.reverse();
for (j = 0, len1 = ref4.length; j < len1; j++) {
call = ref4[j];
if (ifn) {
if (call.variable instanceof Call) {
call.variable = ifn;
} else {
call.variable.base = ifn;
}
}
ifn = unfoldSoak(o, call, 'variable');
}
return ifn;
};
Call.prototype.compileNode = function(o) {
var arg, argIndex, compiledArgs, compiledArray, fragments, j, len1, preface, ref3, ref4;
if ((ref3 = this.variable) != null) {
ref3.front = this.front;
}
compiledArray = Splat.compileSplattedArray(o, this.args, true);
if (compiledArray.length) {
return this.compileSplat(o, compiledArray);
}
compiledArgs = [];
ref4 = this.args;
for (argIndex = j = 0, len1 = ref4.length; j < len1; argIndex = ++j) {
arg = ref4[argIndex];
if (argIndex) {
compiledArgs.push(this.makeCode(", "));
}
compiledArgs.push.apply(compiledArgs, arg.compileToFragments(o, LEVEL_LIST));
}
fragments = [];
if (this.isSuper) {
preface = this.superReference(o) + (".call(" + (this.superThis(o)));
if (compiledArgs.length) {
preface += ", ";
}
fragments.push(this.makeCode(preface));
} else {
if (this.isNew) {
fragments.push(this.makeCode('new '));
}
fragments.push.apply(fragments, this.variable.compileToFragments(o, LEVEL_ACCESS));
fragments.push(this.makeCode("("));
}
fragments.push.apply(fragments, compiledArgs);
fragments.push(this.makeCode(")"));
return fragments;
};
Call.prototype.compileSplat = function(o, splatArgs) {
var answer, base, fun, idt, name, ref;
if (this.isSuper) {
return [].concat(this.makeCode((this.superReference(o)) + ".apply(" + (this.superThis(o)) + ", "), splatArgs, this.makeCode(")"));
}
if (this.isNew) {
idt = this.tab + TAB;
return [].concat(this.makeCode("(function(func, args, ctor) {\n" + idt + "ctor.prototype = func.prototype;\n" + idt + "var child = new ctor, result = func.apply(child, args);\n" + idt + "return Object(result) === result ? result : child;\n" + this.tab + "})("), this.variable.compileToFragments(o, LEVEL_LIST), this.makeCode(", "), splatArgs, this.makeCode(", function(){})"));
}
answer = [];
base = new Value(this.variable);
if ((name = base.properties.pop()) && base.isComplex()) {
ref = o.scope.freeVariable('ref');
answer = answer.concat(this.makeCode("(" + ref + " = "), base.compileToFragments(o, LEVEL_LIST), this.makeCode(")"), name.compileToFragments(o));
} else {
fun = base.compileToFragments(o, LEVEL_ACCESS);
if (SIMPLENUM.test(fragmentsToText(fun))) {
fun = this.wrapInBraces(fun);
}
if (name) {
ref = fragmentsToText(fun);
fun.push.apply(fun, name.compileToFragments(o));
} else {
ref = 'null';
}
answer = answer.concat(fun);
}
return answer = answer.concat(this.makeCode(".apply(" + ref + ", "), splatArgs, this.makeCode(")"));
};
return Call;
})(Base);
exports.Extends = Extends = (function(superClass1) {
extend1(Extends, superClass1);
function Extends(child1, parent1) {
this.child = child1;
this.parent = parent1;
}
Extends.prototype.children = ['child', 'parent'];
Extends.prototype.compileToFragments = function(o) {
return new Call(new Value(new Literal(utility('extend', o))), [this.child, this.parent]).compileToFragments(o);
};
return Extends;
})(Base);
exports.Access = Access = (function(superClass1) {
extend1(Access, superClass1);
function Access(name1, tag) {
this.name = name1;
this.name.asKey = true;
this.soak = tag === 'soak';
}
Access.prototype.children = ['name'];
Access.prototype.compileToFragments = function(o) {
var name;
name = this.name.compileToFragments(o);
if (IDENTIFIER.test(fragmentsToText(name))) {
name.unshift(this.makeCode("."));
} else {
name.unshift(this.makeCode("["));
name.push(this.makeCode("]"));
}
return name;
};
Access.prototype.isComplex = NO;
return Access;
})(Base);
exports.Index = Index = (function(superClass1) {
extend1(Index, superClass1);
function Index(index1) {
this.index = index1;
}
Index.prototype.children = ['index'];
Index.prototype.compileToFragments = function(o) {
return [].concat(this.makeCode("["), this.index.compileToFragments(o, LEVEL_PAREN), this.makeCode("]"));
};
Index.prototype.isComplex = function() {
return this.index.isComplex();
};
return Index;
})(Base);
exports.Range = Range = (function(superClass1) {
extend1(Range, superClass1);
Range.prototype.children = ['from', 'to'];
function Range(from1, to1, tag) {
this.from = from1;
this.to = to1;
this.exclusive = tag === 'exclusive';
this.equals = this.exclusive ? '' : '=';
}
Range.prototype.compileVariables = function(o) {
var isComplex, ref3, ref4, ref5, ref6, step;
o = merge(o, {
top: true
});
isComplex = del(o, 'isComplex');
ref3 = this.cacheToCodeFragments(this.from.cache(o, LEVEL_LIST, isComplex)), this.fromC = ref3[0], this.fromVar = ref3[1];
ref4 = this.cacheToCodeFragments(this.to.cache(o, LEVEL_LIST, isComplex)), this.toC = ref4[0], this.toVar = ref4[1];
if (step = del(o, 'step')) {
ref5 = this.cacheToCodeFragments(step.cache(o, LEVEL_LIST, isComplex)), this.step = ref5[0], this.stepVar = ref5[1];
}
ref6 = [this.fromVar.match(NUMBER), this.toVar.match(NUMBER)], this.fromNum = ref6[0], this.toNum = ref6[1];
if (this.stepVar) {
return this.stepNum = this.stepVar.match(NUMBER);
}
};
Range.prototype.compileNode = function(o) {
var cond, condPart, from, gt, idx, idxName, known, lt, namedIndex, ref3, ref4, stepPart, to, varPart;
if (!this.fromVar) {
this.compileVariables(o);
}
if (!o.index) {
return this.compileArray(o);
}
known = this.fromNum && this.toNum;
idx = del(o, 'index');
idxName = del(o, 'name');
namedIndex = idxName && idxName !== idx;
varPart = idx + " = " + this.fromC;
if (this.toC !== this.toVar) {
varPart += ", " + this.toC;
}
if (this.step !== this.stepVar) {
varPart += ", " + this.step;
}
ref3 = [idx + " <" + this.equals, idx + " >" + this.equals], lt = ref3[0], gt = ref3[1];
condPart = this.stepNum ? parseNum(this.stepNum[0]) > 0 ? lt + " " + this.toVar : gt + " " + this.toVar : known ? ((ref4 = [parseNum(this.fromNum[0]), parseNum(this.toNum[0])], from = ref4[0], to = ref4[1], ref4), from <= to ? lt + " " + to : gt + " " + to) : (cond = this.stepVar ? this.stepVar + " > 0" : this.fromVar + " <= " + this.toVar, cond + " ? " + lt + " " + this.toVar + " : " + gt + " " + this.toVar);
stepPart = this.stepVar ? idx + " += " + this.stepVar : known ? namedIndex ? from <= to ? "++" + idx : "--" + idx : from <= to ? idx + "++" : idx + "--" : namedIndex ? cond + " ? ++" + idx + " : --" + idx : cond + " ? " + idx + "++ : " + idx + "--";
if (namedIndex) {
varPart = idxName + " = " + varPart;
}
if (namedIndex) {
stepPart = idxName + " = " + stepPart;
}
return [this.makeCode(varPart + "; " + condPart + "; " + stepPart)];
};
Range.prototype.compileArray = function(o) {
var args, body, cond, hasArgs, i, idt, j, post, pre, range, ref3, ref4, result, results, vars;
if (this.fromNum && this.toNum && Math.abs(this.fromNum - this.toNum) <= 20) {
range = (function() {
results = [];
for (var j = ref3 = +this.fromNum, ref4 = +this.toNum; ref3 <= ref4 ? j <= ref4 : j >= ref4; ref3 <= ref4 ? j++ : j--){ results.push(j); }
return results;
}).apply(this);
if (this.exclusive) {
range.pop();
}
return [this.makeCode("[" + (range.join(', ')) + "]")];
}
idt = this.tab + TAB;
i = o.scope.freeVariable('i', {
single: true
});
result = o.scope.freeVariable('results');
pre = "\n" + idt + result + " = [];";
if (this.fromNum && this.toNum) {
o.index = i;
body = fragmentsToText(this.compileNode(o));
} else {
vars = (i + " = " + this.fromC) + (this.toC !== this.toVar ? ", " + this.toC : '');
cond = this.fromVar + " <= " + this.toVar;
body = "var " + vars + "; " + cond + " ? " + i + " <" + this.equals + " " + this.toVar + " : " + i + " >" + this.equals + " " + this.toVar + "; " + cond + " ? " + i + "++ : " + i + "--";
}
post = "{ " + result + ".push(" + i + "); }\n" + idt + "return " + result + ";\n" + o.indent;
hasArgs = function(node) {
return node != null ? node.contains(isLiteralArguments) : void 0;
};
if (hasArgs(this.from) || hasArgs(this.to)) {
args = ', arguments';
}
return [this.makeCode("(function() {" + pre + "\n" + idt + "for (" + body + ")" + post + "}).apply(this" + (args != null ? args : '') + ")")];
};
return Range;
})(Base);
exports.Slice = Slice = (function(superClass1) {
extend1(Slice, superClass1);
Slice.prototype.children = ['range'];
function Slice(range1) {
this.range = range1;
Slice.__super__.constructor.call(this);
}
Slice.prototype.compileNode = function(o) {
var compiled, compiledText, from, fromCompiled, ref3, to, toStr;
ref3 = this.range, to = ref3.to, from = ref3.from;
fromCompiled = from && from.compileToFragments(o, LEVEL_PAREN) || [this.makeCode('0')];
if (to) {
compiled = to.compileToFragments(o, LEVEL_PAREN);
compiledText = fragmentsToText(compiled);
if (!(!this.range.exclusive && +compiledText === -1)) {
toStr = ', ' + (this.range.exclusive ? compiledText : SIMPLENUM.test(compiledText) ? "" + (+compiledText + 1) : (compiled = to.compileToFragments(o, LEVEL_ACCESS), "+" + (fragmentsToText(compiled)) + " + 1 || 9e9"));
}
}
return [this.makeCode(".slice(" + (fragmentsToText(fromCompiled)) + (toStr || '') + ")")];
};
return Slice;
})(Base);
exports.Obj = Obj = (function(superClass1) {
extend1(Obj, superClass1);
function Obj(props, generated) {
this.generated = generated != null ? generated : false;
this.objects = this.properties = props || [];
}
Obj.prototype.children = ['properties'];
Obj.prototype.compileNode = function(o) {
var answer, dynamicIndex, hasDynamic, i, idt, indent, j, join, k, key, l, lastNoncom, len1, len2, len3, node, oref, prop, props, ref3, value;
props = this.properties;
if (this.generated) {
for (j = 0, len1 = props.length; j < len1; j++) {
node = props[j];
if (node instanceof Value) {
node.error('cannot have an implicit value in an implicit object');
}
}
}
for (dynamicIndex = k = 0, len2 = props.length; k < len2; dynamicIndex = ++k) {
prop = props[dynamicIndex];
if ((prop.variable || prop).base instanceof Parens) {
break;
}
}
hasDynamic = dynamicIndex < props.length;
idt = o.indent += TAB;
lastNoncom = this.lastNonComment(this.properties);
answer = [];
if (hasDynamic) {
oref = o.scope.freeVariable('obj');
answer.push(this.makeCode("(\n" + idt + oref + " = "));
}
answer.push(this.makeCode("{" + (props.length === 0 || dynamicIndex === 0 ? '}' : '\n')));
for (i = l = 0, len3 = props.length; l < len3; i = ++l) {
prop = props[i];
if (i === dynamicIndex) {
if (i !== 0) {
answer.push(this.makeCode("\n" + idt + "}"));
}
answer.push(this.makeCode(',\n'));
}
join = i === props.length - 1 || i === dynamicIndex - 1 ? '' : prop === lastNoncom || prop instanceof Comment ? '\n' : ',\n';
indent = prop instanceof Comment ? '' : idt;
if (hasDynamic && i < dynamicIndex) {
indent += TAB;
}
if (prop instanceof Assign && prop.variable instanceof Value && prop.variable.hasProperties()) {
prop.variable.error('Invalid object key');
}
if (prop instanceof Value && prop["this"]) {
prop = new Assign(prop.properties[0].name, prop, 'object');
}
if (!(prop instanceof Comment)) {
if (i < dynamicIndex) {
if (!(prop instanceof Assign)) {
prop = new Assign(prop, prop, 'object');
}
(prop.variable.base || prop.variable).asKey = true;
} else {
if (prop instanceof Assign) {
key = prop.variable;
value = prop.value;
} else {
ref3 = prop.base.cache(o), key = ref3[0], value = ref3[1];
}
prop = new Assign(new Value(new Literal(oref), [new Access(key)]), value);
}
}
if (indent) {
answer.push(this.makeCode(indent));
}
answer.push.apply(answer, prop.compileToFragments(o, LEVEL_TOP));
if (join) {
answer.push(this.makeCode(join));
}
}
if (hasDynamic) {
answer.push(this.makeCode(",\n" + idt + oref + "\n" + this.tab + ")"));
} else {
if (props.length !== 0) {
answer.push(this.makeCode("\n" + this.tab + "}"));
}
}
if (this.front && !hasDynamic) {
return this.wrapInBraces(answer);
} else {
return answer;
}
};
Obj.prototype.assigns = function(name) {
var j, len1, prop, ref3;
ref3 = this.properties;
for (j = 0, len1 = ref3.length; j < len1; j++) {
prop = ref3[j];
if (prop.assigns(name)) {
return true;
}
}
return false;
};
return Obj;
})(Base);
exports.Arr = Arr = (function(superClass1) {
extend1(Arr, superClass1);
function Arr(objs) {
this.objects = objs || [];
}
Arr.prototype.children = ['objects'];
Arr.prototype.compileNode = function(o) {
var answer, compiledObjs, fragments, index, j, len1, obj;
if (!this.objects.length) {
return [this.makeCode('[]')];
}
o.indent += TAB;
answer = Splat.compileSplattedArray(o, this.objects);
if (answer.length) {
return answer;
}
answer = [];
compiledObjs = (function() {
var j, len1, ref3, results;
ref3 = this.objects;
results = [];
for (j = 0, len1 = ref3.length; j < len1; j++) {
obj = ref3[j];
results.push(obj.compileToFragments(o, LEVEL_LIST));
}
return results;
}).call(this);
for (index = j = 0, len1 = compiledObjs.length; j < len1; index = ++j) {
fragments = compiledObjs[index];
if (index) {
answer.push(this.makeCode(", "));
}
answer.push.apply(answer, fragments);
}
if (fragmentsToText(answer).indexOf('\n') >= 0) {
answer.unshift(this.makeCode("[\n" + o.indent));
answer.push(this.makeCode("\n" + this.tab + "]"));
} else {
answer.unshift(this.makeCode("["));
answer.push(this.makeCode("]"));
}
return answer;
};
Arr.prototype.assigns = function(name) {
var j, len1, obj, ref3;
ref3 = this.objects;
for (j = 0, len1 = ref3.length; j < len1; j++) {
obj = ref3[j];
if (obj.assigns(name)) {
return true;
}
}
return false;
};
return Arr;
})(Base);
exports.Class = Class = (function(superClass1) {
extend1(Class, superClass1);
function Class(variable1, parent1, body1) {
this.variable = variable1;
this.parent = parent1;
this.body = body1 != null ? body1 : new Block;
this.boundFuncs = [];
this.body.classBody = true;
}
Class.prototype.children = ['variable', 'parent', 'body'];
Class.prototype.determineName = function() {
var decl, ref3, tail;
if (!this.variable) {
return null;
}
ref3 = this.variable.properties, tail = ref3[ref3.length - 1];
decl = tail ? tail instanceof Access && tail.name.value : this.variable.base.value;
if (indexOf.call(STRICT_PROSCRIBED, decl) >= 0) {
this.variable.error("class variable name may not be " + decl);
}
return decl && (decl = IDENTIFIER.test(decl) && decl);
};
Class.prototype.setContext = function(name) {
return this.body.traverseChildren(false, function(node) {
if (node.classBody) {
return false;
}
if (node instanceof Literal && node.value === 'this') {
return node.value = name;
} else if (node instanceof Code) {
if (node.bound) {
return node.context = name;
}
}
});
};
Class.prototype.addBoundFunctions = function(o) {
var bvar, j, len1, lhs, ref3;
ref3 = this.boundFuncs;
for (j = 0, len1 = ref3.length; j < len1; j++) {
bvar = ref3[j];
lhs = (new Value(new Literal("this"), [new Access(bvar)])).compile(o);
this.ctor.body.unshift(new Literal(lhs + " = " + (utility('bind', o)) + "(" + lhs + ", this)"));
}
};
Class.prototype.addProperties = function(node, name, o) {
var acc, assign, base, exprs, func, props;
props = node.base.properties.slice(0);
exprs = (function() {
var results;
results = [];
while (assign = props.shift()) {
if (assign instanceof Assign) {
base = assign.variable.base;
delete assign.context;
func = assign.value;
if (base.value === 'constructor') {
if (this.ctor) {
assign.error('cannot define more than one constructor in a class');
}
if (func.bound) {
assign.error('cannot define a constructor as a bound function');
}
if (func instanceof Code) {
assign = this.ctor = func;
} else {
this.externalCtor = o.classScope.freeVariable('class');
assign = new Assign(new Literal(this.externalCtor), func);
}
} else {
if (assign.variable["this"]) {
func["static"] = true;
} else {
acc = base.isComplex() ? new Index(base) : new Access(base);
assign.variable = new Value(new Literal(name), [new Access(new Literal('prototype')), acc]);
if (func instanceof Code && func.bound) {
this.boundFuncs.push(base);
func.bound = false;
}
}
}
}
results.push(assign);
}
return results;
}).call(this);
return compact(exprs);
};
Class.prototype.walkBody = function(name, o) {
return this.traverseChildren(false, (function(_this) {
return function(child) {
var cont, exps, i, j, len1, node, ref3;
cont = true;
if (child instanceof Class) {
return false;
}
if (child instanceof Block) {
ref3 = exps = child.expressions;
for (i = j = 0, len1 = ref3.length; j < len1; i = ++j) {
node = ref3[i];
if (node instanceof Assign && node.variable.looksStatic(name)) {
node.value["static"] = true;
} else if (node instanceof Value && node.isObject(true)) {
cont = false;
exps[i] = _this.addProperties(node, name, o);
}
}
child.expressions = exps = flatten(exps);
}
return cont && !(child instanceof Class);
};
})(this));
};
Class.prototype.hoistDirectivePrologue = function() {
var expressions, index, node;
index = 0;
expressions = this.body.expressions;
while ((node = expressions[index]) && node instanceof Comment || node instanceof Value && node.isString()) {
++index;
}
return this.directives = expressions.splice(0, index);
};
Class.prototype.ensureConstructor = function(name) {
if (!this.ctor) {
this.ctor = new Code;
if (this.externalCtor) {
this.ctor.body.push(new Literal(this.externalCtor + ".apply(this, arguments)"));
} else if (this.parent) {
this.ctor.body.push(new Literal(name + ".__super__.constructor.apply(this, arguments)"));
}
this.ctor.body.makeReturn();
this.body.expressions.unshift(this.ctor);
}
this.ctor.ctor = this.ctor.name = name;
this.ctor.klass = null;
return this.ctor.noReturn = true;
};
Class.prototype.compileNode = function(o) {
var args, argumentsNode, func, jumpNode, klass, lname, name, ref3, superClass;
if (jumpNode = this.body.jumps()) {
jumpNode.error('Class bodies cannot contain pure statements');
}
if (argumentsNode = this.body.contains(isLiteralArguments)) {
argumentsNode.error("Class bodies shouldn't reference arguments");
}
name = this.determineName() || '_Class';
if (name.reserved) {
name = "_" + name;
}
lname = new Literal(name);
func = new Code([], Block.wrap([this.body]));
args = [];
o.classScope = func.makeScope(o.scope);
this.hoistDirectivePrologue();
this.setContext(name);
this.walkBody(name, o);
this.ensureConstructor(name);
this.addBoundFunctions(o);
this.body.spaced = true;
this.body.expressions.push(lname);
if (this.parent) {
superClass = new Literal(o.classScope.freeVariable('superClass', {
reserve: false
}));
this.body.expressions.unshift(new Extends(lname, superClass));
func.params.push(new Param(superClass));
args.push(this.parent);
}
(ref3 = this.body.expressions).unshift.apply(ref3, this.directives);
klass = new Parens(new Call(func, args));
if (this.variable) {
klass = new Assign(this.variable, klass);
}
return klass.compileToFragments(o);
};
return Class;
})(Base);
exports.Assign = Assign = (function(superClass1) {
extend1(Assign, superClass1);
function Assign(variable1, value1, context, options) {
var forbidden, name, ref3;
this.variable = variable1;
this.value = value1;
this.context = context;
this.param = options && options.param;
this.subpattern = options && options.subpattern;
forbidden = (ref3 = (name = this.variable.unwrapAll().value), indexOf.call(STRICT_PROSCRIBED, ref3) >= 0);
if (forbidden && this.context !== 'object') {
this.variable.error("variable name may not be \"" + name + "\"");
}
}
Assign.prototype.children = ['variable', 'value'];
Assign.prototype.isStatement = function(o) {
return (o != null ? o.level : void 0) === LEVEL_TOP && (this.context != null) && indexOf.call(this.context, "?") >= 0;
};
Assign.prototype.assigns = function(name) {
return this[this.context === 'object' ? 'value' : 'variable'].assigns(name);
};
Assign.prototype.unfoldSoak = function(o) {
return unfoldSoak(o, this, 'variable');
};
Assign.prototype.compileNode = function(o) {
var answer, compiledName, isValue, j, name, properties, prototype, ref3, ref4, ref5, ref6, ref7, val, varBase;
if (isValue = this.variable instanceof Value) {
if (this.variable.isArray() || this.variable.isObject()) {
return this.compilePatternMatch(o);
}
if (this.variable.isSplice()) {
return this.compileSplice(o);
}
if ((ref3 = this.context) === '||=' || ref3 === '&&=' || ref3 === '?=') {
return this.compileConditional(o);
}
if ((ref4 = this.context) === '**=' || ref4 === '//=' || ref4 === '%%=') {
return this.compileSpecialMath(o);
}
}
if (this.value instanceof Code) {
if (this.value["static"]) {
this.value.klass = this.variable.base;
this.value.name = this.variable.properties[0];
this.value.variable = this.variable;
} else if (((ref5 = this.variable.properties) != null ? ref5.length : void 0) >= 2) {
ref6 = this.variable.properties, properties = 3 <= ref6.length ? slice.call(ref6, 0, j = ref6.length - 2) : (j = 0, []), prototype = ref6[j++], name = ref6[j++];
if (((ref7 = prototype.name) != null ? ref7.value : void 0) === 'prototype') {
this.value.klass = new Value(this.variable.base, properties);
this.value.name = name;
this.value.variable = this.variable;
}
}
}
if (!this.context) {
varBase = this.variable.unwrapAll();
if (!varBase.isAssignable()) {
this.variable.error("\"" + (this.variable.compile(o)) + "\" cannot be assigned");
}
if (!(typeof varBase.hasProperties === "function" ? varBase.hasProperties() : void 0)) {
if (this.param) {
o.scope.add(varBase.value, 'var');
} else {
o.scope.find(varBase.value);
}
}
}
val = this.value.compileToFragments(o, LEVEL_LIST);
compiledName = this.variable.compileToFragments(o, LEVEL_LIST);
if (this.context === 'object') {
return compiledName.concat(this.makeCode(": "), val);
}
answer = compiledName.concat(this.makeCode(" " + (this.context || '=') + " "), val);
if (o.level <= LEVEL_LIST) {
return answer;
} else {
return this.wrapInBraces(answer);
}
};
Assign.prototype.compilePatternMatch = function(o) {
var acc, assigns, code, expandedIdx, fragments, i, idx, isObject, ivar, j, len1, name, obj, objects, olen, ref, ref3, ref4, ref5, ref6, ref7, ref8, rest, top, val, value, vvar, vvarText;
top = o.level === LEVEL_TOP;
value = this.value;
objects = this.variable.base.objects;
if (!(olen = objects.length)) {
code = value.compileToFragments(o);
if (o.level >= LEVEL_OP) {
return this.wrapInBraces(code);
} else {
return code;
}
}
isObject = this.variable.isObject();
if (top && olen === 1 && !((obj = objects[0]) instanceof Splat)) {
if (obj instanceof Assign) {
ref3 = obj, (ref4 = ref3.variable, idx = ref4.base), obj = ref3.value;
} else {
idx = isObject ? obj["this"] ? obj.properties[0].name : obj : new Literal(0);
}
acc = IDENTIFIER.test(idx.unwrap().value || 0);
value = new Value(value);
value.properties.push(new (acc ? Access : Index)(idx));
if (ref5 = obj.unwrap().value, indexOf.call(RESERVED, ref5) >= 0) {
obj.error("assignment to a reserved word: " + (obj.compile(o)));
}
return new Assign(obj, value, null, {
param: this.param
}).compileToFragments(o, LEVEL_TOP);
}
vvar = value.compileToFragments(o, LEVEL_LIST);
vvarText = fragmentsToText(vvar);
assigns = [];
expandedIdx = false;
if (!IDENTIFIER.test(vvarText) || this.variable.assigns(vvarText)) {
assigns.push([this.makeCode((ref = o.scope.freeVariable('ref')) + " = ")].concat(slice.call(vvar)));
vvar = [this.makeCode(ref)];
vvarText = ref;
}
for (i = j = 0, len1 = objects.length; j < len1; i = ++j) {
obj = objects[i];
idx = i;
if (isObject) {
if (obj instanceof Assign) {
ref6 = obj, (ref7 = ref6.variable, idx = ref7.base), obj = ref6.value;
} else {
if (obj.base instanceof Parens) {
ref8 = new Value(obj.unwrapAll()).cacheReference(o), obj = ref8[0], idx = ref8[1];
} else {
idx = obj["this"] ? obj.properties[0].name : obj;
}
}
}
if (!expandedIdx && obj instanceof Splat) {
name = obj.name.unwrap().value;
obj = obj.unwrap();
val = olen + " <= " + vvarText + ".length ? " + (utility('slice', o)) + ".call(" + vvarText + ", " + i;
if (rest = olen - i - 1) {
ivar = o.scope.freeVariable('i', {
single: true
});
val += ", " + ivar + " = " + vvarText + ".length - " + rest + ") : (" + ivar + " = " + i + ", [])";
} else {
val += ") : []";
}
val = new Literal(val);
expandedIdx = ivar + "++";
} else if (!expandedIdx && obj instanceof Expansion) {
if (rest = olen - i - 1) {
if (rest === 1) {
expandedIdx = vvarText + ".length - 1";
} else {
ivar = o.scope.freeVariable('i', {
single: true
});
val = new Literal(ivar + " = " + vvarText + ".length - " + rest);
expandedIdx = ivar + "++";
assigns.push(val.compileToFragments(o, LEVEL_LIST));
}
}
continue;
} else {
name = obj.unwrap().value;
if (obj instanceof Splat || obj instanceof Expansion) {
obj.error("multiple splats/expansions are disallowed in an assignment");
}
if (typeof idx === 'number') {
idx = new Literal(expandedIdx || idx);
acc = false;
} else {
acc = isObject && IDENTIFIER.test(idx.unwrap().value || 0);
}
val = new Value(new Literal(vvarText), [new (acc ? Access : Index)(idx)]);
}
if ((name != null) && indexOf.call(RESERVED, name) >= 0) {
obj.error("assignment to a reserved word: " + (obj.compile(o)));
}
assigns.push(new Assign(obj, val, null, {
param: this.param,
subpattern: true
}).compileToFragments(o, LEVEL_LIST));
}
if (!(top || this.subpattern)) {
assigns.push(vvar);
}
fragments = this.joinFragmentArrays(assigns, ', ');
if (o.level < LEVEL_LIST) {
return fragments;
} else {
return this.wrapInBraces(fragments);
}
};
Assign.prototype.compileConditional = function(o) {
var fragments, left, ref3, right;
ref3 = this.variable.cacheReference(o), left = ref3[0], right = ref3[1];
if (!left.properties.length && left.base instanceof Literal && left.base.value !== "this" && !o.scope.check(left.base.value)) {
this.variable.error("the variable \"" + left.base.value + "\" can't be assigned with " + this.context + " because it has not been declared before");
}
if (indexOf.call(this.context, "?") >= 0) {
o.isExistentialEquals = true;
return new If(new Existence(left), right, {
type: 'if'
}).addElse(new Assign(right, this.value, '=')).compileToFragments(o);
} else {
fragments = new Op(this.context.slice(0, -1), left, new Assign(right, this.value, '=')).compileToFragments(o);
if (o.level <= LEVEL_LIST) {
return fragments;
} else {
return this.wrapInBraces(fragments);
}
}
};
Assign.prototype.compileSpecialMath = function(o) {
var left, ref3, right;
ref3 = this.variable.cacheReference(o), left = ref3[0], right = ref3[1];
return new Assign(left, new Op(this.context.slice(0, -1), right, this.value)).compileToFragments(o);
};
Assign.prototype.compileSplice = function(o) {
var answer, exclusive, from, fromDecl, fromRef, name, ref3, ref4, ref5, to, valDef, valRef;
ref3 = this.variable.properties.pop().range, from = ref3.from, to = ref3.to, exclusive = ref3.exclusive;
name = this.variable.compile(o);
if (from) {
ref4 = this.cacheToCodeFragments(from.cache(o, LEVEL_OP)), fromDecl = ref4[0], fromRef = ref4[1];
} else {
fromDecl = fromRef = '0';
}
if (to) {
if (from instanceof Value && from.isSimpleNumber() && to instanceof Value && to.isSimpleNumber()) {
to = to.compile(o) - fromRef;
if (!exclusive) {
to += 1;
}
} else {
to = to.compile(o, LEVEL_ACCESS) + ' - ' + fromRef;
if (!exclusive) {
to += ' + 1';
}
}
} else {
to = "9e9";
}
ref5 = this.value.cache(o, LEVEL_LIST), valDef = ref5[0], valRef = ref5[1];
answer = [].concat(this.makeCode("[].splice.apply(" + name + ", [" + fromDecl + ", " + to + "].concat("), valDef, this.makeCode(")), "), valRef);
if (o.level > LEVEL_TOP) {
return this.wrapInBraces(answer);
} else {
return answer;
}
};
return Assign;
})(Base);
exports.Code = Code = (function(superClass1) {
extend1(Code, superClass1);
function Code(params, body, tag) {
this.params = params || [];
this.body = body || new Block;
this.bound = tag === 'boundfunc';
this.isGenerator = !!this.body.contains(function(node) {
var ref3;
return node instanceof Op && ((ref3 = node.operator) === 'yield' || ref3 === 'yield*');
});
}
Code.prototype.children = ['params', 'body'];
Code.prototype.isStatement = function() {
return !!this.ctor;
};
Code.prototype.jumps = NO;
Code.prototype.makeScope = function(parentScope) {
return new Scope(parentScope, this.body, this);
};
Code.prototype.compileNode = function(o) {
var answer, boundfunc, code, exprs, i, j, k, l, len1, len2, len3, len4, len5, len6, lit, m, p, param, params, q, r, ref, ref3, ref4, ref5, ref6, ref7, ref8, splats, uniqs, val, wasEmpty, wrapper;
if (this.bound && ((ref3 = o.scope.method) != null ? ref3.bound : void 0)) {
this.context = o.scope.method.context;
}
if (this.bound && !this.context) {
this.context = '_this';
wrapper = new Code([new Param(new Literal(this.context))], new Block([this]));
boundfunc = new Call(wrapper, [new Literal('this')]);
boundfunc.updateLocationDataIfMissing(this.locationData);
return boundfunc.compileNode(o);
}
o.scope = del(o, 'classScope') || this.makeScope(o.scope);
o.scope.shared = del(o, 'sharedScope');
o.indent += TAB;
delete o.bare;
delete o.isExistentialEquals;
params = [];
exprs = [];
ref4 = this.params;
for (j = 0, len1 = ref4.length; j < len1; j++) {
param = ref4[j];
if (!(param instanceof Expansion)) {
o.scope.parameter(param.asReference(o));
}
}
ref5 = this.params;
for (k = 0, len2 = ref5.length; k < len2; k++) {
param = ref5[k];
if (!(param.splat || param instanceof Expansion)) {
continue;
}
ref6 = this.params;
for (l = 0, len3 = ref6.length; l < len3; l++) {
p = ref6[l];
if (!(p instanceof Expansion) && p.name.value) {
o.scope.add(p.name.value, 'var', true);
}
}
splats = new Assign(new Value(new Arr((function() {
var len4, m, ref7, results;
ref7 = this.params;
results = [];
for (m = 0, len4 = ref7.length; m < len4; m++) {
p = ref7[m];
results.push(p.asReference(o));
}
return results;
}).call(this))), new Value(new Literal('arguments')));
break;
}
ref7 = this.params;
for (m = 0, len4 = ref7.length; m < len4; m++) {
param = ref7[m];
if (param.isComplex()) {
val = ref = param.asReference(o);
if (param.value) {
val = new Op('?', ref, param.value);
}
exprs.push(new Assign(new Value(param.name), val, '=', {
param: true
}));
} else {
ref = param;
if (param.value) {
lit = new Literal(ref.name.value + ' == null');
val = new Assign(new Value(param.name), param.value, '=');
exprs.push(new If(lit, val));
}
}
if (!splats) {
params.push(ref);
}
}
wasEmpty = this.body.isEmpty();
if (splats) {
exprs.unshift(splats);
}
if (exprs.length) {
(ref8 = this.body.expressions).unshift.apply(ref8, exprs);
}
for (i = q = 0, len5 = params.length; q < len5; i = ++q) {
p = params[i];
params[i] = p.compileToFragments(o);
o.scope.parameter(fragmentsToText(params[i]));
}
uniqs = [];
this.eachParamName(function(name, node) {
if (indexOf.call(uniqs, name) >= 0) {
node.error("multiple parameters named " + name);
}
return uniqs.push(name);
});
if (!(wasEmpty || this.noReturn)) {
this.body.makeReturn();
}
code = 'function';
if (this.isGenerator) {
code += '*';
}
if (this.ctor) {
code += ' ' + this.name;
}
code += '(';
answer = [this.makeCode(code)];
for (i = r = 0, len6 = params.length; r < len6; i = ++r) {
p = params[i];
if (i) {
answer.push(this.makeCode(", "));
}
answer.push.apply(answer, p);
}
answer.push(this.makeCode(') {'));
if (!this.body.isEmpty()) {
answer = answer.concat(this.makeCode("\n"), this.body.compileWithDeclarations(o), this.makeCode("\n" + this.tab));
}
answer.push(this.makeCode('}'));
if (this.ctor) {
return [this.makeCode(this.tab)].concat(slice.call(answer));
}
if (this.front || (o.level >= LEVEL_ACCESS)) {
return this.wrapInBraces(answer);
} else {
return answer;
}
};
Code.prototype.eachParamName = function(iterator) {
var j, len1, param, ref3, results;
ref3 = this.params;
results = [];
for (j = 0, len1 = ref3.length; j < len1; j++) {
param = ref3[j];
results.push(param.eachName(iterator));
}
return results;
};
Code.prototype.traverseChildren = function(crossScope, func) {
if (crossScope) {
return Code.__super__.traverseChildren.call(this, crossScope, func);
}
};
return Code;
})(Base);
exports.Param = Param = (function(superClass1) {
extend1(Param, superClass1);
function Param(name1, value1, splat) {
var name, ref3;
this.name = name1;
this.value = value1;
this.splat = splat;
if (ref3 = (name = this.name.unwrapAll().value), indexOf.call(STRICT_PROSCRIBED, ref3) >= 0) {
this.name.error("parameter name \"" + name + "\" is not allowed");
}
}
Param.prototype.children = ['name', 'value'];
Param.prototype.compileToFragments = function(o) {
return this.name.compileToFragments(o, LEVEL_LIST);
};
Param.prototype.asReference = function(o) {
var name, node;
if (this.reference) {
return this.reference;
}
node = this.name;
if (node["this"]) {
name = node.properties[0].name.value;
if (name.reserved) {
name = "_" + name;
}
node = new Literal(o.scope.freeVariable(name));
} else if (node.isComplex()) {
node = new Literal(o.scope.freeVariable('arg'));
}
node = new Value(node);
if (this.splat) {
node = new Splat(node);
}
node.updateLocationDataIfMissing(this.locationData);
return this.reference = node;
};
Param.prototype.isComplex = function() {
return this.name.isComplex();
};
Param.prototype.eachName = function(iterator, name) {
var atParam, j, len1, node, obj, ref3;
if (name == null) {
name = this.name;
}
atParam = function(obj) {
return iterator("@" + obj.properties[0].name.value, obj);
};
if (name instanceof Literal) {
return iterator(name.value, name);
}
if (name instanceof Value) {
return atParam(name);
}
ref3 = name.objects;
for (j = 0, len1 = ref3.length; j < len1; j++) {
obj = ref3[j];
if (obj instanceof Assign) {
this.eachName(iterator, obj.value.unwrap());
} else if (obj instanceof Splat) {
node = obj.name.unwrap();
iterator(node.value, node);
} else if (obj instanceof Value) {
if (obj.isArray() || obj.isObject()) {
this.eachName(iterator, obj.base);
} else if (obj["this"]) {
atParam(obj);
} else {
iterator(obj.base.value, obj.base);
}
} else if (!(obj instanceof Expansion)) {
obj.error("illegal parameter " + (obj.compile()));
}
}
};
return Param;
})(Base);
exports.Splat = Splat = (function(superClass1) {
extend1(Splat, superClass1);
Splat.prototype.children = ['name'];
Splat.prototype.isAssignable = YES;
function Splat(name) {
this.name = name.compile ? name : new Literal(name);
}
Splat.prototype.assigns = function(name) {
return this.name.assigns(name);
};
Splat.prototype.compileToFragments = function(o) {
return this.name.compileToFragments(o);
};
Splat.prototype.unwrap = function() {
return this.name;
};
Splat.compileSplattedArray = function(o, list, apply) {
var args, base, compiledNode, concatPart, fragments, i, index, j, last, len1, node;
index = -1;
while ((node = list[++index]) && !(node instanceof Splat)) {
continue;
}
if (index >= list.length) {
return [];
}
if (list.length === 1) {
node = list[0];
fragments = node.compileToFragments(o, LEVEL_LIST);
if (apply) {
return fragments;
}
return [].concat(node.makeCode((utility('slice', o)) + ".call("), fragments, node.makeCode(")"));
}
args = list.slice(index);
for (i = j = 0, len1 = args.length; j < len1; i = ++j) {
node = args[i];
compiledNode = node.compileToFragments(o, LEVEL_LIST);
args[i] = node instanceof Splat ? [].concat(node.makeCode((utility('slice', o)) + ".call("), compiledNode, node.makeCode(")")) : [].concat(node.makeCode("["), compiledNode, node.makeCode("]"));
}
if (index === 0) {
node = list[0];
concatPart = node.joinFragmentArrays(args.slice(1), ', ');
return args[0].concat(node.makeCode(".concat("), concatPart, node.makeCode(")"));
}
base = (function() {
var k, len2, ref3, results;
ref3 = list.slice(0, index);
results = [];
for (k = 0, len2 = ref3.length; k < len2; k++) {
node = ref3[k];
results.push(node.compileToFragments(o, LEVEL_LIST));
}
return results;
})();
base = list[0].joinFragmentArrays(base, ', ');
concatPart = list[index].joinFragmentArrays(args, ', ');
last = list[list.length - 1];
return [].concat(list[0].makeCode("["), base, list[index].makeCode("].concat("), concatPart, last.makeCode(")"));
};
return Splat;
})(Base);
exports.Expansion = Expansion = (function(superClass1) {
extend1(Expansion, superClass1);
function Expansion() {
return Expansion.__super__.constructor.apply(this, arguments);
}
Expansion.prototype.isComplex = NO;
Expansion.prototype.compileNode = function(o) {
return this.error('Expansion must be used inside a destructuring assignment or parameter list');
};
Expansion.prototype.asReference = function(o) {
return this;
};
Expansion.prototype.eachName = function(iterator) {};
return Expansion;
})(Base);
exports.While = While = (function(superClass1) {
extend1(While, superClass1);
function While(condition, options) {
this.condition = (options != null ? options.invert : void 0) ? condition.invert() : condition;
this.guard = options != null ? options.guard : void 0;
}
While.prototype.children = ['condition', 'guard', 'body'];
While.prototype.isStatement = YES;
While.prototype.makeReturn = function(res) {
if (res) {
return While.__super__.makeReturn.apply(this, arguments);
} else {
this.returns = !this.jumps({
loop: true
});
return this;
}
};
While.prototype.addBody = function(body1) {
this.body = body1;
return this;
};
While.prototype.jumps = function() {
var expressions, j, jumpNode, len1, node;
expressions = this.body.expressions;
if (!expressions.length) {
return false;
}
for (j = 0, len1 = expressions.length; j < len1; j++) {
node = expressions[j];
if (jumpNode = node.jumps({
loop: true
})) {
return jumpNode;
}
}
return false;
};
While.prototype.compileNode = function(o) {
var answer, body, rvar, set;
o.indent += TAB;
set = '';
body = this.body;
if (body.isEmpty()) {
body = this.makeCode('');
} else {
if (this.returns) {
body.makeReturn(rvar = o.scope.freeVariable('results'));
set = "" + this.tab + rvar + " = [];\n";
}
if (this.guard) {
if (body.expressions.length > 1) {
body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue")));
} else {
if (this.guard) {
body = Block.wrap([new If(this.guard, body)]);
}
}
}
body = [].concat(this.makeCode("\n"), body.compileToFragments(o, LEVEL_TOP), this.makeCode("\n" + this.tab));
}
answer = [].concat(this.makeCode(set + this.tab + "while ("), this.condition.compileToFragments(o, LEVEL_PAREN), this.makeCode(") {"), body, this.makeCode("}"));
if (this.returns) {
answer.push(this.makeCode("\n" + this.tab + "return " + rvar + ";"));
}
return answer;
};
return While;
})(Base);
exports.Op = Op = (function(superClass1) {
var CONVERSIONS, INVERSIONS;
extend1(Op, superClass1);
function Op(op, first, second, flip) {
if (op === 'in') {
return new In(first, second);
}
if (op === 'do') {
return this.generateDo(first);
}
if (op === 'new') {
if (first instanceof Call && !first["do"] && !first.isNew) {
return first.newInstance();
}
if (first instanceof Code && first.bound || first["do"]) {
first = new Parens(first);
}
}
this.operator = CONVERSIONS[op] || op;
this.first = first;
this.second = second;
this.flip = !!flip;
return this;
}
CONVERSIONS = {
'==': '===',
'!=': '!==',
'of': 'in',
'yieldfrom': 'yield*'
};
INVERSIONS = {
'!==': '===',
'===': '!=='
};
Op.prototype.children = ['first', 'second'];
Op.prototype.isSimpleNumber = NO;
Op.prototype.isYield = function() {
var ref3;
return (ref3 = this.operator) === 'yield' || ref3 === 'yield*';
};
Op.prototype.isYieldReturn = function() {
return this.isYield() && this.first instanceof Return;
};
Op.prototype.isUnary = function() {
return !this.second;
};
Op.prototype.isComplex = function() {
var ref3;
return !(this.isUnary() && ((ref3 = this.operator) === '+' || ref3 === '-') && this.first instanceof Value && this.first.isSimpleNumber());
};
Op.prototype.isChainable = function() {
var ref3;
return (ref3 = this.operator) === '<' || ref3 === '>' || ref3 === '>=' || ref3 === '<=' || ref3 === '===' || ref3 === '!==';
};
Op.prototype.invert = function() {
var allInvertable, curr, fst, op, ref3;
if (this.isChainable() && this.first.isChainable()) {
allInvertable = true;
curr = this;
while (curr && curr.operator) {
allInvertable && (allInvertable = curr.operator in INVERSIONS);
curr = curr.first;
}
if (!allInvertable) {
return new Parens(this).invert();
}
curr = this;
while (curr && curr.operator) {
curr.invert = !curr.invert;
curr.operator = INVERSIONS[curr.operator];
curr = curr.first;
}
return this;
} else if (op = INVERSIONS[this.operator]) {
this.operator = op;
if (this.first.unwrap() instanceof Op) {
this.first.invert();
}
return this;
} else if (this.second) {
return new Parens(this).invert();
} else if (this.operator === '!' && (fst = this.first.unwrap()) instanceof Op && ((ref3 = fst.operator) === '!' || ref3 === 'in' || ref3 === 'instanceof')) {
return fst;
} else {
return new Op('!', this);
}
};
Op.prototype.unfoldSoak = function(o) {
var ref3;
return ((ref3 = this.operator) === '++' || ref3 === '--' || ref3 === 'delete') && unfoldSoak(o, this, 'first');
};
Op.prototype.generateDo = function(exp) {
var call, func, j, len1, param, passedParams, ref, ref3;
passedParams = [];
func = exp instanceof Assign && (ref = exp.value.unwrap()) instanceof Code ? ref : exp;
ref3 = func.params || [];
for (j = 0, len1 = ref3.length; j < len1; j++) {
param = ref3[j];
if (param.value) {
passedParams.push(param.value);
delete param.value;
} else {
passedParams.push(param);
}
}
call = new Call(exp, passedParams);
call["do"] = true;
return call;
};
Op.prototype.compileNode = function(o) {
var answer, isChain, lhs, ref3, ref4, rhs;
isChain = this.isChainable() && this.first.isChainable();
if (!isChain) {
this.first.front = this.front;
}
if (this.operator === 'delete' && o.scope.check(this.first.unwrapAll().value)) {
this.error('delete operand may not be argument or var');
}
if (((ref3 = this.operator) === '--' || ref3 === '++') && (ref4 = this.first.unwrapAll().value, indexOf.call(STRICT_PROSCRIBED, ref4) >= 0)) {
this.error("cannot increment/decrement \"" + (this.first.unwrapAll().value) + "\"");
}
if (this.isYield()) {
return this.compileYield(o);
}
if (this.isUnary()) {
return this.compileUnary(o);
}
if (isChain) {
return this.compileChain(o);
}
switch (this.operator) {
case '?':
return this.compileExistence(o);
case '**':
return this.compilePower(o);
case '//':
return this.compileFloorDivision(o);
case '%%':
return this.compileModulo(o);
default:
lhs = this.first.compileToFragments(o, LEVEL_OP);
rhs = this.second.compileToFragments(o, LEVEL_OP);
answer = [].concat(lhs, this.makeCode(" " + this.operator + " "), rhs);
if (o.level <= LEVEL_OP) {
return answer;
} else {
return this.wrapInBraces(answer);
}
}
};
Op.prototype.compileChain = function(o) {
var fragments, fst, ref3, shared;
ref3 = this.first.second.cache(o), this.first.second = ref3[0], shared = ref3[1];
fst = this.first.compileToFragments(o, LEVEL_OP);
fragments = fst.concat(this.makeCode(" " + (this.invert ? '&&' : '||') + " "), shared.compileToFragments(o), this.makeCode(" " + this.operator + " "), this.second.compileToFragments(o, LEVEL_OP));
return this.wrapInBraces(fragments);
};
Op.prototype.compileExistence = function(o) {
var fst, ref;
if (this.first.isComplex()) {
ref = new Literal(o.scope.freeVariable('ref'));
fst = new Parens(new Assign(ref, this.first));
} else {
fst = this.first;
ref = fst;
}
return new If(new Existence(fst), ref, {
type: 'if'
}).addElse(this.second).compileToFragments(o);
};
Op.prototype.compileUnary = function(o) {
var op, parts, plusMinus;
parts = [];
op = this.operator;
parts.push([this.makeCode(op)]);
if (op === '!' && this.first instanceof Existence) {
this.first.negated = !this.first.negated;
return this.first.compileToFragments(o);
}
if (o.level >= LEVEL_ACCESS) {
return (new Parens(this)).compileToFragments(o);
}
plusMinus = op === '+' || op === '-';
if ((op === 'new' || op === 'typeof' || op === 'delete') || plusMinus && this.first instanceof Op && this.first.operator === op) {
parts.push([this.makeCode(' ')]);
}
if ((plusMinus && this.first instanceof Op) || (op === 'new' && this.first.isStatement(o))) {
this.first = new Parens(this.first);
}
parts.push(this.first.compileToFragments(o, LEVEL_OP));
if (this.flip) {
parts.reverse();
}
return this.joinFragmentArrays(parts, '');
};
Op.prototype.compileYield = function(o) {
var op, parts;
parts = [];
op = this.operator;
if (o.scope.parent == null) {
this.error('yield statements must occur within a function generator.');
}
if (indexOf.call(Object.keys(this.first), 'expression') >= 0 && !(this.first instanceof Throw)) {
if (this.isYieldReturn()) {
parts.push(this.first.compileToFragments(o, LEVEL_TOP));
} else if (this.first.expression != null) {
parts.push(this.first.expression.compileToFragments(o, LEVEL_OP));
}
} else {
parts.push([this.makeCode("(" + op + " ")]);
parts.push(this.first.compileToFragments(o, LEVEL_OP));
parts.push([this.makeCode(")")]);
}
return this.joinFragmentArrays(parts, '');
};
Op.prototype.compilePower = function(o) {
var pow;
pow = new Value(new Literal('Math'), [new Access(new Literal('pow'))]);
return new Call(pow, [this.first, this.second]).compileToFragments(o);
};
Op.prototype.compileFloorDivision = function(o) {
var div, floor;
floor = new Value(new Literal('Math'), [new Access(new Literal('floor'))]);
div = new Op('/', this.first, this.second);
return new Call(floor, [div]).compileToFragments(o);
};
Op.prototype.compileModulo = function(o) {
var mod;
mod = new Value(new Literal(utility('modulo', o)));
return new Call(mod, [this.first, this.second]).compileToFragments(o);
};
Op.prototype.toString = function(idt) {
return Op.__super__.toString.call(this, idt, this.constructor.name + ' ' + this.operator);
};
return Op;
})(Base);
exports.In = In = (function(superClass1) {
extend1(In, superClass1);
function In(object, array) {
this.object = object;
this.array = array;
}
In.prototype.children = ['object', 'array'];
In.prototype.invert = NEGATE;
In.prototype.compileNode = function(o) {
var hasSplat, j, len1, obj, ref3;
if (this.array instanceof Value && this.array.isArray() && this.array.base.objects.length) {
ref3 = this.array.base.objects;
for (j = 0, len1 = ref3.length; j < len1; j++) {
obj = ref3[j];
if (!(obj instanceof Splat)) {
continue;
}
hasSplat = true;
break;
}
if (!hasSplat) {
return this.compileOrTest(o);
}
}
return this.compileLoopTest(o);
};
In.prototype.compileOrTest = function(o) {
var cmp, cnj, i, item, j, len1, ref, ref3, ref4, ref5, sub, tests;
ref3 = this.object.cache(o, LEVEL_OP), sub = ref3[0], ref = ref3[1];
ref4 = this.negated ? [' !== ', ' && '] : [' === ', ' || '], cmp = ref4[0], cnj = ref4[1];
tests = [];
ref5 = this.array.base.objects;
for (i = j = 0, len1 = ref5.length; j < len1; i = ++j) {
item = ref5[i];
if (i) {
tests.push(this.makeCode(cnj));
}
tests = tests.concat((i ? ref : sub), this.makeCode(cmp), item.compileToFragments(o, LEVEL_ACCESS));
}
if (o.level < LEVEL_OP) {
return tests;
} else {
return this.wrapInBraces(tests);
}
};
In.prototype.compileLoopTest = function(o) {
var fragments, ref, ref3, sub;
ref3 = this.object.cache(o, LEVEL_LIST), sub = ref3[0], ref = ref3[1];
fragments = [].concat(this.makeCode(utility('indexOf', o) + ".call("), this.array.compileToFragments(o, LEVEL_LIST), this.makeCode(", "), ref, this.makeCode(") " + (this.negated ? '< 0' : '>= 0')));
if (fragmentsToText(sub) === fragmentsToText(ref)) {
return fragments;
}
fragments = sub.concat(this.makeCode(', '), fragments);
if (o.level < LEVEL_LIST) {
return fragments;
} else {
return this.wrapInBraces(fragments);
}
};
In.prototype.toString = function(idt) {
return In.__super__.toString.call(this, idt, this.constructor.name + (this.negated ? '!' : ''));
};
return In;
})(Base);
exports.Try = Try = (function(superClass1) {
extend1(Try, superClass1);
function Try(attempt, errorVariable, recovery, ensure) {
this.attempt = attempt;
this.errorVariable = errorVariable;
this.recovery = recovery;
this.ensure = ensure;
}
Try.prototype.children = ['attempt', 'recovery', 'ensure'];
Try.prototype.isStatement = YES;
Try.prototype.jumps = function(o) {
var ref3;
return this.attempt.jumps(o) || ((ref3 = this.recovery) != null ? ref3.jumps(o) : void 0);
};
Try.prototype.makeReturn = function(res) {
if (this.attempt) {
this.attempt = this.attempt.makeReturn(res);
}
if (this.recovery) {
this.recovery = this.recovery.makeReturn(res);
}
return this;
};
Try.prototype.compileNode = function(o) {
var catchPart, ensurePart, placeholder, tryPart;
o.indent += TAB;
tryPart = this.attempt.compileToFragments(o, LEVEL_TOP);
catchPart = this.recovery ? (placeholder = new Literal('_error'), this.errorVariable ? this.recovery.unshift(new Assign(this.errorVariable, placeholder)) : void 0, [].concat(this.makeCode(" catch ("), placeholder.compileToFragments(o), this.makeCode(") {\n"), this.recovery.compileToFragments(o, LEVEL_TOP), this.makeCode("\n" + this.tab + "}"))) : !(this.ensure || this.recovery) ? [this.makeCode(' catch (_error) {}')] : [];
ensurePart = this.ensure ? [].concat(this.makeCode(" finally {\n"), this.ensure.compileToFragments(o, LEVEL_TOP), this.makeCode("\n" + this.tab + "}")) : [];
return [].concat(this.makeCode(this.tab + "try {\n"), tryPart, this.makeCode("\n" + this.tab + "}"), catchPart, ensurePart);
};
return Try;
})(Base);
exports.Throw = Throw = (function(superClass1) {
extend1(Throw, superClass1);
function Throw(expression) {
this.expression = expression;
}
Throw.prototype.children = ['expression'];
Throw.prototype.isStatement = YES;
Throw.prototype.jumps = NO;
Throw.prototype.makeReturn = THIS;
Throw.prototype.compileNode = function(o) {
return [].concat(this.makeCode(this.tab + "throw "), this.expression.compileToFragments(o), this.makeCode(";"));
};
return Throw;
})(Base);
exports.Existence = Existence = (function(superClass1) {
extend1(Existence, superClass1);
function Existence(expression) {
this.expression = expression;
}
Existence.prototype.children = ['expression'];
Existence.prototype.invert = NEGATE;
Existence.prototype.compileNode = function(o) {
var cmp, cnj, code, ref3;
this.expression.front = this.front;
code = this.expression.compile(o, LEVEL_OP);
if (IDENTIFIER.test(code) && !o.scope.check(code)) {
ref3 = this.negated ? ['===', '||'] : ['!==', '&&'], cmp = ref3[0], cnj = ref3[1];
code = "typeof " + code + " " + cmp + " \"undefined\" " + cnj + " " + code + " " + cmp + " null";
} else {
code = code + " " + (this.negated ? '==' : '!=') + " null";
}
return [this.makeCode(o.level <= LEVEL_COND ? code : "(" + code + ")")];
};
return Existence;
})(Base);
exports.Parens = Parens = (function(superClass1) {
extend1(Parens, superClass1);
function Parens(body1) {
this.body = body1;
}
Parens.prototype.children = ['body'];
Parens.prototype.unwrap = function() {
return this.body;
};
Parens.prototype.isComplex = function() {
return this.body.isComplex();
};
Parens.prototype.compileNode = function(o) {
var bare, expr, fragments;
expr = this.body.unwrap();
if (expr instanceof Value && expr.isAtomic()) {
expr.front = this.front;
return expr.compileToFragments(o);
}
fragments = expr.compileToFragments(o, LEVEL_PAREN);
bare = o.level < LEVEL_OP && (expr instanceof Op || expr instanceof Call || (expr instanceof For && expr.returns));
if (bare) {
return fragments;
} else {
return this.wrapInBraces(fragments);
}
};
return Parens;
})(Base);
exports.For = For = (function(superClass1) {
extend1(For, superClass1);
function For(body, source) {
var ref3;
this.source = source.source, this.guard = source.guard, this.step = source.step, this.name = source.name, this.index = source.index;
this.body = Block.wrap([body]);
this.own = !!source.own;
this.object = !!source.object;
if (this.object) {
ref3 = [this.index, this.name], this.name = ref3[0], this.index = ref3[1];
}
if (this.index instanceof Value) {
this.index.error('index cannot be a pattern matching expression');
}
this.range = this.source instanceof Value && this.source.base instanceof Range && !this.source.properties.length;
this.pattern = this.name instanceof Value;
if (this.range && this.index) {
this.index.error('indexes do not apply to range loops');
}
if (this.range && this.pattern) {
this.name.error('cannot pattern match over range loops');
}
if (this.own && !this.object) {
this.name.error('cannot use own with for-in');
}
this.returns = false;
}
For.prototype.children = ['body', 'source', 'guard', 'step'];
For.prototype.compileNode = function(o) {
var body, bodyFragments, compare, compareDown, declare, declareDown, defPart, defPartFragments, down, forPartFragments, guardPart, idt1, increment, index, ivar, kvar, kvarAssign, last, lvar, name, namePart, ref, ref3, ref4, resultPart, returnResult, rvar, scope, source, step, stepNum, stepVar, svar, varPart;
body = Block.wrap([this.body]);
ref3 = body.expressions, last = ref3[ref3.length - 1];
if ((last != null ? last.jumps() : void 0) instanceof Return) {
this.returns = false;
}
source = this.range ? this.source.base : this.source;
scope = o.scope;
if (!this.pattern) {
name = this.name && (this.name.compile(o, LEVEL_LIST));
}
index = this.index && (this.index.compile(o, LEVEL_LIST));
if (name && !this.pattern) {
scope.find(name);
}
if (index) {
scope.find(index);
}
if (this.returns) {
rvar = scope.freeVariable('results');
}
ivar = (this.object && index) || scope.freeVariable('i', {
single: true
});
kvar = (this.range && name) || index || ivar;
kvarAssign = kvar !== ivar ? kvar + " = " : "";
if (this.step && !this.range) {
ref4 = this.cacheToCodeFragments(this.step.cache(o, LEVEL_LIST, isComplexOrAssignable)), step = ref4[0], stepVar = ref4[1];
stepNum = stepVar.match(NUMBER);
}
if (this.pattern) {
name = ivar;
}
varPart = '';
guardPart = '';
defPart = '';
idt1 = this.tab + TAB;
if (this.range) {
forPartFragments = source.compileToFragments(merge(o, {
index: ivar,
name: name,
step: this.step,
isComplex: isComplexOrAssignable
}));
} else {
svar = this.source.compile(o, LEVEL_LIST);
if ((name || this.own) && !IDENTIFIER.test(svar)) {
defPart += "" + this.tab + (ref = scope.freeVariable('ref')) + " = " + svar + ";\n";
svar = ref;
}
if (name && !this.pattern) {
namePart = name + " = " + svar + "[" + kvar + "]";
}
if (!this.object) {
if (step !== stepVar) {
defPart += "" + this.tab + step + ";\n";
}
if (!(this.step && stepNum && (down = parseNum(stepNum[0]) < 0))) {
lvar = scope.freeVariable('len');
}
declare = "" + kvarAssign + ivar + " = 0, " + lvar + " = " + svar + ".length";
declareDown = "" + kvarAssign + ivar + " = " + svar + ".length - 1";
compare = ivar + " < " + lvar;
compareDown = ivar + " >= 0";
if (this.step) {
if (stepNum) {
if (down) {
compare = compareDown;
declare = declareDown;
}
} else {
compare = stepVar + " > 0 ? " + compare + " : " + compareDown;
declare = "(" + stepVar + " > 0 ? (" + declare + ") : " + declareDown + ")";
}
increment = ivar + " += " + stepVar;
} else {
increment = "" + (kvar !== ivar ? "++" + ivar : ivar + "++");
}
forPartFragments = [this.makeCode(declare + "; " + compare + "; " + kvarAssign + increment)];
}
}
if (this.returns) {
resultPart = "" + this.tab + rvar + " = [];\n";
returnResult = "\n" + this.tab + "return " + rvar + ";";
body.makeReturn(rvar);
}
if (this.guard) {
if (body.expressions.length > 1) {
body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue")));
} else {
if (this.guard) {
body = Block.wrap([new If(this.guard, body)]);
}
}
}
if (this.pattern) {
body.expressions.unshift(new Assign(this.name, new Literal(svar + "[" + kvar + "]")));
}
defPartFragments = [].concat(this.makeCode(defPart), this.pluckDirectCall(o, body));
if (namePart) {
varPart = "\n" + idt1 + namePart + ";";
}
if (this.object) {
forPartFragments = [this.makeCode(kvar + " in " + svar)];
if (this.own) {
guardPart = "\n" + idt1 + "if (!" + (utility('hasProp', o)) + ".call(" + svar + ", " + kvar + ")) continue;";
}
}
bodyFragments = body.compileToFragments(merge(o, {
indent: idt1
}), LEVEL_TOP);
if (bodyFragments && (bodyFragments.length > 0)) {
bodyFragments = [].concat(this.makeCode("\n"), bodyFragments, this.makeCode("\n"));
}
return [].concat(defPartFragments, this.makeCode("" + (resultPart || '') + this.tab + "for ("), forPartFragments, this.makeCode(") {" + guardPart + varPart), bodyFragments, this.makeCode(this.tab + "}" + (returnResult || '')));
};
For.prototype.pluckDirectCall = function(o, body) {
var base, defs, expr, fn, idx, j, len1, ref, ref3, ref4, ref5, ref6, ref7, ref8, ref9, val;
defs = [];
ref3 = body.expressions;
for (idx = j = 0, len1 = ref3.length; j < len1; idx = ++j) {
expr = ref3[idx];
expr = expr.unwrapAll();
if (!(expr instanceof Call)) {
continue;
}
val = (ref4 = expr.variable) != null ? ref4.unwrapAll() : void 0;
if (!((val instanceof Code) || (val instanceof Value && ((ref5 = val.base) != null ? ref5.unwrapAll() : void 0) instanceof Code && val.properties.length === 1 && ((ref6 = (ref7 = val.properties[0].name) != null ? ref7.value : void 0) === 'call' || ref6 === 'apply')))) {
continue;
}
fn = ((ref8 = val.base) != null ? ref8.unwrapAll() : void 0) || val;
ref = new Literal(o.scope.freeVariable('fn'));
base = new Value(ref);
if (val.base) {
ref9 = [base, val], val.base = ref9[0], base = ref9[1];
}
body.expressions[idx] = new Call(base, expr.args);
defs = defs.concat(this.makeCode(this.tab), new Assign(ref, fn).compileToFragments(o, LEVEL_TOP), this.makeCode(';\n'));
}
return defs;
};
return For;
})(While);
exports.Switch = Switch = (function(superClass1) {
extend1(Switch, superClass1);
function Switch(subject, cases, otherwise) {
this.subject = subject;
this.cases = cases;
this.otherwise = otherwise;
}
Switch.prototype.children = ['subject', 'cases', 'otherwise'];
Switch.prototype.isStatement = YES;
Switch.prototype.jumps = function(o) {
var block, conds, j, jumpNode, len1, ref3, ref4, ref5;
if (o == null) {
o = {
block: true
};
}
ref3 = this.cases;
for (j = 0, len1 = ref3.length; j < len1; j++) {
ref4 = ref3[j], conds = ref4[0], block = ref4[1];
if (jumpNode = block.jumps(o)) {
return jumpNode;
}
}
return (ref5 = this.otherwise) != null ? ref5.jumps(o) : void 0;
};
Switch.prototype.makeReturn = function(res) {
var j, len1, pair, ref3, ref4;
ref3 = this.cases;
for (j = 0, len1 = ref3.length; j < len1; j++) {
pair = ref3[j];
pair[1].makeReturn(res);
}
if (res) {
this.otherwise || (this.otherwise = new Block([new Literal('void 0')]));
}
if ((ref4 = this.otherwise) != null) {
ref4.makeReturn(res);
}
return this;
};
Switch.prototype.compileNode = function(o) {
var block, body, cond, conditions, expr, fragments, i, idt1, idt2, j, k, len1, len2, ref3, ref4, ref5;
idt1 = o.indent + TAB;
idt2 = o.indent = idt1 + TAB;
fragments = [].concat(this.makeCode(this.tab + "switch ("), (this.subject ? this.subject.compileToFragments(o, LEVEL_PAREN) : this.makeCode("false")), this.makeCode(") {\n"));
ref3 = this.cases;
for (i = j = 0, len1 = ref3.length; j < len1; i = ++j) {
ref4 = ref3[i], conditions = ref4[0], block = ref4[1];
ref5 = flatten([conditions]);
for (k = 0, len2 = ref5.length; k < len2; k++) {
cond = ref5[k];
if (!this.subject) {
cond = cond.invert();
}
fragments = fragments.concat(this.makeCode(idt1 + "case "), cond.compileToFragments(o, LEVEL_PAREN), this.makeCode(":\n"));
}
if ((body = block.compileToFragments(o, LEVEL_TOP)).length > 0) {
fragments = fragments.concat(body, this.makeCode('\n'));
}
if (i === this.cases.length - 1 && !this.otherwise) {
break;
}
expr = this.lastNonComment(block.expressions);
if (expr instanceof Return || (expr instanceof Literal && expr.jumps() && expr.value !== 'debugger')) {
continue;
}
fragments.push(cond.makeCode(idt2 + 'break;\n'));
}
if (this.otherwise && this.otherwise.expressions.length) {
fragments.push.apply(fragments, [this.makeCode(idt1 + "default:\n")].concat(slice.call(this.otherwise.compileToFragments(o, LEVEL_TOP)), [this.makeCode("\n")]));
}
fragments.push(this.makeCode(this.tab + '}'));
return fragments;
};
return Switch;
})(Base);
exports.If = If = (function(superClass1) {
extend1(If, superClass1);
function If(condition, body1, options) {
this.body = body1;
if (options == null) {
options = {};
}
this.condition = options.type === 'unless' ? condition.invert() : condition;
this.elseBody = null;
this.isChain = false;
this.soak = options.soak;
}
If.prototype.children = ['condition', 'body', 'elseBody'];
If.prototype.bodyNode = function() {
var ref3;
return (ref3 = this.body) != null ? ref3.unwrap() : void 0;
};
If.prototype.elseBodyNode = function() {
var ref3;
return (ref3 = this.elseBody) != null ? ref3.unwrap() : void 0;
};
If.prototype.addElse = function(elseBody) {
if (this.isChain) {
this.elseBodyNode().addElse(elseBody);
} else {
this.isChain = elseBody instanceof If;
this.elseBody = this.ensureBlock(elseBody);
this.elseBody.updateLocationDataIfMissing(elseBody.locationData);
}
return this;
};
If.prototype.isStatement = function(o) {
var ref3;
return (o != null ? o.level : void 0) === LEVEL_TOP || this.bodyNode().isStatement(o) || ((ref3 = this.elseBodyNode()) != null ? ref3.isStatement(o) : void 0);
};
If.prototype.jumps = function(o) {
var ref3;
return this.body.jumps(o) || ((ref3 = this.elseBody) != null ? ref3.jumps(o) : void 0);
};
If.prototype.compileNode = function(o) {
if (this.isStatement(o)) {
return this.compileStatement(o);
} else {
return this.compileExpression(o);
}
};
If.prototype.makeReturn = function(res) {
if (res) {
this.elseBody || (this.elseBody = new Block([new Literal('void 0')]));
}
this.body && (this.body = new Block([this.body.makeReturn(res)]));
this.elseBody && (this.elseBody = new Block([this.elseBody.makeReturn(res)]));
return this;
};
If.prototype.ensureBlock = function(node) {
if (node instanceof Block) {
return node;
} else {
return new Block([node]);
}
};
If.prototype.compileStatement = function(o) {
var answer, body, child, cond, exeq, ifPart, indent;
child = del(o, 'chainChild');
exeq = del(o, 'isExistentialEquals');
if (exeq) {
return new If(this.condition.invert(), this.elseBodyNode(), {
type: 'if'
}).compileToFragments(o);
}
indent = o.indent + TAB;
cond = this.condition.compileToFragments(o, LEVEL_PAREN);
body = this.ensureBlock(this.body).compileToFragments(merge(o, {
indent: indent
}));
ifPart = [].concat(this.makeCode("if ("), cond, this.makeCode(") {\n"), body, this.makeCode("\n" + this.tab + "}"));
if (!child) {
ifPart.unshift(this.makeCode(this.tab));
}
if (!this.elseBody) {
return ifPart;
}
answer = ifPart.concat(this.makeCode(' else '));
if (this.isChain) {
o.chainChild = true;
answer = answer.concat(this.elseBody.unwrap().compileToFragments(o, LEVEL_TOP));
} else {
answer = answer.concat(this.makeCode("{\n"), this.elseBody.compileToFragments(merge(o, {
indent: indent
}), LEVEL_TOP), this.makeCode("\n" + this.tab + "}"));
}
return answer;
};
If.prototype.compileExpression = function(o) {
var alt, body, cond, fragments;
cond = this.condition.compileToFragments(o, LEVEL_COND);
body = this.bodyNode().compileToFragments(o, LEVEL_LIST);
alt = this.elseBodyNode() ? this.elseBodyNode().compileToFragments(o, LEVEL_LIST) : [this.makeCode('void 0')];
fragments = cond.concat(this.makeCode(" ? "), body, this.makeCode(" : "), alt);
if (o.level >= LEVEL_COND) {
return this.wrapInBraces(fragments);
} else {
return fragments;
}
};
If.prototype.unfoldSoak = function() {
return this.soak && this;
};
return If;
})(Base);
UTILITIES = {
extend: function(o) {
return "function(child, parent) { for (var key in parent) { if (" + (utility('hasProp', o)) + ".call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }";
},
bind: function() {
return 'function(fn, me){ return function(){ return fn.apply(me, arguments); }; }';
},
indexOf: function() {
return "[].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }";
},
modulo: function() {
return "function(a, b) { return (+a % (b = +b) + b) % b; }";
},
hasProp: function() {
return '{}.hasOwnProperty';
},
slice: function() {
return '[].slice';
}
};
LEVEL_TOP = 1;
LEVEL_PAREN = 2;
LEVEL_LIST = 3;
LEVEL_COND = 4;
LEVEL_OP = 5;
LEVEL_ACCESS = 6;
TAB = ' ';
IDENTIFIER = /^(?!\d)[$\w\x7f-\uffff]+$/;
SIMPLENUM = /^[+-]?\d+$/;
HEXNUM = /^[+-]?0x[\da-f]+/i;
NUMBER = /^[+-]?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)$/i;
IS_STRING = /^['"]/;
IS_REGEX = /^\//;
utility = function(name, o) {
var ref, root;
root = o.scope.root;
if (name in root.utilities) {
return root.utilities[name];
} else {
ref = root.freeVariable(name);
root.assign(ref, UTILITIES[name](o));
return root.utilities[name] = ref;
}
};
multident = function(code, tab) {
code = code.replace(/\n/g, '$&' + tab);
return code.replace(/\s+$/, '');
};
parseNum = function(x) {
if (x == null) {
return 0;
} else if (x.match(HEXNUM)) {
return parseInt(x, 16);
} else {
return parseFloat(x);
}
};
isLiteralArguments = function(node) {
return node instanceof Literal && node.value === 'arguments' && !node.asKey;
};
isLiteralThis = function(node) {
return (node instanceof Literal && node.value === 'this' && !node.asKey) || (node instanceof Code && node.bound) || (node instanceof Call && node.isSuper);
};
isComplexOrAssignable = function(node) {
return node.isComplex() || (typeof node.isAssignable === "function" ? node.isAssignable() : void 0);
};
unfoldSoak = function(o, parent, name) {
var ifn;
if (!(ifn = parent[name].unfoldSoak(o))) {
return;
}
parent[name] = ifn.body;
ifn.body = new Value(parent);
return ifn;
};
}).call(this);
},{"./helpers":6,"./lexer":7,"./scope":12}],9:[function(require,module,exports){
(function (process){
/* parser generated by jison 0.4.15 */
/*
Returns a Parser object of the following structure:
Parser: {
yy: {}
}
Parser.prototype: {
yy: {},
trace: function(),
symbols_: {associative list: name ==> number},
terminals_: {associative list: number ==> name},
productions_: [...],
performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$),
table: [...],
defaultActions: {...},
parseError: function(str, hash),
parse: function(input),
lexer: {
EOF: 1,
parseError: function(str, hash),
setInput: function(input),
input: function(),
unput: function(str),
more: function(),
less: function(n),
pastInput: function(),
upcomingInput: function(),
showPosition: function(),
test_match: function(regex_match_array, rule_index),
next: function(),
lex: function(),
begin: function(condition),
popState: function(),
_currentRules: function(),
topState: function(),
pushState: function(condition),
options: {
ranges: boolean (optional: true ==> token location info will include a .range[] member)
flex: boolean (optional: true ==> flex-like lexing behaviour where the rules are tested exhaustively to find the longest match)
backtrack_lexer: boolean (optional: true ==> lexer regexes are tested in order and for each matching regex the action code is invoked; the lexer terminates the scan when a token is returned by the action code)
},
performAction: function(yy, yy_, $avoiding_name_collisions, YY_START),
rules: [...],
conditions: {associative list: name ==> set},
}
}
token location info (@$, _$, etc.): {
first_line: n,
last_line: n,
first_column: n,
last_column: n,
range: [start_number, end_number] (where the numbers are indexes into the input string, regular zero-based)
}
the parseError function receives a 'hash' object with these members for lexer and parser errors: {
text: (matched text)
token: (the produced terminal token, if any)
line: (yylineno)
}
while parser (grammar) errors will also provide these members, i.e. parser errors deliver a superset of attributes: {
loc: (yylloc)
expected: (string describing the set of expected tokens)
recoverable: (boolean: TRUE when the parser has a error recovery rule available for this particular error)
}
*/
var parser = (function(){
var o=function(k,v,o,l){for(o=o||{},l=k.length;l--;o[k[l]]=v);return o},$V0=[1,20],$V1=[1,75],$V2=[1,71],$V3=[1,76],$V4=[1,77],$V5=[1,73],$V6=[1,74],$V7=[1,50],$V8=[1,52],$V9=[1,53],$Va=[1,54],$Vb=[1,55],$Vc=[1,45],$Vd=[1,46],$Ve=[1,27],$Vf=[1,60],$Vg=[1,61],$Vh=[1,70],$Vi=[1,43],$Vj=[1,26],$Vk=[1,58],$Vl=[1,59],$Vm=[1,57],$Vn=[1,38],$Vo=[1,44],$Vp=[1,56],$Vq=[1,65],$Vr=[1,66],$Vs=[1,67],$Vt=[1,68],$Vu=[1,42],$Vv=[1,64],$Vw=[1,29],$Vx=[1,30],$Vy=[1,31],$Vz=[1,32],$VA=[1,33],$VB=[1,34],$VC=[1,35],$VD=[1,78],$VE=[1,6,26,34,108],$VF=[1,88],$VG=[1,81],$VH=[1,80],$VI=[1,79],$VJ=[1,82],$VK=[1,83],$VL=[1,84],$VM=[1,85],$VN=[1,86],$VO=[1,87],$VP=[1,91],$VQ=[1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,117,132,135,136,141,142,143,144,145,146,147],$VR=[1,97],$VS=[1,98],$VT=[1,99],$VU=[1,100],$VV=[1,102],$VW=[1,103],$VX=[1,96],$VY=[2,112],$VZ=[1,6,25,26,34,55,60,63,72,73,74,75,77,79,80,84,90,91,92,97,99,108,110,111,112,116,117,132,135,136,141,142,143,144,145,146,147],$V_=[2,79],$V$=[1,108],$V01=[2,58],$V11=[1,112],$V21=[1,117],$V31=[1,118],$V41=[1,120],$V51=[1,6,25,26,34,46,55,60,63,72,73,74,75,77,79,80,84,90,91,92,97,99,108,110,111,112,116,117,132,135,136,141,142,143,144,145,146,147],$V61=[2,76],$V71=[1,6,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,117,132,135,136,141,142,143,144,145,146,147],$V81=[1,155],$V91=[1,157],$Va1=[1,152],$Vb1=[1,6,25,26,34,46,55,60,63,72,73,74,75,77,79,80,84,86,90,91,92,97,99,108,110,111,112,116,117,132,135,136,139,140,141,142,143,144,145,146,147,148],$Vc1=[2,95],$Vd1=[1,6,25,26,34,49,55,60,63,72,73,74,75,77,79,80,84,90,91,92,97,99,108,110,111,112,116,117,132,135,136,141,142,143,144,145,146,147],$Ve1=[1,6,25,26,34,46,49,55,60,63,72,73,74,75,77,79,80,84,86,90,91,92,97,99,108,110,111,112,116,117,123,124,132,135,136,139,140,141,142,143,144,145,146,147,148],$Vf1=[1,206],$Vg1=[1,205],$Vh1=[1,6,25,26,34,38,55,60,63,72,73,74,75,77,79,80,84,90,91,92,97,99,108,110,111,112,116,117,132,135,136,141,142,143,144,145,146,147],$Vi1=[2,56],$Vj1=[1,216],$Vk1=[6,25,26,55,60],$Vl1=[6,25,26,46,55,60,63],$Vm1=[1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,117,132,135,136,142,144,145,146,147],$Vn1=[1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,117,132],$Vo1=[72,73,74,75,77,80,90,91],$Vp1=[1,235],$Vq1=[2,133],$Vr1=[1,6,25,26,34,46,55,60,63,72,73,74,75,77,79,80,84,90,91,92,97,99,108,110,111,112,116,117,123,124,132,135,136,141,142,143,144,145,146,147],$Vs1=[1,244],$Vt1=[6,25,26,60,92,97],$Vu1=[1,6,25,26,34,55,60,63,79,84,92,97,99,108,117,132],$Vv1=[1,6,25,26,34,55,60,63,79,84,92,97,99,108,111,117,132],$Vw1=[123,124],$Vx1=[60,123,124],$Vy1=[1,255],$Vz1=[6,25,26,60,84],$VA1=[6,25,26,49,60,84],$VB1=[1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,117,132,135,136,144,145,146,147],$VC1=[11,28,30,32,33,36,37,40,41,42,43,44,51,52,53,57,58,79,82,85,89,94,95,96,102,106,107,110,112,114,116,125,131,133,134,135,136,137,139,140],$VD1=[2,122],$VE1=[6,25,26],$VF1=[2,57],$VG1=[1,268],$VH1=[1,269],$VI1=[1,6,25,26,34,55,60,63,79,84,92,97,99,104,105,108,110,111,112,116,117,127,129,132,135,136,141,142,143,144,145,146,147],$VJ1=[26,127,129],$VK1=[1,6,26,34,55,60,63,79,84,92,97,99,108,111,117,132],$VL1=[2,71],$VM1=[1,291],$VN1=[1,292],$VO1=[1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,111,112,116,117,127,132,135,136,141,142,143,144,145,146,147],$VP1=[1,6,25,26,34,55,60,63,79,84,92,97,99,108,110,112,116,117,132],$VQ1=[1,303],$VR1=[1,304],$VS1=[6,25,26,60],$VT1=[1,6,25,26,34,55,60,63,79,84,92,97,99,104,108,110,111,112,116,117,132,135,136,141,142,143,144,145,146,147],$VU1=[25,60];
var parser = {trace: function trace() { },
yy: {},
symbols_: {"error":2,"Root":3,"Body":4,"Line":5,"TERMINATOR":6,"Expression":7,"Statement":8,"Return":9,"Comment":10,"STATEMENT":11,"Value":12,"Invocation":13,"Code":14,"Operation":15,"Assign":16,"If":17,"Try":18,"While":19,"For":20,"Switch":21,"Class":22,"Throw":23,"Block":24,"INDENT":25,"OUTDENT":26,"Identifier":27,"IDENTIFIER":28,"AlphaNumeric":29,"NUMBER":30,"String":31,"STRING":32,"STRING_START":33,"STRING_END":34,"Regex":35,"REGEX":36,"REGEX_START":37,"REGEX_END":38,"Literal":39,"JS":40,"DEBUGGER":41,"UNDEFINED":42,"NULL":43,"BOOL":44,"Assignable":45,"=":46,"AssignObj":47,"ObjAssignable":48,":":49,"ThisProperty":50,"RETURN":51,"HERECOMMENT":52,"PARAM_START":53,"ParamList":54,"PARAM_END":55,"FuncGlyph":56,"->":57,"=>":58,"OptComma":59,",":60,"Param":61,"ParamVar":62,"...":63,"Array":64,"Object":65,"Splat":66,"SimpleAssignable":67,"Accessor":68,"Parenthetical":69,"Range":70,"This":71,".":72,"?.":73,"::":74,"?::":75,"Index":76,"INDEX_START":77,"IndexValue":78,"INDEX_END":79,"INDEX_SOAK":80,"Slice":81,"{":82,"AssignList":83,"}":84,"CLASS":85,"EXTENDS":86,"OptFuncExist":87,"Arguments":88,"SUPER":89,"FUNC_EXIST":90,"CALL_START":91,"CALL_END":92,"ArgList":93,"THIS":94,"@":95,"[":96,"]":97,"RangeDots":98,"..":99,"Arg":100,"SimpleArgs":101,"TRY":102,"Catch":103,"FINALLY":104,"CATCH":105,"THROW":106,"(":107,")":108,"WhileSource":109,"WHILE":110,"WHEN":111,"UNTIL":112,"Loop":113,"LOOP":114,"ForBody":115,"FOR":116,"BY":117,"ForStart":118,"ForSource":119,"ForVariables":120,"OWN":121,"ForValue":122,"FORIN":123,"FOROF":124,"SWITCH":125,"Whens":126,"ELSE":127,"When":128,"LEADING_WHEN":129,"IfBlock":130,"IF":131,"POST_IF":132,"UNARY":133,"UNARY_MATH":134,"-":135,"+":136,"YIELD":137,"FROM":138,"--":139,"++":140,"?":141,"MATH":142,"**":143,"SHIFT":144,"COMPARE":145,"LOGIC":146,"RELATION":147,"COMPOUND_ASSIGN":148,"$accept":0,"$end":1},
terminals_: {2:"error",6:"TERMINATOR",11:"STATEMENT",25:"INDENT",26:"OUTDENT",28:"IDENTIFIER",30:"NUMBER",32:"STRING",33:"STRING_START",34:"STRING_END",36:"REGEX",37:"REGEX_START",38:"REGEX_END",40:"JS",41:"DEBUGGER",42:"UNDEFINED",43:"NULL",44:"BOOL",46:"=",49:":",51:"RETURN",52:"HERECOMMENT",53:"PARAM_START",55:"PARAM_END",57:"->",58:"=>",60:",",63:"...",72:".",73:"?.",74:"::",75:"?::",77:"INDEX_START",79:"INDEX_END",80:"INDEX_SOAK",82:"{",84:"}",85:"CLASS",86:"EXTENDS",89:"SUPER",90:"FUNC_EXIST",91:"CALL_START",92:"CALL_END",94:"THIS",95:"@",96:"[",97:"]",99:"..",102:"TRY",104:"FINALLY",105:"CATCH",106:"THROW",107:"(",108:")",110:"WHILE",111:"WHEN",112:"UNTIL",114:"LOOP",116:"FOR",117:"BY",121:"OWN",123:"FORIN",124:"FOROF",125:"SWITCH",127:"ELSE",129:"LEADING_WHEN",131:"IF",132:"POST_IF",133:"UNARY",134:"UNARY_MATH",135:"-",136:"+",137:"YIELD",138:"FROM",139:"--",140:"++",141:"?",142:"MATH",143:"**",144:"SHIFT",145:"COMPARE",146:"LOGIC",147:"RELATION",148:"COMPOUND_ASSIGN"},
productions_: [0,[3,0],[3,1],[4,1],[4,3],[4,2],[5,1],[5,1],[8,1],[8,1],[8,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[24,2],[24,3],[27,1],[29,1],[29,1],[31,1],[31,3],[35,1],[35,3],[39,1],[39,1],[39,1],[39,1],[39,1],[39,1],[39,1],[16,3],[16,4],[16,5],[47,1],[47,3],[47,5],[47,1],[48,1],[48,1],[48,1],[9,2],[9,1],[10,1],[14,5],[14,2],[56,1],[56,1],[59,0],[59,1],[54,0],[54,1],[54,3],[54,4],[54,6],[61,1],[61,2],[61,3],[61,1],[62,1],[62,1],[62,1],[62,1],[66,2],[67,1],[67,2],[67,2],[67,1],[45,1],[45,1],[45,1],[12,1],[12,1],[12,1],[12,1],[12,1],[68,2],[68,2],[68,2],[68,2],[68,1],[68,1],[76,3],[76,2],[78,1],[78,1],[65,4],[83,0],[83,1],[83,3],[83,4],[83,6],[22,1],[22,2],[22,3],[22,4],[22,2],[22,3],[22,4],[22,5],[13,3],[13,3],[13,1],[13,2],[87,0],[87,1],[88,2],[88,4],[71,1],[71,1],[50,2],[64,2],[64,4],[98,1],[98,1],[70,5],[81,3],[81,2],[81,2],[81,1],[93,1],[93,3],[93,4],[93,4],[93,6],[100,1],[100,1],[100,1],[101,1],[101,3],[18,2],[18,3],[18,4],[18,5],[103,3],[103,3],[103,2],[23,2],[69,3],[69,5],[109,2],[109,4],[109,2],[109,4],[19,2],[19,2],[19,2],[19,1],[113,2],[113,2],[20,2],[20,2],[20,2],[115,2],[115,4],[115,2],[118,2],[118,3],[122,1],[122,1],[122,1],[122,1],[120,1],[120,3],[119,2],[119,2],[119,4],[119,4],[119,4],[119,6],[119,6],[21,5],[21,7],[21,4],[21,6],[126,1],[126,2],[128,3],[128,4],[130,3],[130,5],[17,1],[17,3],[17,3],[17,3],[15,2],[15,2],[15,2],[15,2],[15,2],[15,2],[15,3],[15,2],[15,2],[15,2],[15,2],[15,2],[15,3],[15,3],[15,3],[15,3],[15,3],[15,3],[15,3],[15,3],[15,3],[15,5],[15,4],[15,3]],
performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate /* action[1] */, $$ /* vstack */, _$ /* lstack */) {
/* this == yyval */
var $0 = $$.length - 1;
switch (yystate) {
case 1:
return this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Block);
break;
case 2:
return this.$ = $$[$0];
break;
case 3:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(yy.Block.wrap([$$[$0]]));
break;
case 4:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])($$[$0-2].push($$[$0]));
break;
case 5:
this.$ = $$[$0-1];
break;
case 6: case 7: case 8: case 9: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 27: case 32: case 34: case 45: case 46: case 47: case 48: case 56: case 57: case 67: case 68: case 69: case 70: case 75: case 76: case 79: case 83: case 89: case 133: case 134: case 136: case 166: case 167: case 183: case 189:
this.$ = $$[$0];
break;
case 10: case 25: case 26: case 28: case 30: case 33: case 35:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Literal($$[$0]));
break;
case 23:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Block);
break;
case 24: case 31: case 90:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])($$[$0-1]);
break;
case 29: case 146:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Parens($$[$0-1]));
break;
case 36:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Undefined);
break;
case 37:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Null);
break;
case 38:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Bool($$[$0]));
break;
case 39:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Assign($$[$0-2], $$[$0]));
break;
case 40:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.Assign($$[$0-3], $$[$0]));
break;
case 41:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Assign($$[$0-4], $$[$0-1]));
break;
case 42: case 72: case 77: case 78: case 80: case 81: case 82: case 168: case 169:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Value($$[$0]));
break;
case 43:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Assign(yy.addLocationDataFn(_$[$0-2])(new yy.Value($$[$0-2])), $$[$0], 'object'));
break;
case 44:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Assign(yy.addLocationDataFn(_$[$0-4])(new yy.Value($$[$0-4])), $$[$0-1], 'object'));
break;
case 49:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Return($$[$0]));
break;
case 50:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Return);
break;
case 51:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Comment($$[$0]));
break;
case 52:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Code($$[$0-3], $$[$0], $$[$0-1]));
break;
case 53:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Code([], $$[$0], $$[$0-1]));
break;
case 54:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])('func');
break;
case 55:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])('boundfunc');
break;
case 58: case 95:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])([]);
break;
case 59: case 96: case 128: case 170:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])([$$[$0]]);
break;
case 60: case 97: case 129:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])($$[$0-2].concat($$[$0]));
break;
case 61: case 98: case 130:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])($$[$0-3].concat($$[$0]));
break;
case 62: case 99: case 132:
this.$ = yy.addLocationDataFn(_$[$0-5], _$[$0])($$[$0-5].concat($$[$0-2]));
break;
case 63:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Param($$[$0]));
break;
case 64:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Param($$[$0-1], null, true));
break;
case 65:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Param($$[$0-2], $$[$0]));
break;
case 66: case 135:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Expansion);
break;
case 71:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Splat($$[$0-1]));
break;
case 73:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])($$[$0-1].add($$[$0]));
break;
case 74:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Value($$[$0-1], [].concat($$[$0])));
break;
case 84:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Access($$[$0]));
break;
case 85:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Access($$[$0], 'soak'));
break;
case 86:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])([yy.addLocationDataFn(_$[$0-1])(new yy.Access(new yy.Literal('prototype'))), yy.addLocationDataFn(_$[$0])(new yy.Access($$[$0]))]);
break;
case 87:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])([yy.addLocationDataFn(_$[$0-1])(new yy.Access(new yy.Literal('prototype'), 'soak')), yy.addLocationDataFn(_$[$0])(new yy.Access($$[$0]))]);
break;
case 88:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Access(new yy.Literal('prototype')));
break;
case 91:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(yy.extend($$[$0], {
soak: true
}));
break;
case 92:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Index($$[$0]));
break;
case 93:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Slice($$[$0]));
break;
case 94:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.Obj($$[$0-2], $$[$0-3].generated));
break;
case 100:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Class);
break;
case 101:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Class(null, null, $$[$0]));
break;
case 102:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Class(null, $$[$0]));
break;
case 103:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.Class(null, $$[$0-1], $$[$0]));
break;
case 104:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Class($$[$0]));
break;
case 105:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Class($$[$0-1], null, $$[$0]));
break;
case 106:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.Class($$[$0-2], $$[$0]));
break;
case 107:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Class($$[$0-3], $$[$0-1], $$[$0]));
break;
case 108: case 109:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Call($$[$0-2], $$[$0], $$[$0-1]));
break;
case 110:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Call('super', [new yy.Splat(new yy.Literal('arguments'))]));
break;
case 111:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Call('super', $$[$0]));
break;
case 112:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(false);
break;
case 113:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(true);
break;
case 114:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])([]);
break;
case 115: case 131:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])($$[$0-2]);
break;
case 116: case 117:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Value(new yy.Literal('this')));
break;
case 118:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Value(yy.addLocationDataFn(_$[$0-1])(new yy.Literal('this')), [yy.addLocationDataFn(_$[$0])(new yy.Access($$[$0]))], 'this'));
break;
case 119:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Arr([]));
break;
case 120:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.Arr($$[$0-2]));
break;
case 121:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])('inclusive');
break;
case 122:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])('exclusive');
break;
case 123:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Range($$[$0-3], $$[$0-1], $$[$0-2]));
break;
case 124:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Range($$[$0-2], $$[$0], $$[$0-1]));
break;
case 125:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Range($$[$0-1], null, $$[$0]));
break;
case 126:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Range(null, $$[$0], $$[$0-1]));
break;
case 127:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])(new yy.Range(null, null, $$[$0]));
break;
case 137:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])([].concat($$[$0-2], $$[$0]));
break;
case 138:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Try($$[$0]));
break;
case 139:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Try($$[$0-1], $$[$0][0], $$[$0][1]));
break;
case 140:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.Try($$[$0-2], null, null, $$[$0]));
break;
case 141:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Try($$[$0-3], $$[$0-2][0], $$[$0-2][1], $$[$0]));
break;
case 142:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])([$$[$0-1], $$[$0]]);
break;
case 143:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])([yy.addLocationDataFn(_$[$0-1])(new yy.Value($$[$0-1])), $$[$0]]);
break;
case 144:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])([null, $$[$0]]);
break;
case 145:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Throw($$[$0]));
break;
case 147:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Parens($$[$0-2]));
break;
case 148:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.While($$[$0]));
break;
case 149:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.While($$[$0-2], {
guard: $$[$0]
}));
break;
case 150:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.While($$[$0], {
invert: true
}));
break;
case 151:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.While($$[$0-2], {
invert: true,
guard: $$[$0]
}));
break;
case 152:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])($$[$0-1].addBody($$[$0]));
break;
case 153: case 154:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])($$[$0].addBody(yy.addLocationDataFn(_$[$0-1])(yy.Block.wrap([$$[$0-1]]))));
break;
case 155:
this.$ = yy.addLocationDataFn(_$[$0], _$[$0])($$[$0]);
break;
case 156:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.While(yy.addLocationDataFn(_$[$0-1])(new yy.Literal('true'))).addBody($$[$0]));
break;
case 157:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.While(yy.addLocationDataFn(_$[$0-1])(new yy.Literal('true'))).addBody(yy.addLocationDataFn(_$[$0])(yy.Block.wrap([$$[$0]]))));
break;
case 158: case 159:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.For($$[$0-1], $$[$0]));
break;
case 160:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.For($$[$0], $$[$0-1]));
break;
case 161:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])({
source: yy.addLocationDataFn(_$[$0])(new yy.Value($$[$0]))
});
break;
case 162:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])({
source: yy.addLocationDataFn(_$[$0-2])(new yy.Value($$[$0-2])),
step: $$[$0]
});
break;
case 163:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])((function () {
$$[$0].own = $$[$0-1].own;
$$[$0].name = $$[$0-1][0];
$$[$0].index = $$[$0-1][1];
return $$[$0];
}()));
break;
case 164:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])($$[$0]);
break;
case 165:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])((function () {
$$[$0].own = true;
return $$[$0];
}()));
break;
case 171:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])([$$[$0-2], $$[$0]]);
break;
case 172:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])({
source: $$[$0]
});
break;
case 173:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])({
source: $$[$0],
object: true
});
break;
case 174:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])({
source: $$[$0-2],
guard: $$[$0]
});
break;
case 175:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])({
source: $$[$0-2],
guard: $$[$0],
object: true
});
break;
case 176:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])({
source: $$[$0-2],
step: $$[$0]
});
break;
case 177:
this.$ = yy.addLocationDataFn(_$[$0-5], _$[$0])({
source: $$[$0-4],
guard: $$[$0-2],
step: $$[$0]
});
break;
case 178:
this.$ = yy.addLocationDataFn(_$[$0-5], _$[$0])({
source: $$[$0-4],
step: $$[$0-2],
guard: $$[$0]
});
break;
case 179:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Switch($$[$0-3], $$[$0-1]));
break;
case 180:
this.$ = yy.addLocationDataFn(_$[$0-6], _$[$0])(new yy.Switch($$[$0-5], $$[$0-3], $$[$0-1]));
break;
case 181:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.Switch(null, $$[$0-1]));
break;
case 182:
this.$ = yy.addLocationDataFn(_$[$0-5], _$[$0])(new yy.Switch(null, $$[$0-3], $$[$0-1]));
break;
case 184:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])($$[$0-1].concat($$[$0]));
break;
case 185:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])([[$$[$0-1], $$[$0]]]);
break;
case 186:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])([[$$[$0-2], $$[$0-1]]]);
break;
case 187:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.If($$[$0-1], $$[$0], {
type: $$[$0-2]
}));
break;
case 188:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])($$[$0-4].addElse(yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.If($$[$0-1], $$[$0], {
type: $$[$0-2]
}))));
break;
case 190:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])($$[$0-2].addElse($$[$0]));
break;
case 191: case 192:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.If($$[$0], yy.addLocationDataFn(_$[$0-2])(yy.Block.wrap([$$[$0-2]])), {
type: $$[$0-1],
statement: true
}));
break;
case 193: case 194: case 197: case 198:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Op($$[$0-1], $$[$0]));
break;
case 195:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Op('-', $$[$0]));
break;
case 196:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Op('+', $$[$0]));
break;
case 199:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Op($$[$0-2].concat($$[$0-1]), $$[$0]));
break;
case 200:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Op('--', $$[$0]));
break;
case 201:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Op('++', $$[$0]));
break;
case 202:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Op('--', $$[$0-1], null, true));
break;
case 203:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Op('++', $$[$0-1], null, true));
break;
case 204:
this.$ = yy.addLocationDataFn(_$[$0-1], _$[$0])(new yy.Existence($$[$0-1]));
break;
case 205:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Op('+', $$[$0-2], $$[$0]));
break;
case 206:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Op('-', $$[$0-2], $$[$0]));
break;
case 207: case 208: case 209: case 210: case 211:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Op($$[$0-1], $$[$0-2], $$[$0]));
break;
case 212:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])((function () {
if ($$[$0-1].charAt(0) === '!') {
return new yy.Op($$[$0-1].slice(1), $$[$0-2], $$[$0]).invert();
} else {
return new yy.Op($$[$0-1], $$[$0-2], $$[$0]);
}
}()));
break;
case 213:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Assign($$[$0-2], $$[$0], $$[$0-1]));
break;
case 214:
this.$ = yy.addLocationDataFn(_$[$0-4], _$[$0])(new yy.Assign($$[$0-4], $$[$0-1], $$[$0-3]));
break;
case 215:
this.$ = yy.addLocationDataFn(_$[$0-3], _$[$0])(new yy.Assign($$[$0-3], $$[$0], $$[$0-2]));
break;
case 216:
this.$ = yy.addLocationDataFn(_$[$0-2], _$[$0])(new yy.Extends($$[$0-2], $$[$0]));
break;
}
},
table: [{1:[2,1],3:1,4:2,5:3,7:4,8:5,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,50:63,51:$Vc,52:$Vd,53:$Ve,56:28,57:$Vf,58:$Vg,64:47,65:48,67:36,69:23,70:24,71:25,82:$Vh,85:$Vi,89:$Vj,94:$Vk,95:$Vl,96:$Vm,102:$Vn,106:$Vo,107:$Vp,109:39,110:$Vq,112:$Vr,113:40,114:$Vs,115:41,116:$Vt,118:69,125:$Vu,130:37,131:$Vv,133:$Vw,134:$Vx,135:$Vy,136:$Vz,137:$VA,139:$VB,140:$VC},{1:[3]},{1:[2,2],6:$VD},o($VE,[2,3]),o($VE,[2,6],{118:69,109:89,115:90,110:$Vq,112:$Vr,116:$Vt,132:$VF,135:$VG,136:$VH,141:$VI,142:$VJ,143:$VK,144:$VL,145:$VM,146:$VN,147:$VO}),o($VE,[2,7],{118:69,109:92,115:93,110:$Vq,112:$Vr,116:$Vt,132:$VP}),o($VQ,[2,11],{87:94,68:95,76:101,72:$VR,73:$VS,74:$VT,75:$VU,77:$VV,80:$VW,90:$VX,91:$VY}),o($VQ,[2,12],{76:101,87:104,68:105,72:$VR,73:$VS,74:$VT,75:$VU,77:$VV,80:$VW,90:$VX,91:$VY}),o($VQ,[2,13]),o($VQ,[2,14]),o($VQ,[2,15]),o($VQ,[2,16]),o($VQ,[2,17]),o($VQ,[2,18]),o($VQ,[2,19]),o($VQ,[2,20]),o($VQ,[2,21]),o($VQ,[2,22]),o($VQ,[2,8]),o($VQ,[2,9]),o($VQ,[2,10]),o($VZ,$V_,{46:[1,106]}),o($VZ,[2,80]),o($VZ,[2,81]),o($VZ,[2,82]),o($VZ,[2,83]),o([1,6,25,26,34,38,55,60,63,72,73,74,75,77,79,80,84,90,92,97,99,108,110,111,112,116,117,132,135,136,141,142,143,144,145,146,147],[2,110],{88:107,91:$V$}),o([6,25,55,60],$V01,{54:109,61:110,62:111,27:113,50:114,64:115,65:116,28:$V1,63:$V11,82:$Vh,95:$V21,96:$V31}),{24:119,25:$V41},{7:121,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,50:63,51:$Vc,52:$Vd,53:$Ve,56:28,57:$Vf,58:$Vg,64:47,65:48,67:36,69:23,70:24,71:25,82:$Vh,85:$Vi,89:$Vj,94:$Vk,95:$Vl,96:$Vm,102:$Vn,106:$Vo,107:$Vp,109:39,110:$Vq,112:$Vr,113:40,114:$Vs,115:41,116:$Vt,118:69,125:$Vu,130:37,131:$Vv,133:$Vw,134:$Vx,135:$Vy,136:$Vz,137:$VA,139:$VB,140:$VC},{7:123,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,50:63,51:$Vc,52:$Vd,53:$Ve,56:28,57:$Vf,58:$Vg,64:47,65:48,67:36,69:23,70:24,71:25,82:$Vh,85:$Vi,89:$Vj,94:$Vk,95:$Vl,96:$Vm,102:$Vn,106:$Vo,107:$Vp,109:39,110:$Vq,112:$Vr,113:40,114:$Vs,115:41,116:$Vt,118:69,125:$Vu,130:37,131:$Vv,133:$Vw,134:$Vx,135:$Vy,136:$Vz,137:$VA,139:$VB,140:$VC},{7:124,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,50:63,51:$Vc,52:$Vd,53:$Ve,56:28,57:$Vf,58:$Vg,64:47,65:48,67:36,69:23,70:24,71:25,82:$Vh,85:$Vi,89:$Vj,94:$Vk,95:$Vl,96:$Vm,102:$Vn,106:$Vo,107:$Vp,109:39,110:$Vq,112:$Vr,113:40,114:$Vs,115:41,116:$Vt,118:69,125:$Vu,130:37,131:$Vv,133:$Vw,134:$Vx,135:$Vy,136:$Vz,137:$VA,139:$VB,140:$VC},{7:125,8:122,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,50:63,51:$Vc,52:$Vd,53:$Ve,56:28,57:$Vf,58:$Vg,64:47,65:48,67:36,69:23,70:24,71:25,82:$Vh,85:$Vi,89:$Vj,94:$Vk,95:$Vl,96:$Vm,102:$Vn,106:$Vo,107:$Vp,109:39,110:$Vq,112:$Vr,113:40,114:$Vs,115:41,116:$Vt,118:69,125:$Vu,130:37,131:$Vv,133:$Vw,134:$Vx,135:$Vy,136:$Vz,137:$VA,139:$VB,140:$VC},{7:127,8:126,9:18,10:19,11:$V0,12:6,13:7,14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39:22,40:$V7,41:$V8,42:$V9,43:$Va,44:$Vb,45:21,50:63,51:$Vc,52:$Vd,53:$Ve,56:28,57:$Vf,58:$Vg,64:47,65:48,67:36,69:23,70:24,71:25,82:$Vh,85:$Vi,89:$Vj,94:$Vk,95:$Vl,96:$Vm,102:$Vn,106:$Vo,107:$Vp,109:39,110:$Vq,112:$Vr,113:40,114:$Vs,115:41,116:$Vt,118:69,125:$Vu,130:37,131:$Vv,133:$Vw,134:$Vx,135:$Vy,136:$Vz,137:$VA,138:[1,128],139:$VB,140:$VC},{12:130,13:131,27:62,28:$V1,29:49,30:$V2,31:72,32:$V3,33:$V4,35:51,36:$V5,37:$V6,39
defaultActions: {60:[2,54],61:[2,55],96:[2,113],203:[2,93]},
parseError: function parseError(str, hash) {
if (hash.recoverable) {
this.trace(str);
} else {
throw new Error(str);
}
},
parse: function parse(input) {
var self = this, stack = [0], tstack = [], vstack = [null], lstack = [], table = this.table, yytext = '', yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;
var args = lstack.slice.call(arguments, 1);
var lexer = Object.create(this.lexer);
var sharedState = { yy: {} };
for (var k in this.yy) {
if (Object.prototype.hasOwnProperty.call(this.yy, k)) {
sharedState.yy[k] = this.yy[k];
}
}
lexer.setInput(input, sharedState.yy);
sharedState.yy.lexer = lexer;
sharedState.yy.parser = this;
if (typeof lexer.yylloc == 'undefined') {
lexer.yylloc = {};
}
var yyloc = lexer.yylloc;
lstack.push(yyloc);
var ranges = lexer.options && lexer.options.ranges;
if (typeof sharedState.yy.parseError === 'function') {
this.parseError = sharedState.yy.parseError;
} else {
this.parseError = Object.getPrototypeOf(this).parseError;
}
function popStack(n) {
stack.length = stack.length - 2 * n;
vstack.length = vstack.length - n;
lstack.length = lstack.length - n;
}
_token_stack:
function lex() {
var token;
token = lexer.lex() || EOF;
if (typeof token !== 'number') {
token = self.symbols_[token] || token;
}
return token;
}
var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;
while (true) {
state = stack[stack.length - 1];
if (this.defaultActions[state]) {
action = this.defaultActions[state];
} else {
if (symbol === null || typeof symbol == 'undefined') {
symbol = lex();
}
action = table[state] && table[state][symbol];
}
if (typeof action === 'undefined' || !action.length || !action[0]) {
var errStr = '';
expected = [];
for (p in table[state]) {
if (this.terminals_[p] && p > TERROR) {
expected.push('\'' + this.terminals_[p] + '\'');
}
}
if (lexer.showPosition) {
errStr = 'Parse error on line ' + (yylineno + 1) + ':\n' + lexer.showPosition() + '\nExpecting ' + expected.join(', ') + ', got \'' + (this.terminals_[symbol] || symbol) + '\'';
} else {
errStr = 'Parse error on line ' + (yylineno + 1) + ': Unexpected ' + (symbol == EOF ? 'end of input' : '\'' + (this.terminals_[symbol] || symbol) + '\'');
}
this.parseError(errStr, {
text: lexer.match,
token: this.terminals_[symbol] || symbol,
line: lexer.yylineno,
loc: yyloc,
expected: expected
});
}
if (action[0] instanceof Array && action.length > 1) {
throw new Error('Parse Error: multiple actions possible at state: ' + state + ', token: ' + symbol);
}
switch (action[0]) {
case 1:
stack.push(symbol);
vstack.push(lexer.yytext);
lstack.push(lexer.yylloc);
stack.push(action[1]);
symbol = null;
if (!preErrorSymbol) {
yyleng = lexer.yyleng;
yytext = lexer.yytext;
yylineno = lexer.yylineno;
yyloc = lexer.yylloc;
if (recovering > 0) {
recovering--;
}
} else {
symbol = preErrorSymbol;
preErrorSymbol = null;
}
break;
case 2:
len = this.productions_[action[1]][1];
yyval.$ = vstack[vstack.length - len];
yyval._$ = {
first_line: lstack[lstack.length - (len || 1)].first_line,
last_line: lstack[lstack.length - 1].last_line,
first_column: lstack[lstack.length - (len || 1)].first_column,
last_column: lstack[lstack.length - 1].last_column
};
if (ranges) {
yyval._$.range = [
lstack[lstack.length - (len || 1)].range[0],
lstack[lstack.length - 1].range[1]
];
}
r = this.performAction.apply(yyval, [
yytext,
yyleng,
yylineno,
sharedState.yy,
action[1],
vstack,
lstack
].concat(args));
if (typeof r !== 'undefined') {
return r;
}
if (len) {
stack = stack.slice(0, -1 * len * 2);
vstack = vstack.slice(0, -1 * len);
lstack = lstack.slice(0, -1 * len);
}
stack.push(this.productions_[action[1]][0]);
vstack.push(yyval.$);
lstack.push(yyval._$);
newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
stack.push(newState);
break;
case 3:
return true;
}
}
return true;
}};
function Parser () {
this.yy = {};
}
Parser.prototype = parser;parser.Parser = Parser;
return new Parser;
})();
if (typeof require !== 'undefined' && typeof exports !== 'undefined') {
exports.parser = parser;
exports.Parser = parser.Parser;
exports.parse = function () { return parser.parse.apply(parser, arguments); };
exports.main = function commonjsMain(args) {
if (!args[1]) {
console.log('Usage: '+args[0]+' FILE');
process.exit(1);
}
var source = require('fs').readFileSync(require('path').normalize(args[1]), "utf8");
return exports.parser.parse(source);
};
if (typeof module !== 'undefined' && require.main === module) {
exports.main(process.argv.slice(1));
}
}
}).call(this,require('_process'))
},{"_process":82,"fs":58,"path":81}],10:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var CoffeeScript, Module, binary, child_process, ext, findExtension, fork, helpers, i, len, loadFile, path, ref;
CoffeeScript = require('./coffee-script');
child_process = require('child_process');
helpers = require('./helpers');
path = require('path');
loadFile = function(module, filename) {
var answer;
answer = CoffeeScript._compileFile(filename, false);
return module._compile(answer, filename);
};
if (require.extensions) {
ref = CoffeeScript.FILE_EXTENSIONS;
for (i = 0, len = ref.length; i < len; i++) {
ext = ref[i];
require.extensions[ext] = loadFile;
}
Module = require('module');
findExtension = function(filename) {
var curExtension, extensions;
extensions = path.basename(filename).split('.');
if (extensions[0] === '') {
extensions.shift();
}
while (extensions.shift()) {
curExtension = '.' + extensions.join('.');
if (Module._extensions[curExtension]) {
return curExtension;
}
}
return '.js';
};
Module.prototype.load = function(filename) {
var extension;
this.filename = filename;
this.paths = Module._nodeModulePaths(path.dirname(filename));
extension = findExtension(filename);
Module._extensions[extension](this, filename);
return this.loaded = true;
};
}
if (child_process) {
fork = child_process.fork;
binary = require.resolve('../../bin/coffee');
child_process.fork = function(path, args, options) {
if (helpers.isCoffee(path)) {
if (!Array.isArray(args)) {
options = args || {};
args = [];
}
args = [path].concat(args);
path = binary;
}
return fork(path, args, options);
};
}
}).call(this);
},{"./coffee-script":5,"./helpers":6,"child_process":58,"module":58,"path":81}],11:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var BALANCED_PAIRS, CALL_CLOSERS, EXPRESSION_CLOSE, EXPRESSION_END, EXPRESSION_START, IMPLICIT_CALL, IMPLICIT_END, IMPLICIT_FUNC, IMPLICIT_UNSPACED_CALL, INVERSES, LINEBREAKS, SINGLE_CLOSERS, SINGLE_LINERS, generate, k, left, len, ref, rite,
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
slice = [].slice;
generate = function(tag, value, origin) {
var tok;
tok = [tag, value];
tok.generated = true;
if (origin) {
tok.origin = origin;
}
return tok;
};
exports.Rewriter = (function() {
function Rewriter() {}
Rewriter.prototype.rewrite = function(tokens1) {
this.tokens = tokens1;
this.removeLeadingNewlines();
this.closeOpenCalls();
this.closeOpenIndexes();
this.normalizeLines();
this.tagPostfixConditionals();
this.addImplicitBracesAndParens();
this.addLocationDataToGeneratedTokens();
return this.tokens;
};
Rewriter.prototype.scanTokens = function(block) {
var i, token, tokens;
tokens = this.tokens;
i = 0;
while (token = tokens[i]) {
i += block.call(this, token, i, tokens);
}
return true;
};
Rewriter.prototype.detectEnd = function(i, condition, action) {
var levels, ref, ref1, token, tokens;
tokens = this.tokens;
levels = 0;
while (token = tokens[i]) {
if (levels === 0 && condition.call(this, token, i)) {
return action.call(this, token, i);
}
if (!token || levels < 0) {
return action.call(this, token, i - 1);
}
if (ref = token[0], indexOf.call(EXPRESSION_START, ref) >= 0) {
levels += 1;
} else if (ref1 = token[0], indexOf.call(EXPRESSION_END, ref1) >= 0) {
levels -= 1;
}
i += 1;
}
return i - 1;
};
Rewriter.prototype.removeLeadingNewlines = function() {
var i, k, len, ref, tag;
ref = this.tokens;
for (i = k = 0, len = ref.length; k < len; i = ++k) {
tag = ref[i][0];
if (tag !== 'TERMINATOR') {
break;
}
}
if (i) {
return this.tokens.splice(0, i);
}
};
Rewriter.prototype.closeOpenCalls = function() {
var action, condition;
condition = function(token, i) {
var ref;
return ((ref = token[0]) === ')' || ref === 'CALL_END') || token[0] === 'OUTDENT' && this.tag(i - 1) === ')';
};
action = function(token, i) {
return this.tokens[token[0] === 'OUTDENT' ? i - 1 : i][0] = 'CALL_END';
};
return this.scanTokens(function(token, i) {
if (token[0] === 'CALL_START') {
this.detectEnd(i + 1, condition, action);
}
return 1;
});
};
Rewriter.prototype.closeOpenIndexes = function() {
var action, condition;
condition = function(token, i) {
var ref;
return (ref = token[0]) === ']' || ref === 'INDEX_END';
};
action = function(token, i) {
return token[0] = 'INDEX_END';
};
return this.scanTokens(function(token, i) {
if (token[0] === 'INDEX_START') {
this.detectEnd(i + 1, condition, action);
}
return 1;
});
};
Rewriter.prototype.indexOfTag = function() {
var fuzz, i, j, k, pattern, ref, ref1;
i = arguments[0], pattern = 2 <= arguments.length ? slice.call(arguments, 1) : [];
fuzz = 0;
for (j = k = 0, ref = pattern.length; 0 <= ref ? k < ref : k > ref; j = 0 <= ref ? ++k : --k) {
while (this.tag(i + j + fuzz) === 'HERECOMMENT') {
fuzz += 2;
}
if (pattern[j] == null) {
continue;
}
if (typeof pattern[j] === 'string') {
pattern[j] = [pattern[j]];
}
if (ref1 = this.tag(i + j + fuzz), indexOf.call(pattern[j], ref1) < 0) {
return -1;
}
}
return i + j + fuzz - 1;
};
Rewriter.prototype.looksObjectish = function(j) {
var end, index;
if (this.indexOfTag(j, '@', null, ':') > -1 || this.indexOfTag(j, null, ':') > -1) {
return true;
}
index = this.indexOfTag(j, EXPRESSION_START);
if (index > -1) {
end = null;
this.detectEnd(index + 1, (function(token) {
var ref;
return ref = token[0], indexOf.call(EXPRESSION_END, ref) >= 0;
}), (function(token, i) {
return end = i;
}));
if (this.tag(end + 1) === ':') {
return true;
}
}
return false;
};
Rewriter.prototype.findTagsBackwards = function(i, tags) {
var backStack, ref, ref1, ref2, ref3, ref4, ref5;
backStack = [];
while (i >= 0 && (backStack.length || (ref2 = this.tag(i), indexOf.call(tags, ref2) < 0) && ((ref3 = this.tag(i), indexOf.call(EXPRESSION_START, ref3) < 0) || this.tokens[i].generated) && (ref4 = this.tag(i), indexOf.call(LINEBREAKS, ref4) < 0))) {
if (ref = this.tag(i), indexOf.call(EXPRESSION_END, ref) >= 0) {
backStack.push(this.tag(i));
}
if ((ref1 = this.tag(i), indexOf.call(EXPRESSION_START, ref1) >= 0) && backStack.length) {
backStack.pop();
}
i -= 1;
}
return ref5 = this.tag(i), indexOf.call(tags, ref5) >= 0;
};
Rewriter.prototype.addImplicitBracesAndParens = function() {
var stack, start;
stack = [];
start = null;
return this.scanTokens(function(token, i, tokens) {
var endImplicitCall, endImplicitObject, forward, inImplicit, inImplicitCall, inImplicitControl, inImplicitObject, newLine, nextTag, offset, prevTag, prevToken, ref, ref1, ref2, ref3, ref4, ref5, s, sameLine, stackIdx, stackTag, stackTop, startIdx, startImplicitCall, startImplicitObject, startsLine, tag;
tag = token[0];
prevTag = (prevToken = i > 0 ? tokens[i - 1] : [])[0];
nextTag = (i < tokens.length - 1 ? tokens[i + 1] : [])[0];
stackTop = function() {
return stack[stack.length - 1];
};
startIdx = i;
forward = function(n) {
return i - startIdx + n;
};
inImplicit = function() {
var ref, ref1;
return (ref = stackTop()) != null ? (ref1 = ref[2]) != null ? ref1.ours : void 0 : void 0;
};
inImplicitCall = function() {
var ref;
return inImplicit() && ((ref = stackTop()) != null ? ref[0] : void 0) === '(';
};
inImplicitObject = function() {
var ref;
return inImplicit() && ((ref = stackTop()) != null ? ref[0] : void 0) === '{';
};
inImplicitControl = function() {
var ref;
return inImplicit && ((ref = stackTop()) != null ? ref[0] : void 0) === 'CONTROL';
};
startImplicitCall = function(j) {
var idx;
idx = j != null ? j : i;
stack.push([
'(', idx, {
ours: true
}
]);
tokens.splice(idx, 0, generate('CALL_START', '('));
if (j == null) {
return i += 1;
}
};
endImplicitCall = function() {
stack.pop();
tokens.splice(i, 0, generate('CALL_END', ')', ['', 'end of input', token[2]]));
return i += 1;
};
startImplicitObject = function(j, startsLine) {
var idx, val;
if (startsLine == null) {
startsLine = true;
}
idx = j != null ? j : i;
stack.push([
'{', idx, {
sameLine: true,
startsLine: startsLine,
ours: true
}
]);
val = new String('{');
val.generated = true;
tokens.splice(idx, 0, generate('{', val, token));
if (j == null) {
return i += 1;
}
};
endImplicitObject = function(j) {
j = j != null ? j : i;
stack.pop();
tokens.splice(j, 0, generate('}', '}', token));
return i += 1;
};
if (inImplicitCall() && (tag === 'IF' || tag === 'TRY' || tag === 'FINALLY' || tag === 'CATCH' || tag === 'CLASS' || tag === 'SWITCH')) {
stack.push([
'CONTROL', i, {
ours: true
}
]);
return forward(1);
}
if (tag === 'INDENT' && inImplicit()) {
if (prevTag !== '=>' && prevTag !== '->' && prevTag !== '[' && prevTag !== '(' && prevTag !== ',' && prevTag !== '{' && prevTag !== 'TRY' && prevTag !== 'ELSE' && prevTag !== '=') {
while (inImplicitCall()) {
endImplicitCall();
}
}
if (inImplicitControl()) {
stack.pop();
}
stack.push([tag, i]);
return forward(1);
}
if (indexOf.call(EXPRESSION_START, tag) >= 0) {
stack.push([tag, i]);
return forward(1);
}
if (indexOf.call(EXPRESSION_END, tag) >= 0) {
while (inImplicit()) {
if (inImplicitCall()) {
endImplicitCall();
} else if (inImplicitObject()) {
endImplicitObject();
} else {
stack.pop();
}
}
start = stack.pop();
}
if ((indexOf.call(IMPLICIT_FUNC, tag) >= 0 && token.spaced || tag === '?' && i > 0 && !tokens[i - 1].spaced) && (indexOf.call(IMPLICIT_CALL, nextTag) >= 0 || indexOf.call(IMPLICIT_UNSPACED_CALL, nextTag) >= 0 && !((ref = tokens[i + 1]) != null ? ref.spaced : void 0) && !((ref1 = tokens[i + 1]) != null ? ref1.newLine : void 0))) {
if (tag === '?') {
tag = token[0] = 'FUNC_EXIST';
}
startImplicitCall(i + 1);
return forward(2);
}
if (indexOf.call(IMPLICIT_FUNC, tag) >= 0 && this.indexOfTag(i + 1, 'INDENT', null, ':') > -1 && !this.findTagsBackwards(i, ['CLASS', 'EXTENDS', 'IF', 'CATCH', 'SWITCH', 'LEADING_WHEN', 'FOR', 'WHILE', 'UNTIL'])) {
startImplicitCall(i + 1);
stack.push(['INDENT', i + 2]);
return forward(3);
}
if (tag === ':') {
s = (function() {
var ref2;
switch (false) {
case ref2 = this.tag(i - 1), indexOf.call(EXPRESSION_END, ref2) < 0:
return start[1];
case this.tag(i - 2) !== '@':
return i - 2;
default:
return i - 1;
}
}).call(this);
while (this.tag(s - 2) === 'HERECOMMENT') {
s -= 2;
}
this.insideForDeclaration = nextTag === 'FOR';
startsLine = s === 0 || (ref2 = this.tag(s - 1), indexOf.call(LINEBREAKS, ref2) >= 0) || tokens[s - 1].newLine;
if (stackTop()) {
ref3 = stackTop(), stackTag = ref3[0], stackIdx = ref3[1];
if ((stackTag === '{' || stackTag === 'INDENT' && this.tag(stackIdx - 1) === '{') && (startsLine || this.tag(s - 1) === ',' || this.tag(s - 1) === '{')) {
return forward(1);
}
}
startImplicitObject(s, !!startsLine);
return forward(2);
}
if (inImplicitObject() && indexOf.call(LINEBREAKS, tag) >= 0) {
stackTop()[2].sameLine = false;
}
newLine = prevTag === 'OUTDENT' || prevToken.newLine;
if (indexOf.call(IMPLICIT_END, tag) >= 0 || indexOf.call(CALL_CLOSERS, tag) >= 0 && newLine) {
while (inImplicit()) {
ref4 = stackTop(), stackTag = ref4[0], stackIdx = ref4[1], (ref5 = ref4[2], sameLine = ref5.sameLine, startsLine = ref5.startsLine);
if (inImplicitCall() && prevTag !== ',') {
endImplicitCall();
} else if (inImplicitObject() && !this.insideForDeclaration && sameLine && tag !== 'TERMINATOR' && prevTag !== ':') {
endImplicitObject();
} else if (inImplicitObject() && tag === 'TERMINATOR' && prevTag !== ',' && !(startsLine && this.looksObjectish(i + 1))) {
if (nextTag === 'HERECOMMENT') {
return forward(1);
}
endImplicitObject();
} else {
break;
}
}
}
if (tag === ',' && !this.looksObjectish(i + 1) && inImplicitObject() && !this.insideForDeclaration && (nextTag !== 'TERMINATOR' || !this.looksObjectish(i + 2))) {
offset = nextTag === 'OUTDENT' ? 1 : 0;
while (inImplicitObject()) {
endImplicitObject(i + offset);
}
}
return forward(1);
});
};
Rewriter.prototype.addLocationDataToGeneratedTokens = function() {
return this.scanTokens(function(token, i, tokens) {
var column, line, nextLocation, prevLocation, ref, ref1;
if (token[2]) {
return 1;
}
if (!(token.generated || token.explicit)) {
return 1;
}
if (token[0] === '{' && (nextLocation = (ref = tokens[i + 1]) != null ? ref[2] : void 0)) {
line = nextLocation.first_line, column = nextLocation.first_column;
} else if (prevLocation = (ref1 = tokens[i - 1]) != null ? ref1[2] : void 0) {
line = prevLocation.last_line, column = prevLocation.last_column;
} else {
line = column = 0;
}
token[2] = {
first_line: line,
first_column: column,
last_line: line,
last_column: column
};
return 1;
});
};
Rewriter.prototype.normalizeLines = function() {
var action, condition, indent, outdent, starter;
starter = indent = outdent = null;
condition = function(token, i) {
var ref, ref1, ref2, ref3;
return token[1] !== ';' && (ref = token[0], indexOf.call(SINGLE_CLOSERS, ref) >= 0) && !(token[0] === 'TERMINATOR' && (ref1 = this.tag(i + 1), indexOf.call(EXPRESSION_CLOSE, ref1) >= 0)) && !(token[0] === 'ELSE' && starter !== 'THEN') && !(((ref2 = token[0]) === 'CATCH' || ref2 === 'FINALLY') && (starter === '->' || starter === '=>')) || (ref3 = token[0], indexOf.call(CALL_CLOSERS, ref3) >= 0) && this.tokens[i - 1].newLine;
};
action = function(token, i) {
return this.tokens.splice((this.tag(i - 1) === ',' ? i - 1 : i), 0, outdent);
};
return this.scanTokens(function(token, i, tokens) {
var j, k, ref, ref1, ref2, tag;
tag = token[0];
if (tag === 'TERMINATOR') {
if (this.tag(i + 1) === 'ELSE' && this.tag(i - 1) !== 'OUTDENT') {
tokens.splice.apply(tokens, [i, 1].concat(slice.call(this.indentation())));
return 1;
}
if (ref = this.tag(i + 1), indexOf.call(EXPRESSION_CLOSE, ref) >= 0) {
tokens.splice(i, 1);
return 0;
}
}
if (tag === 'CATCH') {
for (j = k = 1; k <= 2; j = ++k) {
if (!((ref1 = this.tag(i + j)) === 'OUTDENT' || ref1 === 'TERMINATOR' || ref1 === 'FINALLY')) {
continue;
}
tokens.splice.apply(tokens, [i + j, 0].concat(slice.call(this.indentation())));
return 2 + j;
}
}
if (indexOf.call(SINGLE_LINERS, tag) >= 0 && this.tag(i + 1) !== 'INDENT' && !(tag === 'ELSE' && this.tag(i + 1) === 'IF')) {
starter = tag;
ref2 = this.indentation(tokens[i]), indent = ref2[0], outdent = ref2[1];
if (starter === 'THEN') {
indent.fromThen = true;
}
tokens.splice(i + 1, 0, indent);
this.detectEnd(i + 2, condition, action);
if (tag === 'THEN') {
tokens.splice(i, 1);
}
return 1;
}
return 1;
});
};
Rewriter.prototype.tagPostfixConditionals = function() {
var action, condition, original;
original = null;
condition = function(token, i) {
var prevTag, tag;
tag = token[0];
prevTag = this.tokens[i - 1][0];
return tag === 'TERMINATOR' || (tag === 'INDENT' && indexOf.call(SINGLE_LINERS, prevTag) < 0);
};
action = function(token, i) {
if (token[0] !== 'INDENT' || (token.generated && !token.fromThen)) {
return original[0] = 'POST_' + original[0];
}
};
return this.scanTokens(function(token, i) {
if (token[0] !== 'IF') {
return 1;
}
original = token;
this.detectEnd(i + 1, condition, action);
return 1;
});
};
Rewriter.prototype.indentation = function(origin) {
var indent, outdent;
indent = ['INDENT', 2];
outdent = ['OUTDENT', 2];
if (origin) {
indent.generated = outdent.generated = true;
indent.origin = outdent.origin = origin;
} else {
indent.explicit = outdent.explicit = true;
}
return [indent, outdent];
};
Rewriter.prototype.generate = generate;
Rewriter.prototype.tag = function(i) {
var ref;
return (ref = this.tokens[i]) != null ? ref[0] : void 0;
};
return Rewriter;
})();
BALANCED_PAIRS = [['(', ')'], ['[', ']'], ['{', '}'], ['INDENT', 'OUTDENT'], ['CALL_START', 'CALL_END'], ['PARAM_START', 'PARAM_END'], ['INDEX_START', 'INDEX_END'], ['STRING_START', 'STRING_END'], ['REGEX_START', 'REGEX_END']];
exports.INVERSES = INVERSES = {};
EXPRESSION_START = [];
EXPRESSION_END = [];
for (k = 0, len = BALANCED_PAIRS.length; k < len; k++) {
ref = BALANCED_PAIRS[k], left = ref[0], rite = ref[1];
EXPRESSION_START.push(INVERSES[rite] = left);
EXPRESSION_END.push(INVERSES[left] = rite);
}
EXPRESSION_CLOSE = ['CATCH', 'THEN', 'ELSE', 'FINALLY'].concat(EXPRESSION_END);
IMPLICIT_FUNC = ['IDENTIFIER', 'SUPER', ')', 'CALL_END', ']', 'INDEX_END', '@', 'THIS'];
IMPLICIT_CALL = ['IDENTIFIER', 'NUMBER', 'STRING', 'STRING_START', 'JS', 'REGEX', 'REGEX_START', 'NEW', 'PARAM_START', 'CLASS', 'IF', 'TRY', 'SWITCH', 'THIS', 'BOOL', 'NULL', 'UNDEFINED', 'UNARY', 'YIELD', 'UNARY_MATH', 'SUPER', 'THROW', '@', '->', '=>', '[', '(', '{', '--', '++'];
IMPLICIT_UNSPACED_CALL = ['+', '-'];
IMPLICIT_END = ['POST_IF', 'FOR', 'WHILE', 'UNTIL', 'WHEN', 'BY', 'LOOP', 'TERMINATOR'];
SINGLE_LINERS = ['ELSE', '->', '=>', 'TRY', 'FINALLY', 'THEN'];
SINGLE_CLOSERS = ['TERMINATOR', 'CATCH', 'FINALLY', 'ELSE', 'OUTDENT', 'LEADING_WHEN'];
LINEBREAKS = ['TERMINATOR', 'INDENT', 'OUTDENT'];
CALL_CLOSERS = ['.', '?.', '::', '?::'];
}).call(this);
},{}],12:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var Scope,
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
exports.Scope = Scope = (function() {
function Scope(parent, expressions, method, referencedVars) {
var ref, ref1;
this.parent = parent;
this.expressions = expressions;
this.method = method;
this.referencedVars = referencedVars;
this.variables = [
{
name: 'arguments',
type: 'arguments'
}
];
this.positions = {};
if (!this.parent) {
this.utilities = {};
}
this.root = (ref = (ref1 = this.parent) != null ? ref1.root : void 0) != null ? ref : this;
}
Scope.prototype.add = function(name, type, immediate) {
if (this.shared && !immediate) {
return this.parent.add(name, type, immediate);
}
if (Object.prototype.hasOwnProperty.call(this.positions, name)) {
return this.variables[this.positions[name]].type = type;
} else {
return this.positions[name] = this.variables.push({
name: name,
type: type
}) - 1;
}
};
Scope.prototype.namedMethod = function() {
var ref;
if (((ref = this.method) != null ? ref.name : void 0) || !this.parent) {
return this.method;
}
return this.parent.namedMethod();
};
Scope.prototype.find = function(name) {
if (this.check(name)) {
return true;
}
this.add(name, 'var');
return false;
};
Scope.prototype.parameter = function(name) {
if (this.shared && this.parent.check(name, true)) {
return;
}
return this.add(name, 'param');
};
Scope.prototype.check = function(name) {
var ref;
return !!(this.type(name) || ((ref = this.parent) != null ? ref.check(name) : void 0));
};
Scope.prototype.temporary = function(name, index, single) {
if (single == null) {
single = false;
}
if (single) {
return (index + parseInt(name, 36)).toString(36).replace(/\d/g, 'a');
} else {
return name + (index || '');
}
};
Scope.prototype.type = function(name) {
var i, len, ref, v;
ref = this.variables;
for (i = 0, len = ref.length; i < len; i++) {
v = ref[i];
if (v.name === name) {
return v.type;
}
}
return null;
};
Scope.prototype.freeVariable = function(name, options) {
var index, ref, temp;
if (options == null) {
options = {};
}
index = 0;
while (true) {
temp = this.temporary(name, index, options.single);
if (!(this.check(temp) || indexOf.call(this.root.referencedVars, temp) >= 0)) {
break;
}
index++;
}
if ((ref = options.reserve) != null ? ref : true) {
this.add(temp, 'var', true);
}
return temp;
};
Scope.prototype.assign = function(name, value) {
this.add(name, {
value: value,
assigned: true
}, true);
return this.hasAssignments = true;
};
Scope.prototype.hasDeclarations = function() {
return !!this.declaredVariables().length;
};
Scope.prototype.declaredVariables = function() {
var v;
return ((function() {
var i, len, ref, results;
ref = this.variables;
results = [];
for (i = 0, len = ref.length; i < len; i++) {
v = ref[i];
if (v.type === 'var') {
results.push(v.name);
}
}
return results;
}).call(this)).sort();
};
Scope.prototype.assignedVariables = function() {
var i, len, ref, results, v;
ref = this.variables;
results = [];
for (i = 0, len = ref.length; i < len; i++) {
v = ref[i];
if (v.type.assigned) {
results.push(v.name + " = " + v.type.value);
}
}
return results;
};
return Scope;
})();
}).call(this);
},{}],13:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var LineMap, SourceMap;
LineMap = (function() {
function LineMap(line1) {
this.line = line1;
this.columns = [];
}
LineMap.prototype.add = function(column, arg, options) {
var sourceColumn, sourceLine;
sourceLine = arg[0], sourceColumn = arg[1];
if (options == null) {
options = {};
}
if (this.columns[column] && options.noReplace) {
return;
}
return this.columns[column] = {
line: this.line,
column: column,
sourceLine: sourceLine,
sourceColumn: sourceColumn
};
};
LineMap.prototype.sourceLocation = function(column) {
var mapping;
while (!((mapping = this.columns[column]) || (column <= 0))) {
column--;
}
return mapping && [mapping.sourceLine, mapping.sourceColumn];
};
return LineMap;
})();
SourceMap = (function() {
var BASE64_CHARS, VLQ_CONTINUATION_BIT, VLQ_SHIFT, VLQ_VALUE_MASK;
function SourceMap() {
this.lines = [];
}
SourceMap.prototype.add = function(sourceLocation, generatedLocation, options) {
var base, column, line, lineMap;
if (options == null) {
options = {};
}
line = generatedLocation[0], column = generatedLocation[1];
lineMap = ((base = this.lines)[line] || (base[line] = new LineMap(line)));
return lineMap.add(column, sourceLocation, options);
};
SourceMap.prototype.sourceLocation = function(arg) {
var column, line, lineMap;
line = arg[0], column = arg[1];
while (!((lineMap = this.lines[line]) || (line <= 0))) {
line--;
}
return lineMap && lineMap.sourceLocation(column);
};
SourceMap.prototype.generate = function(options, code) {
var buffer, i, j, lastColumn, lastSourceColumn, lastSourceLine, len, len1, lineMap, lineNumber, mapping, needComma, ref, ref1, v3, writingline;
if (options == null) {
options = {};
}
if (code == null) {
code = null;
}
writingline = 0;
lastColumn = 0;
lastSourceLine = 0;
lastSourceColumn = 0;
needComma = false;
buffer = "";
ref = this.lines;
for (lineNumber = i = 0, len = ref.length; i < len; lineNumber = ++i) {
lineMap = ref[lineNumber];
if (lineMap) {
ref1 = lineMap.columns;
for (j = 0, len1 = ref1.length; j < len1; j++) {
mapping = ref1[j];
if (!(mapping)) {
continue;
}
while (writingline < mapping.line) {
lastColumn = 0;
needComma = false;
buffer += ";";
writingline++;
}
if (needComma) {
buffer += ",";
needComma = false;
}
buffer += this.encodeVlq(mapping.column - lastColumn);
lastColumn = mapping.column;
buffer += this.encodeVlq(0);
buffer += this.encodeVlq(mapping.sourceLine - lastSourceLine);
lastSourceLine = mapping.sourceLine;
buffer += this.encodeVlq(mapping.sourceColumn - lastSourceColumn);
lastSourceColumn = mapping.sourceColumn;
needComma = true;
}
}
}
v3 = {
version: 3,
file: options.generatedFile || '',
sourceRoot: options.sourceRoot || '',
sources: options.sourceFiles || [''],
names: [],
mappings: buffer
};
if (options.inline) {
v3.sourcesContent = [code];
}
return JSON.stringify(v3, null, 2);
};
VLQ_SHIFT = 5;
VLQ_CONTINUATION_BIT = 1 << VLQ_SHIFT;
VLQ_VALUE_MASK = VLQ_CONTINUATION_BIT - 1;
SourceMap.prototype.encodeVlq = function(value) {
var answer, nextChunk, signBit, valueToEncode;
answer = '';
signBit = value < 0 ? 1 : 0;
valueToEncode = (Math.abs(value) << 1) + signBit;
while (valueToEncode || !answer) {
nextChunk = valueToEncode & VLQ_VALUE_MASK;
valueToEncode = valueToEncode >> VLQ_SHIFT;
if (valueToEncode) {
nextChunk |= VLQ_CONTINUATION_BIT;
}
answer += this.encodeBase64(nextChunk);
}
return answer;
};
BASE64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
SourceMap.prototype.encodeBase64 = function(value) {
return BASE64_CHARS[value] || (function() {
throw new Error("Cannot Base64 encode value: " + value);
})();
};
return SourceMap;
})();
module.exports = SourceMap;
}).call(this);
},{}],14:[function(require,module,exports){
// super simple module for the most common nodejs use case.
exports.markdown = require("./markdown");
exports.parse = exports.markdown.toHTML;
},{"./markdown":15}],15:[function(require,module,exports){
// Released under MIT license
// Copyright (c) 2009-2010 Dominic Baggott
// Copyright (c) 2009-2010 Ash Berlin
// Copyright (c) 2011 Christoph Dorn <christoph@christophdorn.com> (http://www.christophdorn.com)
/*jshint browser:true, devel:true */
(function( expose ) {
/**
* class Markdown
*
* Markdown processing in Javascript done right. We have very particular views
* on what constitutes 'right' which include:
*
* - produces well-formed HTML (this means that em and strong nesting is
* important)
*
* - has an intermediate representation to allow processing of parsed data (We
* in fact have two, both as [JsonML]: a markdown tree and an HTML tree).
*
* - is easily extensible to add new dialects without having to rewrite the
* entire parsing mechanics
*
* - has a good test suite
*
* This implementation fulfills all of these (except that the test suite could
* do with expanding to automatically run all the fixtures from other Markdown
* implementations.)
*
* ##### Intermediate Representation
*
* *TODO* Talk about this :) Its JsonML, but document the node names we use.
*
* [JsonML]: http://jsonml.org/ "JSON Markup Language"
**/
var Markdown = expose.Markdown = function(dialect) {
switch (typeof dialect) {
case "undefined":
this.dialect = Markdown.dialects.Gruber;
break;
case "object":
this.dialect = dialect;
break;
default:
if ( dialect in Markdown.dialects ) {
this.dialect = Markdown.dialects[dialect];
}
else {
throw new Error("Unknown Markdown dialect '" + String(dialect) + "'");
}
break;
}
this.em_state = [];
this.strong_state = [];
this.debug_indent = "";
};
/**
* parse( markdown, [dialect] ) -> JsonML
* - markdown (String): markdown string to parse
* - dialect (String | Dialect): the dialect to use, defaults to gruber
*
* Parse `markdown` and return a markdown document as a Markdown.JsonML tree.
**/
expose.parse = function( source, dialect ) {
// dialect will default if undefined
var md = new Markdown( dialect );
return md.toTree( source );
};
/**
* toHTML( markdown, [dialect] ) -> String
* toHTML( md_tree ) -> String
* - markdown (String): markdown string to parse
* - md_tree (Markdown.JsonML): parsed markdown tree
*
* Take markdown (either as a string or as a JsonML tree) and run it through
* [[toHTMLTree]] then turn it into a well-formated HTML fragment.
**/
expose.toHTML = function toHTML( source , dialect , options ) {
var input = expose.toHTMLTree( source , dialect , options );
return expose.renderJsonML( input );
};
/**
* toHTMLTree( markdown, [dialect] ) -> JsonML
* toHTMLTree( md_tree ) -> JsonML
* - markdown (String): markdown string to parse
* - dialect (String | Dialect): the dialect to use, defaults to gruber
* - md_tree (Markdown.JsonML): parsed markdown tree
*
* Turn markdown into HTML, represented as a JsonML tree. If a string is given
* to this function, it is first parsed into a markdown tree by calling
* [[parse]].
**/
expose.toHTMLTree = function toHTMLTree( input, dialect , options ) {
// convert string input to an MD tree
if ( typeof input ==="string" ) input = this.parse( input, dialect );
// Now convert the MD tree to an HTML tree
// remove references from the tree
var attrs = extract_attr( input ),
refs = {};
if ( attrs && attrs.references ) {
refs = attrs.references;
}
var html = convert_tree_to_html( input, refs , options );
merge_text_nodes( html );
return html;
};
// For Spidermonkey based engines
function mk_block_toSource() {
return "Markdown.mk_block( " +
uneval(this.toString()) +
", " +
uneval(this.trailing) +
", " +
uneval(this.lineNumber) +
" )";
}
// node
function mk_block_inspect() {
var util = require("util");
return "Markdown.mk_block( " +
util.inspect(this.toString()) +
", " +
util.inspect(this.trailing) +
", " +
util.inspect(this.lineNumber) +
" )";
}
var mk_block = Markdown.mk_block = function(block, trail, line) {
// Be helpful for default case in tests.
if ( arguments.length == 1 ) trail = "\n\n";
var s = new String(block);
s.trailing = trail;
// To make it clear its not just a string
s.inspect = mk_block_inspect;
s.toSource = mk_block_toSource;
if ( line != undefined )
s.lineNumber = line;
return s;
};
function count_lines( str ) {
var n = 0, i = -1;
while ( ( i = str.indexOf("\n", i + 1) ) !== -1 ) n++;
return n;
}
// Internal - split source into rough blocks
Markdown.prototype.split_blocks = function splitBlocks( input, startLine ) {
input = input.replace(/(\r\n|\n|\r)/g, "\n");
// [\s\S] matches _anything_ (newline or space)
// [^] is equivalent but doesn't work in IEs.
var re = /([\s\S]+?)($|\n#|\n(?:\s*\n|$)+)/g,
blocks = [],
m;
var line_no = 1;
if ( ( m = /^(\s*\n)/.exec(input) ) != null ) {
// skip (but count) leading blank lines
line_no += count_lines( m[0] );
re.lastIndex = m[0].length;
}
while ( ( m = re.exec(input) ) !== null ) {
if (m[2] == "\n#") {
m[2] = "\n";
re.lastIndex--;
}
blocks.push( mk_block( m[1], m[2], line_no ) );
line_no += count_lines( m[0] );
}
return blocks;
};
/**
* Markdown#processBlock( block, next ) -> undefined | [ JsonML, ... ]
* - block (String): the block to process
* - next (Array): the following blocks
*
* Process `block` and return an array of JsonML nodes representing `block`.
*
* It does this by asking each block level function in the dialect to process
* the block until one can. Succesful handling is indicated by returning an
* array (with zero or more JsonML nodes), failure by a false value.
*
* Blocks handlers are responsible for calling [[Markdown#processInline]]
* themselves as appropriate.
*
* If the blocks were split incorrectly or adjacent blocks need collapsing you
* can adjust `next` in place using shift/splice etc.
*
* If any of this default behaviour is not right for the dialect, you can
* define a `__call__` method on the dialect that will get invoked to handle
* the block processing.
*/
Markdown.prototype.processBlock = function processBlock( block, next ) {
var cbs = this.dialect.block,
ord = cbs.__order__;
if ( "__call__" in cbs ) {
return cbs.__call__.call(this, block, next);
}
for ( var i = 0; i < ord.length; i++ ) {
//D:this.debug( "Testing", ord[i] );
var res = cbs[ ord[i] ].call( this, block, next );
if ( res ) {
//D:this.debug(" matched");
if ( !isArray(res) || ( res.length > 0 && !( isArray(res[0]) ) ) )
this.debug(ord[i], "didn't return a proper array");
//D:this.debug( "" );
return res;
}
}
// Uhoh! no match! Should we throw an error?
return [];
};
Markdown.prototype.processInline = function processInline( block ) {
return this.dialect.inline.__call__.call( this, String( block ) );
};
/**
* Markdown#toTree( source ) -> JsonML
* - source (String): markdown source to parse
*
* Parse `source` into a JsonML tree representing the markdown document.
**/
// custom_tree means set this.tree to `custom_tree` and restore old value on return
Markdown.prototype.toTree = function toTree( source, custom_root ) {
var blocks = source instanceof Array ? source : this.split_blocks( source );
// Make tree a member variable so its easier to mess with in extensions
var old_tree = this.tree;
try {
this.tree = custom_root || this.tree || [ "markdown" ];
blocks:
while ( blocks.length ) {
var b = this.processBlock( blocks.shift(), blocks );
// Reference blocks and the like won't return any content
if ( !b.length ) continue blocks;
this.tree.push.apply( this.tree, b );
}
return this.tree;
}
finally {
if ( custom_root ) {
this.tree = old_tree;
}
}
};
// Noop by default
Markdown.prototype.debug = function () {
var args = Array.prototype.slice.call( arguments);
args.unshift(this.debug_indent);
if ( typeof print !== "undefined" )
print.apply( print, args );
if ( typeof console !== "undefined" && typeof console.log !== "undefined" )
console.log.apply( null, args );
}
Markdown.prototype.loop_re_over_block = function( re, block, cb ) {
// Dont use /g regexps with this
var m,
b = block.valueOf();
while ( b.length && (m = re.exec(b) ) != null ) {
b = b.substr( m[0].length );
cb.call(this, m);
}
return b;
};
/**
* Markdown.dialects
*
* Namespace of built-in dialects.
**/
Markdown.dialects = {};
/**
* Markdown.dialects.Gruber
*
* The default dialect that follows the rules set out by John Gruber's
* markdown.pl as closely as possible. Well actually we follow the behaviour of
* that script which in some places is not exactly what the syntax web page
* says.
**/
Markdown.dialects.Gruber = {
block: {
atxHeader: function atxHeader( block, next ) {
var m = block.match( /^(#{1,6})\s*(.*?)\s*#*\s*(?:\n|$)/ );
if ( !m ) return undefined;
var header = [ "header", { level: m[ 1 ].length } ];
Array.prototype.push.apply(header, this.processInline(m[ 2 ]));
if ( m[0].length < block.length )
next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) );
return [ header ];
},
setextHeader: function setextHeader( block, next ) {
var m = block.match( /^(.*)\n([-=])\2\2+(?:\n|$)/ );
if ( !m ) return undefined;
var level = ( m[ 2 ] === "=" ) ? 1 : 2;
var header = [ "header", { level : level }, m[ 1 ] ];
if ( m[0].length < block.length )
next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) );
return [ header ];
},
code: function code( block, next ) {
// | Foo
// |bar
// should be a code block followed by a paragraph. Fun
//
// There might also be adjacent code block to merge.
var ret = [],
re = /^(?: {0,3}\t| {4})(.*)\n?/,
lines;
// 4 spaces + content
if ( !block.match( re ) ) return undefined;
block_search:
do {
// Now pull out the rest of the lines
var b = this.loop_re_over_block(
re, block.valueOf(), function( m ) { ret.push( m[1] ); } );
if ( b.length ) {
// Case alluded to in first comment. push it back on as a new block
next.unshift( mk_block(b, block.trailing) );
break block_search;
}
else if ( next.length ) {
// Check the next block - it might be code too
if ( !next[0].match( re ) ) break block_search;
// Pull how how many blanks lines follow - minus two to account for .join
ret.push ( block.trailing.replace(/[^\n]/g, "").substring(2) );
block = next.shift();
}
else {
break block_search;
}
} while ( true );
return [ [ "code_block", ret.join("\n") ] ];
},
horizRule: function horizRule( block, next ) {
// this needs to find any hr in the block to handle abutting blocks
var m = block.match( /^(?:([\s\S]*?)\n)?[ \t]*([-_*])(?:[ \t]*\2){2,}[ \t]*(?:\n([\s\S]*))?$/ );
if ( !m ) {
return undefined;
}
var jsonml = [ [ "hr" ] ];
// if there's a leading abutting block, process it
if ( m[ 1 ] ) {
jsonml.unshift.apply( jsonml, this.processBlock( m[ 1 ], [] ) );
}
// if there's a trailing abutting block, stick it into next
if ( m[ 3 ] ) {
next.unshift( mk_block( m[ 3 ] ) );
}
return jsonml;
},
// There are two types of lists. Tight and loose. Tight lists have no whitespace
// between the items (and result in text just in the <li>) and loose lists,
// which have an empty line between list items, resulting in (one or more)
// paragraphs inside the <li>.
//
// There are all sorts weird edge cases about the original markdown.pl's
// handling of lists:
//
// * Nested lists are supposed to be indented by four chars per level. But
// if they aren't, you can get a nested list by indenting by less than
// four so long as the indent doesn't match an indent of an existing list
// item in the 'nest stack'.
//
// * The type of the list (bullet or number) is controlled just by the
// first item at the indent. Subsequent changes are ignored unless they
// are for nested lists
//
lists: (function( ) {
// Use a closure to hide a few variables.
var any_list = "[*+-]|\\d+\\.",
bullet_list = /[*+-]/,
number_list = /\d+\./,
// Capture leading indent as it matters for determining nested lists.
is_list_re = new RegExp( "^( {0,3})(" + any_list + ")[ \t]+" ),
indent_re = "(?: {0,3}\\t| {4})";
// TODO: Cache this regexp for certain depths.
// Create a regexp suitable for matching an li for a given stack depth
function regex_for_depth( depth ) {
return new RegExp(
// m[1] = indent, m[2] = list_type
"(?:^(" + indent_re + "{0," + depth + "} {0,3})(" + any_list + ")\\s+)|" +
// m[3] = cont
"(^" + indent_re + "{0," + (depth-1) + "}[ ]{0,4})"
);
}
function expand_tab( input ) {
return input.replace( / {0,3}\t/g, " " );
}
// Add inline content `inline` to `li`. inline comes from processInline
// so is an array of content
function add(li, loose, inline, nl) {
if ( loose ) {
li.push( [ "para" ].concat(inline) );
return;
}
// Hmmm, should this be any block level element or just paras?
var add_to = li[li.length -1] instanceof Array && li[li.length - 1][0] == "para"
? li[li.length -1]
: li;
// If there is already some content in this list, add the new line in
if ( nl && li.length > 1 ) inline.unshift(nl);
for ( var i = 0; i < inline.length; i++ ) {
var what = inline[i],
is_str = typeof what == "string";
if ( is_str && add_to.length > 1 && typeof add_to[add_to.length-1] == "string" ) {
add_to[ add_to.length-1 ] += what;
}
else {
add_to.push( what );
}
}
}
// contained means have an indent greater than the current one. On
// *every* line in the block
function get_contained_blocks( depth, blocks ) {
var re = new RegExp( "^(" + indent_re + "{" + depth + "}.*?\\n?)*$" ),
replace = new RegExp("^" + indent_re + "{" + depth + "}", "gm"),
ret = [];
while ( blocks.length > 0 ) {
if ( re.exec( blocks[0] ) ) {
var b = blocks.shift(),
// Now remove that indent
x = b.replace( replace, "");
ret.push( mk_block( x, b.trailing, b.lineNumber ) );
}
else {
break;
}
}
return ret;
}
// passed to stack.forEach to turn list items up the stack into paras
function paragraphify(s, i, stack) {
var list = s.list;
var last_li = list[list.length-1];
if ( last_li[1] instanceof Array && last_li[1][0] == "para" ) {
return;
}
if ( i + 1 == stack.length ) {
// Last stack frame
// Keep the same array, but replace the contents
last_li.push( ["para"].concat( last_li.splice(1, last_li.length - 1) ) );
}
else {
var sublist = last_li.pop();
last_li.push( ["para"].concat( last_li.splice(1, last_li.length - 1) ), sublist );
}
}
// The matcher function
return function( block, next ) {
var m = block.match( is_list_re );
if ( !m ) return undefined;
function make_list( m ) {
var list = bullet_list.exec( m[2] )
? ["bulletlist"]
: ["numberlist"];
stack.push( { list: list, indent: m[1] } );
return list;
}
var stack = [], // Stack of lists for nesting.
list = make_list( m ),
last_li,
loose = false,
ret = [ stack[0].list ],
i;
// Loop to search over block looking for inner block elements and loose lists
loose_search:
while ( true ) {
// Split into lines preserving new lines at end of line
var lines = block.split( /(?=\n)/ );
// We have to grab all lines for a li and call processInline on them
// once as there are some inline things that can span lines.
var li_accumulate = "";
// Loop over the lines in this block looking for tight lists.
tight_search:
for ( var line_no = 0; line_no < lines.length; line_no++ ) {
var nl = "",
l = lines[line_no].replace(/^\n/, function(n) { nl = n; return ""; });
// TODO: really should cache this
var line_re = regex_for_depth( stack.length );
m = l.match( line_re );
//print( "line:", uneval(l), "\nline match:", uneval(m) );
// We have a list item
if ( m[1] !== undefined ) {
// Process the previous list item, if any
if ( li_accumulate.length ) {
add( last_li, loose, this.processInline( li_accumulate ), nl );
// Loose mode will have been dealt with. Reset it
loose = false;
li_accumulate = "";
}
m[1] = expand_tab( m[1] );
var wanted_depth = Math.floor(m[1].length/4)+1;
//print( "want:", wanted_depth, "stack:", stack.length);
if ( wanted_depth > stack.length ) {
// Deep enough for a nested list outright
//print ( "new nested list" );
list = make_list( m );
last_li.push( list );
last_li = list[1] = [ "listitem" ];
}
else {
// We aren't deep enough to be strictly a new level. This is
// where Md.pl goes nuts. If the indent matches a level in the
// stack, put it there, else put it one deeper then the
// wanted_depth deserves.
var found = false;
for ( i = 0; i < stack.length; i++ ) {
if ( stack[ i ].indent != m[1] ) continue;
list = stack[ i ].list;
stack.splice( i+1, stack.length - (i+1) );
found = true;
break;
}
if (!found) {
//print("not found. l:", uneval(l));
wanted_depth++;
if ( wanted_depth <= stack.length ) {
stack.splice(wanted_depth, stack.length - wanted_depth);
//print("Desired depth now", wanted_depth, "stack:", stack.length);
list = stack[wanted_depth-1].list;
//print("list:", uneval(list) );
}
else {
//print ("made new stack for messy indent");
list = make_list(m);
last_li.push(list);
}
}
//print( uneval(list), "last", list === stack[stack.length-1].list );
last_li = [ "listitem" ];
list.push(last_li);
} // end depth of shenegains
nl = "";
}
// Add content
if ( l.length > m[0].length ) {
li_accumulate += nl + l.substr( m[0].length );
}
} // tight_search
if ( li_accumulate.length ) {
add( last_li, loose, this.processInline( li_accumulate ), nl );
// Loose mode will have been dealt with. Reset it
loose = false;
li_accumulate = "";
}
// Look at the next block - we might have a loose list. Or an extra
// paragraph for the current li
var contained = get_contained_blocks( stack.length, next );
// Deal with code blocks or properly nested lists
if ( contained.length > 0 ) {
// Make sure all listitems up the stack are paragraphs
forEach( stack, paragraphify, this);
last_li.push.apply( last_li, this.toTree( contained, [] ) );
}
var next_block = next[0] && next[0].valueOf() || "";
if ( next_block.match(is_list_re) || next_block.match( /^ / ) ) {
block = next.shift();
// Check for an HR following a list: features/lists/hr_abutting
var hr = this.dialect.block.horizRule( block, next );
if ( hr ) {
ret.push.apply(ret, hr);
break;
}
// Make sure all listitems up the stack are paragraphs
forEach( stack, paragraphify, this);
loose = true;
continue loose_search;
}
break;
} // loose_search
return ret;
};
})(),
blockquote: function blockquote( block, next ) {
if ( !block.match( /^>/m ) )
return undefined;
var jsonml = [];
// separate out the leading abutting block, if any. I.e. in this case:
//
// a
// > b
//
if ( block[ 0 ] != ">" ) {
var lines = block.split( /\n/ ),
prev = [],
line_no = block.lineNumber;
// keep shifting lines until you find a crotchet
while ( lines.length && lines[ 0 ][ 0 ] != ">" ) {
prev.push( lines.shift() );
line_no++;
}
var abutting = mk_block( prev.join( "\n" ), "\n", block.lineNumber );
jsonml.push.apply( jsonml, this.processBlock( abutting, [] ) );
// reassemble new block of just block quotes!
block = mk_block( lines.join( "\n" ), block.trailing, line_no );
}
// if the next block is also a blockquote merge it in
while ( next.length && next[ 0 ][ 0 ] == ">" ) {
var b = next.shift();
block = mk_block( block + block.trailing + b, b.trailing, block.lineNumber );
}
// Strip off the leading "> " and re-process as a block.
var input = block.replace( /^> ?/gm, "" ),
old_tree = this.tree,
processedBlock = this.toTree( input, [ "blockquote" ] ),
attr = extract_attr( processedBlock );
// If any link references were found get rid of them
if ( attr && attr.references ) {
delete attr.references;
// And then remove the attribute object if it's empty
if ( isEmpty( attr ) ) {
processedBlock.splice( 1, 1 );
}
}
jsonml.push( processedBlock );
return jsonml;
},
referenceDefn: function referenceDefn( block, next) {
var re = /^\s*\[(.*?)\]:\s*(\S+)(?:\s+(?:(['"])(.*?)\3|\((.*?)\)))?\n?/;
// interesting matches are [ , ref_id, url, , title, title ]
if ( !block.match(re) )
return undefined;
// make an attribute node if it doesn't exist
if ( !extract_attr( this.tree ) ) {
this.tree.splice( 1, 0, {} );
}
var attrs = extract_attr( this.tree );
// make a references hash if it doesn't exist
if ( attrs.references === undefined ) {
attrs.references = {};
}
var b = this.loop_re_over_block(re, block, function( m ) {
if ( m[2] && m[2][0] == "<" && m[2][m[2].length-1] == ">" )
m[2] = m[2].substring( 1, m[2].length - 1 );
var ref = attrs.references[ m[1].toLowerCase() ] = {
href: m[2]
};
if ( m[4] !== undefined )
ref.title = m[4];
else if ( m[5] !== undefined )
ref.title = m[5];
} );
if ( b.length )
next.unshift( mk_block( b, block.trailing ) );
return [];
},
para: function para( block, next ) {
// everything's a para!
return [ ["para"].concat( this.processInline( block ) ) ];
}
}
};
Markdown.dialects.Gruber.inline = {
__oneElement__: function oneElement( text, patterns_or_re, previous_nodes ) {
var m,
res,
lastIndex = 0;
patterns_or_re = patterns_or_re || this.dialect.inline.__patterns__;
var re = new RegExp( "([\\s\\S]*?)(" + (patterns_or_re.source || patterns_or_re) + ")" );
m = re.exec( text );
if (!m) {
// Just boring text
return [ text.length, text ];
}
else if ( m[1] ) {
// Some un-interesting text matched. Return that first
return [ m[1].length, m[1] ];
}
var res;
if ( m[2] in this.dialect.inline ) {
res = this.dialect.inline[ m[2] ].call(
this,
text.substr( m.index ), m, previous_nodes || [] );
}
// Default for now to make dev easier. just slurp special and output it.
res = res || [ m[2].length, m[2] ];
return res;
},
__call__: function inline( text, patterns ) {
var out = [],
res;
function add(x) {
//D:self.debug(" adding output", uneval(x));
if ( typeof x == "string" && typeof out[out.length-1] == "string" )
out[ out.length-1 ] += x;
else
out.push(x);
}
while ( text.length > 0 ) {
res = this.dialect.inline.__oneElement__.call(this, text, patterns, out );
text = text.substr( res.shift() );
forEach(res, add )
}
return out;
},
// These characters are intersting elsewhere, so have rules for them so that
// chunks of plain text blocks don't include them
"]": function () {},
"}": function () {},
__escape__ : /^\\[\\`\*_{}\[\]()#\+.!\-]/,
"\\": function escaped( text ) {
// [ length of input processed, node/children to add... ]
// Only esacape: \ ` * _ { } [ ] ( ) # * + - . !
if ( this.dialect.inline.__escape__.exec( text ) )
return [ 2, text.charAt( 1 ) ];
else
// Not an esacpe
return [ 1, "\\" ];
},
"![": function image( text ) {
// Unlike images, alt text is plain text only. no other elements are
// allowed in there
// ![Alt text](/path/to/img.jpg "Optional title")
// 1 2 3 4 <--- captures
var m = text.match( /^!\[(.*?)\][ \t]*\([ \t]*([^")]*?)(?:[ \t]+(["'])(.*?)\3)?[ \t]*\)/ );
if ( m ) {
if ( m[2] && m[2][0] == "<" && m[2][m[2].length-1] == ">" )
m[2] = m[2].substring( 1, m[2].length - 1 );
m[2] = this.dialect.inline.__call__.call( this, m[2], /\\/ )[0];
var attrs = { alt: m[1], href: m[2] || "" };
if ( m[4] !== undefined)
attrs.title = m[4];
return [ m[0].length, [ "img", attrs ] ];
}
// ![Alt text][id]
m = text.match( /^!\[(.*?)\][ \t]*\[(.*?)\]/ );
if ( m ) {
// We can't check if the reference is known here as it likely wont be
// found till after. Check it in md tree->hmtl tree conversion
return [ m[0].length, [ "img_ref", { alt: m[1], ref: m[2].toLowerCase(), original: m[0] } ] ];
}
// Just consume the '!['
return [ 2, "![" ];
},
"[": function link( text ) {
var orig = String(text);
// Inline content is possible inside `link text`
var res = Markdown.DialectHelpers.inline_until_char.call( this, text.substr(1), "]" );
// No closing ']' found. Just consume the [
if ( !res ) return [ 1, "[" ];
var consumed = 1 + res[ 0 ],
children = res[ 1 ],
link,
attrs;
// At this point the first [...] has been parsed. See what follows to find
// out which kind of link we are (reference or direct url)
text = text.substr( consumed );
// [link text](/path/to/img.jpg "Optional title")
// 1 2 3 <--- captures
// This will capture up to the last paren in the block. We then pull
// back based on if there a matching ones in the url
// ([here](/url/(test))
// The parens have to be balanced
var m = text.match( /^\s*\([ \t]*([^"']*)(?:[ \t]+(["'])(.*?)\2)?[ \t]*\)/ );
if ( m ) {
var url = m[1];
consumed += m[0].length;
if ( url && url[0] == "<" && url[url.length-1] == ">" )
url = url.substring( 1, url.length - 1 );
// If there is a title we don't have to worry about parens in the url
if ( !m[3] ) {
var open_parens = 1; // One open that isn't in the capture
for ( var len = 0; len < url.length; len++ ) {
switch ( url[len] ) {
case "(":
open_parens++;
break;
case ")":
if ( --open_parens == 0) {
consumed -= url.length - len;
url = url.substring(0, len);
}
break;
}
}
}
// Process escapes only
url = this.dialect.inline.__call__.call( this, url, /\\/ )[0];
attrs = { href: url || "" };
if ( m[3] !== undefined)
attrs.title = m[3];
link = [ "link", attrs ].concat( children );
return [ consumed, link ];
}
// [Alt text][id]
// [Alt text] [id]
m = text.match( /^\s*\[(.*?)\]/ );
if ( m ) {
consumed += m[ 0 ].length;
// [links][] uses links as its reference
attrs = { ref: ( m[ 1 ] || String(children) ).toLowerCase(), original: orig.substr( 0, consumed ) };
link = [ "link_ref", attrs ].concat( children );
// We can't check if the reference is known here as it likely wont be
// found till after. Check it in md tree->hmtl tree conversion.
// Store the original so that conversion can revert if the ref isn't found.
return [ consumed, link ];
}
// [id]
// Only if id is plain (no formatting.)
if ( children.length == 1 && typeof children[0] == "string" ) {
attrs = { ref: children[0].toLowerCase(), original: orig.substr( 0, consumed ) };
link = [ "link_ref", attrs, children[0] ];
return [ consumed, link ];
}
// Just consume the "["
return [ 1, "[" ];
},
"<": function autoLink( text ) {
var m;
if ( ( m = text.match( /^<(?:((https?|ftp|mailto):[^>]+)|(.*?@.*?\.[a-zA-Z]+))>/ ) ) != null ) {
if ( m[3] ) {
return [ m[0].length, [ "link", { href: "mailto:" + m[3] }, m[3] ] ];
}
else if ( m[2] == "mailto" ) {
return [ m[0].length, [ "link", { href: m[1] }, m[1].substr("mailto:".length ) ] ];
}
else
return [ m[0].length, [ "link", { href: m[1] }, m[1] ] ];
}
return [ 1, "<" ];
},
"`": function inlineCode( text ) {
// Inline code block. as many backticks as you like to start it
// Always skip over the opening ticks.
var m = text.match( /(`+)(([\s\S]*?)\1)/ );
if ( m && m[2] )
return [ m[1].length + m[2].length, [ "inlinecode", m[3] ] ];
else {
// TODO: No matching end code found - warn!
return [ 1, "`" ];
}
},
" \n": function lineBreak( text ) {
return [ 3, [ "linebreak" ] ];
}
};
// Meta Helper/generator method for em and strong handling
function strong_em( tag, md ) {
var state_slot = tag + "_state",
other_slot = tag == "strong" ? "em_state" : "strong_state";
function CloseTag(len) {
this.len_after = len;
this.name = "close_" + md;
}
return function ( text, orig_match ) {
if ( this[state_slot][0] == md ) {
// Most recent em is of this type
//D:this.debug("closing", md);
this[state_slot].shift();
// "Consume" everything to go back to the recrusion in the else-block below
return[ text.length, new CloseTag(text.length-md.length) ];
}
else {
// Store a clone of the em/strong states
var other = this[other_slot].slice(),
state = this[state_slot].slice();
this[state_slot].unshift(md);
//D:this.debug_indent += " ";
// Recurse
var res = this.processInline( text.substr( md.length ) );
//D:this.debug_indent = this.debug_indent.substr(2);
var last = res[res.length - 1];
//D:this.debug("processInline from", tag + ": ", uneval( res ) );
var check = this[state_slot].shift();
if ( last instanceof CloseTag ) {
res.pop();
// We matched! Huzzah.
var consumed = text.length - last.len_after;
return [ consumed, [ tag ].concat(res) ];
}
else {
// Restore the state of the other kind. We might have mistakenly closed it.
this[other_slot] = other;
this[state_slot] = state;
// We can't reuse the processed result as it could have wrong parsing contexts in it.
return [ md.length, md ];
}
}
}; // End returned function
}
Markdown.dialects.Gruber.inline["**"] = strong_em("strong", "**");
Markdown.dialects.Gruber.inline["__"] = strong_em("strong", "__");
Markdown.dialects.Gruber.inline["*"] = strong_em("em", "*");
Markdown.dialects.Gruber.inline["_"] = strong_em("em", "_");
// Build default order from insertion order.
Markdown.buildBlockOrder = function(d) {
var ord = [];
for ( var i in d ) {
if ( i == "__order__" || i == "__call__" ) continue;
ord.push( i );
}
d.__order__ = ord;
};
// Build patterns for inline matcher
Markdown.buildInlinePatterns = function(d) {
var patterns = [];
for ( var i in d ) {
// __foo__ is reserved and not a pattern
if ( i.match( /^__.*__$/) ) continue;
var l = i.replace( /([\\.*+?|()\[\]{}])/g, "\\$1" )
.replace( /\n/, "\\n" );
patterns.push( i.length == 1 ? l : "(?:" + l + ")" );
}
patterns = patterns.join("|");
d.__patterns__ = patterns;
//print("patterns:", uneval( patterns ) );
var fn = d.__call__;
d.__call__ = function(text, pattern) {
if ( pattern != undefined ) {
return fn.call(this, text, pattern);
}
else
{
return fn.call(this, text, patterns);
}
};
};
Markdown.DialectHelpers = {};
Markdown.DialectHelpers.inline_until_char = function( text, want ) {
var consumed = 0,
nodes = [];
while ( true ) {
if ( text.charAt( consumed ) == want ) {
// Found the character we were looking for
consumed++;
return [ consumed, nodes ];
}
if ( consumed >= text.length ) {
// No closing char found. Abort.
return null;
}
var res = this.dialect.inline.__oneElement__.call(this, text.substr( consumed ) );
consumed += res[ 0 ];
// Add any returned nodes.
nodes.push.apply( nodes, res.slice( 1 ) );
}
}
// Helper function to make sub-classing a dialect easier
Markdown.subclassDialect = function( d ) {
function Block() {}
Block.prototype = d.block;
function Inline() {}
Inline.prototype = d.inline;
return { block: new Block(), inline: new Inline() };
};
Markdown.buildBlockOrder ( Markdown.dialects.Gruber.block );
Markdown.buildInlinePatterns( Markdown.dialects.Gruber.inline );
Markdown.dialects.Maruku = Markdown.subclassDialect( Markdown.dialects.Gruber );
Markdown.dialects.Maruku.processMetaHash = function processMetaHash( meta_string ) {
var meta = split_meta_hash( meta_string ),
attr = {};
for ( var i = 0; i < meta.length; ++i ) {
// id: #foo
if ( /^#/.test( meta[ i ] ) ) {
attr.id = meta[ i ].substring( 1 );
}
// class: .foo
else if ( /^\./.test( meta[ i ] ) ) {
// if class already exists, append the new one
if ( attr["class"] ) {
attr["class"] = attr["class"] + meta[ i ].replace( /./, " " );
}
else {
attr["class"] = meta[ i ].substring( 1 );
}
}
// attribute: foo=bar
else if ( /\=/.test( meta[ i ] ) ) {
var s = meta[ i ].split( /\=/ );
attr[ s[ 0 ] ] = s[ 1 ];
}
}
return attr;
}
function split_meta_hash( meta_string ) {
var meta = meta_string.split( "" ),
parts = [ "" ],
in_quotes = false;
while ( meta.length ) {
var letter = meta.shift();
switch ( letter ) {
case " " :
// if we're in a quoted section, keep it
if ( in_quotes ) {
parts[ parts.length - 1 ] += letter;
}
// otherwise make a new part
else {
parts.push( "" );
}
break;
case "'" :
case '"' :
// reverse the quotes and move straight on
in_quotes = !in_quotes;
break;
case "\\" :
// shift off the next letter to be used straight away.
// it was escaped so we'll keep it whatever it is
letter = meta.shift();
default :
parts[ parts.length - 1 ] += letter;
break;
}
}
return parts;
}
Markdown.dialects.Maruku.block.document_meta = function document_meta( block, next ) {
// we're only interested in the first block
if ( block.lineNumber > 1 ) return undefined;
// document_meta blocks consist of one or more lines of `Key: Value\n`
if ( ! block.match( /^(?:\w+:.*\n)*\w+:.*$/ ) ) return undefined;
// make an attribute node if it doesn't exist
if ( !extract_attr( this.tree ) ) {
this.tree.splice( 1, 0, {} );
}
var pairs = block.split( /\n/ );
for ( p in pairs ) {
var m = pairs[ p ].match( /(\w+):\s*(.*)$/ ),
key = m[ 1 ].toLowerCase(),
value = m[ 2 ];
this.tree[ 1 ][ key ] = value;
}
// document_meta produces no content!
return [];
};
Markdown.dialects.Maruku.block.block_meta = function block_meta( block, next ) {
// check if the last line of the block is an meta hash
var m = block.match( /(^|\n) {0,3}\{:\s*((?:\\\}|[^\}])*)\s*\}$/ );
if ( !m ) return undefined;
// process the meta hash
var attr = this.dialect.processMetaHash( m[ 2 ] );
var hash;
// if we matched ^ then we need to apply meta to the previous block
if ( m[ 1 ] === "" ) {
var node = this.tree[ this.tree.length - 1 ];
hash = extract_attr( node );
// if the node is a string (rather than JsonML), bail
if ( typeof node === "string" ) return undefined;
// create the attribute hash if it doesn't exist
if ( !hash ) {
hash = {};
node.splice( 1, 0, hash );
}
// add the attributes in
for ( a in attr ) {
hash[ a ] = attr[ a ];
}
// return nothing so the meta hash is removed
return [];
}
// pull the meta hash off the block and process what's left
var b = block.replace( /\n.*$/, "" ),
result = this.processBlock( b, [] );
// get or make the attributes hash
hash = extract_attr( result[ 0 ] );
if ( !hash ) {
hash = {};
result[ 0 ].splice( 1, 0, hash );
}
// attach the attributes to the block
for ( a in attr ) {
hash[ a ] = attr[ a ];
}
return result;
};
Markdown.dialects.Maruku.block.definition_list = function definition_list( block, next ) {
// one or more terms followed by one or more definitions, in a single block
var tight = /^((?:[^\s:].*\n)+):\s+([\s\S]+)$/,
list = [ "dl" ],
i, m;
// see if we're dealing with a tight or loose block
if ( ( m = block.match( tight ) ) ) {
// pull subsequent tight DL blocks out of `next`
var blocks = [ block ];
while ( next.length && tight.exec( next[ 0 ] ) ) {
blocks.push( next.shift() );
}
for ( var b = 0; b < blocks.length; ++b ) {
var m = blocks[ b ].match( tight ),
terms = m[ 1 ].replace( /\n$/, "" ).split( /\n/ ),
defns = m[ 2 ].split( /\n:\s+/ );
// print( uneval( m ) );
for ( i = 0; i < terms.length; ++i ) {
list.push( [ "dt", terms[ i ] ] );
}
for ( i = 0; i < defns.length; ++i ) {
// run inline processing over the definition
list.push( [ "dd" ].concat( this.processInline( defns[ i ].replace( /(\n)\s+/, "$1" ) ) ) );
}
}
}
else {
return undefined;
}
return [ list ];
};
// splits on unescaped instances of @ch. If @ch is not a character the result
// can be unpredictable
Markdown.dialects.Maruku.block.table = function table (block, next) {
var _split_on_unescaped = function(s, ch) {
ch = ch || '\\s';
if (ch.match(/^[\\|\[\]{}?*.+^$]$/)) { ch = '\\' + ch; }
var res = [ ],
r = new RegExp('^((?:\\\\.|[^\\\\' + ch + '])*)' + ch + '(.*)'),
m;
while(m = s.match(r)) {
res.push(m[1]);
s = m[2];
}
res.push(s);
return res;
}
var leading_pipe = /^ {0,3}\|(.+)\n {0,3}\|\s*([\-:]+[\-| :]*)\n((?:\s*\|.*(?:\n|$))*)(?=\n|$)/,
// find at least an unescaped pipe in each line
no_leading_pipe = /^ {0,3}(\S(?:\\.|[^\\|])*\|.*)\n {0,3}([\-:]+\s*\|[\-| :]*)\n((?:(?:\\.|[^\\|])*\|.*(?:\n|$))*)(?=\n|$)/,
i, m;
if (m = block.match(leading_pipe)) {
// remove leading pipes in contents
// (header and horizontal rule already have the leading pipe left out)
m[3] = m[3].replace(/^\s*\|/gm, '');
} else if (! ( m = block.match(no_leading_pipe))) {
return undefined;
}
var table = [ "table", [ "thead", [ "tr" ] ], [ "tbody" ] ];
// remove trailing pipes, then split on pipes
// (no escaped pipes are allowed in horizontal rule)
m[2] = m[2].replace(/\|\s*$/, '').split('|');
// process alignment
var html_attrs = [ ];
forEach (m[2], function (s) {
if (s.match(/^\s*-+:\s*$/)) html_attrs.push({align: "right"});
else if (s.match(/^\s*:-+\s*$/)) html_attrs.push({align: "left"});
else if (s.match(/^\s*:-+:\s*$/)) html_attrs.push({align: "center"});
else html_attrs.push({});
});
// now for the header, avoid escaped pipes
m[1] = _split_on_unescaped(m[1].replace(/\|\s*$/, ''), '|');
for (i = 0; i < m[1].length; i++) {
table[1][1].push(['th', html_attrs[i] || {}].concat(
this.processInline(m[1][i].trim())));
}
// now for body contents
forEach (m[3].replace(/\|\s*$/mg, '').split('\n'), function (row) {
var html_row = ['tr'];
row = _split_on_unescaped(row, '|');
for (i = 0; i < row.length; i++) {
html_row.push(['td', html_attrs[i] || {}].concat(this.processInline(row[i].trim())));
}
table[2].push(html_row);
}, this);
return [table];
}
Markdown.dialects.Maruku.inline[ "{:" ] = function inline_meta( text, matches, out ) {
if ( !out.length ) {
return [ 2, "{:" ];
}
// get the preceeding element
var before = out[ out.length - 1 ];
if ( typeof before === "string" ) {
return [ 2, "{:" ];
}
// match a meta hash
var m = text.match( /^\{:\s*((?:\\\}|[^\}])*)\s*\}/ );
// no match, false alarm
if ( !m ) {
return [ 2, "{:" ];
}
// attach the attributes to the preceeding element
var meta = this.dialect.processMetaHash( m[ 1 ] ),
attr = extract_attr( before );
if ( !attr ) {
attr = {};
before.splice( 1, 0, attr );
}
for ( var k in meta ) {
attr[ k ] = meta[ k ];
}
// cut out the string and replace it with nothing
return [ m[ 0 ].length, "" ];
};
Markdown.dialects.Maruku.inline.__escape__ = /^\\[\\`\*_{}\[\]()#\+.!\-|:]/;
Markdown.buildBlockOrder ( Markdown.dialects.Maruku.block );
Markdown.buildInlinePatterns( Markdown.dialects.Maruku.inline );
var isArray = Array.isArray || function(obj) {
return Object.prototype.toString.call(obj) == "[object Array]";
};
var forEach;
// Don't mess with Array.prototype. Its not friendly
if ( Array.prototype.forEach ) {
forEach = function( arr, cb, thisp ) {
return arr.forEach( cb, thisp );
};
}
else {
forEach = function(arr, cb, thisp) {
for (var i = 0; i < arr.length; i++) {
cb.call(thisp || arr, arr[i], i, arr);
}
}
}
var isEmpty = function( obj ) {
for ( var key in obj ) {
if ( hasOwnProperty.call( obj, key ) ) {
return false;
}
}
return true;
}
function extract_attr( jsonml ) {
return isArray(jsonml)
&& jsonml.length > 1
&& typeof jsonml[ 1 ] === "object"
&& !( isArray(jsonml[ 1 ]) )
? jsonml[ 1 ]
: undefined;
}
/**
* renderJsonML( jsonml[, options] ) -> String
* - jsonml (Array): JsonML array to render to XML
* - options (Object): options
*
* Converts the given JsonML into well-formed XML.
*
* The options currently understood are:
*
* - root (Boolean): wether or not the root node should be included in the
* output, or just its children. The default `false` is to not include the
* root itself.
*/
expose.renderJsonML = function( jsonml, options ) {
options = options || {};
// include the root element in the rendered output?
options.root = options.root || false;
var content = [];
if ( options.root ) {
content.push( render_tree( jsonml ) );
}
else {
jsonml.shift(); // get rid of the tag
if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) {
jsonml.shift(); // get rid of the attributes
}
while ( jsonml.length ) {
content.push( render_tree( jsonml.shift() ) );
}
}
return content.join( "\n\n" );
};
function escapeHTML( text ) {
return text.replace( /&/g, "&amp;" )
.replace( /</g, "&lt;" )
.replace( />/g, "&gt;" )
.replace( /"/g, "&quot;" )
.replace( /'/g, "&#39;" );
}
function render_tree( jsonml ) {
// basic case
if ( typeof jsonml === "string" ) {
return escapeHTML( jsonml );
}
var tag = jsonml.shift(),
attributes = {},
content = [];
if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) {
attributes = jsonml.shift();
}
while ( jsonml.length ) {
content.push( render_tree( jsonml.shift() ) );
}
var tag_attrs = "";
for ( var a in attributes ) {
tag_attrs += " " + a + '="' + escapeHTML( attributes[ a ] ) + '"';
}
// be careful about adding whitespace here for inline elements
if ( tag == "img" || tag == "br" || tag == "hr" ) {
return "<"+ tag + tag_attrs + "/>";
}
else {
return "<"+ tag + tag_attrs + ">" + content.join( "" ) + "</" + tag + ">";
}
}
function convert_tree_to_html( tree, references, options ) {
var i;
options = options || {};
// shallow clone
var jsonml = tree.slice( 0 );
if ( typeof options.preprocessTreeNode === "function" ) {
jsonml = options.preprocessTreeNode(jsonml, references);
}
// Clone attributes if they exist
var attrs = extract_attr( jsonml );
if ( attrs ) {
jsonml[ 1 ] = {};
for ( i in attrs ) {
jsonml[ 1 ][ i ] = attrs[ i ];
}
attrs = jsonml[ 1 ];
}
// basic case
if ( typeof jsonml === "string" ) {
return jsonml;
}
// convert this node
switch ( jsonml[ 0 ] ) {
case "header":
jsonml[ 0 ] = "h" + jsonml[ 1 ].level;
delete jsonml[ 1 ].level;
break;
case "bulletlist":
jsonml[ 0 ] = "ul";
break;
case "numberlist":
jsonml[ 0 ] = "ol";
break;
case "listitem":
jsonml[ 0 ] = "li";
break;
case "para":
jsonml[ 0 ] = "p";
break;
case "markdown":
jsonml[ 0 ] = "html";
if ( attrs ) delete attrs.references;
break;
case "code_block":
jsonml[ 0 ] = "pre";
i = attrs ? 2 : 1;
var code = [ "code" ];
code.push.apply( code, jsonml.splice( i, jsonml.length - i ) );
jsonml[ i ] = code;
break;
case "inlinecode":
jsonml[ 0 ] = "code";
break;
case "img":
jsonml[ 1 ].src = jsonml[ 1 ].href;
delete jsonml[ 1 ].href;
break;
case "linebreak":
jsonml[ 0 ] = "br";
break;
case "link":
jsonml[ 0 ] = "a";
break;
case "link_ref":
jsonml[ 0 ] = "a";
// grab this ref and clean up the attribute node
var ref = references[ attrs.ref ];
// if the reference exists, make the link
if ( ref ) {
delete attrs.ref;
// add in the href and title, if present
attrs.href = ref.href;
if ( ref.title ) {
attrs.title = ref.title;
}
// get rid of the unneeded original text
delete attrs.original;
}
// the reference doesn't exist, so revert to plain text
else {
return attrs.original;
}
break;
case "img_ref":
jsonml[ 0 ] = "img";
// grab this ref and clean up the attribute node
var ref = references[ attrs.ref ];
// if the reference exists, make the link
if ( ref ) {
delete attrs.ref;
// add in the href and title, if present
attrs.src = ref.href;
if ( ref.title ) {
attrs.title = ref.title;
}
// get rid of the unneeded original text
delete attrs.original;
}
// the reference doesn't exist, so revert to plain text
else {
return attrs.original;
}
break;
}
// convert all the children
i = 1;
// deal with the attribute node, if it exists
if ( attrs ) {
// if there are keys, skip over it
for ( var key in jsonml[ 1 ] ) {
i = 2;
break;
}
// if there aren't, remove it
if ( i === 1 ) {
jsonml.splice( i, 1 );
}
}
for ( ; i < jsonml.length; ++i ) {
jsonml[ i ] = convert_tree_to_html( jsonml[ i ], references, options );
}
return jsonml;
}
// merges adjacent text nodes into a single node
function merge_text_nodes( jsonml ) {
// skip the tag name and attribute hash
var i = extract_attr( jsonml ) ? 2 : 1;
while ( i < jsonml.length ) {
// if it's a string check the next item too
if ( typeof jsonml[ i ] === "string" ) {
if ( i + 1 < jsonml.length && typeof jsonml[ i + 1 ] === "string" ) {
// merge the second string into the first and remove it
jsonml[ i ] += jsonml.splice( i + 1, 1 )[ 0 ];
}
else {
++i;
}
}
// if it's not a string recurse
else {
merge_text_nodes( jsonml[ i ] );
++i;
}
}
}
} )( (function() {
if ( typeof exports === "undefined" ) {
window.markdown = {};
return window.markdown;
}
else {
return exports;
}
} )() );
},{"util":97}],16:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var Data;
Data = (function() {
function Data(data) {
this.data = data != null ? data : [];
this.pos = 0;
this.length = this.data.length;
}
Data.prototype.readByte = function() {
return this.data[this.pos++];
};
Data.prototype.writeByte = function(byte) {
return this.data[this.pos++] = byte;
};
Data.prototype.byteAt = function(index) {
return this.data[index];
};
Data.prototype.readBool = function() {
return !!this.readByte();
};
Data.prototype.writeBool = function(val) {
return this.writeByte(val ? 1 : 0);
};
Data.prototype.readUInt32 = function() {
var b1, b2, b3, b4;
b1 = this.readByte() * 0x1000000;
b2 = this.readByte() << 16;
b3 = this.readByte() << 8;
b4 = this.readByte();
return b1 + b2 + b3 + b4;
};
Data.prototype.writeUInt32 = function(val) {
this.writeByte((val >>> 24) & 0xff);
this.writeByte((val >> 16) & 0xff);
this.writeByte((val >> 8) & 0xff);
return this.writeByte(val & 0xff);
};
Data.prototype.readInt32 = function() {
var int;
int = this.readUInt32();
if (int >= 0x80000000) {
return int - 0x100000000;
} else {
return int;
}
};
Data.prototype.writeInt32 = function(val) {
if (val < 0) {
val += 0x100000000;
}
return this.writeUInt32(val);
};
Data.prototype.readUInt16 = function() {
var b1, b2;
b1 = this.readByte() << 8;
b2 = this.readByte();
return b1 | b2;
};
Data.prototype.writeUInt16 = function(val) {
this.writeByte((val >> 8) & 0xff);
return this.writeByte(val & 0xff);
};
Data.prototype.readInt16 = function() {
var int;
int = this.readUInt16();
if (int >= 0x8000) {
return int - 0x10000;
} else {
return int;
}
};
Data.prototype.writeInt16 = function(val) {
if (val < 0) {
val += 0x10000;
}
return this.writeUInt16(val);
};
Data.prototype.readString = function(length) {
var i, ret, _i;
ret = [];
for (i = _i = 0; 0 <= length ? _i < length : _i > length; i = 0 <= length ? ++_i : --_i) {
ret[i] = String.fromCharCode(this.readByte());
}
return ret.join('');
};
Data.prototype.writeString = function(val) {
var i, _i, _ref, _results;
_results = [];
for (i = _i = 0, _ref = val.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
_results.push(this.writeByte(val.charCodeAt(i)));
}
return _results;
};
Data.prototype.stringAt = function(pos, length) {
this.pos = pos;
return this.readString(length);
};
Data.prototype.readShort = function() {
return this.readInt16();
};
Data.prototype.writeShort = function(val) {
return this.writeInt16(val);
};
Data.prototype.readLongLong = function() {
var b1, b2, b3, b4, b5, b6, b7, b8;
b1 = this.readByte();
b2 = this.readByte();
b3 = this.readByte();
b4 = this.readByte();
b5 = this.readByte();
b6 = this.readByte();
b7 = this.readByte();
b8 = this.readByte();
if (b1 & 0x80) {
return ((b1 ^ 0xff) * 0x100000000000000 + (b2 ^ 0xff) * 0x1000000000000 + (b3 ^ 0xff) * 0x10000000000 + (b4 ^ 0xff) * 0x100000000 + (b5 ^ 0xff) * 0x1000000 + (b6 ^ 0xff) * 0x10000 + (b7 ^ 0xff) * 0x100 + (b8 ^ 0xff) + 1) * -1;
}
return b1 * 0x100000000000000 + b2 * 0x1000000000000 + b3 * 0x10000000000 + b4 * 0x100000000 + b5 * 0x1000000 + b6 * 0x10000 + b7 * 0x100 + b8;
};
Data.prototype.writeLongLong = function(val) {
var high, low;
high = Math.floor(val / 0x100000000);
low = val & 0xffffffff;
this.writeByte((high >> 24) & 0xff);
this.writeByte((high >> 16) & 0xff);
this.writeByte((high >> 8) & 0xff);
this.writeByte(high & 0xff);
this.writeByte((low >> 24) & 0xff);
this.writeByte((low >> 16) & 0xff);
this.writeByte((low >> 8) & 0xff);
return this.writeByte(low & 0xff);
};
Data.prototype.readInt = function() {
return this.readInt32();
};
Data.prototype.writeInt = function(val) {
return this.writeInt32(val);
};
Data.prototype.slice = function(start, end) {
return this.data.slice(start, end);
};
Data.prototype.read = function(bytes) {
var buf, i, _i;
buf = [];
for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) {
buf.push(this.readByte());
}
return buf;
};
Data.prototype.write = function(bytes) {
var byte, _i, _len, _results;
_results = [];
for (_i = 0, _len = bytes.length; _i < _len; _i++) {
byte = bytes[_i];
_results.push(this.writeByte(byte));
}
return _results;
};
return Data;
})();
module.exports = Data;
}).call(this);
},{}],17:[function(require,module,exports){
(function (Buffer){
// Generated by CoffeeScript 1.7.1
/*
PDFDocument - represents an entire PDF document
By Devon Govett
*/
(function() {
var PDFDocument, PDFObject, PDFPage, PDFReference, fs, stream,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
stream = require('stream');
fs = require('fs');
PDFObject = require('./object');
PDFReference = require('./reference');
PDFPage = require('./page');
PDFDocument = (function(_super) {
var mixin;
__extends(PDFDocument, _super);
function PDFDocument(options) {
var key, val, _ref, _ref1;
this.options = options != null ? options : {};
PDFDocument.__super__.constructor.apply(this, arguments);
this.version = 1.3;
this.compress = (_ref = this.options.compress) != null ? _ref : true;
this._pageBuffer = [];
this._pageBufferStart = 0;
this._offsets = [];
this._waiting = 0;
this._ended = false;
this._offset = 0;
this._root = this.ref({
Type: 'Catalog',
Pages: this.ref({
Type: 'Pages',
Count: 0,
Kids: []
})
});
this.page = null;
this.initColor();
this.initVector();
this.initFonts();
this.initText();
this.initImages();
this.info = {
Producer: 'PDFKit',
Creator: 'PDFKit',
CreationDate: new Date()
};
if (this.options.info) {
_ref1 = this.options.info;
for (key in _ref1) {
val = _ref1[key];
this.info[key] = val;
}
}
this._write("%PDF-" + this.version);
this._write("%\xFF\xFF\xFF\xFF");
this.addPage();
}
mixin = function(methods) {
var method, name, _results;
_results = [];
for (name in methods) {
method = methods[name];
_results.push(PDFDocument.prototype[name] = method);
}
return _results;
};
mixin(require('./mixins/color'));
mixin(require('./mixins/vector'));
mixin(require('./mixins/fonts'));
mixin(require('./mixins/text'));
mixin(require('./mixins/images'));
mixin(require('./mixins/annotations'));
PDFDocument.prototype.addPage = function(options) {
var pages;
if (options == null) {
options = this.options;
}
if (!this.options.bufferPages) {
this.flushPages();
}
this.page = new PDFPage(this, options);
this._pageBuffer.push(this.page);
pages = this._root.data.Pages.data;
pages.Kids.push(this.page.dictionary);
pages.Count++;
this.x = this.page.margins.left;
this.y = this.page.margins.top;
this._ctm = [1, 0, 0, 1, 0, 0];
this.transform(1, 0, 0, -1, 0, this.page.height);
return this;
};
PDFDocument.prototype.bufferedPageRange = function() {
return {
start: this._pageBufferStart,
count: this._pageBuffer.length
};
};
PDFDocument.prototype.switchToPage = function(n) {
var page;
if (!(page = this._pageBuffer[n - this._pageBufferStart])) {
throw new Error("switchToPage(" + n + ") out of bounds, current buffer covers pages " + this._pageBufferStart + " to " + (this._pageBufferStart + this._pageBuffer.length - 1));
}
return this.page = page;
};
PDFDocument.prototype.flushPages = function() {
var page, pages, _i, _len;
pages = this._pageBuffer;
this._pageBuffer = [];
this._pageBufferStart += pages.length;
for (_i = 0, _len = pages.length; _i < _len; _i++) {
page = pages[_i];
page.end();
}
};
PDFDocument.prototype.ref = function(data) {
var ref;
ref = new PDFReference(this, this._offsets.length + 1, data);
this._offsets.push(null);
this._waiting++;
return ref;
};
PDFDocument.prototype._read = function() {};
PDFDocument.prototype._write = function(data) {
if (!Buffer.isBuffer(data)) {
data = new Buffer(data + '\n', 'binary');
}
this.push(data);
return this._offset += data.length;
};
PDFDocument.prototype.addContent = function(data) {
this.page.write(data);
return this;
};
PDFDocument.prototype._refEnd = function(ref) {
this._offsets[ref.id - 1] = ref.offset;
if (--this._waiting === 0 && this._ended) {
this._finalize();
return this._ended = false;
}
};
PDFDocument.prototype.write = function(filename, fn) {
var err;
err = new Error('PDFDocument#write is deprecated, and will be removed in a future version of PDFKit. Please pipe the document into a Node stream.');
console.warn(err.stack);
this.pipe(fs.createWriteStream(filename));
this.end();
return this.once('end', fn);
};
PDFDocument.prototype.output = function(fn) {
throw new Error('PDFDocument#output is deprecated, and has been removed from PDFKit. Please pipe the document into a Node stream.');
};
PDFDocument.prototype.end = function() {
var font, key, name, val, _ref, _ref1;
this.flushPages();
this._info = this.ref();
_ref = this.info;
for (key in _ref) {
val = _ref[key];
if (typeof val === 'string') {
val = new String(val);
}
this._info.data[key] = val;
}
this._info.end();
_ref1 = this._fontFamilies;
for (name in _ref1) {
font = _ref1[name];
font.embed();
}
this._root.end();
this._root.data.Pages.end();
if (this._waiting === 0) {
return this._finalize();
} else {
return this._ended = true;
}
};
PDFDocument.prototype._finalize = function(fn) {
var offset, xRefOffset, _i, _len, _ref;
xRefOffset = this._offset;
this._write("xref");
this._write("0 " + (this._offsets.length + 1));
this._write("0000000000 65535 f ");
_ref = this._offsets;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
offset = _ref[_i];
offset = ('0000000000' + offset).slice(-10);
this._write(offset + ' 00000 n ');
}
this._write('trailer');
this._write(PDFObject.convert({
Size: this._offsets.length + 1,
Root: this._root,
Info: this._info
}));
this._write('startxref');
this._write("" + xRefOffset);
this._write('%%EOF');
return this.push(null);
};
PDFDocument.prototype.toString = function() {
return "[object PDFDocument]";
};
return PDFDocument;
})(stream.Readable);
module.exports = PDFDocument;
}).call(this);
}).call(this,require("buffer").Buffer)
},{"./mixins/annotations":41,"./mixins/color":42,"./mixins/fonts":43,"./mixins/images":44,"./mixins/text":45,"./mixins/vector":46,"./object":47,"./page":48,"./reference":50,"buffer":74,"fs":58,"stream":94}],18:[function(require,module,exports){
(function (Buffer){
// Generated by CoffeeScript 1.7.1
/*
PDFFont - embeds fonts in PDF documents
By Devon Govett
*/
(function() {
var AFMFont, PDFFont, Subset, TTFFont, fs;
TTFFont = require('./font/ttf');
AFMFont = require('./font/afm');
Subset = require('./font/subset');
fs = require('fs');
PDFFont = (function() {
var STANDARD_FONTS, toUnicodeCmap;
function PDFFont(document, src, family, id) {
this.document = document;
this.id = id;
if (typeof src === 'string') {
if (src in STANDARD_FONTS) {
this.isAFM = true;
this.font = new AFMFont(STANDARD_FONTS[src]());
this.registerAFM(src);
return;
} else if (/\.(ttf|ttc)$/i.test(src)) {
this.font = TTFFont.open(src, family);
} else if (/\.dfont$/i.test(src)) {
this.font = TTFFont.fromDFont(src, family);
} else {
throw new Error('Not a supported font format or standard PDF font.');
}
} else if (Buffer.isBuffer(src)) {
this.font = TTFFont.fromBuffer(src, family);
} else if (src instanceof Uint8Array) {
this.font = TTFFont.fromBuffer(new Buffer(src), family);
} else if (src instanceof ArrayBuffer) {
this.font = TTFFont.fromBuffer(new Buffer(new Uint8Array(src)), family);
} else {
throw new Error('Not a supported font format or standard PDF font.');
}
this.subset = new Subset(this.font);
this.registerTTF();
}
STANDARD_FONTS = {
"Courier": function() {
return "StartFontMetrics 4.1\nComment Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.\nComment Creation Date: Thu May 1 17:27:09 1997\nComment UniqueID 43050\nComment VMusage 39754 50779\nFontName Courier\nFullName Courier\nFamilyName Courier\nWeight Medium\nItalicAngle 0\nIsFixedPitch true\nCharacterSet ExtendedRoman\nFontBBox -23 -250 715 805 \nUnderlinePosition -100\nUnderlineThickness 50\nVersion 003.000\nNotice Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.\nEncodingScheme AdobeStandardEncoding\nCapHeight 562\nXHeight 426\nAscender 629\nDescender -157\nStdHW 51\nStdVW 51\nStartCharMetrics 315\nC 32 ; WX 600 ; N space ; B 0 0 0 0 ;\nC 33 ; WX 600 ; N exclam ; B 236 -15 364 572 ;\nC 34 ; WX 600 ; N quotedbl ; B 187 328 413 562 ;\nC 35 ; WX 600 ; N numbersign ; B 93 -32 507 639 ;\nC 36 ; WX 600 ; N dollar ; B 105 -126 496 662 ;\nC 37 ; WX 600 ; N percent ; B 81 -15 518 622 ;\nC 38 ; WX 600 ; N ampersand ; B 63 -15 538 543 ;\nC 39 ; WX 600 ; N quoteright ; B 213 328 376 562 ;\nC 40 ; WX 600 ; N parenleft ; B 269 -108 440 622 ;\nC 41 ; WX 600 ; N parenright ; B 160 -108 331 622 ;\nC 42 ; WX 600 ; N asterisk ; B 116 257 484 607 ;\nC 43 ; WX 600 ; N plus ; B 80 44 520 470 ;\nC 44 ; WX 600 ; N comma ; B 181 -112 344 122 ;\nC 45 ; WX 600 ; N hyphen ; B 103 231 497 285 ;\nC 46 ; WX 600 ; N period ; B 229 -15 371 109 ;\nC 47 ; WX 600 ; N slash ; B 125 -80 475 629 ;\nC 48 ; WX 600 ; N zero ; B 106 -15 494 622 ;\nC 49 ; WX 600 ; N one ; B 96 0 505 622 ;\nC 50 ; WX 600 ; N two ; B 70 0 471 622 ;\nC 51 ; WX 600 ; N three ; B 75 -15 466 622 ;\nC 52 ; WX 600 ; N four ; B 78 0 500 622 ;\nC 53 ; WX 600 ; N five ; B 92 -15 497 607 ;\nC 54 ; WX 600 ; N six ; B 111 -15 497 622 ;\nC 55 ; WX 600 ; N seven ; B 82 0 483 607 ;\nC 56 ; WX 600 ; N eight ; B 102 -15 498 622 ;\nC 57 ; WX 600 ; N nine ; B 96 -15 489 622 ;\nC 58 ; WX 600 ; N colon ; B 229 -15 371 385 ;\nC 59 ; WX 600 ; N semicolon ; B 181 -112 371 385 ;\nC 60 ; WX 600 ; N less ; B 41 42 519 472 ;\nC 61 ; WX 600 ; N equal ; B 80 138 520 376 ;\nC 62 ; WX 600 ; N greater ; B 66 42 544 472 ;\nC 63 ; WX 600 ; N question ; B 129 -15 492 572 ;\nC 64 ; WX 600 ; N at ; B 77 -15 533 622 ;\nC 65 ; WX 600 ; N A ; B 3 0 597 562 ;\nC 66 ; WX 600 ; N B ; B 43 0 559 562 ;\nC 67 ; WX 600 ; N C ; B 41 -18 540 580 ;\nC 68 ; WX 600 ; N D ; B 43 0 574 562 ;\nC 69 ; WX 600 ; N E ; B 53 0 550 562 ;\nC 70 ; WX 600 ; N F ; B 53 0 545 562 ;\nC 71 ; WX 600 ; N G ; B 31 -18 575 580 ;\nC 72 ; WX 600 ; N H ; B 32 0 568 562 ;\nC 73 ; WX 600 ; N I ; B 96 0 504 562 ;\nC 74 ; WX 600 ; N J ; B 34 -18 566 562 ;\nC 75 ; WX 600 ; N K ; B 38 0 582 562 ;\nC 76 ; WX 600 ; N L ; B 47 0 554 562 ;\nC 77 ; WX 600 ; N M ; B 4 0 596 562 ;\nC 78 ; WX 600 ; N N ; B 7 -13 593 562 ;\nC 79 ; WX 600 ; N O ; B 43 -18 557 580 ;\nC 80 ; WX 600 ; N P ; B 79 0 558 562 ;\nC 81 ; WX 600 ; N Q ; B 43 -138 557 580 ;\nC 82 ; WX 600 ; N R ; B 38 0 588 562 ;\nC 83 ; WX 600 ; N S ; B 72 -20 529 580 ;\nC 84 ; WX 600 ; N T ; B 38 0 563 562 ;\nC 85 ; WX 600 ; N U ; B 17 -18 583 562 ;\nC 86 ; WX 600 ; N V ; B -4 -13 604 562 ;\nC 87 ; WX 600 ; N W ; B -3 -13 603 562 ;\nC 88 ; WX 600 ; N X ; B 23 0 577 562 ;\nC 89 ; WX 600 ; N Y ; B 24 0 576 562 ;\nC 90 ; WX 600 ; N Z ; B 86 0 514 562 ;\nC 91 ; WX 600 ; N bracketleft ; B 269 -108 442 622 ;\nC 92 ; WX 600 ; N backslash ; B 118 -80 482 629 ;\nC 93 ; WX 600 ; N bracketright ; B 158 -108 331 622 ;\nC 94 ; WX 600 ; N asciicircum ; B 94 354 506 622 ;\nC 95 ; WX 600 ; N underscore ; B 0 -125 600 -75 ;\nC 96 ; WX 600 ; N quoteleft ; B 224 328 387 562 ;\nC 97 ; WX 600 ; N a ; B 53 -15 559 441 ;\nC 98 ; WX 600 ; N b ; B 14 -15 575 629 ;\nC 99 ; WX 600 ; N c ; B 66 -15 529 441 ;\nC 100 ; WX 600 ; N d ; B 45 -15 591 629 ;\nC 101 ; WX 600 ; N e ; B 66 -15 548 441 ;\nC 102 ; WX 600 ; N f ; B 114 0 531 629 ; L i fi ; L l fl ;\nC 103 ; WX 600 ; N g ; B 45 -157 566 441 ;\nC 104 ; WX 600 ; N h ; B 18 0 582 629 ;\nC 105 ; WX 600 ; N i ; B 95 0 505 657 ;\nC 106 ; WX 600 ; N j ; B 82 -157 410 657 ;\nC 107 ; WX 6
},
"Courier-Bold": function() {
return "StartFontMetrics 4.1\nComment Copyright (c) 1989, 1990, 1991, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.\nComment Creation Date: Mon Jun 23 16:28:00 1997\nComment UniqueID 43048\nComment VMusage 41139 52164\nFontName Courier-Bold\nFullName Courier Bold\nFamilyName Courier\nWeight Bold\nItalicAngle 0\nIsFixedPitch true\nCharacterSet ExtendedRoman\nFontBBox -113 -250 749 801 \nUnderlinePosition -100\nUnderlineThickness 50\nVersion 003.000\nNotice Copyright (c) 1989, 1990, 1991, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.\nEncodingScheme AdobeStandardEncoding\nCapHeight 562\nXHeight 439\nAscender 629\nDescender -157\nStdHW 84\nStdVW 106\nStartCharMetrics 315\nC 32 ; WX 600 ; N space ; B 0 0 0 0 ;\nC 33 ; WX 600 ; N exclam ; B 202 -15 398 572 ;\nC 34 ; WX 600 ; N quotedbl ; B 135 277 465 562 ;\nC 35 ; WX 600 ; N numbersign ; B 56 -45 544 651 ;\nC 36 ; WX 600 ; N dollar ; B 82 -126 519 666 ;\nC 37 ; WX 600 ; N percent ; B 5 -15 595 616 ;\nC 38 ; WX 600 ; N ampersand ; B 36 -15 546 543 ;\nC 39 ; WX 600 ; N quoteright ; B 171 277 423 562 ;\nC 40 ; WX 600 ; N parenleft ; B 219 -102 461 616 ;\nC 41 ; WX 600 ; N parenright ; B 139 -102 381 616 ;\nC 42 ; WX 600 ; N asterisk ; B 91 219 509 601 ;\nC 43 ; WX 600 ; N plus ; B 71 39 529 478 ;\nC 44 ; WX 600 ; N comma ; B 123 -111 393 174 ;\nC 45 ; WX 600 ; N hyphen ; B 100 203 500 313 ;\nC 46 ; WX 600 ; N period ; B 192 -15 408 171 ;\nC 47 ; WX 600 ; N slash ; B 98 -77 502 626 ;\nC 48 ; WX 600 ; N zero ; B 87 -15 513 616 ;\nC 49 ; WX 600 ; N one ; B 81 0 539 616 ;\nC 50 ; WX 600 ; N two ; B 61 0 499 616 ;\nC 51 ; WX 600 ; N three ; B 63 -15 501 616 ;\nC 52 ; WX 600 ; N four ; B 53 0 507 616 ;\nC 53 ; WX 600 ; N five ; B 70 -15 521 601 ;\nC 54 ; WX 600 ; N six ; B 90 -15 521 616 ;\nC 55 ; WX 600 ; N seven ; B 55 0 494 601 ;\nC 56 ; WX 600 ; N eight ; B 83 -15 517 616 ;\nC 57 ; WX 600 ; N nine ; B 79 -15 510 616 ;\nC 58 ; WX 600 ; N colon ; B 191 -15 407 425 ;\nC 59 ; WX 600 ; N semicolon ; B 123 -111 408 425 ;\nC 60 ; WX 600 ; N less ; B 66 15 523 501 ;\nC 61 ; WX 600 ; N equal ; B 71 118 529 398 ;\nC 62 ; WX 600 ; N greater ; B 77 15 534 501 ;\nC 63 ; WX 600 ; N question ; B 98 -14 501 580 ;\nC 64 ; WX 600 ; N at ; B 16 -15 584 616 ;\nC 65 ; WX 600 ; N A ; B -9 0 609 562 ;\nC 66 ; WX 600 ; N B ; B 30 0 573 562 ;\nC 67 ; WX 600 ; N C ; B 22 -18 560 580 ;\nC 68 ; WX 600 ; N D ; B 30 0 594 562 ;\nC 69 ; WX 600 ; N E ; B 25 0 560 562 ;\nC 70 ; WX 600 ; N F ; B 39 0 570 562 ;\nC 71 ; WX 600 ; N G ; B 22 -18 594 580 ;\nC 72 ; WX 600 ; N H ; B 20 0 580 562 ;\nC 73 ; WX 600 ; N I ; B 77 0 523 562 ;\nC 74 ; WX 600 ; N J ; B 37 -18 601 562 ;\nC 75 ; WX 600 ; N K ; B 21 0 599 562 ;\nC 76 ; WX 600 ; N L ; B 39 0 578 562 ;\nC 77 ; WX 600 ; N M ; B -2 0 602 562 ;\nC 78 ; WX 600 ; N N ; B 8 -12 610 562 ;\nC 79 ; WX 600 ; N O ; B 22 -18 578 580 ;\nC 80 ; WX 600 ; N P ; B 48 0 559 562 ;\nC 81 ; WX 600 ; N Q ; B 32 -138 578 580 ;\nC 82 ; WX 600 ; N R ; B 24 0 599 562 ;\nC 83 ; WX 600 ; N S ; B 47 -22 553 582 ;\nC 84 ; WX 600 ; N T ; B 21 0 579 562 ;\nC 85 ; WX 600 ; N U ; B 4 -18 596 562 ;\nC 86 ; WX 600 ; N V ; B -13 0 613 562 ;\nC 87 ; WX 600 ; N W ; B -18 0 618 562 ;\nC 88 ; WX 600 ; N X ; B 12 0 588 562 ;\nC 89 ; WX 600 ; N Y ; B 12 0 589 562 ;\nC 90 ; WX 600 ; N Z ; B 62 0 539 562 ;\nC 91 ; WX 600 ; N bracketleft ; B 245 -102 475 616 ;\nC 92 ; WX 600 ; N backslash ; B 99 -77 503 626 ;\nC 93 ; WX 600 ; N bracketright ; B 125 -102 355 616 ;\nC 94 ; WX 600 ; N asciicircum ; B 108 250 492 616 ;\nC 95 ; WX 600 ; N underscore ; B 0 -125 600 -75 ;\nC 96 ; WX 600 ; N quoteleft ; B 178 277 428 562 ;\nC 97 ; WX 600 ; N a ; B 35 -15 570 454 ;\nC 98 ; WX 600 ; N b ; B 0 -15 584 626 ;\nC 99 ; WX 600 ; N c ; B 40 -15 545 459 ;\nC 100 ; WX 600 ; N d ; B 20 -15 591 626 ;\nC 101 ; WX 600 ; N e ; B 40 -15 563 454 ;\nC 102 ; WX 600 ; N f ; B 83 0 547 626 ; L i fi ; L l fl ;\nC 103 ; WX 600 ; N g ; B 30 -146 580 454 ;\nC 104 ; WX 600 ; N h ; B 5 0 592 626 ;\nC 105 ; WX 600 ; N i ; B 77 0 523 658 ;\nC 106 ; WX 600 ; N j ; B 63 -146 440 658 ;\nC 107 ; WX 600 ; N k ; B 2
},
"Courier-Oblique": function() {
return "StartFontMetrics 4.1\nComment Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.\nComment Creation Date: Thu May 1 17:37:52 1997\nComment UniqueID 43051\nComment VMusage 16248 75829\nFontName Courier-Oblique\nFullName Courier Oblique\nFamilyName Courier\nWeight Medium\nItalicAngle -12\nIsFixedPitch true\nCharacterSet ExtendedRoman\nFontBBox -27 -250 849 805 \nUnderlinePosition -100\nUnderlineThickness 50\nVersion 003.000\nNotice Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.\nEncodingScheme AdobeStandardEncoding\nCapHeight 562\nXHeight 426\nAscender 629\nDescender -157\nStdHW 51\nStdVW 51\nStartCharMetrics 315\nC 32 ; WX 600 ; N space ; B 0 0 0 0 ;\nC 33 ; WX 600 ; N exclam ; B 243 -15 464 572 ;\nC 34 ; WX 600 ; N quotedbl ; B 273 328 532 562 ;\nC 35 ; WX 600 ; N numbersign ; B 133 -32 596 639 ;\nC 36 ; WX 600 ; N dollar ; B 108 -126 596 662 ;\nC 37 ; WX 600 ; N percent ; B 134 -15 599 622 ;\nC 38 ; WX 600 ; N ampersand ; B 87 -15 580 543 ;\nC 39 ; WX 600 ; N quoteright ; B 283 328 495 562 ;\nC 40 ; WX 600 ; N parenleft ; B 313 -108 572 622 ;\nC 41 ; WX 600 ; N parenright ; B 137 -108 396 622 ;\nC 42 ; WX 600 ; N asterisk ; B 212 257 580 607 ;\nC 43 ; WX 600 ; N plus ; B 129 44 580 470 ;\nC 44 ; WX 600 ; N comma ; B 157 -112 370 122 ;\nC 45 ; WX 600 ; N hyphen ; B 152 231 558 285 ;\nC 46 ; WX 600 ; N period ; B 238 -15 382 109 ;\nC 47 ; WX 600 ; N slash ; B 112 -80 604 629 ;\nC 48 ; WX 600 ; N zero ; B 154 -15 575 622 ;\nC 49 ; WX 600 ; N one ; B 98 0 515 622 ;\nC 50 ; WX 600 ; N two ; B 70 0 568 622 ;\nC 51 ; WX 600 ; N three ; B 82 -15 538 622 ;\nC 52 ; WX 600 ; N four ; B 108 0 541 622 ;\nC 53 ; WX 600 ; N five ; B 99 -15 589 607 ;\nC 54 ; WX 600 ; N six ; B 155 -15 629 622 ;\nC 55 ; WX 600 ; N seven ; B 182 0 612 607 ;\nC 56 ; WX 600 ; N eight ; B 132 -15 588 622 ;\nC 57 ; WX 600 ; N nine ; B 93 -15 574 622 ;\nC 58 ; WX 600 ; N colon ; B 238 -15 441 385 ;\nC 59 ; WX 600 ; N semicolon ; B 157 -112 441 385 ;\nC 60 ; WX 600 ; N less ; B 96 42 610 472 ;\nC 61 ; WX 600 ; N equal ; B 109 138 600 376 ;\nC 62 ; WX 600 ; N greater ; B 85 42 599 472 ;\nC 63 ; WX 600 ; N question ; B 222 -15 583 572 ;\nC 64 ; WX 600 ; N at ; B 127 -15 582 622 ;\nC 65 ; WX 600 ; N A ; B 3 0 607 562 ;\nC 66 ; WX 600 ; N B ; B 43 0 616 562 ;\nC 67 ; WX 600 ; N C ; B 93 -18 655 580 ;\nC 68 ; WX 600 ; N D ; B 43 0 645 562 ;\nC 69 ; WX 600 ; N E ; B 53 0 660 562 ;\nC 70 ; WX 600 ; N F ; B 53 0 660 562 ;\nC 71 ; WX 600 ; N G ; B 83 -18 645 580 ;\nC 72 ; WX 600 ; N H ; B 32 0 687 562 ;\nC 73 ; WX 600 ; N I ; B 96 0 623 562 ;\nC 74 ; WX 600 ; N J ; B 52 -18 685 562 ;\nC 75 ; WX 600 ; N K ; B 38 0 671 562 ;\nC 76 ; WX 600 ; N L ; B 47 0 607 562 ;\nC 77 ; WX 600 ; N M ; B 4 0 715 562 ;\nC 78 ; WX 600 ; N N ; B 7 -13 712 562 ;\nC 79 ; WX 600 ; N O ; B 94 -18 625 580 ;\nC 80 ; WX 600 ; N P ; B 79 0 644 562 ;\nC 81 ; WX 600 ; N Q ; B 95 -138 625 580 ;\nC 82 ; WX 600 ; N R ; B 38 0 598 562 ;\nC 83 ; WX 600 ; N S ; B 76 -20 650 580 ;\nC 84 ; WX 600 ; N T ; B 108 0 665 562 ;\nC 85 ; WX 600 ; N U ; B 125 -18 702 562 ;\nC 86 ; WX 600 ; N V ; B 105 -13 723 562 ;\nC 87 ; WX 600 ; N W ; B 106 -13 722 562 ;\nC 88 ; WX 600 ; N X ; B 23 0 675 562 ;\nC 89 ; WX 600 ; N Y ; B 133 0 695 562 ;\nC 90 ; WX 600 ; N Z ; B 86 0 610 562 ;\nC 91 ; WX 600 ; N bracketleft ; B 246 -108 574 622 ;\nC 92 ; WX 600 ; N backslash ; B 249 -80 468 629 ;\nC 93 ; WX 600 ; N bracketright ; B 135 -108 463 622 ;\nC 94 ; WX 600 ; N asciicircum ; B 175 354 587 622 ;\nC 95 ; WX 600 ; N underscore ; B -27 -125 584 -75 ;\nC 96 ; WX 600 ; N quoteleft ; B 343 328 457 562 ;\nC 97 ; WX 600 ; N a ; B 76 -15 569 441 ;\nC 98 ; WX 600 ; N b ; B 29 -15 625 629 ;\nC 99 ; WX 600 ; N c ; B 106 -15 608 441 ;\nC 100 ; WX 600 ; N d ; B 85 -15 640 629 ;\nC 101 ; WX 600 ; N e ; B 106 -15 598 441 ;\nC 102 ; WX 600 ; N f ; B 114 0 662 629 ; L i fi ; L l fl ;\nC 103 ; WX 600 ; N g ; B 61 -157 657 441 ;\nC 104 ; WX 600 ; N h ; B 33 0 592 629 ;\nC 105 ; WX 600 ; N i ; B 95 0 515 657 ;\nC 106 ; WX 600 ; N j
},
"Courier-BoldOblique": function() {
return "StartFontMetrics 4.1\nComment Copyright (c) 1989, 1990, 1991, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.\nComment Creation Date: Mon Jun 23 16:28:46 1997\nComment UniqueID 43049\nComment VMusage 17529 79244\nFontName Courier-BoldOblique\nFullName Courier Bold Oblique\nFamilyName Courier\nWeight Bold\nItalicAngle -12\nIsFixedPitch true\nCharacterSet ExtendedRoman\nFontBBox -57 -250 869 801 \nUnderlinePosition -100\nUnderlineThickness 50\nVersion 003.000\nNotice Copyright (c) 1989, 1990, 1991, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.\nEncodingScheme AdobeStandardEncoding\nCapHeight 562\nXHeight 439\nAscender 629\nDescender -157\nStdHW 84\nStdVW 106\nStartCharMetrics 315\nC 32 ; WX 600 ; N space ; B 0 0 0 0 ;\nC 33 ; WX 600 ; N exclam ; B 215 -15 495 572 ;\nC 34 ; WX 600 ; N quotedbl ; B 211 277 585 562 ;\nC 35 ; WX 600 ; N numbersign ; B 88 -45 641 651 ;\nC 36 ; WX 600 ; N dollar ; B 87 -126 630 666 ;\nC 37 ; WX 600 ; N percent ; B 101 -15 625 616 ;\nC 38 ; WX 600 ; N ampersand ; B 61 -15 595 543 ;\nC 39 ; WX 600 ; N quoteright ; B 229 277 543 562 ;\nC 40 ; WX 600 ; N parenleft ; B 265 -102 592 616 ;\nC 41 ; WX 600 ; N parenright ; B 117 -102 444 616 ;\nC 42 ; WX 600 ; N asterisk ; B 179 219 598 601 ;\nC 43 ; WX 600 ; N plus ; B 114 39 596 478 ;\nC 44 ; WX 600 ; N comma ; B 99 -111 430 174 ;\nC 45 ; WX 600 ; N hyphen ; B 143 203 567 313 ;\nC 46 ; WX 600 ; N period ; B 206 -15 427 171 ;\nC 47 ; WX 600 ; N slash ; B 90 -77 626 626 ;\nC 48 ; WX 600 ; N zero ; B 135 -15 593 616 ;\nC 49 ; WX 600 ; N one ; B 93 0 562 616 ;\nC 50 ; WX 600 ; N two ; B 61 0 594 616 ;\nC 51 ; WX 600 ; N three ; B 71 -15 571 616 ;\nC 52 ; WX 600 ; N four ; B 81 0 559 616 ;\nC 53 ; WX 600 ; N five ; B 77 -15 621 601 ;\nC 54 ; WX 600 ; N six ; B 135 -15 652 616 ;\nC 55 ; WX 600 ; N seven ; B 147 0 622 601 ;\nC 56 ; WX 600 ; N eight ; B 115 -15 604 616 ;\nC 57 ; WX 600 ; N nine ; B 75 -15 592 616 ;\nC 58 ; WX 600 ; N colon ; B 205 -15 480 425 ;\nC 59 ; WX 600 ; N semicolon ; B 99 -111 481 425 ;\nC 60 ; WX 600 ; N less ; B 120 15 613 501 ;\nC 61 ; WX 600 ; N equal ; B 96 118 614 398 ;\nC 62 ; WX 600 ; N greater ; B 97 15 589 501 ;\nC 63 ; WX 600 ; N question ; B 183 -14 592 580 ;\nC 64 ; WX 600 ; N at ; B 65 -15 642 616 ;\nC 65 ; WX 600 ; N A ; B -9 0 632 562 ;\nC 66 ; WX 600 ; N B ; B 30 0 630 562 ;\nC 67 ; WX 600 ; N C ; B 74 -18 675 580 ;\nC 68 ; WX 600 ; N D ; B 30 0 664 562 ;\nC 69 ; WX 600 ; N E ; B 25 0 670 562 ;\nC 70 ; WX 600 ; N F ; B 39 0 684 562 ;\nC 71 ; WX 600 ; N G ; B 74 -18 675 580 ;\nC 72 ; WX 600 ; N H ; B 20 0 700 562 ;\nC 73 ; WX 600 ; N I ; B 77 0 643 562 ;\nC 74 ; WX 600 ; N J ; B 58 -18 721 562 ;\nC 75 ; WX 600 ; N K ; B 21 0 692 562 ;\nC 76 ; WX 600 ; N L ; B 39 0 636 562 ;\nC 77 ; WX 600 ; N M ; B -2 0 722 562 ;\nC 78 ; WX 600 ; N N ; B 8 -12 730 562 ;\nC 79 ; WX 600 ; N O ; B 74 -18 645 580 ;\nC 80 ; WX 600 ; N P ; B 48 0 643 562 ;\nC 81 ; WX 600 ; N Q ; B 83 -138 636 580 ;\nC 82 ; WX 600 ; N R ; B 24 0 617 562 ;\nC 83 ; WX 600 ; N S ; B 54 -22 673 582 ;\nC 84 ; WX 600 ; N T ; B 86 0 679 562 ;\nC 85 ; WX 600 ; N U ; B 101 -18 716 562 ;\nC 86 ; WX 600 ; N V ; B 84 0 733 562 ;\nC 87 ; WX 600 ; N W ; B 79 0 738 562 ;\nC 88 ; WX 600 ; N X ; B 12 0 690 562 ;\nC 89 ; WX 600 ; N Y ; B 109 0 709 562 ;\nC 90 ; WX 600 ; N Z ; B 62 0 637 562 ;\nC 91 ; WX 600 ; N bracketleft ; B 223 -102 606 616 ;\nC 92 ; WX 600 ; N backslash ; B 222 -77 496 626 ;\nC 93 ; WX 600 ; N bracketright ; B 103 -102 486 616 ;\nC 94 ; WX 600 ; N asciicircum ; B 171 250 556 616 ;\nC 95 ; WX 600 ; N underscore ; B -27 -125 585 -75 ;\nC 96 ; WX 600 ; N quoteleft ; B 297 277 487 562 ;\nC 97 ; WX 600 ; N a ; B 61 -15 593 454 ;\nC 98 ; WX 600 ; N b ; B 13 -15 636 626 ;\nC 99 ; WX 600 ; N c ; B 81 -15 631 459 ;\nC 100 ; WX 600 ; N d ; B 60 -15 645 626 ;\nC 101 ; WX 600 ; N e ; B 81 -15 605 454 ;\nC 102 ; WX 600 ; N f ; B 83 0 677 626 ; L i fi ; L l fl ;\nC 103 ; WX 600 ; N g ; B 40 -146 674 454 ;\nC 104 ; WX 600 ; N h ; B 18 0 615 626 ;\nC 105 ; WX 600 ; N i ; B 77 0 546 658 ;\nC 106 ; WX 600 ; N j ; B 36 -146 580 658
},
"Helvetica": function() {
return "StartFontMetrics 4.1\nComment Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.\nComment Creation Date: Thu May 1 12:38:23 1997\nComment UniqueID 43054\nComment VMusage 37069 48094\nFontName Helvetica\nFullName Helvetica\nFamilyName Helvetica\nWeight Medium\nItalicAngle 0\nIsFixedPitch false\nCharacterSet ExtendedRoman\nFontBBox -166 -225 1000 931 \nUnderlinePosition -100\nUnderlineThickness 50\nVersion 002.000\nNotice Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.Helvetica is a trademark of Linotype-Hell AG and/or its subsidiaries.\nEncodingScheme AdobeStandardEncoding\nCapHeight 718\nXHeight 523\nAscender 718\nDescender -207\nStdHW 76\nStdVW 88\nStartCharMetrics 315\nC 32 ; WX 278 ; N space ; B 0 0 0 0 ;\nC 33 ; WX 278 ; N exclam ; B 90 0 187 718 ;\nC 34 ; WX 355 ; N quotedbl ; B 70 463 285 718 ;\nC 35 ; WX 556 ; N numbersign ; B 28 0 529 688 ;\nC 36 ; WX 556 ; N dollar ; B 32 -115 520 775 ;\nC 37 ; WX 889 ; N percent ; B 39 -19 850 703 ;\nC 38 ; WX 667 ; N ampersand ; B 44 -15 645 718 ;\nC 39 ; WX 222 ; N quoteright ; B 53 463 157 718 ;\nC 40 ; WX 333 ; N parenleft ; B 68 -207 299 733 ;\nC 41 ; WX 333 ; N parenright ; B 34 -207 265 733 ;\nC 42 ; WX 389 ; N asterisk ; B 39 431 349 718 ;\nC 43 ; WX 584 ; N plus ; B 39 0 545 505 ;\nC 44 ; WX 278 ; N comma ; B 87 -147 191 106 ;\nC 45 ; WX 333 ; N hyphen ; B 44 232 289 322 ;\nC 46 ; WX 278 ; N period ; B 87 0 191 106 ;\nC 47 ; WX 278 ; N slash ; B -17 -19 295 737 ;\nC 48 ; WX 556 ; N zero ; B 37 -19 519 703 ;\nC 49 ; WX 556 ; N one ; B 101 0 359 703 ;\nC 50 ; WX 556 ; N two ; B 26 0 507 703 ;\nC 51 ; WX 556 ; N three ; B 34 -19 522 703 ;\nC 52 ; WX 556 ; N four ; B 25 0 523 703 ;\nC 53 ; WX 556 ; N five ; B 32 -19 514 688 ;\nC 54 ; WX 556 ; N six ; B 38 -19 518 703 ;\nC 55 ; WX 556 ; N seven ; B 37 0 523 688 ;\nC 56 ; WX 556 ; N eight ; B 38 -19 517 703 ;\nC 57 ; WX 556 ; N nine ; B 42 -19 514 703 ;\nC 58 ; WX 278 ; N colon ; B 87 0 191 516 ;\nC 59 ; WX 278 ; N semicolon ; B 87 -147 191 516 ;\nC 60 ; WX 584 ; N less ; B 48 11 536 495 ;\nC 61 ; WX 584 ; N equal ; B 39 115 545 390 ;\nC 62 ; WX 584 ; N greater ; B 48 11 536 495 ;\nC 63 ; WX 556 ; N question ; B 56 0 492 727 ;\nC 64 ; WX 1015 ; N at ; B 147 -19 868 737 ;\nC 65 ; WX 667 ; N A ; B 14 0 654 718 ;\nC 66 ; WX 667 ; N B ; B 74 0 627 718 ;\nC 67 ; WX 722 ; N C ; B 44 -19 681 737 ;\nC 68 ; WX 722 ; N D ; B 81 0 674 718 ;\nC 69 ; WX 667 ; N E ; B 86 0 616 718 ;\nC 70 ; WX 611 ; N F ; B 86 0 583 718 ;\nC 71 ; WX 778 ; N G ; B 48 -19 704 737 ;\nC 72 ; WX 722 ; N H ; B 77 0 646 718 ;\nC 73 ; WX 278 ; N I ; B 91 0 188 718 ;\nC 74 ; WX 500 ; N J ; B 17 -19 428 718 ;\nC 75 ; WX 667 ; N K ; B 76 0 663 718 ;\nC 76 ; WX 556 ; N L ; B 76 0 537 718 ;\nC 77 ; WX 833 ; N M ; B 73 0 761 718 ;\nC 78 ; WX 722 ; N N ; B 76 0 646 718 ;\nC 79 ; WX 778 ; N O ; B 39 -19 739 737 ;\nC 80 ; WX 667 ; N P ; B 86 0 622 718 ;\nC 81 ; WX 778 ; N Q ; B 39 -56 739 737 ;\nC 82 ; WX 722 ; N R ; B 88 0 684 718 ;\nC 83 ; WX 667 ; N S ; B 49 -19 620 737 ;\nC 84 ; WX 611 ; N T ; B 14 0 597 718 ;\nC 85 ; WX 722 ; N U ; B 79 -19 644 718 ;\nC 86 ; WX 667 ; N V ; B 20 0 647 718 ;\nC 87 ; WX 944 ; N W ; B 16 0 928 718 ;\nC 88 ; WX 667 ; N X ; B 19 0 648 718 ;\nC 89 ; WX 667 ; N Y ; B 14 0 653 718 ;\nC 90 ; WX 611 ; N Z ; B 23 0 588 718 ;\nC 91 ; WX 278 ; N bracketleft ; B 63 -196 250 722 ;\nC 92 ; WX 278 ; N backslash ; B -17 -19 295 737 ;\nC 93 ; WX 278 ; N bracketright ; B 28 -196 215 722 ;\nC 94 ; WX 469 ; N asciicircum ; B -14 264 483 688 ;\nC 95 ; WX 556 ; N underscore ; B 0 -125 556 -75 ;\nC 96 ; WX 222 ; N quoteleft ; B 65 470 169 725 ;\nC 97 ; WX 556 ; N a ; B 36 -15 530 538 ;\nC 98 ; WX 556 ; N b ; B 58 -15 517 718 ;\nC 99 ; WX 500 ; N c ; B 30 -15 477 538 ;\nC 100 ; WX 556 ; N d ; B 35 -15 499 718 ;\nC 101 ; WX 556 ; N e ; B 40 -15 516 538 ;\nC 102 ; WX 278 ; N f ; B 14 0 262 728 ; L i fi ; L l fl ;\nC 103 ; WX 556 ; N g ; B 40 -220 499 538 ;\nC 104 ; WX 556 ; N h ; B 65 0 491 718 ;\nC 105 ; WX 222 ; N i ; B 67 0 155 718 ;\nC 106 ; WX 222 ; N j
},
"Helvetica-Bold": function() {
return "StartFontMetrics 4.1\nComment Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.\nComment Creation Date: Thu May 1 12:43:52 1997\nComment UniqueID 43052\nComment VMusage 37169 48194\nFontName Helvetica-Bold\nFullName Helvetica Bold\nFamilyName Helvetica\nWeight Bold\nItalicAngle 0\nIsFixedPitch false\nCharacterSet ExtendedRoman\nFontBBox -170 -228 1003 962 \nUnderlinePosition -100\nUnderlineThickness 50\nVersion 002.000\nNotice Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.Helvetica is a trademark of Linotype-Hell AG and/or its subsidiaries.\nEncodingScheme AdobeStandardEncoding\nCapHeight 718\nXHeight 532\nAscender 718\nDescender -207\nStdHW 118\nStdVW 140\nStartCharMetrics 315\nC 32 ; WX 278 ; N space ; B 0 0 0 0 ;\nC 33 ; WX 333 ; N exclam ; B 90 0 244 718 ;\nC 34 ; WX 474 ; N quotedbl ; B 98 447 376 718 ;\nC 35 ; WX 556 ; N numbersign ; B 18 0 538 698 ;\nC 36 ; WX 556 ; N dollar ; B 30 -115 523 775 ;\nC 37 ; WX 889 ; N percent ; B 28 -19 861 710 ;\nC 38 ; WX 722 ; N ampersand ; B 54 -19 701 718 ;\nC 39 ; WX 278 ; N quoteright ; B 69 445 209 718 ;\nC 40 ; WX 333 ; N parenleft ; B 35 -208 314 734 ;\nC 41 ; WX 333 ; N parenright ; B 19 -208 298 734 ;\nC 42 ; WX 389 ; N asterisk ; B 27 387 362 718 ;\nC 43 ; WX 584 ; N plus ; B 40 0 544 506 ;\nC 44 ; WX 278 ; N comma ; B 64 -168 214 146 ;\nC 45 ; WX 333 ; N hyphen ; B 27 215 306 345 ;\nC 46 ; WX 278 ; N period ; B 64 0 214 146 ;\nC 47 ; WX 278 ; N slash ; B -33 -19 311 737 ;\nC 48 ; WX 556 ; N zero ; B 32 -19 524 710 ;\nC 49 ; WX 556 ; N one ; B 69 0 378 710 ;\nC 50 ; WX 556 ; N two ; B 26 0 511 710 ;\nC 51 ; WX 556 ; N three ; B 27 -19 516 710 ;\nC 52 ; WX 556 ; N four ; B 27 0 526 710 ;\nC 53 ; WX 556 ; N five ; B 27 -19 516 698 ;\nC 54 ; WX 556 ; N six ; B 31 -19 520 710 ;\nC 55 ; WX 556 ; N seven ; B 25 0 528 698 ;\nC 56 ; WX 556 ; N eight ; B 32 -19 524 710 ;\nC 57 ; WX 556 ; N nine ; B 30 -19 522 710 ;\nC 58 ; WX 333 ; N colon ; B 92 0 242 512 ;\nC 59 ; WX 333 ; N semicolon ; B 92 -168 242 512 ;\nC 60 ; WX 584 ; N less ; B 38 -8 546 514 ;\nC 61 ; WX 584 ; N equal ; B 40 87 544 419 ;\nC 62 ; WX 584 ; N greater ; B 38 -8 546 514 ;\nC 63 ; WX 611 ; N question ; B 60 0 556 727 ;\nC 64 ; WX 975 ; N at ; B 118 -19 856 737 ;\nC 65 ; WX 722 ; N A ; B 20 0 702 718 ;\nC 66 ; WX 722 ; N B ; B 76 0 669 718 ;\nC 67 ; WX 722 ; N C ; B 44 -19 684 737 ;\nC 68 ; WX 722 ; N D ; B 76 0 685 718 ;\nC 69 ; WX 667 ; N E ; B 76 0 621 718 ;\nC 70 ; WX 611 ; N F ; B 76 0 587 718 ;\nC 71 ; WX 778 ; N G ; B 44 -19 713 737 ;\nC 72 ; WX 722 ; N H ; B 71 0 651 718 ;\nC 73 ; WX 278 ; N I ; B 64 0 214 718 ;\nC 74 ; WX 556 ; N J ; B 22 -18 484 718 ;\nC 75 ; WX 722 ; N K ; B 87 0 722 718 ;\nC 76 ; WX 611 ; N L ; B 76 0 583 718 ;\nC 77 ; WX 833 ; N M ; B 69 0 765 718 ;\nC 78 ; WX 722 ; N N ; B 69 0 654 718 ;\nC 79 ; WX 778 ; N O ; B 44 -19 734 737 ;\nC 80 ; WX 667 ; N P ; B 76 0 627 718 ;\nC 81 ; WX 778 ; N Q ; B 44 -52 737 737 ;\nC 82 ; WX 722 ; N R ; B 76 0 677 718 ;\nC 83 ; WX 667 ; N S ; B 39 -19 629 737 ;\nC 84 ; WX 611 ; N T ; B 14 0 598 718 ;\nC 85 ; WX 722 ; N U ; B 72 -19 651 718 ;\nC 86 ; WX 667 ; N V ; B 19 0 648 718 ;\nC 87 ; WX 944 ; N W ; B 16 0 929 718 ;\nC 88 ; WX 667 ; N X ; B 14 0 653 718 ;\nC 89 ; WX 667 ; N Y ; B 15 0 653 718 ;\nC 90 ; WX 611 ; N Z ; B 25 0 586 718 ;\nC 91 ; WX 333 ; N bracketleft ; B 63 -196 309 722 ;\nC 92 ; WX 278 ; N backslash ; B -33 -19 311 737 ;\nC 93 ; WX 333 ; N bracketright ; B 24 -196 270 722 ;\nC 94 ; WX 584 ; N asciicircum ; B 62 323 522 698 ;\nC 95 ; WX 556 ; N underscore ; B 0 -125 556 -75 ;\nC 96 ; WX 278 ; N quoteleft ; B 69 454 209 727 ;\nC 97 ; WX 556 ; N a ; B 29 -14 527 546 ;\nC 98 ; WX 611 ; N b ; B 61 -14 578 718 ;\nC 99 ; WX 556 ; N c ; B 34 -14 524 546 ;\nC 100 ; WX 611 ; N d ; B 34 -14 551 718 ;\nC 101 ; WX 556 ; N e ; B 23 -14 528 546 ;\nC 102 ; WX 333 ; N f ; B 10 0 318 727 ; L i fi ; L l fl ;\nC 103 ; WX 611 ; N g ; B 40 -217 553 546 ;\nC 104 ; WX 611 ; N h ; B 65 0 546 718 ;\nC 105 ; WX 278 ; N i ; B 69 0 209 725 ;\nC 106 ; WX 278
},
"Helvetica-Oblique": function() {
return "StartFontMetrics 4.1\nComment Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.\nComment Creation Date: Thu May 1 12:44:31 1997\nComment UniqueID 43055\nComment VMusage 14960 69346\nFontName Helvetica-Oblique\nFullName Helvetica Oblique\nFamilyName Helvetica\nWeight Medium\nItalicAngle -12\nIsFixedPitch false\nCharacterSet ExtendedRoman\nFontBBox -170 -225 1116 931 \nUnderlinePosition -100\nUnderlineThickness 50\nVersion 002.000\nNotice Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.Helvetica is a trademark of Linotype-Hell AG and/or its subsidiaries.\nEncodingScheme AdobeStandardEncoding\nCapHeight 718\nXHeight 523\nAscender 718\nDescender -207\nStdHW 76\nStdVW 88\nStartCharMetrics 315\nC 32 ; WX 278 ; N space ; B 0 0 0 0 ;\nC 33 ; WX 278 ; N exclam ; B 90 0 340 718 ;\nC 34 ; WX 355 ; N quotedbl ; B 168 463 438 718 ;\nC 35 ; WX 556 ; N numbersign ; B 73 0 631 688 ;\nC 36 ; WX 556 ; N dollar ; B 69 -115 617 775 ;\nC 37 ; WX 889 ; N percent ; B 147 -19 889 703 ;\nC 38 ; WX 667 ; N ampersand ; B 77 -15 647 718 ;\nC 39 ; WX 222 ; N quoteright ; B 151 463 310 718 ;\nC 40 ; WX 333 ; N parenleft ; B 108 -207 454 733 ;\nC 41 ; WX 333 ; N parenright ; B -9 -207 337 733 ;\nC 42 ; WX 389 ; N asterisk ; B 165 431 475 718 ;\nC 43 ; WX 584 ; N plus ; B 85 0 606 505 ;\nC 44 ; WX 278 ; N comma ; B 56 -147 214 106 ;\nC 45 ; WX 333 ; N hyphen ; B 93 232 357 322 ;\nC 46 ; WX 278 ; N period ; B 87 0 214 106 ;\nC 47 ; WX 278 ; N slash ; B -21 -19 452 737 ;\nC 48 ; WX 556 ; N zero ; B 93 -19 608 703 ;\nC 49 ; WX 556 ; N one ; B 207 0 508 703 ;\nC 50 ; WX 556 ; N two ; B 26 0 617 703 ;\nC 51 ; WX 556 ; N three ; B 75 -19 610 703 ;\nC 52 ; WX 556 ; N four ; B 61 0 576 703 ;\nC 53 ; WX 556 ; N five ; B 68 -19 621 688 ;\nC 54 ; WX 556 ; N six ; B 91 -19 615 703 ;\nC 55 ; WX 556 ; N seven ; B 137 0 669 688 ;\nC 56 ; WX 556 ; N eight ; B 74 -19 607 703 ;\nC 57 ; WX 556 ; N nine ; B 82 -19 609 703 ;\nC 58 ; WX 278 ; N colon ; B 87 0 301 516 ;\nC 59 ; WX 278 ; N semicolon ; B 56 -147 301 516 ;\nC 60 ; WX 584 ; N less ; B 94 11 641 495 ;\nC 61 ; WX 584 ; N equal ; B 63 115 628 390 ;\nC 62 ; WX 584 ; N greater ; B 50 11 597 495 ;\nC 63 ; WX 556 ; N question ; B 161 0 610 727 ;\nC 64 ; WX 1015 ; N at ; B 215 -19 965 737 ;\nC 65 ; WX 667 ; N A ; B 14 0 654 718 ;\nC 66 ; WX 667 ; N B ; B 74 0 712 718 ;\nC 67 ; WX 722 ; N C ; B 108 -19 782 737 ;\nC 68 ; WX 722 ; N D ; B 81 0 764 718 ;\nC 69 ; WX 667 ; N E ; B 86 0 762 718 ;\nC 70 ; WX 611 ; N F ; B 86 0 736 718 ;\nC 71 ; WX 778 ; N G ; B 111 -19 799 737 ;\nC 72 ; WX 722 ; N H ; B 77 0 799 718 ;\nC 73 ; WX 278 ; N I ; B 91 0 341 718 ;\nC 74 ; WX 500 ; N J ; B 47 -19 581 718 ;\nC 75 ; WX 667 ; N K ; B 76 0 808 718 ;\nC 76 ; WX 556 ; N L ; B 76 0 555 718 ;\nC 77 ; WX 833 ; N M ; B 73 0 914 718 ;\nC 78 ; WX 722 ; N N ; B 76 0 799 718 ;\nC 79 ; WX 778 ; N O ; B 105 -19 826 737 ;\nC 80 ; WX 667 ; N P ; B 86 0 737 718 ;\nC 81 ; WX 778 ; N Q ; B 105 -56 826 737 ;\nC 82 ; WX 722 ; N R ; B 88 0 773 718 ;\nC 83 ; WX 667 ; N S ; B 90 -19 713 737 ;\nC 84 ; WX 611 ; N T ; B 148 0 750 718 ;\nC 85 ; WX 722 ; N U ; B 123 -19 797 718 ;\nC 86 ; WX 667 ; N V ; B 173 0 800 718 ;\nC 87 ; WX 944 ; N W ; B 169 0 1081 718 ;\nC 88 ; WX 667 ; N X ; B 19 0 790 718 ;\nC 89 ; WX 667 ; N Y ; B 167 0 806 718 ;\nC 90 ; WX 611 ; N Z ; B 23 0 741 718 ;\nC 91 ; WX 278 ; N bracketleft ; B 21 -196 403 722 ;\nC 92 ; WX 278 ; N backslash ; B 140 -19 291 737 ;\nC 93 ; WX 278 ; N bracketright ; B -14 -196 368 722 ;\nC 94 ; WX 469 ; N asciicircum ; B 42 264 539 688 ;\nC 95 ; WX 556 ; N underscore ; B -27 -125 540 -75 ;\nC 96 ; WX 222 ; N quoteleft ; B 165 470 323 725 ;\nC 97 ; WX 556 ; N a ; B 61 -15 559 538 ;\nC 98 ; WX 556 ; N b ; B 58 -15 584 718 ;\nC 99 ; WX 500 ; N c ; B 74 -15 553 538 ;\nC 100 ; WX 556 ; N d ; B 84 -15 652 718 ;\nC 101 ; WX 556 ; N e ; B 84 -15 578 538 ;\nC 102 ; WX 278 ; N f ; B 86 0 416 728 ; L i fi ; L l fl ;\nC 103 ; WX 556 ; N g ; B 42 -220 610 538 ;\nC 104 ; WX 556 ; N h ; B 65 0 573 718 ;\nC 105 ; WX 222 ; N i ; B
},
"Helvetica-BoldOblique": function() {
return "StartFontMetrics 4.1\nComment Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.\nComment Creation Date: Thu May 1 12:45:12 1997\nComment UniqueID 43053\nComment VMusage 14482 68586\nFontName Helvetica-BoldOblique\nFullName Helvetica Bold Oblique\nFamilyName Helvetica\nWeight Bold\nItalicAngle -12\nIsFixedPitch false\nCharacterSet ExtendedRoman\nFontBBox -174 -228 1114 962 \nUnderlinePosition -100\nUnderlineThickness 50\nVersion 002.000\nNotice Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.Helvetica is a trademark of Linotype-Hell AG and/or its subsidiaries.\nEncodingScheme AdobeStandardEncoding\nCapHeight 718\nXHeight 532\nAscender 718\nDescender -207\nStdHW 118\nStdVW 140\nStartCharMetrics 315\nC 32 ; WX 278 ; N space ; B 0 0 0 0 ;\nC 33 ; WX 333 ; N exclam ; B 94 0 397 718 ;\nC 34 ; WX 474 ; N quotedbl ; B 193 447 529 718 ;\nC 35 ; WX 556 ; N numbersign ; B 60 0 644 698 ;\nC 36 ; WX 556 ; N dollar ; B 67 -115 622 775 ;\nC 37 ; WX 889 ; N percent ; B 136 -19 901 710 ;\nC 38 ; WX 722 ; N ampersand ; B 89 -19 732 718 ;\nC 39 ; WX 278 ; N quoteright ; B 167 445 362 718 ;\nC 40 ; WX 333 ; N parenleft ; B 76 -208 470 734 ;\nC 41 ; WX 333 ; N parenright ; B -25 -208 369 734 ;\nC 42 ; WX 389 ; N asterisk ; B 146 387 481 718 ;\nC 43 ; WX 584 ; N plus ; B 82 0 610 506 ;\nC 44 ; WX 278 ; N comma ; B 28 -168 245 146 ;\nC 45 ; WX 333 ; N hyphen ; B 73 215 379 345 ;\nC 46 ; WX 278 ; N period ; B 64 0 245 146 ;\nC 47 ; WX 278 ; N slash ; B -37 -19 468 737 ;\nC 48 ; WX 556 ; N zero ; B 86 -19 617 710 ;\nC 49 ; WX 556 ; N one ; B 173 0 529 710 ;\nC 50 ; WX 556 ; N two ; B 26 0 619 710 ;\nC 51 ; WX 556 ; N three ; B 65 -19 608 710 ;\nC 52 ; WX 556 ; N four ; B 60 0 598 710 ;\nC 53 ; WX 556 ; N five ; B 64 -19 636 698 ;\nC 54 ; WX 556 ; N six ; B 85 -19 619 710 ;\nC 55 ; WX 556 ; N seven ; B 125 0 676 698 ;\nC 56 ; WX 556 ; N eight ; B 69 -19 616 710 ;\nC 57 ; WX 556 ; N nine ; B 78 -19 615 710 ;\nC 58 ; WX 333 ; N colon ; B 92 0 351 512 ;\nC 59 ; WX 333 ; N semicolon ; B 56 -168 351 512 ;\nC 60 ; WX 584 ; N less ; B 82 -8 655 514 ;\nC 61 ; WX 584 ; N equal ; B 58 87 633 419 ;\nC 62 ; WX 584 ; N greater ; B 36 -8 609 514 ;\nC 63 ; WX 611 ; N question ; B 165 0 671 727 ;\nC 64 ; WX 975 ; N at ; B 186 -19 954 737 ;\nC 65 ; WX 722 ; N A ; B 20 0 702 718 ;\nC 66 ; WX 722 ; N B ; B 76 0 764 718 ;\nC 67 ; WX 722 ; N C ; B 107 -19 789 737 ;\nC 68 ; WX 722 ; N D ; B 76 0 777 718 ;\nC 69 ; WX 667 ; N E ; B 76 0 757 718 ;\nC 70 ; WX 611 ; N F ; B 76 0 740 718 ;\nC 71 ; WX 778 ; N G ; B 108 -19 817 737 ;\nC 72 ; WX 722 ; N H ; B 71 0 804 718 ;\nC 73 ; WX 278 ; N I ; B 64 0 367 718 ;\nC 74 ; WX 556 ; N J ; B 60 -18 637 718 ;\nC 75 ; WX 722 ; N K ; B 87 0 858 718 ;\nC 76 ; WX 611 ; N L ; B 76 0 611 718 ;\nC 77 ; WX 833 ; N M ; B 69 0 918 718 ;\nC 78 ; WX 722 ; N N ; B 69 0 807 718 ;\nC 79 ; WX 778 ; N O ; B 107 -19 823 737 ;\nC 80 ; WX 667 ; N P ; B 76 0 738 718 ;\nC 81 ; WX 778 ; N Q ; B 107 -52 823 737 ;\nC 82 ; WX 722 ; N R ; B 76 0 778 718 ;\nC 83 ; WX 667 ; N S ; B 81 -19 718 737 ;\nC 84 ; WX 611 ; N T ; B 140 0 751 718 ;\nC 85 ; WX 722 ; N U ; B 116 -19 804 718 ;\nC 86 ; WX 667 ; N V ; B 172 0 801 718 ;\nC 87 ; WX 944 ; N W ; B 169 0 1082 718 ;\nC 88 ; WX 667 ; N X ; B 14 0 791 718 ;\nC 89 ; WX 667 ; N Y ; B 168 0 806 718 ;\nC 90 ; WX 611 ; N Z ; B 25 0 737 718 ;\nC 91 ; WX 333 ; N bracketleft ; B 21 -196 462 722 ;\nC 92 ; WX 278 ; N backslash ; B 124 -19 307 737 ;\nC 93 ; WX 333 ; N bracketright ; B -18 -196 423 722 ;\nC 94 ; WX 584 ; N asciicircum ; B 131 323 591 698 ;\nC 95 ; WX 556 ; N underscore ; B -27 -125 540 -75 ;\nC 96 ; WX 278 ; N quoteleft ; B 165 454 361 727 ;\nC 97 ; WX 556 ; N a ; B 55 -14 583 546 ;\nC 98 ; WX 611 ; N b ; B 61 -14 645 718 ;\nC 99 ; WX 556 ; N c ; B 79 -14 599 546 ;\nC 100 ; WX 611 ; N d ; B 82 -14 704 718 ;\nC 101 ; WX 556 ; N e ; B 70 -14 593 546 ;\nC 102 ; WX 333 ; N f ; B 87 0 469 727 ; L i fi ; L l fl ;\nC 103 ; WX 611 ; N g ; B 38 -217 666 546 ;\nC 104 ; WX 611 ; N h ; B 65 0 629 718 ;\nC 105 ; WX 278 ;
},
"Times-Roman": function() {
return "StartFontMetrics 4.1\nComment Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.\nComment Creation Date: Thu May 1 12:49:17 1997\nComment UniqueID 43068\nComment VMusage 43909 54934\nFontName Times-Roman\nFullName Times Roman\nFamilyName Times\nWeight Roman\nItalicAngle 0\nIsFixedPitch false\nCharacterSet ExtendedRoman\nFontBBox -168 -218 1000 898 \nUnderlinePosition -100\nUnderlineThickness 50\nVersion 002.000\nNotice Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.Times is a trademark of Linotype-Hell AG and/or its subsidiaries.\nEncodingScheme AdobeStandardEncoding\nCapHeight 662\nXHeight 450\nAscender 683\nDescender -217\nStdHW 28\nStdVW 84\nStartCharMetrics 315\nC 32 ; WX 250 ; N space ; B 0 0 0 0 ;\nC 33 ; WX 333 ; N exclam ; B 130 -9 238 676 ;\nC 34 ; WX 408 ; N quotedbl ; B 77 431 331 676 ;\nC 35 ; WX 500 ; N numbersign ; B 5 0 496 662 ;\nC 36 ; WX 500 ; N dollar ; B 44 -87 457 727 ;\nC 37 ; WX 833 ; N percent ; B 61 -13 772 676 ;\nC 38 ; WX 778 ; N ampersand ; B 42 -13 750 676 ;\nC 39 ; WX 333 ; N quoteright ; B 79 433 218 676 ;\nC 40 ; WX 333 ; N parenleft ; B 48 -177 304 676 ;\nC 41 ; WX 333 ; N parenright ; B 29 -177 285 676 ;\nC 42 ; WX 500 ; N asterisk ; B 69 265 432 676 ;\nC 43 ; WX 564 ; N plus ; B 30 0 534 506 ;\nC 44 ; WX 250 ; N comma ; B 56 -141 195 102 ;\nC 45 ; WX 333 ; N hyphen ; B 39 194 285 257 ;\nC 46 ; WX 250 ; N period ; B 70 -11 181 100 ;\nC 47 ; WX 278 ; N slash ; B -9 -14 287 676 ;\nC 48 ; WX 500 ; N zero ; B 24 -14 476 676 ;\nC 49 ; WX 500 ; N one ; B 111 0 394 676 ;\nC 50 ; WX 500 ; N two ; B 30 0 475 676 ;\nC 51 ; WX 500 ; N three ; B 43 -14 431 676 ;\nC 52 ; WX 500 ; N four ; B 12 0 472 676 ;\nC 53 ; WX 500 ; N five ; B 32 -14 438 688 ;\nC 54 ; WX 500 ; N six ; B 34 -14 468 684 ;\nC 55 ; WX 500 ; N seven ; B 20 -8 449 662 ;\nC 56 ; WX 500 ; N eight ; B 56 -14 445 676 ;\nC 57 ; WX 500 ; N nine ; B 30 -22 459 676 ;\nC 58 ; WX 278 ; N colon ; B 81 -11 192 459 ;\nC 59 ; WX 278 ; N semicolon ; B 80 -141 219 459 ;\nC 60 ; WX 564 ; N less ; B 28 -8 536 514 ;\nC 61 ; WX 564 ; N equal ; B 30 120 534 386 ;\nC 62 ; WX 564 ; N greater ; B 28 -8 536 514 ;\nC 63 ; WX 444 ; N question ; B 68 -8 414 676 ;\nC 64 ; WX 921 ; N at ; B 116 -14 809 676 ;\nC 65 ; WX 722 ; N A ; B 15 0 706 674 ;\nC 66 ; WX 667 ; N B ; B 17 0 593 662 ;\nC 67 ; WX 667 ; N C ; B 28 -14 633 676 ;\nC 68 ; WX 722 ; N D ; B 16 0 685 662 ;\nC 69 ; WX 611 ; N E ; B 12 0 597 662 ;\nC 70 ; WX 556 ; N F ; B 12 0 546 662 ;\nC 71 ; WX 722 ; N G ; B 32 -14 709 676 ;\nC 72 ; WX 722 ; N H ; B 19 0 702 662 ;\nC 73 ; WX 333 ; N I ; B 18 0 315 662 ;\nC 74 ; WX 389 ; N J ; B 10 -14 370 662 ;\nC 75 ; WX 722 ; N K ; B 34 0 723 662 ;\nC 76 ; WX 611 ; N L ; B 12 0 598 662 ;\nC 77 ; WX 889 ; N M ; B 12 0 863 662 ;\nC 78 ; WX 722 ; N N ; B 12 -11 707 662 ;\nC 79 ; WX 722 ; N O ; B 34 -14 688 676 ;\nC 80 ; WX 556 ; N P ; B 16 0 542 662 ;\nC 81 ; WX 722 ; N Q ; B 34 -178 701 676 ;\nC 82 ; WX 667 ; N R ; B 17 0 659 662 ;\nC 83 ; WX 556 ; N S ; B 42 -14 491 676 ;\nC 84 ; WX 611 ; N T ; B 17 0 593 662 ;\nC 85 ; WX 722 ; N U ; B 14 -14 705 662 ;\nC 86 ; WX 722 ; N V ; B 16 -11 697 662 ;\nC 87 ; WX 944 ; N W ; B 5 -11 932 662 ;\nC 88 ; WX 722 ; N X ; B 10 0 704 662 ;\nC 89 ; WX 722 ; N Y ; B 22 0 703 662 ;\nC 90 ; WX 611 ; N Z ; B 9 0 597 662 ;\nC 91 ; WX 333 ; N bracketleft ; B 88 -156 299 662 ;\nC 92 ; WX 278 ; N backslash ; B -9 -14 287 676 ;\nC 93 ; WX 333 ; N bracketright ; B 34 -156 245 662 ;\nC 94 ; WX 469 ; N asciicircum ; B 24 297 446 662 ;\nC 95 ; WX 500 ; N underscore ; B 0 -125 500 -75 ;\nC 96 ; WX 333 ; N quoteleft ; B 115 433 254 676 ;\nC 97 ; WX 444 ; N a ; B 37 -10 442 460 ;\nC 98 ; WX 500 ; N b ; B 3 -10 468 683 ;\nC 99 ; WX 444 ; N c ; B 25 -10 412 460 ;\nC 100 ; WX 500 ; N d ; B 27 -10 491 683 ;\nC 101 ; WX 444 ; N e ; B 25 -10 424 460 ;\nC 102 ; WX 333 ; N f ; B 20 0 383 683 ; L i fi ; L l fl ;\nC 103 ; WX 500 ; N g ; B 28 -218 470 460 ;\nC 104 ; WX 500 ; N h ; B 9 0 487 683 ;\nC 105 ; WX 278 ; N i ; B 16 0 253 683 ;\nC 106 ;
},
"Times-Bold": function() {
return "StartFontMetrics 4.1\nComment Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.\nComment Creation Date: Thu May 1 12:52:56 1997\nComment UniqueID 43065\nComment VMusage 41636 52661\nFontName Times-Bold\nFullName Times Bold\nFamilyName Times\nWeight Bold\nItalicAngle 0\nIsFixedPitch false\nCharacterSet ExtendedRoman\nFontBBox -168 -218 1000 935 \nUnderlinePosition -100\nUnderlineThickness 50\nVersion 002.000\nNotice Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.Times is a trademark of Linotype-Hell AG and/or its subsidiaries.\nEncodingScheme AdobeStandardEncoding\nCapHeight 676\nXHeight 461\nAscender 683\nDescender -217\nStdHW 44\nStdVW 139\nStartCharMetrics 315\nC 32 ; WX 250 ; N space ; B 0 0 0 0 ;\nC 33 ; WX 333 ; N exclam ; B 81 -13 251 691 ;\nC 34 ; WX 555 ; N quotedbl ; B 83 404 472 691 ;\nC 35 ; WX 500 ; N numbersign ; B 4 0 496 700 ;\nC 36 ; WX 500 ; N dollar ; B 29 -99 472 750 ;\nC 37 ; WX 1000 ; N percent ; B 124 -14 877 692 ;\nC 38 ; WX 833 ; N ampersand ; B 62 -16 787 691 ;\nC 39 ; WX 333 ; N quoteright ; B 79 356 263 691 ;\nC 40 ; WX 333 ; N parenleft ; B 46 -168 306 694 ;\nC 41 ; WX 333 ; N parenright ; B 27 -168 287 694 ;\nC 42 ; WX 500 ; N asterisk ; B 56 255 447 691 ;\nC 43 ; WX 570 ; N plus ; B 33 0 537 506 ;\nC 44 ; WX 250 ; N comma ; B 39 -180 223 155 ;\nC 45 ; WX 333 ; N hyphen ; B 44 171 287 287 ;\nC 46 ; WX 250 ; N period ; B 41 -13 210 156 ;\nC 47 ; WX 278 ; N slash ; B -24 -19 302 691 ;\nC 48 ; WX 500 ; N zero ; B 24 -13 476 688 ;\nC 49 ; WX 500 ; N one ; B 65 0 442 688 ;\nC 50 ; WX 500 ; N two ; B 17 0 478 688 ;\nC 51 ; WX 500 ; N three ; B 16 -14 468 688 ;\nC 52 ; WX 500 ; N four ; B 19 0 475 688 ;\nC 53 ; WX 500 ; N five ; B 22 -8 470 676 ;\nC 54 ; WX 500 ; N six ; B 28 -13 475 688 ;\nC 55 ; WX 500 ; N seven ; B 17 0 477 676 ;\nC 56 ; WX 500 ; N eight ; B 28 -13 472 688 ;\nC 57 ; WX 500 ; N nine ; B 26 -13 473 688 ;\nC 58 ; WX 333 ; N colon ; B 82 -13 251 472 ;\nC 59 ; WX 333 ; N semicolon ; B 82 -180 266 472 ;\nC 60 ; WX 570 ; N less ; B 31 -8 539 514 ;\nC 61 ; WX 570 ; N equal ; B 33 107 537 399 ;\nC 62 ; WX 570 ; N greater ; B 31 -8 539 514 ;\nC 63 ; WX 500 ; N question ; B 57 -13 445 689 ;\nC 64 ; WX 930 ; N at ; B 108 -19 822 691 ;\nC 65 ; WX 722 ; N A ; B 9 0 689 690 ;\nC 66 ; WX 667 ; N B ; B 16 0 619 676 ;\nC 67 ; WX 722 ; N C ; B 49 -19 687 691 ;\nC 68 ; WX 722 ; N D ; B 14 0 690 676 ;\nC 69 ; WX 667 ; N E ; B 16 0 641 676 ;\nC 70 ; WX 611 ; N F ; B 16 0 583 676 ;\nC 71 ; WX 778 ; N G ; B 37 -19 755 691 ;\nC 72 ; WX 778 ; N H ; B 21 0 759 676 ;\nC 73 ; WX 389 ; N I ; B 20 0 370 676 ;\nC 74 ; WX 500 ; N J ; B 3 -96 479 676 ;\nC 75 ; WX 778 ; N K ; B 30 0 769 676 ;\nC 76 ; WX 667 ; N L ; B 19 0 638 676 ;\nC 77 ; WX 944 ; N M ; B 14 0 921 676 ;\nC 78 ; WX 722 ; N N ; B 16 -18 701 676 ;\nC 79 ; WX 778 ; N O ; B 35 -19 743 691 ;\nC 80 ; WX 611 ; N P ; B 16 0 600 676 ;\nC 81 ; WX 778 ; N Q ; B 35 -176 743 691 ;\nC 82 ; WX 722 ; N R ; B 26 0 715 676 ;\nC 83 ; WX 556 ; N S ; B 35 -19 513 692 ;\nC 84 ; WX 667 ; N T ; B 31 0 636 676 ;\nC 85 ; WX 722 ; N U ; B 16 -19 701 676 ;\nC 86 ; WX 722 ; N V ; B 16 -18 701 676 ;\nC 87 ; WX 1000 ; N W ; B 19 -15 981 676 ;\nC 88 ; WX 722 ; N X ; B 16 0 699 676 ;\nC 89 ; WX 722 ; N Y ; B 15 0 699 676 ;\nC 90 ; WX 667 ; N Z ; B 28 0 634 676 ;\nC 91 ; WX 333 ; N bracketleft ; B 67 -149 301 678 ;\nC 92 ; WX 278 ; N backslash ; B -25 -19 303 691 ;\nC 93 ; WX 333 ; N bracketright ; B 32 -149 266 678 ;\nC 94 ; WX 581 ; N asciicircum ; B 73 311 509 676 ;\nC 95 ; WX 500 ; N underscore ; B 0 -125 500 -75 ;\nC 96 ; WX 333 ; N quoteleft ; B 70 356 254 691 ;\nC 97 ; WX 500 ; N a ; B 25 -14 488 473 ;\nC 98 ; WX 556 ; N b ; B 17 -14 521 676 ;\nC 99 ; WX 444 ; N c ; B 25 -14 430 473 ;\nC 100 ; WX 556 ; N d ; B 25 -14 534 676 ;\nC 101 ; WX 444 ; N e ; B 25 -14 426 473 ;\nC 102 ; WX 333 ; N f ; B 14 0 389 691 ; L i fi ; L l fl ;\nC 103 ; WX 500 ; N g ; B 28 -206 483 473 ;\nC 104 ; WX 556 ; N h ; B 16 0 534 676 ;\nC 105 ; WX 278 ; N i ; B 16 0 255 691 ;\nC 106
},
"Times-Italic": function() {
return "StartFontMetrics 4.1\nComment Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.\nComment Creation Date: Thu May 1 12:56:55 1997\nComment UniqueID 43067\nComment VMusage 47727 58752\nFontName Times-Italic\nFullName Times Italic\nFamilyName Times\nWeight Medium\nItalicAngle -15.5\nIsFixedPitch false\nCharacterSet ExtendedRoman\nFontBBox -169 -217 1010 883 \nUnderlinePosition -100\nUnderlineThickness 50\nVersion 002.000\nNotice Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.Times is a trademark of Linotype-Hell AG and/or its subsidiaries.\nEncodingScheme AdobeStandardEncoding\nCapHeight 653\nXHeight 441\nAscender 683\nDescender -217\nStdHW 32\nStdVW 76\nStartCharMetrics 315\nC 32 ; WX 250 ; N space ; B 0 0 0 0 ;\nC 33 ; WX 333 ; N exclam ; B 39 -11 302 667 ;\nC 34 ; WX 420 ; N quotedbl ; B 144 421 432 666 ;\nC 35 ; WX 500 ; N numbersign ; B 2 0 540 676 ;\nC 36 ; WX 500 ; N dollar ; B 31 -89 497 731 ;\nC 37 ; WX 833 ; N percent ; B 79 -13 790 676 ;\nC 38 ; WX 778 ; N ampersand ; B 76 -18 723 666 ;\nC 39 ; WX 333 ; N quoteright ; B 151 436 290 666 ;\nC 40 ; WX 333 ; N parenleft ; B 42 -181 315 669 ;\nC 41 ; WX 333 ; N parenright ; B 16 -180 289 669 ;\nC 42 ; WX 500 ; N asterisk ; B 128 255 492 666 ;\nC 43 ; WX 675 ; N plus ; B 86 0 590 506 ;\nC 44 ; WX 250 ; N comma ; B -4 -129 135 101 ;\nC 45 ; WX 333 ; N hyphen ; B 49 192 282 255 ;\nC 46 ; WX 250 ; N period ; B 27 -11 138 100 ;\nC 47 ; WX 278 ; N slash ; B -65 -18 386 666 ;\nC 48 ; WX 500 ; N zero ; B 32 -7 497 676 ;\nC 49 ; WX 500 ; N one ; B 49 0 409 676 ;\nC 50 ; WX 500 ; N two ; B 12 0 452 676 ;\nC 51 ; WX 500 ; N three ; B 15 -7 465 676 ;\nC 52 ; WX 500 ; N four ; B 1 0 479 676 ;\nC 53 ; WX 500 ; N five ; B 15 -7 491 666 ;\nC 54 ; WX 500 ; N six ; B 30 -7 521 686 ;\nC 55 ; WX 500 ; N seven ; B 75 -8 537 666 ;\nC 56 ; WX 500 ; N eight ; B 30 -7 493 676 ;\nC 57 ; WX 500 ; N nine ; B 23 -17 492 676 ;\nC 58 ; WX 333 ; N colon ; B 50 -11 261 441 ;\nC 59 ; WX 333 ; N semicolon ; B 27 -129 261 441 ;\nC 60 ; WX 675 ; N less ; B 84 -8 592 514 ;\nC 61 ; WX 675 ; N equal ; B 86 120 590 386 ;\nC 62 ; WX 675 ; N greater ; B 84 -8 592 514 ;\nC 63 ; WX 500 ; N question ; B 132 -12 472 664 ;\nC 64 ; WX 920 ; N at ; B 118 -18 806 666 ;\nC 65 ; WX 611 ; N A ; B -51 0 564 668 ;\nC 66 ; WX 611 ; N B ; B -8 0 588 653 ;\nC 67 ; WX 667 ; N C ; B 66 -18 689 666 ;\nC 68 ; WX 722 ; N D ; B -8 0 700 653 ;\nC 69 ; WX 611 ; N E ; B -1 0 634 653 ;\nC 70 ; WX 611 ; N F ; B 8 0 645 653 ;\nC 71 ; WX 722 ; N G ; B 52 -18 722 666 ;\nC 72 ; WX 722 ; N H ; B -8 0 767 653 ;\nC 73 ; WX 333 ; N I ; B -8 0 384 653 ;\nC 74 ; WX 444 ; N J ; B -6 -18 491 653 ;\nC 75 ; WX 667 ; N K ; B 7 0 722 653 ;\nC 76 ; WX 556 ; N L ; B -8 0 559 653 ;\nC 77 ; WX 833 ; N M ; B -18 0 873 653 ;\nC 78 ; WX 667 ; N N ; B -20 -15 727 653 ;\nC 79 ; WX 722 ; N O ; B 60 -18 699 666 ;\nC 80 ; WX 611 ; N P ; B 0 0 605 653 ;\nC 81 ; WX 722 ; N Q ; B 59 -182 699 666 ;\nC 82 ; WX 611 ; N R ; B -13 0 588 653 ;\nC 83 ; WX 500 ; N S ; B 17 -18 508 667 ;\nC 84 ; WX 556 ; N T ; B 59 0 633 653 ;\nC 85 ; WX 722 ; N U ; B 102 -18 765 653 ;\nC 86 ; WX 611 ; N V ; B 76 -18 688 653 ;\nC 87 ; WX 833 ; N W ; B 71 -18 906 653 ;\nC 88 ; WX 611 ; N X ; B -29 0 655 653 ;\nC 89 ; WX 556 ; N Y ; B 78 0 633 653 ;\nC 90 ; WX 556 ; N Z ; B -6 0 606 653 ;\nC 91 ; WX 389 ; N bracketleft ; B 21 -153 391 663 ;\nC 92 ; WX 278 ; N backslash ; B -41 -18 319 666 ;\nC 93 ; WX 389 ; N bracketright ; B 12 -153 382 663 ;\nC 94 ; WX 422 ; N asciicircum ; B 0 301 422 666 ;\nC 95 ; WX 500 ; N underscore ; B 0 -125 500 -75 ;\nC 96 ; WX 333 ; N quoteleft ; B 171 436 310 666 ;\nC 97 ; WX 500 ; N a ; B 17 -11 476 441 ;\nC 98 ; WX 500 ; N b ; B 23 -11 473 683 ;\nC 99 ; WX 444 ; N c ; B 30 -11 425 441 ;\nC 100 ; WX 500 ; N d ; B 15 -13 527 683 ;\nC 101 ; WX 444 ; N e ; B 31 -11 412 441 ;\nC 102 ; WX 278 ; N f ; B -147 -207 424 678 ; L i fi ; L l fl ;\nC 103 ; WX 500 ; N g ; B 8 -206 472 441 ;\nC 104 ; WX 500 ; N h ; B 19 -9 478 683 ;\nC 105 ; WX 278 ; N i ; B 49 -11
},
"Times-BoldItalic": function() {
return "StartFontMetrics 4.1\nComment Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.\nComment Creation Date: Thu May 1 13:04:06 1997\nComment UniqueID 43066\nComment VMusage 45874 56899\nFontName Times-BoldItalic\nFullName Times Bold Italic\nFamilyName Times\nWeight Bold\nItalicAngle -15\nIsFixedPitch false\nCharacterSet ExtendedRoman\nFontBBox -200 -218 996 921 \nUnderlinePosition -100\nUnderlineThickness 50\nVersion 002.000\nNotice Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.Times is a trademark of Linotype-Hell AG and/or its subsidiaries.\nEncodingScheme AdobeStandardEncoding\nCapHeight 669\nXHeight 462\nAscender 683\nDescender -217\nStdHW 42\nStdVW 121\nStartCharMetrics 315\nC 32 ; WX 250 ; N space ; B 0 0 0 0 ;\nC 33 ; WX 389 ; N exclam ; B 67 -13 370 684 ;\nC 34 ; WX 555 ; N quotedbl ; B 136 398 536 685 ;\nC 35 ; WX 500 ; N numbersign ; B -33 0 533 700 ;\nC 36 ; WX 500 ; N dollar ; B -20 -100 497 733 ;\nC 37 ; WX 833 ; N percent ; B 39 -10 793 692 ;\nC 38 ; WX 778 ; N ampersand ; B 5 -19 699 682 ;\nC 39 ; WX 333 ; N quoteright ; B 98 369 302 685 ;\nC 40 ; WX 333 ; N parenleft ; B 28 -179 344 685 ;\nC 41 ; WX 333 ; N parenright ; B -44 -179 271 685 ;\nC 42 ; WX 500 ; N asterisk ; B 65 249 456 685 ;\nC 43 ; WX 570 ; N plus ; B 33 0 537 506 ;\nC 44 ; WX 250 ; N comma ; B -60 -182 144 134 ;\nC 45 ; WX 333 ; N hyphen ; B 2 166 271 282 ;\nC 46 ; WX 250 ; N period ; B -9 -13 139 135 ;\nC 47 ; WX 278 ; N slash ; B -64 -18 342 685 ;\nC 48 ; WX 500 ; N zero ; B 17 -14 477 683 ;\nC 49 ; WX 500 ; N one ; B 5 0 419 683 ;\nC 50 ; WX 500 ; N two ; B -27 0 446 683 ;\nC 51 ; WX 500 ; N three ; B -15 -13 450 683 ;\nC 52 ; WX 500 ; N four ; B -15 0 503 683 ;\nC 53 ; WX 500 ; N five ; B -11 -13 487 669 ;\nC 54 ; WX 500 ; N six ; B 23 -15 509 679 ;\nC 55 ; WX 500 ; N seven ; B 52 0 525 669 ;\nC 56 ; WX 500 ; N eight ; B 3 -13 476 683 ;\nC 57 ; WX 500 ; N nine ; B -12 -10 475 683 ;\nC 58 ; WX 333 ; N colon ; B 23 -13 264 459 ;\nC 59 ; WX 333 ; N semicolon ; B -25 -183 264 459 ;\nC 60 ; WX 570 ; N less ; B 31 -8 539 514 ;\nC 61 ; WX 570 ; N equal ; B 33 107 537 399 ;\nC 62 ; WX 570 ; N greater ; B 31 -8 539 514 ;\nC 63 ; WX 500 ; N question ; B 79 -13 470 684 ;\nC 64 ; WX 832 ; N at ; B 63 -18 770 685 ;\nC 65 ; WX 667 ; N A ; B -67 0 593 683 ;\nC 66 ; WX 667 ; N B ; B -24 0 624 669 ;\nC 67 ; WX 667 ; N C ; B 32 -18 677 685 ;\nC 68 ; WX 722 ; N D ; B -46 0 685 669 ;\nC 69 ; WX 667 ; N E ; B -27 0 653 669 ;\nC 70 ; WX 667 ; N F ; B -13 0 660 669 ;\nC 71 ; WX 722 ; N G ; B 21 -18 706 685 ;\nC 72 ; WX 778 ; N H ; B -24 0 799 669 ;\nC 73 ; WX 389 ; N I ; B -32 0 406 669 ;\nC 74 ; WX 500 ; N J ; B -46 -99 524 669 ;\nC 75 ; WX 667 ; N K ; B -21 0 702 669 ;\nC 76 ; WX 611 ; N L ; B -22 0 590 669 ;\nC 77 ; WX 889 ; N M ; B -29 -12 917 669 ;\nC 78 ; WX 722 ; N N ; B -27 -15 748 669 ;\nC 79 ; WX 722 ; N O ; B 27 -18 691 685 ;\nC 80 ; WX 611 ; N P ; B -27 0 613 669 ;\nC 81 ; WX 722 ; N Q ; B 27 -208 691 685 ;\nC 82 ; WX 667 ; N R ; B -29 0 623 669 ;\nC 83 ; WX 556 ; N S ; B 2 -18 526 685 ;\nC 84 ; WX 611 ; N T ; B 50 0 650 669 ;\nC 85 ; WX 722 ; N U ; B 67 -18 744 669 ;\nC 86 ; WX 667 ; N V ; B 65 -18 715 669 ;\nC 87 ; WX 889 ; N W ; B 65 -18 940 669 ;\nC 88 ; WX 667 ; N X ; B -24 0 694 669 ;\nC 89 ; WX 611 ; N Y ; B 73 0 659 669 ;\nC 90 ; WX 611 ; N Z ; B -11 0 590 669 ;\nC 91 ; WX 333 ; N bracketleft ; B -37 -159 362 674 ;\nC 92 ; WX 278 ; N backslash ; B -1 -18 279 685 ;\nC 93 ; WX 333 ; N bracketright ; B -56 -157 343 674 ;\nC 94 ; WX 570 ; N asciicircum ; B 67 304 503 669 ;\nC 95 ; WX 500 ; N underscore ; B 0 -125 500 -75 ;\nC 96 ; WX 333 ; N quoteleft ; B 128 369 332 685 ;\nC 97 ; WX 500 ; N a ; B -21 -14 455 462 ;\nC 98 ; WX 500 ; N b ; B -14 -13 444 699 ;\nC 99 ; WX 444 ; N c ; B -5 -13 392 462 ;\nC 100 ; WX 500 ; N d ; B -21 -13 517 699 ;\nC 101 ; WX 444 ; N e ; B 5 -13 398 462 ;\nC 102 ; WX 333 ; N f ; B -169 -205 446 698 ; L i fi ; L l fl ;\nC 103 ; WX 500 ; N g ; B -52 -203 478 462 ;\nC 104 ; WX 556 ; N h ; B -13 -9 498 699
},
"Symbol": function() {
return "StartFontMetrics 4.1\nComment Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All rights reserved.\nComment Creation Date: Thu May 1 15:12:25 1997\nComment UniqueID 43064\nComment VMusage 30820 39997\nFontName Symbol\nFullName Symbol\nFamilyName Symbol\nWeight Medium\nItalicAngle 0\nIsFixedPitch false\nCharacterSet Special\nFontBBox -180 -293 1090 1010 \nUnderlinePosition -100\nUnderlineThickness 50\nVersion 001.008\nNotice Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All rights reserved.\nEncodingScheme FontSpecific\nStdHW 92\nStdVW 85\nStartCharMetrics 190\nC 32 ; WX 250 ; N space ; B 0 0 0 0 ;\nC 33 ; WX 333 ; N exclam ; B 128 -17 240 672 ;\nC 34 ; WX 713 ; N universal ; B 31 0 681 705 ;\nC 35 ; WX 500 ; N numbersign ; B 20 -16 481 673 ;\nC 36 ; WX 549 ; N existential ; B 25 0 478 707 ;\nC 37 ; WX 833 ; N percent ; B 63 -36 771 655 ;\nC 38 ; WX 778 ; N ampersand ; B 41 -18 750 661 ;\nC 39 ; WX 439 ; N suchthat ; B 48 -17 414 500 ;\nC 40 ; WX 333 ; N parenleft ; B 53 -191 300 673 ;\nC 41 ; WX 333 ; N parenright ; B 30 -191 277 673 ;\nC 42 ; WX 500 ; N asteriskmath ; B 65 134 427 551 ;\nC 43 ; WX 549 ; N plus ; B 10 0 539 533 ;\nC 44 ; WX 250 ; N comma ; B 56 -152 194 104 ;\nC 45 ; WX 549 ; N minus ; B 11 233 535 288 ;\nC 46 ; WX 250 ; N period ; B 69 -17 181 95 ;\nC 47 ; WX 278 ; N slash ; B 0 -18 254 646 ;\nC 48 ; WX 500 ; N zero ; B 24 -14 476 685 ;\nC 49 ; WX 500 ; N one ; B 117 0 390 673 ;\nC 50 ; WX 500 ; N two ; B 25 0 475 685 ;\nC 51 ; WX 500 ; N three ; B 43 -14 435 685 ;\nC 52 ; WX 500 ; N four ; B 15 0 469 685 ;\nC 53 ; WX 500 ; N five ; B 32 -14 445 690 ;\nC 54 ; WX 500 ; N six ; B 34 -14 468 685 ;\nC 55 ; WX 500 ; N seven ; B 24 -16 448 673 ;\nC 56 ; WX 500 ; N eight ; B 56 -14 445 685 ;\nC 57 ; WX 500 ; N nine ; B 30 -18 459 685 ;\nC 58 ; WX 278 ; N colon ; B 81 -17 193 460 ;\nC 59 ; WX 278 ; N semicolon ; B 83 -152 221 460 ;\nC 60 ; WX 549 ; N less ; B 26 0 523 522 ;\nC 61 ; WX 549 ; N equal ; B 11 141 537 390 ;\nC 62 ; WX 549 ; N greater ; B 26 0 523 522 ;\nC 63 ; WX 444 ; N question ; B 70 -17 412 686 ;\nC 64 ; WX 549 ; N congruent ; B 11 0 537 475 ;\nC 65 ; WX 722 ; N Alpha ; B 4 0 684 673 ;\nC 66 ; WX 667 ; N Beta ; B 29 0 592 673 ;\nC 67 ; WX 722 ; N Chi ; B -9 0 704 673 ;\nC 68 ; WX 612 ; N Delta ; B 6 0 608 688 ;\nC 69 ; WX 611 ; N Epsilon ; B 32 0 617 673 ;\nC 70 ; WX 763 ; N Phi ; B 26 0 741 673 ;\nC 71 ; WX 603 ; N Gamma ; B 24 0 609 673 ;\nC 72 ; WX 722 ; N Eta ; B 39 0 729 673 ;\nC 73 ; WX 333 ; N Iota ; B 32 0 316 673 ;\nC 74 ; WX 631 ; N theta1 ; B 18 -18 623 689 ;\nC 75 ; WX 722 ; N Kappa ; B 35 0 722 673 ;\nC 76 ; WX 686 ; N Lambda ; B 6 0 680 688 ;\nC 77 ; WX 889 ; N Mu ; B 28 0 887 673 ;\nC 78 ; WX 722 ; N Nu ; B 29 -8 720 673 ;\nC 79 ; WX 722 ; N Omicron ; B 41 -17 715 685 ;\nC 80 ; WX 768 ; N Pi ; B 25 0 745 673 ;\nC 81 ; WX 741 ; N Theta ; B 41 -17 715 685 ;\nC 82 ; WX 556 ; N Rho ; B 28 0 563 673 ;\nC 83 ; WX 592 ; N Sigma ; B 5 0 589 673 ;\nC 84 ; WX 611 ; N Tau ; B 33 0 607 673 ;\nC 85 ; WX 690 ; N Upsilon ; B -8 0 694 673 ;\nC 86 ; WX 439 ; N sigma1 ; B 40 -233 436 500 ;\nC 87 ; WX 768 ; N Omega ; B 34 0 736 688 ;\nC 88 ; WX 645 ; N Xi ; B 40 0 599 673 ;\nC 89 ; WX 795 ; N Psi ; B 15 0 781 684 ;\nC 90 ; WX 611 ; N Zeta ; B 44 0 636 673 ;\nC 91 ; WX 333 ; N bracketleft ; B 86 -155 299 674 ;\nC 92 ; WX 863 ; N therefore ; B 163 0 701 487 ;\nC 93 ; WX 333 ; N bracketright ; B 33 -155 246 674 ;\nC 94 ; WX 658 ; N perpendicular ; B 15 0 652 674 ;\nC 95 ; WX 500 ; N underscore ; B -2 -125 502 -75 ;\nC 96 ; WX 500 ; N radicalex ; B 480 881 1090 917 ;\nC 97 ; WX 631 ; N alpha ; B 41 -18 622 500 ;\nC 98 ; WX 549 ; N beta ; B 61 -223 515 741 ;\nC 99 ; WX 549 ; N chi ; B 12 -231 522 499 ;\nC 100 ; WX 494 ; N delta ; B 40 -19 481 740 ;\nC 101 ; WX 439 ; N epsilon ; B 22 -19 427 502 ;\nC 102 ; WX 521 ; N phi ; B 28 -224 492 673 ;\nC 103 ; WX 411 ; N gamma ; B 5 -225 484 499 ;\nC 104 ; WX 603 ; N eta ; B 0 -202 527 514 ;\nC 105 ; WX 329 ; N iota ; B 0 -17 301 503 ;\nC 106 ; WX 603 ; N phi1 ; B 36 -224 587 499 ;\nC 107 ; WX 549 ;
},
"ZapfDingbats": function() {
return "StartFontMetrics 4.1\nComment Copyright (c) 1985, 1987, 1988, 1989, 1997 Adobe Systems Incorporated. All Rights Reserved.\nComment Creation Date: Thu May 1 15:14:13 1997\nComment UniqueID 43082\nComment VMusage 45775 55535\nFontName ZapfDingbats\nFullName ITC Zapf Dingbats\nFamilyName ZapfDingbats\nWeight Medium\nItalicAngle 0\nIsFixedPitch false\nCharacterSet Special\nFontBBox -1 -143 981 820 \nUnderlinePosition -100\nUnderlineThickness 50\nVersion 002.000\nNotice Copyright (c) 1985, 1987, 1988, 1989, 1997 Adobe Systems Incorporated. All Rights Reserved.ITC Zapf Dingbats is a registered trademark of International Typeface Corporation.\nEncodingScheme FontSpecific\nStdHW 28\nStdVW 90\nStartCharMetrics 202\nC 32 ; WX 278 ; N space ; B 0 0 0 0 ;\nC 33 ; WX 974 ; N a1 ; B 35 72 939 621 ;\nC 34 ; WX 961 ; N a2 ; B 35 81 927 611 ;\nC 35 ; WX 974 ; N a202 ; B 35 72 939 621 ;\nC 36 ; WX 980 ; N a3 ; B 35 0 945 692 ;\nC 37 ; WX 719 ; N a4 ; B 34 139 685 566 ;\nC 38 ; WX 789 ; N a5 ; B 35 -14 755 705 ;\nC 39 ; WX 790 ; N a119 ; B 35 -14 755 705 ;\nC 40 ; WX 791 ; N a118 ; B 35 -13 761 705 ;\nC 41 ; WX 690 ; N a117 ; B 34 138 655 553 ;\nC 42 ; WX 960 ; N a11 ; B 35 123 925 568 ;\nC 43 ; WX 939 ; N a12 ; B 35 134 904 559 ;\nC 44 ; WX 549 ; N a13 ; B 29 -11 516 705 ;\nC 45 ; WX 855 ; N a14 ; B 34 59 820 632 ;\nC 46 ; WX 911 ; N a15 ; B 35 50 876 642 ;\nC 47 ; WX 933 ; N a16 ; B 35 139 899 550 ;\nC 48 ; WX 911 ; N a105 ; B 35 50 876 642 ;\nC 49 ; WX 945 ; N a17 ; B 35 139 909 553 ;\nC 50 ; WX 974 ; N a18 ; B 35 104 938 587 ;\nC 51 ; WX 755 ; N a19 ; B 34 -13 721 705 ;\nC 52 ; WX 846 ; N a20 ; B 36 -14 811 705 ;\nC 53 ; WX 762 ; N a21 ; B 35 0 727 692 ;\nC 54 ; WX 761 ; N a22 ; B 35 0 727 692 ;\nC 55 ; WX 571 ; N a23 ; B -1 -68 571 661 ;\nC 56 ; WX 677 ; N a24 ; B 36 -13 642 705 ;\nC 57 ; WX 763 ; N a25 ; B 35 0 728 692 ;\nC 58 ; WX 760 ; N a26 ; B 35 0 726 692 ;\nC 59 ; WX 759 ; N a27 ; B 35 0 725 692 ;\nC 60 ; WX 754 ; N a28 ; B 35 0 720 692 ;\nC 61 ; WX 494 ; N a6 ; B 35 0 460 692 ;\nC 62 ; WX 552 ; N a7 ; B 35 0 517 692 ;\nC 63 ; WX 537 ; N a8 ; B 35 0 503 692 ;\nC 64 ; WX 577 ; N a9 ; B 35 96 542 596 ;\nC 65 ; WX 692 ; N a10 ; B 35 -14 657 705 ;\nC 66 ; WX 786 ; N a29 ; B 35 -14 751 705 ;\nC 67 ; WX 788 ; N a30 ; B 35 -14 752 705 ;\nC 68 ; WX 788 ; N a31 ; B 35 -14 753 705 ;\nC 69 ; WX 790 ; N a32 ; B 35 -14 756 705 ;\nC 70 ; WX 793 ; N a33 ; B 35 -13 759 705 ;\nC 71 ; WX 794 ; N a34 ; B 35 -13 759 705 ;\nC 72 ; WX 816 ; N a35 ; B 35 -14 782 705 ;\nC 73 ; WX 823 ; N a36 ; B 35 -14 787 705 ;\nC 74 ; WX 789 ; N a37 ; B 35 -14 754 705 ;\nC 75 ; WX 841 ; N a38 ; B 35 -14 807 705 ;\nC 76 ; WX 823 ; N a39 ; B 35 -14 789 705 ;\nC 77 ; WX 833 ; N a40 ; B 35 -14 798 705 ;\nC 78 ; WX 816 ; N a41 ; B 35 -13 782 705 ;\nC 79 ; WX 831 ; N a42 ; B 35 -14 796 705 ;\nC 80 ; WX 923 ; N a43 ; B 35 -14 888 705 ;\nC 81 ; WX 744 ; N a44 ; B 35 0 710 692 ;\nC 82 ; WX 723 ; N a45 ; B 35 0 688 692 ;\nC 83 ; WX 749 ; N a46 ; B 35 0 714 692 ;\nC 84 ; WX 790 ; N a47 ; B 34 -14 756 705 ;\nC 85 ; WX 792 ; N a48 ; B 35 -14 758 705 ;\nC 86 ; WX 695 ; N a49 ; B 35 -14 661 706 ;\nC 87 ; WX 776 ; N a50 ; B 35 -6 741 699 ;\nC 88 ; WX 768 ; N a51 ; B 35 -7 734 699 ;\nC 89 ; WX 792 ; N a52 ; B 35 -14 757 705 ;\nC 90 ; WX 759 ; N a53 ; B 35 0 725 692 ;\nC 91 ; WX 707 ; N a54 ; B 35 -13 672 704 ;\nC 92 ; WX 708 ; N a55 ; B 35 -14 672 705 ;\nC 93 ; WX 682 ; N a56 ; B 35 -14 647 705 ;\nC 94 ; WX 701 ; N a57 ; B 35 -14 666 705 ;\nC 95 ; WX 826 ; N a58 ; B 35 -14 791 705 ;\nC 96 ; WX 815 ; N a59 ; B 35 -14 780 705 ;\nC 97 ; WX 789 ; N a60 ; B 35 -14 754 705 ;\nC 98 ; WX 789 ; N a61 ; B 35 -14 754 705 ;\nC 99 ; WX 707 ; N a62 ; B 34 -14 673 705 ;\nC 100 ; WX 687 ; N a63 ; B 36 0 651 692 ;\nC 101 ; WX 696 ; N a64 ; B 35 0 661 691 ;\nC 102 ; WX 689 ; N a65 ; B 35 0 655 692 ;\nC 103 ; WX 786 ; N a66 ; B 34 -14 751 705 ;\nC 104 ; WX 787 ; N a67 ; B 35 -14 752 705 ;\nC 105 ; WX 713 ; N a68 ; B 35 -14 678 705 ;\nC 106 ; WX 791 ; N a69 ; B 35 -14 756 705 ;\nC 107 ; WX 785 ; N a70 ; B 36 -14 751 705 ;\nC 108 ; WX 791 ; N a71 ; B 35 -14 757 705 ;\nC 109 ; WX 873 ;
}
};
PDFFont.prototype.use = function(characters) {
var _ref;
return (_ref = this.subset) != null ? _ref.use(characters) : void 0;
};
PDFFont.prototype.embed = function() {
if (this.embedded || (this.dictionary == null)) {
return;
}
if (this.isAFM) {
this.embedAFM();
} else {
this.embedTTF();
}
return this.embedded = true;
};
PDFFont.prototype.encode = function(text) {
var _ref;
if (this.isAFM) {
return this.font.encodeText(text);
} else {
return ((_ref = this.subset) != null ? _ref.encodeText(text) : void 0) || text;
}
};
PDFFont.prototype.ref = function() {
return this.dictionary != null ? this.dictionary : this.dictionary = this.document.ref();
};
PDFFont.prototype.registerTTF = function() {
var e, hi, low, raw, _ref;
this.name = this.font.name.postscriptName;
this.scaleFactor = 1000.0 / this.font.head.unitsPerEm;
this.bbox = (function() {
var _i, _len, _ref, _results;
_ref = this.font.bbox;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
e = _ref[_i];
_results.push(Math.round(e * this.scaleFactor));
}
return _results;
}).call(this);
this.stemV = 0;
if (this.font.post.exists) {
raw = this.font.post.italic_angle;
hi = raw >> 16;
low = raw & 0xFF;
if (hi & 0x8000 !== 0) {
hi = -((hi ^ 0xFFFF) + 1);
}
this.italicAngle = +("" + hi + "." + low);
} else {
this.italicAngle = 0;
}
this.ascender = Math.round(this.font.ascender * this.scaleFactor);
this.decender = Math.round(this.font.decender * this.scaleFactor);
this.lineGap = Math.round(this.font.lineGap * this.scaleFactor);
this.capHeight = (this.font.os2.exists && this.font.os2.capHeight) || this.ascender;
this.xHeight = (this.font.os2.exists && this.font.os2.xHeight) || 0;
this.familyClass = (this.font.os2.exists && this.font.os2.familyClass || 0) >> 8;
this.isSerif = (_ref = this.familyClass) === 1 || _ref === 2 || _ref === 3 || _ref === 4 || _ref === 5 || _ref === 7;
this.isScript = this.familyClass === 10;
this.flags = 0;
if (this.font.post.isFixedPitch) {
this.flags |= 1 << 0;
}
if (this.isSerif) {
this.flags |= 1 << 1;
}
if (this.isScript) {
this.flags |= 1 << 3;
}
if (this.italicAngle !== 0) {
this.flags |= 1 << 6;
}
this.flags |= 1 << 5;
if (!this.font.cmap.unicode) {
throw new Error('No unicode cmap for font');
}
};
PDFFont.prototype.embedTTF = function() {
var charWidths, cmap, code, data, descriptor, firstChar, fontfile, glyph;
data = this.subset.encode();
fontfile = this.document.ref();
fontfile.write(data);
fontfile.data.Length1 = fontfile.uncompressedLength;
fontfile.end();
descriptor = this.document.ref({
Type: 'FontDescriptor',
FontName: this.subset.postscriptName,
FontFile2: fontfile,
FontBBox: this.bbox,
Flags: this.flags,
StemV: this.stemV,
ItalicAngle: this.italicAngle,
Ascent: this.ascender,
Descent: this.decender,
CapHeight: this.capHeight,
XHeight: this.xHeight
});
descriptor.end();
firstChar = +Object.keys(this.subset.cmap)[0];
charWidths = (function() {
var _ref, _results;
_ref = this.subset.cmap;
_results = [];
for (code in _ref) {
glyph = _ref[code];
_results.push(Math.round(this.font.widthOfGlyph(glyph)));
}
return _results;
}).call(this);
cmap = this.document.ref();
cmap.end(toUnicodeCmap(this.subset.subset));
this.dictionary.data = {
Type: 'Font',
BaseFont: this.subset.postscriptName,
Subtype: 'TrueType',
FontDescriptor: descriptor,
FirstChar: firstChar,
LastChar: firstChar + charWidths.length - 1,
Widths: charWidths,
Encoding: 'MacRomanEncoding',
ToUnicode: cmap
};
return this.dictionary.end();
};
toUnicodeCmap = function(map) {
var code, codes, range, unicode, unicodeMap, _i, _len;
unicodeMap = '/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo <<\n /Registry (Adobe)\n /Ordering (UCS)\n /Supplement 0\n>> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<00><ff>\nendcodespacerange';
codes = Object.keys(map).sort(function(a, b) {
return a - b;
});
range = [];
for (_i = 0, _len = codes.length; _i < _len; _i++) {
code = codes[_i];
if (range.length >= 100) {
unicodeMap += "\n" + range.length + " beginbfchar\n" + (range.join('\n')) + "\nendbfchar";
range = [];
}
unicode = ('0000' + map[code].toString(16)).slice(-4);
code = (+code).toString(16);
range.push("<" + code + "><" + unicode + ">");
}
if (range.length) {
unicodeMap += "\n" + range.length + " beginbfchar\n" + (range.join('\n')) + "\nendbfchar\n";
}
return unicodeMap += 'endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend';
};
PDFFont.prototype.registerAFM = function(name) {
var _ref;
this.name = name;
return _ref = this.font, this.ascender = _ref.ascender, this.decender = _ref.decender, this.bbox = _ref.bbox, this.lineGap = _ref.lineGap, _ref;
};
PDFFont.prototype.embedAFM = function() {
this.dictionary.data = {
Type: 'Font',
BaseFont: this.name,
Subtype: 'Type1',
Encoding: 'WinAnsiEncoding'
};
return this.dictionary.end();
};
PDFFont.prototype.widthOfString = function(string, size) {
var charCode, i, scale, width, _i, _ref;
string = '' + string;
width = 0;
for (i = _i = 0, _ref = string.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
charCode = string.charCodeAt(i);
width += this.font.widthOfGlyph(this.font.characterToGlyph(charCode)) || 0;
}
scale = size / 1000;
return width * scale;
};
PDFFont.prototype.lineHeight = function(size, includeGap) {
var gap;
if (includeGap == null) {
includeGap = false;
}
gap = includeGap ? this.lineGap : 0;
return (this.ascender + gap - this.decender) / 1000 * size;
};
return PDFFont;
})();
module.exports = PDFFont;
}).call(this);
}).call(this,require("buffer").Buffer)
},{"./font/afm":19,"./font/subset":22,"./font/ttf":34,"buffer":74,"fs":58}],19:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var AFMFont, fs;
fs = require('fs');
AFMFont = (function() {
var WIN_ANSI_MAP, characters;
AFMFont.open = function(filename) {
return new AFMFont(fs.readFileSync(filename, 'utf8'));
};
function AFMFont(contents) {
var e, i;
this.contents = contents;
this.attributes = {};
this.glyphWidths = {};
this.boundingBoxes = {};
this.parse();
this.charWidths = (function() {
var _i, _results;
_results = [];
for (i = _i = 0; _i <= 255; i = ++_i) {
_results.push(this.glyphWidths[characters[i]]);
}
return _results;
}).call(this);
this.bbox = (function() {
var _i, _len, _ref, _results;
_ref = this.attributes['FontBBox'].split(/\s+/);
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
e = _ref[_i];
_results.push(+e);
}
return _results;
}).call(this);
this.ascender = +(this.attributes['Ascender'] || 0);
this.decender = +(this.attributes['Descender'] || 0);
this.lineGap = (this.bbox[3] - this.bbox[1]) - (this.ascender - this.decender);
}
AFMFont.prototype.parse = function() {
var a, key, line, match, name, section, value, _i, _len, _ref;
section = '';
_ref = this.contents.split('\n');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
line = _ref[_i];
if (match = line.match(/^Start(\w+)/)) {
section = match[1];
continue;
} else if (match = line.match(/^End(\w+)/)) {
section = '';
continue;
}
switch (section) {
case 'FontMetrics':
match = line.match(/(^\w+)\s+(.*)/);
key = match[1];
value = match[2];
if (a = this.attributes[key]) {
if (!Array.isArray(a)) {
a = this.attributes[key] = [a];
}
a.push(value);
} else {
this.attributes[key] = value;
}
break;
case 'CharMetrics':
if (!/^CH?\s/.test(line)) {
continue;
}
name = line.match(/\bN\s+(\.?\w+)\s*;/)[1];
this.glyphWidths[name] = +line.match(/\bWX\s+(\d+)\s*;/)[1];
}
}
};
WIN_ANSI_MAP = {
402: 131,
8211: 150,
8212: 151,
8216: 145,
8217: 146,
8218: 130,
8220: 147,
8221: 148,
8222: 132,
8224: 134,
8225: 135,
8226: 149,
8230: 133,
8364: 128,
8240: 137,
8249: 139,
8250: 155,
710: 136,
8482: 153,
338: 140,
339: 156,
732: 152,
352: 138,
353: 154,
376: 159,
381: 142,
382: 158
};
AFMFont.prototype.encodeText = function(text) {
var char, i, string, _i, _ref;
string = '';
for (i = _i = 0, _ref = text.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
char = text.charCodeAt(i);
char = WIN_ANSI_MAP[char] || char;
string += String.fromCharCode(char);
}
return string;
};
AFMFont.prototype.characterToGlyph = function(character) {
return characters[WIN_ANSI_MAP[character] || character];
};
AFMFont.prototype.widthOfGlyph = function(glyph) {
return this.glyphWidths[glyph];
};
characters = '.notdef .notdef .notdef .notdef\n.notdef .notdef .notdef .notdef\n.notdef .notdef .notdef .notdef\n.notdef .notdef .notdef .notdef\n.notdef .notdef .notdef .notdef\n.notdef .notdef .notdef .notdef\n.notdef .notdef .notdef .notdef\n.notdef .notdef .notdef .notdef\n\nspace exclam quotedbl numbersign\ndollar percent ampersand quotesingle\nparenleft parenright asterisk plus\ncomma hyphen period slash\nzero one two three\nfour five six seven\neight nine colon semicolon\nless equal greater question\n\nat A B C\nD E F G\nH I J K\nL M N O\nP Q R S\nT U V W\nX Y Z bracketleft\nbackslash bracketright asciicircum underscore\n\ngrave a b c\nd e f g\nh i j k\nl m n o\np q r s\nt u v w\nx y z braceleft\nbar braceright asciitilde .notdef\n\nEuro .notdef quotesinglbase florin\nquotedblbase ellipsis dagger daggerdbl\ncircumflex perthousand Scaron guilsinglleft\nOE .notdef Zcaron .notdef\n.notdef quoteleft quoteright quotedblleft\nquotedblright bullet endash emdash\ntilde trademark scaron guilsinglright\noe .notdef zcaron ydieresis\n\nspace exclamdown cent sterling\ncurrency yen brokenbar section\ndieresis copyright ordfeminine guillemotleft\nlogicalnot hyphen registered macron\ndegree plusminus twosuperior threesuperior\nacute mu paragraph periodcentered\ncedilla onesuperior ordmasculine guillemotright\nonequarter onehalf threequarters questiondown\n\nAgrave Aacute Acircumflex Atilde\nAdieresis Aring AE Ccedilla\nEgrave Eacute Ecircumflex Edieresis\nIgrave Iacute Icircumflex Idieresis\nEth Ntilde Ograve Oacute\nOcircumflex Otilde Odieresis multiply\nOslash Ugrave Uacute Ucircumflex\nUdieresis Yacute Thorn germandbls\n\nagrave aacute acircumflex atilde\nadieresis aring ae ccedilla\negrave eacute ecircumflex edieresis\nigrave iacute icircumflex idieresis\neth ntilde ograve oacute\nocircumflex otilde odieresis divide\noslash ugrave uacute ucircumflex\nudieresis yacute thorn ydieresis'.split(/\s+/);
return AFMFont;
})();
module.exports = AFMFont;
}).call(this);
},{"fs":58}],20:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var DFont, Data, Directory, NameTable, fs;
fs = require('fs');
Data = require('../data');
Directory = require('./directory');
NameTable = require('./tables/name');
DFont = (function() {
DFont.open = function(filename) {
var contents;
contents = fs.readFileSync(filename);
return new DFont(contents);
};
function DFont(contents) {
this.contents = new Data(contents);
this.parse(this.contents);
}
DFont.prototype.parse = function(data) {
var attr, b2, b3, b4, dataLength, dataOffset, dataOfs, entry, font, handle, i, id, j, len, length, mapLength, mapOffset, maxIndex, maxTypeIndex, name, nameListOffset, nameOfs, p, pos, refListOffset, type, typeListOffset, _i, _j;
dataOffset = data.readInt();
mapOffset = data.readInt();
dataLength = data.readInt();
mapLength = data.readInt();
this.map = {};
data.pos = mapOffset + 24;
typeListOffset = data.readShort() + mapOffset;
nameListOffset = data.readShort() + mapOffset;
data.pos = typeListOffset;
maxIndex = data.readShort();
for (i = _i = 0; _i <= maxIndex; i = _i += 1) {
type = data.readString(4);
maxTypeIndex = data.readShort();
refListOffset = data.readShort();
this.map[type] = {
list: [],
named: {}
};
pos = data.pos;
data.pos = typeListOffset + refListOffset;
for (j = _j = 0; _j <= maxTypeIndex; j = _j += 1) {
id = data.readShort();
nameOfs = data.readShort();
attr = data.readByte();
b2 = data.readByte() << 16;
b3 = data.readByte() << 8;
b4 = data.readByte();
dataOfs = dataOffset + (0 | b2 | b3 | b4);
handle = data.readUInt32();
entry = {
id: id,
attributes: attr,
offset: dataOfs,
handle: handle
};
p = data.pos;
if (nameOfs !== -1 && (nameListOffset + nameOfs < mapOffset + mapLength)) {
data.pos = nameListOffset + nameOfs;
len = data.readByte();
entry.name = data.readString(len);
} else if (type === 'sfnt') {
data.pos = entry.offset;
length = data.readUInt32();
font = {};
font.contents = new Data(data.slice(data.pos, data.pos + length));
font.directory = new Directory(font.contents);
name = new NameTable(font);
entry.name = name.fontName[0].raw;
}
data.pos = p;
this.map[type].list.push(entry);
if (entry.name) {
this.map[type].named[entry.name] = entry;
}
}
data.pos = pos;
}
};
DFont.prototype.getNamedFont = function(name) {
var data, entry, length, pos, ret, _ref;
data = this.contents;
pos = data.pos;
entry = (_ref = this.map.sfnt) != null ? _ref.named[name] : void 0;
if (!entry) {
throw new Error("Font " + name + " not found in DFont file.");
}
data.pos = entry.offset;
length = data.readUInt32();
ret = data.slice(data.pos, data.pos + length);
data.pos = pos;
return ret;
};
return DFont;
})();
module.exports = DFont;
}).call(this);
},{"../data":16,"./directory":21,"./tables/name":31,"fs":58}],21:[function(require,module,exports){
(function (Buffer){
// Generated by CoffeeScript 1.7.1
(function() {
var Data, Directory,
__slice = [].slice;
Data = require('../data');
Directory = (function() {
var checksum;
function Directory(data) {
var entry, i, _i, _ref;
this.scalarType = data.readInt();
this.tableCount = data.readShort();
this.searchRange = data.readShort();
this.entrySelector = data.readShort();
this.rangeShift = data.readShort();
this.tables = {};
for (i = _i = 0, _ref = this.tableCount; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
entry = {
tag: data.readString(4),
checksum: data.readInt(),
offset: data.readInt(),
length: data.readInt()
};
this.tables[entry.tag] = entry;
}
}
Directory.prototype.encode = function(tables) {
var adjustment, directory, directoryLength, entrySelector, headOffset, log2, offset, rangeShift, searchRange, sum, table, tableCount, tableData, tag;
tableCount = Object.keys(tables).length;
log2 = Math.log(2);
searchRange = Math.floor(Math.log(tableCount) / log2) * 16;
entrySelector = Math.floor(searchRange / log2);
rangeShift = tableCount * 16 - searchRange;
directory = new Data;
directory.writeInt(this.scalarType);
directory.writeShort(tableCount);
directory.writeShort(searchRange);
directory.writeShort(entrySelector);
directory.writeShort(rangeShift);
directoryLength = tableCount * 16;
offset = directory.pos + directoryLength;
headOffset = null;
tableData = [];
for (tag in tables) {
table = tables[tag];
directory.writeString(tag);
directory.writeInt(checksum(table));
directory.writeInt(offset);
directory.writeInt(table.length);
tableData = tableData.concat(table);
if (tag === 'head') {
headOffset = offset;
}
offset += table.length;
while (offset % 4) {
tableData.push(0);
offset++;
}
}
directory.write(tableData);
sum = checksum(directory.data);
adjustment = 0xB1B0AFBA - sum;
directory.pos = headOffset + 8;
directory.writeUInt32(adjustment);
return new Buffer(directory.data);
};
checksum = function(data) {
var i, sum, tmp, _i, _ref;
data = __slice.call(data);
while (data.length % 4) {
data.push(0);
}
tmp = new Data(data);
sum = 0;
for (i = _i = 0, _ref = data.length; _i < _ref; i = _i += 4) {
sum += tmp.readUInt32();
}
return sum & 0xFFFFFFFF;
};
return Directory;
})();
module.exports = Directory;
}).call(this);
}).call(this,require("buffer").Buffer)
},{"../data":16,"buffer":74}],22:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var CmapTable, Subset, utils,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
CmapTable = require('./tables/cmap');
utils = require('./utils');
Subset = (function() {
function Subset(font) {
this.font = font;
this.subset = {};
this.unicodes = {};
this.next = 33;
}
Subset.prototype.use = function(character) {
var i, _i, _ref;
if (typeof character === 'string') {
for (i = _i = 0, _ref = character.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
this.use(character.charCodeAt(i));
}
return;
}
if (!this.unicodes[character]) {
this.subset[this.next] = character;
return this.unicodes[character] = this.next++;
}
};
Subset.prototype.encodeText = function(text) {
var char, i, string, _i, _ref;
string = '';
for (i = _i = 0, _ref = text.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
char = this.unicodes[text.charCodeAt(i)];
string += String.fromCharCode(char);
}
return string;
};
Subset.prototype.generateCmap = function() {
var mapping, roman, unicode, unicodeCmap, _ref;
unicodeCmap = this.font.cmap.tables[0].codeMap;
mapping = {};
_ref = this.subset;
for (roman in _ref) {
unicode = _ref[roman];
mapping[roman] = unicodeCmap[unicode];
}
return mapping;
};
Subset.prototype.glyphIDs = function() {
var ret, roman, unicode, unicodeCmap, val, _ref;
unicodeCmap = this.font.cmap.tables[0].codeMap;
ret = [0];
_ref = this.subset;
for (roman in _ref) {
unicode = _ref[roman];
val = unicodeCmap[unicode];
if ((val != null) && __indexOf.call(ret, val) < 0) {
ret.push(val);
}
}
return ret.sort();
};
Subset.prototype.glyphsFor = function(glyphIDs) {
var additionalIDs, glyph, glyphs, id, _i, _len, _ref;
glyphs = {};
for (_i = 0, _len = glyphIDs.length; _i < _len; _i++) {
id = glyphIDs[_i];
glyphs[id] = this.font.glyf.glyphFor(id);
}
additionalIDs = [];
for (id in glyphs) {
glyph = glyphs[id];
if (glyph != null ? glyph.compound : void 0) {
additionalIDs.push.apply(additionalIDs, glyph.glyphIDs);
}
}
if (additionalIDs.length > 0) {
_ref = this.glyphsFor(additionalIDs);
for (id in _ref) {
glyph = _ref[id];
glyphs[id] = glyph;
}
}
return glyphs;
};
Subset.prototype.encode = function() {
var cmap, code, glyf, glyphs, id, ids, loca, name, new2old, newIDs, nextGlyphID, old2new, oldID, oldIDs, tables, _ref, _ref1;
cmap = CmapTable.encode(this.generateCmap(), 'unicode');
glyphs = this.glyphsFor(this.glyphIDs());
old2new = {
0: 0
};
_ref = cmap.charMap;
for (code in _ref) {
ids = _ref[code];
old2new[ids.old] = ids["new"];
}
nextGlyphID = cmap.maxGlyphID;
for (oldID in glyphs) {
if (!(oldID in old2new)) {
old2new[oldID] = nextGlyphID++;
}
}
new2old = utils.invert(old2new);
newIDs = Object.keys(new2old).sort(function(a, b) {
return a - b;
});
oldIDs = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = newIDs.length; _i < _len; _i++) {
id = newIDs[_i];
_results.push(new2old[id]);
}
return _results;
})();
glyf = this.font.glyf.encode(glyphs, oldIDs, old2new);
loca = this.font.loca.encode(glyf.offsets);
name = this.font.name.encode();
this.postscriptName = name.postscriptName;
this.cmap = {};
_ref1 = cmap.charMap;
for (code in _ref1) {
ids = _ref1[code];
this.cmap[code] = ids.old;
}
tables = {
cmap: cmap.table,
glyf: glyf.table,
loca: loca.table,
hmtx: this.font.hmtx.encode(oldIDs),
hhea: this.font.hhea.encode(oldIDs),
maxp: this.font.maxp.encode(oldIDs),
post: this.font.post.encode(oldIDs),
name: name.table,
head: this.font.head.encode(loca)
};
if (this.font.os2.exists) {
tables['OS/2'] = this.font.os2.raw();
}
return this.font.directory.encode(tables);
};
return Subset;
})();
module.exports = Subset;
}).call(this);
},{"./tables/cmap":24,"./utils":35}],23:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var Table;
Table = (function() {
function Table(file) {
var info;
this.file = file;
info = this.file.directory.tables[this.tag];
this.exists = !!info;
if (info) {
this.offset = info.offset, this.length = info.length;
this.parse(this.file.contents);
}
}
Table.prototype.parse = function() {};
Table.prototype.encode = function() {};
Table.prototype.raw = function() {
if (!this.exists) {
return null;
}
this.file.contents.pos = this.offset;
return this.file.contents.read(this.length);
};
return Table;
})();
module.exports = Table;
}).call(this);
},{}],24:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var CmapEntry, CmapTable, Data, Table,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Table = require('../table');
Data = require('../../data');
CmapTable = (function(_super) {
__extends(CmapTable, _super);
function CmapTable() {
return CmapTable.__super__.constructor.apply(this, arguments);
}
CmapTable.prototype.tag = 'cmap';
CmapTable.prototype.parse = function(data) {
var entry, i, tableCount, _i;
data.pos = this.offset;
this.version = data.readUInt16();
tableCount = data.readUInt16();
this.tables = [];
this.unicode = null;
for (i = _i = 0; 0 <= tableCount ? _i < tableCount : _i > tableCount; i = 0 <= tableCount ? ++_i : --_i) {
entry = new CmapEntry(data, this.offset);
this.tables.push(entry);
if (entry.isUnicode) {
if (this.unicode == null) {
this.unicode = entry;
}
}
}
return true;
};
CmapTable.encode = function(charmap, encoding) {
var result, table;
if (encoding == null) {
encoding = 'macroman';
}
result = CmapEntry.encode(charmap, encoding);
table = new Data;
table.writeUInt16(0);
table.writeUInt16(1);
result.table = table.data.concat(result.subtable);
return result;
};
return CmapTable;
})(Table);
CmapEntry = (function() {
function CmapEntry(data, offset) {
var code, count, endCode, glyphId, glyphIds, i, idDelta, idRangeOffset, index, saveOffset, segCount, segCountX2, start, startCode, tail, _i, _j, _k, _len;
this.platformID = data.readUInt16();
this.encodingID = data.readShort();
this.offset = offset + data.readInt();
saveOffset = data.pos;
data.pos = this.offset;
this.format = data.readUInt16();
this.length = data.readUInt16();
this.language = data.readUInt16();
this.isUnicode = (this.platformID === 3 && this.encodingID === 1 && this.format === 4) || this.platformID === 0 && this.format === 4;
this.codeMap = {};
switch (this.format) {
case 0:
for (i = _i = 0; _i < 256; i = ++_i) {
this.codeMap[i] = data.readByte();
}
break;
case 4:
segCountX2 = data.readUInt16();
segCount = segCountX2 / 2;
data.pos += 6;
endCode = (function() {
var _j, _results;
_results = [];
for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
_results.push(data.readUInt16());
}
return _results;
})();
data.pos += 2;
startCode = (function() {
var _j, _results;
_results = [];
for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
_results.push(data.readUInt16());
}
return _results;
})();
idDelta = (function() {
var _j, _results;
_results = [];
for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
_results.push(data.readUInt16());
}
return _results;
})();
idRangeOffset = (function() {
var _j, _results;
_results = [];
for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
_results.push(data.readUInt16());
}
return _results;
})();
count = (this.length - data.pos + this.offset) / 2;
glyphIds = (function() {
var _j, _results;
_results = [];
for (i = _j = 0; 0 <= count ? _j < count : _j > count; i = 0 <= count ? ++_j : --_j) {
_results.push(data.readUInt16());
}
return _results;
})();
for (i = _j = 0, _len = endCode.length; _j < _len; i = ++_j) {
tail = endCode[i];
start = startCode[i];
for (code = _k = start; start <= tail ? _k <= tail : _k >= tail; code = start <= tail ? ++_k : --_k) {
if (idRangeOffset[i] === 0) {
glyphId = code + idDelta[i];
} else {
index = idRangeOffset[i] / 2 + (code - start) - (segCount - i);
glyphId = glyphIds[index] || 0;
if (glyphId !== 0) {
glyphId += idDelta[i];
}
}
this.codeMap[code] = glyphId & 0xFFFF;
}
}
}
data.pos = saveOffset;
}
CmapEntry.encode = function(charmap, encoding) {
var charMap, code, codeMap, codes, delta, deltas, diff, endCode, endCodes, entrySelector, glyphIDs, i, id, indexes, last, map, nextID, offset, old, rangeOffsets, rangeShift, result, searchRange, segCount, segCountX2, startCode, startCodes, startGlyph, subtable, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _len5, _len6, _len7, _m, _n, _name, _o, _p, _q;
subtable = new Data;
codes = Object.keys(charmap).sort(function(a, b) {
return a - b;
});
switch (encoding) {
case 'macroman':
id = 0;
indexes = (function() {
var _i, _results;
_results = [];
for (i = _i = 0; _i < 256; i = ++_i) {
_results.push(0);
}
return _results;
})();
map = {
0: 0
};
codeMap = {};
for (_i = 0, _len = codes.length; _i < _len; _i++) {
code = codes[_i];
if (map[_name = charmap[code]] == null) {
map[_name] = ++id;
}
codeMap[code] = {
old: charmap[code],
"new": map[charmap[code]]
};
indexes[code] = map[charmap[code]];
}
subtable.writeUInt16(1);
subtable.writeUInt16(0);
subtable.writeUInt32(12);
subtable.writeUInt16(0);
subtable.writeUInt16(262);
subtable.writeUInt16(0);
subtable.write(indexes);
return result = {
charMap: codeMap,
subtable: subtable.data,
maxGlyphID: id + 1
};
case 'unicode':
startCodes = [];
endCodes = [];
nextID = 0;
map = {};
charMap = {};
last = diff = null;
for (_j = 0, _len1 = codes.length; _j < _len1; _j++) {
code = codes[_j];
old = charmap[code];
if (map[old] == null) {
map[old] = ++nextID;
}
charMap[code] = {
old: old,
"new": map[old]
};
delta = map[old] - code;
if ((last == null) || delta !== diff) {
if (last) {
endCodes.push(last);
}
startCodes.push(code);
diff = delta;
}
last = code;
}
if (last) {
endCodes.push(last);
}
endCodes.push(0xFFFF);
startCodes.push(0xFFFF);
segCount = startCodes.length;
segCountX2 = segCount * 2;
searchRange = 2 * Math.pow(Math.log(segCount) / Math.LN2, 2);
entrySelector = Math.log(searchRange / 2) / Math.LN2;
rangeShift = 2 * segCount - searchRange;
deltas = [];
rangeOffsets = [];
glyphIDs = [];
for (i = _k = 0, _len2 = startCodes.length; _k < _len2; i = ++_k) {
startCode = startCodes[i];
endCode = endCodes[i];
if (startCode === 0xFFFF) {
deltas.push(0);
rangeOffsets.push(0);
break;
}
startGlyph = charMap[startCode]["new"];
if (startCode - startGlyph >= 0x8000) {
deltas.push(0);
rangeOffsets.push(2 * (glyphIDs.length + segCount - i));
for (code = _l = startCode; startCode <= endCode ? _l <= endCode : _l >= endCode; code = startCode <= endCode ? ++_l : --_l) {
glyphIDs.push(charMap[code]["new"]);
}
} else {
deltas.push(startGlyph - startCode);
rangeOffsets.push(0);
}
}
subtable.writeUInt16(3);
subtable.writeUInt16(1);
subtable.writeUInt32(12);
subtable.writeUInt16(4);
subtable.writeUInt16(16 + segCount * 8 + glyphIDs.length * 2);
subtable.writeUInt16(0);
subtable.writeUInt16(segCountX2);
subtable.writeUInt16(searchRange);
subtable.writeUInt16(entrySelector);
subtable.writeUInt16(rangeShift);
for (_m = 0, _len3 = endCodes.length; _m < _len3; _m++) {
code = endCodes[_m];
subtable.writeUInt16(code);
}
subtable.writeUInt16(0);
for (_n = 0, _len4 = startCodes.length; _n < _len4; _n++) {
code = startCodes[_n];
subtable.writeUInt16(code);
}
for (_o = 0, _len5 = deltas.length; _o < _len5; _o++) {
delta = deltas[_o];
subtable.writeUInt16(delta);
}
for (_p = 0, _len6 = rangeOffsets.length; _p < _len6; _p++) {
offset = rangeOffsets[_p];
subtable.writeUInt16(offset);
}
for (_q = 0, _len7 = glyphIDs.length; _q < _len7; _q++) {
id = glyphIDs[_q];
subtable.writeUInt16(id);
}
return result = {
charMap: charMap,
subtable: subtable.data,
maxGlyphID: nextID + 1
};
}
};
return CmapEntry;
})();
module.exports = CmapTable;
}).call(this);
},{"../../data":16,"../table":23}],25:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var CompoundGlyph, Data, GlyfTable, SimpleGlyph, Table,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__slice = [].slice;
Table = require('../table');
Data = require('../../data');
GlyfTable = (function(_super) {
__extends(GlyfTable, _super);
function GlyfTable() {
return GlyfTable.__super__.constructor.apply(this, arguments);
}
GlyfTable.prototype.tag = 'glyf';
GlyfTable.prototype.parse = function(data) {
return this.cache = {};
};
GlyfTable.prototype.glyphFor = function(id) {
var data, index, length, loca, numberOfContours, raw, xMax, xMin, yMax, yMin;
if (id in this.cache) {
return this.cache[id];
}
loca = this.file.loca;
data = this.file.contents;
index = loca.indexOf(id);
length = loca.lengthOf(id);
if (length === 0) {
return this.cache[id] = null;
}
data.pos = this.offset + index;
raw = new Data(data.read(length));
numberOfContours = raw.readShort();
xMin = raw.readShort();
yMin = raw.readShort();
xMax = raw.readShort();
yMax = raw.readShort();
if (numberOfContours === -1) {
this.cache[id] = new CompoundGlyph(raw, xMin, yMin, xMax, yMax);
} else {
this.cache[id] = new SimpleGlyph(raw, numberOfContours, xMin, yMin, xMax, yMax);
}
return this.cache[id];
};
GlyfTable.prototype.encode = function(glyphs, mapping, old2new) {
var glyph, id, offsets, table, _i, _len;
table = [];
offsets = [];
for (_i = 0, _len = mapping.length; _i < _len; _i++) {
id = mapping[_i];
glyph = glyphs[id];
offsets.push(table.length);
if (glyph) {
table = table.concat(glyph.encode(old2new));
}
}
offsets.push(table.length);
return {
table: table,
offsets: offsets
};
};
return GlyfTable;
})(Table);
SimpleGlyph = (function() {
function SimpleGlyph(raw, numberOfContours, xMin, yMin, xMax, yMax) {
this.raw = raw;
this.numberOfContours = numberOfContours;
this.xMin = xMin;
this.yMin = yMin;
this.xMax = xMax;
this.yMax = yMax;
this.compound = false;
}
SimpleGlyph.prototype.encode = function() {
return this.raw.data;
};
return SimpleGlyph;
})();
CompoundGlyph = (function() {
var ARG_1_AND_2_ARE_WORDS, MORE_COMPONENTS, WE_HAVE_AN_X_AND_Y_SCALE, WE_HAVE_A_SCALE, WE_HAVE_A_TWO_BY_TWO, WE_HAVE_INSTRUCTIONS;
ARG_1_AND_2_ARE_WORDS = 0x0001;
WE_HAVE_A_SCALE = 0x0008;
MORE_COMPONENTS = 0x0020;
WE_HAVE_AN_X_AND_Y_SCALE = 0x0040;
WE_HAVE_A_TWO_BY_TWO = 0x0080;
WE_HAVE_INSTRUCTIONS = 0x0100;
function CompoundGlyph(raw, xMin, yMin, xMax, yMax) {
var data, flags;
this.raw = raw;
this.xMin = xMin;
this.yMin = yMin;
this.xMax = xMax;
this.yMax = yMax;
this.compound = true;
this.glyphIDs = [];
this.glyphOffsets = [];
data = this.raw;
while (true) {
flags = data.readShort();
this.glyphOffsets.push(data.pos);
this.glyphIDs.push(data.readShort());
if (!(flags & MORE_COMPONENTS)) {
break;
}
if (flags & ARG_1_AND_2_ARE_WORDS) {
data.pos += 4;
} else {
data.pos += 2;
}
if (flags & WE_HAVE_A_TWO_BY_TWO) {
data.pos += 8;
} else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) {
data.pos += 4;
} else if (flags & WE_HAVE_A_SCALE) {
data.pos += 2;
}
}
}
CompoundGlyph.prototype.encode = function(mapping) {
var i, id, result, _i, _len, _ref;
result = new Data(__slice.call(this.raw.data));
_ref = this.glyphIDs;
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
id = _ref[i];
result.pos = this.glyphOffsets[i];
result.writeShort(mapping[id]);
}
return result.data;
};
return CompoundGlyph;
})();
module.exports = GlyfTable;
}).call(this);
},{"../../data":16,"../table":23}],26:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var Data, HeadTable, Table,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Table = require('../table');
Data = require('../../data');
HeadTable = (function(_super) {
__extends(HeadTable, _super);
function HeadTable() {
return HeadTable.__super__.constructor.apply(this, arguments);
}
HeadTable.prototype.tag = 'head';
HeadTable.prototype.parse = function(data) {
data.pos = this.offset;
this.version = data.readInt();
this.revision = data.readInt();
this.checkSumAdjustment = data.readInt();
this.magicNumber = data.readInt();
this.flags = data.readShort();
this.unitsPerEm = data.readShort();
this.created = data.readLongLong();
this.modified = data.readLongLong();
this.xMin = data.readShort();
this.yMin = data.readShort();
this.xMax = data.readShort();
this.yMax = data.readShort();
this.macStyle = data.readShort();
this.lowestRecPPEM = data.readShort();
this.fontDirectionHint = data.readShort();
this.indexToLocFormat = data.readShort();
return this.glyphDataFormat = data.readShort();
};
HeadTable.prototype.encode = function(loca) {
var table;
table = new Data;
table.writeInt(this.version);
table.writeInt(this.revision);
table.writeInt(this.checkSumAdjustment);
table.writeInt(this.magicNumber);
table.writeShort(this.flags);
table.writeShort(this.unitsPerEm);
table.writeLongLong(this.created);
table.writeLongLong(this.modified);
table.writeShort(this.xMin);
table.writeShort(this.yMin);
table.writeShort(this.xMax);
table.writeShort(this.yMax);
table.writeShort(this.macStyle);
table.writeShort(this.lowestRecPPEM);
table.writeShort(this.fontDirectionHint);
table.writeShort(loca.type);
table.writeShort(this.glyphDataFormat);
return table.data;
};
return HeadTable;
})(Table);
module.exports = HeadTable;
}).call(this);
},{"../../data":16,"../table":23}],27:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var Data, HheaTable, Table,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Table = require('../table');
Data = require('../../data');
HheaTable = (function(_super) {
__extends(HheaTable, _super);
function HheaTable() {
return HheaTable.__super__.constructor.apply(this, arguments);
}
HheaTable.prototype.tag = 'hhea';
HheaTable.prototype.parse = function(data) {
data.pos = this.offset;
this.version = data.readInt();
this.ascender = data.readShort();
this.decender = data.readShort();
this.lineGap = data.readShort();
this.advanceWidthMax = data.readShort();
this.minLeftSideBearing = data.readShort();
this.minRightSideBearing = data.readShort();
this.xMaxExtent = data.readShort();
this.caretSlopeRise = data.readShort();
this.caretSlopeRun = data.readShort();
this.caretOffset = data.readShort();
data.pos += 4 * 2;
this.metricDataFormat = data.readShort();
return this.numberOfMetrics = data.readUInt16();
};
HheaTable.prototype.encode = function(ids) {
var i, table, _i, _ref;
table = new Data;
table.writeInt(this.version);
table.writeShort(this.ascender);
table.writeShort(this.decender);
table.writeShort(this.lineGap);
table.writeShort(this.advanceWidthMax);
table.writeShort(this.minLeftSideBearing);
table.writeShort(this.minRightSideBearing);
table.writeShort(this.xMaxExtent);
table.writeShort(this.caretSlopeRise);
table.writeShort(this.caretSlopeRun);
table.writeShort(this.caretOffset);
for (i = _i = 0, _ref = 4 * 2; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
table.writeByte(0);
}
table.writeShort(this.metricDataFormat);
table.writeUInt16(ids.length);
return table.data;
};
return HheaTable;
})(Table);
module.exports = HheaTable;
}).call(this);
},{"../../data":16,"../table":23}],28:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var Data, HmtxTable, Table,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Table = require('../table');
Data = require('../../data');
HmtxTable = (function(_super) {
__extends(HmtxTable, _super);
function HmtxTable() {
return HmtxTable.__super__.constructor.apply(this, arguments);
}
HmtxTable.prototype.tag = 'hmtx';
HmtxTable.prototype.parse = function(data) {
var i, last, lsbCount, m, _i, _j, _ref, _results;
data.pos = this.offset;
this.metrics = [];
for (i = _i = 0, _ref = this.file.hhea.numberOfMetrics; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
this.metrics.push({
advance: data.readUInt16(),
lsb: data.readInt16()
});
}
lsbCount = this.file.maxp.numGlyphs - this.file.hhea.numberOfMetrics;
this.leftSideBearings = (function() {
var _j, _results;
_results = [];
for (i = _j = 0; 0 <= lsbCount ? _j < lsbCount : _j > lsbCount; i = 0 <= lsbCount ? ++_j : --_j) {
_results.push(data.readInt16());
}
return _results;
})();
this.widths = (function() {
var _j, _len, _ref1, _results;
_ref1 = this.metrics;
_results = [];
for (_j = 0, _len = _ref1.length; _j < _len; _j++) {
m = _ref1[_j];
_results.push(m.advance);
}
return _results;
}).call(this);
last = this.widths[this.widths.length - 1];
_results = [];
for (i = _j = 0; 0 <= lsbCount ? _j < lsbCount : _j > lsbCount; i = 0 <= lsbCount ? ++_j : --_j) {
_results.push(this.widths.push(last));
}
return _results;
};
HmtxTable.prototype.forGlyph = function(id) {
var metrics;
if (id in this.metrics) {
return this.metrics[id];
}
return metrics = {
advance: this.metrics[this.metrics.length - 1].advance,
lsb: this.leftSideBearings[id - this.metrics.length]
};
};
HmtxTable.prototype.encode = function(mapping) {
var id, metric, table, _i, _len;
table = new Data;
for (_i = 0, _len = mapping.length; _i < _len; _i++) {
id = mapping[_i];
metric = this.forGlyph(id);
table.writeUInt16(metric.advance);
table.writeUInt16(metric.lsb);
}
return table.data;
};
return HmtxTable;
})(Table);
module.exports = HmtxTable;
}).call(this);
},{"../../data":16,"../table":23}],29:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var Data, LocaTable, Table,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Table = require('../table');
Data = require('../../data');
LocaTable = (function(_super) {
__extends(LocaTable, _super);
function LocaTable() {
return LocaTable.__super__.constructor.apply(this, arguments);
}
LocaTable.prototype.tag = 'loca';
LocaTable.prototype.parse = function(data) {
var format, i;
data.pos = this.offset;
format = this.file.head.indexToLocFormat;
if (format === 0) {
return this.offsets = (function() {
var _i, _ref, _results;
_results = [];
for (i = _i = 0, _ref = this.length; _i < _ref; i = _i += 2) {
_results.push(data.readUInt16() * 2);
}
return _results;
}).call(this);
} else {
return this.offsets = (function() {
var _i, _ref, _results;
_results = [];
for (i = _i = 0, _ref = this.length; _i < _ref; i = _i += 4) {
_results.push(data.readUInt32());
}
return _results;
}).call(this);
}
};
LocaTable.prototype.indexOf = function(id) {
return this.offsets[id];
};
LocaTable.prototype.lengthOf = function(id) {
return this.offsets[id + 1] - this.offsets[id];
};
LocaTable.prototype.encode = function(offsets) {
var o, offset, ret, table, _i, _j, _k, _len, _len1, _len2, _ref;
table = new Data;
for (_i = 0, _len = offsets.length; _i < _len; _i++) {
offset = offsets[_i];
if (!(offset > 0xFFFF)) {
continue;
}
_ref = this.offsets;
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
o = _ref[_j];
table.writeUInt32(o);
}
return ret = {
format: 1,
table: table.data
};
}
for (_k = 0, _len2 = offsets.length; _k < _len2; _k++) {
o = offsets[_k];
table.writeUInt16(o / 2);
}
return ret = {
format: 0,
table: table.data
};
};
return LocaTable;
})(Table);
module.exports = LocaTable;
}).call(this);
},{"../../data":16,"../table":23}],30:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var Data, MaxpTable, Table,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Table = require('../table');
Data = require('../../data');
MaxpTable = (function(_super) {
__extends(MaxpTable, _super);
function MaxpTable() {
return MaxpTable.__super__.constructor.apply(this, arguments);
}
MaxpTable.prototype.tag = 'maxp';
MaxpTable.prototype.parse = function(data) {
data.pos = this.offset;
this.version = data.readInt();
this.numGlyphs = data.readUInt16();
this.maxPoints = data.readUInt16();
this.maxContours = data.readUInt16();
this.maxCompositePoints = data.readUInt16();
this.maxComponentContours = data.readUInt16();
this.maxZones = data.readUInt16();
this.maxTwilightPoints = data.readUInt16();
this.maxStorage = data.readUInt16();
this.maxFunctionDefs = data.readUInt16();
this.maxInstructionDefs = data.readUInt16();
this.maxStackElements = data.readUInt16();
this.maxSizeOfInstructions = data.readUInt16();
this.maxComponentElements = data.readUInt16();
return this.maxComponentDepth = data.readUInt16();
};
MaxpTable.prototype.encode = function(ids) {
var table;
table = new Data;
table.writeInt(this.version);
table.writeUInt16(ids.length);
table.writeUInt16(this.maxPoints);
table.writeUInt16(this.maxContours);
table.writeUInt16(this.maxCompositePoints);
table.writeUInt16(this.maxComponentContours);
table.writeUInt16(this.maxZones);
table.writeUInt16(this.maxTwilightPoints);
table.writeUInt16(this.maxStorage);
table.writeUInt16(this.maxFunctionDefs);
table.writeUInt16(this.maxInstructionDefs);
table.writeUInt16(this.maxStackElements);
table.writeUInt16(this.maxSizeOfInstructions);
table.writeUInt16(this.maxComponentElements);
table.writeUInt16(this.maxComponentDepth);
return table.data;
};
return MaxpTable;
})(Table);
module.exports = MaxpTable;
}).call(this);
},{"../../data":16,"../table":23}],31:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var Data, NameEntry, NameTable, Table, utils,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Table = require('../table');
Data = require('../../data');
utils = require('../utils');
NameTable = (function(_super) {
var subsetTag;
__extends(NameTable, _super);
function NameTable() {
return NameTable.__super__.constructor.apply(this, arguments);
}
NameTable.prototype.tag = 'name';
NameTable.prototype.parse = function(data) {
var count, entries, entry, format, i, name, stringOffset, strings, text, _i, _j, _len, _name;
data.pos = this.offset;
format = data.readShort();
count = data.readShort();
stringOffset = data.readShort();
entries = [];
for (i = _i = 0; 0 <= count ? _i < count : _i > count; i = 0 <= count ? ++_i : --_i) {
entries.push({
platformID: data.readShort(),
encodingID: data.readShort(),
languageID: data.readShort(),
nameID: data.readShort(),
length: data.readShort(),
offset: this.offset + stringOffset + data.readShort()
});
}
strings = {};
for (i = _j = 0, _len = entries.length; _j < _len; i = ++_j) {
entry = entries[i];
data.pos = entry.offset;
text = data.readString(entry.length);
name = new NameEntry(text, entry);
if (strings[_name = entry.nameID] == null) {
strings[_name] = [];
}
strings[entry.nameID].push(name);
}
this.strings = strings;
this.copyright = strings[0];
this.fontFamily = strings[1];
this.fontSubfamily = strings[2];
this.uniqueSubfamily = strings[3];
this.fontName = strings[4];
this.version = strings[5];
this.postscriptName = strings[6][0].raw.replace(/[\x00-\x19\x80-\xff]/g, "");
this.trademark = strings[7];
this.manufacturer = strings[8];
this.designer = strings[9];
this.description = strings[10];
this.vendorUrl = strings[11];
this.designerUrl = strings[12];
this.license = strings[13];
this.licenseUrl = strings[14];
this.preferredFamily = strings[15];
this.preferredSubfamily = strings[17];
this.compatibleFull = strings[18];
return this.sampleText = strings[19];
};
subsetTag = "AAAAAA";
NameTable.prototype.encode = function() {
var id, list, nameID, nameTable, postscriptName, strCount, strTable, string, strings, table, val, _i, _len, _ref;
strings = {};
_ref = this.strings;
for (id in _ref) {
val = _ref[id];
strings[id] = val;
}
postscriptName = new NameEntry("" + subsetTag + "+" + this.postscriptName, {
platformID: 1,
encodingID: 0,
languageID: 0
});
strings[6] = [postscriptName];
subsetTag = utils.successorOf(subsetTag);
strCount = 0;
for (id in strings) {
list = strings[id];
if (list != null) {
strCount += list.length;
}
}
table = new Data;
strTable = new Data;
table.writeShort(0);
table.writeShort(strCount);
table.writeShort(6 + 12 * strCount);
for (nameID in strings) {
list = strings[nameID];
if (list != null) {
for (_i = 0, _len = list.length; _i < _len; _i++) {
string = list[_i];
table.writeShort(string.platformID);
table.writeShort(string.encodingID);
table.writeShort(string.languageID);
table.writeShort(nameID);
table.writeShort(string.length);
table.writeShort(strTable.pos);
strTable.writeString(string.raw);
}
}
}
return nameTable = {
postscriptName: postscriptName.raw,
table: table.data.concat(strTable.data)
};
};
return NameTable;
})(Table);
module.exports = NameTable;
NameEntry = (function() {
function NameEntry(raw, entry) {
this.raw = raw;
this.length = this.raw.length;
this.platformID = entry.platformID;
this.encodingID = entry.encodingID;
this.languageID = entry.languageID;
}
return NameEntry;
})();
}).call(this);
},{"../../data":16,"../table":23,"../utils":35}],32:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var OS2Table, Table,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Table = require('../table');
OS2Table = (function(_super) {
__extends(OS2Table, _super);
function OS2Table() {
return OS2Table.__super__.constructor.apply(this, arguments);
}
OS2Table.prototype.tag = 'OS/2';
OS2Table.prototype.parse = function(data) {
var i;
data.pos = this.offset;
this.version = data.readUInt16();
this.averageCharWidth = data.readShort();
this.weightClass = data.readUInt16();
this.widthClass = data.readUInt16();
this.type = data.readShort();
this.ySubscriptXSize = data.readShort();
this.ySubscriptYSize = data.readShort();
this.ySubscriptXOffset = data.readShort();
this.ySubscriptYOffset = data.readShort();
this.ySuperscriptXSize = data.readShort();
this.ySuperscriptYSize = data.readShort();
this.ySuperscriptXOffset = data.readShort();
this.ySuperscriptYOffset = data.readShort();
this.yStrikeoutSize = data.readShort();
this.yStrikeoutPosition = data.readShort();
this.familyClass = data.readShort();
this.panose = (function() {
var _i, _results;
_results = [];
for (i = _i = 0; _i < 10; i = ++_i) {
_results.push(data.readByte());
}
return _results;
})();
this.charRange = (function() {
var _i, _results;
_results = [];
for (i = _i = 0; _i < 4; i = ++_i) {
_results.push(data.readInt());
}
return _results;
})();
this.vendorID = data.readString(4);
this.selection = data.readShort();
this.firstCharIndex = data.readShort();
this.lastCharIndex = data.readShort();
if (this.version > 0) {
this.ascent = data.readShort();
this.descent = data.readShort();
this.lineGap = data.readShort();
this.winAscent = data.readShort();
this.winDescent = data.readShort();
this.codePageRange = (function() {
var _i, _results;
_results = [];
for (i = _i = 0; _i < 2; i = ++_i) {
_results.push(data.readInt());
}
return _results;
})();
if (this.version > 1) {
this.xHeight = data.readShort();
this.capHeight = data.readShort();
this.defaultChar = data.readShort();
this.breakChar = data.readShort();
return this.maxContext = data.readShort();
}
}
};
OS2Table.prototype.encode = function() {
return this.raw();
};
return OS2Table;
})(Table);
module.exports = OS2Table;
}).call(this);
},{"../table":23}],33:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var Data, PostTable, Table,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Table = require('../table');
Data = require('../../data');
PostTable = (function(_super) {
var POSTSCRIPT_GLYPHS;
__extends(PostTable, _super);
function PostTable() {
return PostTable.__super__.constructor.apply(this, arguments);
}
PostTable.prototype.tag = 'post';
PostTable.prototype.parse = function(data) {
var i, length, numberOfGlyphs, _i, _results;
data.pos = this.offset;
this.format = data.readInt();
this.italicAngle = data.readInt();
this.underlinePosition = data.readShort();
this.underlineThickness = data.readShort();
this.isFixedPitch = data.readInt();
this.minMemType42 = data.readInt();
this.maxMemType42 = data.readInt();
this.minMemType1 = data.readInt();
this.maxMemType1 = data.readInt();
switch (this.format) {
case 0x00010000:
break;
case 0x00020000:
numberOfGlyphs = data.readUInt16();
this.glyphNameIndex = [];
for (i = _i = 0; 0 <= numberOfGlyphs ? _i < numberOfGlyphs : _i > numberOfGlyphs; i = 0 <= numberOfGlyphs ? ++_i : --_i) {
this.glyphNameIndex.push(data.readUInt16());
}
this.names = [];
_results = [];
while (data.pos < this.offset + this.length) {
length = data.readByte();
_results.push(this.names.push(data.readString(length)));
}
return _results;
break;
case 0x00025000:
numberOfGlyphs = data.readUInt16();
return this.offsets = data.read(numberOfGlyphs);
case 0x00030000:
break;
case 0x00040000:
return this.map = (function() {
var _j, _ref, _results1;
_results1 = [];
for (i = _j = 0, _ref = this.file.maxp.numGlyphs; 0 <= _ref ? _j < _ref : _j > _ref; i = 0 <= _ref ? ++_j : --_j) {
_results1.push(data.readUInt32());
}
return _results1;
}).call(this);
}
};
PostTable.prototype.glyphFor = function(code) {
var index;
switch (this.format) {
case 0x00010000:
return POSTSCRIPT_GLYPHS[code] || '.notdef';
case 0x00020000:
index = this.glyphNameIndex[code];
if (index <= 257) {
return POSTSCRIPT_GLYPHS[index];
} else {
return this.names[index - 258] || '.notdef';
}
break;
case 0x00025000:
return POSTSCRIPT_GLYPHS[code + this.offsets[code]] || '.notdef';
case 0x00030000:
return '.notdef';
case 0x00040000:
return this.map[code] || 0xFFFF;
}
};
PostTable.prototype.encode = function(mapping) {
var id, index, indexes, position, post, raw, string, strings, table, _i, _j, _k, _len, _len1, _len2;
if (!this.exists) {
return null;
}
raw = this.raw();
if (this.format === 0x00030000) {
return raw;
}
table = new Data(raw.slice(0, 32));
table.writeUInt32(0x00020000);
table.pos = 32;
indexes = [];
strings = [];
for (_i = 0, _len = mapping.length; _i < _len; _i++) {
id = mapping[_i];
post = this.glyphFor(id);
position = POSTSCRIPT_GLYPHS.indexOf(post);
if (position !== -1) {
indexes.push(position);
} else {
indexes.push(257 + strings.length);
strings.push(post);
}
}
table.writeUInt16(Object.keys(mapping).length);
for (_j = 0, _len1 = indexes.length; _j < _len1; _j++) {
index = indexes[_j];
table.writeUInt16(index);
}
for (_k = 0, _len2 = strings.length; _k < _len2; _k++) {
string = strings[_k];
table.writeByte(string.length);
table.writeString(string);
}
return table.data;
};
POSTSCRIPT_GLYPHS = '.notdef .null nonmarkingreturn space exclam quotedbl numbersign dollar percent\nampersand quotesingle parenleft parenright asterisk plus comma hyphen period slash\nzero one two three four five six seven eight nine colon semicolon less equal greater\nquestion at A B C D E F G H I J K L M N O P Q R S T U V W X Y Z\nbracketleft backslash bracketright asciicircum underscore grave\na b c d e f g h i j k l m n o p q r s t u v w x y z\nbraceleft bar braceright asciitilde Adieresis Aring Ccedilla Eacute Ntilde Odieresis\nUdieresis aacute agrave acircumflex adieresis atilde aring ccedilla eacute egrave\necircumflex edieresis iacute igrave icircumflex idieresis ntilde oacute ograve\nocircumflex odieresis otilde uacute ugrave ucircumflex udieresis dagger degree cent\nsterling section bullet paragraph germandbls registered copyright trademark acute\ndieresis notequal AE Oslash infinity plusminus lessequal greaterequal yen mu\npartialdiff summation product pi integral ordfeminine ordmasculine Omega ae oslash\nquestiondown exclamdown logicalnot radical florin approxequal Delta guillemotleft\nguillemotright ellipsis nonbreakingspace Agrave Atilde Otilde OE oe endash emdash\nquotedblleft quotedblright quoteleft quoteright divide lozenge ydieresis Ydieresis\nfraction currency guilsinglleft guilsinglright fi fl daggerdbl periodcentered\nquotesinglbase quotedblbase perthousand Acircumflex Ecircumflex Aacute Edieresis\nEgrave Iacute Icircumflex Idieresis Igrave Oacute Ocircumflex apple Ograve Uacute\nUcircumflex Ugrave dotlessi circumflex tilde macron breve dotaccent ring cedilla\nhungarumlaut ogonek caron Lslash lslash Scaron scaron Zcaron zcaron brokenbar Eth\neth Yacute yacute Thorn thorn minus multiply onesuperior twosuperior threesuperior\nonehalf onequarter threequarters franc Gbreve gbreve Idotaccent Scedilla scedilla\nCacute cacute Ccaron ccaron dcroat'.split(/\s+/g);
return PostTable;
})(Table);
module.exports = PostTable;
}).call(this);
},{"../../data":16,"../table":23}],34:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var CmapTable, DFont, Data, Directory, GlyfTable, HeadTable, HheaTable, HmtxTable, LocaTable, MaxpTable, NameTable, OS2Table, PostTable, TTFFont, fs;
fs = require('fs');
Data = require('../data');
DFont = require('./dfont');
Directory = require('./directory');
NameTable = require('./tables/name');
HeadTable = require('./tables/head');
CmapTable = require('./tables/cmap');
HmtxTable = require('./tables/hmtx');
HheaTable = require('./tables/hhea');
MaxpTable = require('./tables/maxp');
PostTable = require('./tables/post');
OS2Table = require('./tables/os2');
LocaTable = require('./tables/loca');
GlyfTable = require('./tables/glyf');
TTFFont = (function() {
TTFFont.open = function(filename, name) {
var contents;
contents = fs.readFileSync(filename);
return new TTFFont(contents, name);
};
TTFFont.fromDFont = function(filename, family) {
var dfont;
dfont = DFont.open(filename);
return new TTFFont(dfont.getNamedFont(family));
};
TTFFont.fromBuffer = function(buffer, family) {
var dfont, e, ttf;
try {
ttf = new TTFFont(buffer, family);
if (!(ttf.head.exists && ttf.name.exists && ttf.cmap.exists)) {
dfont = new DFont(buffer);
ttf = new TTFFont(dfont.getNamedFont(family));
if (!(ttf.head.exists && ttf.name.exists && ttf.cmap.exists)) {
throw new Error('Invalid TTF file in DFont');
}
}
return ttf;
} catch (_error) {
e = _error;
throw new Error('Unknown font format in buffer: ' + e.message);
}
};
function TTFFont(rawData, name) {
var data, i, numFonts, offset, offsets, version, _i, _j, _len;
this.rawData = rawData;
data = this.contents = new Data(this.rawData);
if (data.readString(4) === 'ttcf') {
if (!name) {
throw new Error("Must specify a font name for TTC files.");
}
version = data.readInt();
numFonts = data.readInt();
offsets = [];
for (i = _i = 0; 0 <= numFonts ? _i < numFonts : _i > numFonts; i = 0 <= numFonts ? ++_i : --_i) {
offsets[i] = data.readInt();
}
for (i = _j = 0, _len = offsets.length; _j < _len; i = ++_j) {
offset = offsets[i];
data.pos = offset;
this.parse();
if (this.name.postscriptName === name) {
return;
}
}
throw new Error("Font " + name + " not found in TTC file.");
} else {
data.pos = 0;
this.parse();
}
}
TTFFont.prototype.parse = function() {
this.directory = new Directory(this.contents);
this.head = new HeadTable(this);
this.name = new NameTable(this);
this.cmap = new CmapTable(this);
this.hhea = new HheaTable(this);
this.maxp = new MaxpTable(this);
this.hmtx = new HmtxTable(this);
this.post = new PostTable(this);
this.os2 = new OS2Table(this);
this.loca = new LocaTable(this);
this.glyf = new GlyfTable(this);
this.ascender = (this.os2.exists && this.os2.ascender) || this.hhea.ascender;
this.decender = (this.os2.exists && this.os2.decender) || this.hhea.decender;
this.lineGap = (this.os2.exists && this.os2.lineGap) || this.hhea.lineGap;
return this.bbox = [this.head.xMin, this.head.yMin, this.head.xMax, this.head.yMax];
};
TTFFont.prototype.characterToGlyph = function(character) {
var _ref;
return ((_ref = this.cmap.unicode) != null ? _ref.codeMap[character] : void 0) || 0;
};
TTFFont.prototype.widthOfGlyph = function(glyph) {
var scale;
scale = 1000.0 / this.head.unitsPerEm;
return this.hmtx.forGlyph(glyph).advance * scale;
};
return TTFFont;
})();
module.exports = TTFFont;
}).call(this);
},{"../data":16,"./dfont":20,"./directory":21,"./tables/cmap":24,"./tables/glyf":25,"./tables/head":26,"./tables/hhea":27,"./tables/hmtx":28,"./tables/loca":29,"./tables/maxp":30,"./tables/name":31,"./tables/os2":32,"./tables/post":33,"fs":58}],35:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
/*
* An implementation of Ruby's string.succ method.
* By Devon Govett
*
* Returns the successor to str. The successor is calculated by incrementing characters starting
* from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the
* string. Incrementing a digit always results in another digit, and incrementing a letter results in
* another letter of the same case.
*
* If the increment generates a carry, the character to the left of it is incremented. This
* process repeats until there is no carry, adding an additional character if necessary.
*
* succ("abcd") == "abce"
* succ("THX1138") == "THX1139"
* succ("<<koala>>") == "<<koalb>>"
* succ("1999zzz") == "2000aaa"
* succ("ZZZ9999") == "AAAA0000"
*/
(function() {
exports.successorOf = function(input) {
var added, alphabet, carry, i, index, isUpperCase, last, length, next, result;
alphabet = 'abcdefghijklmnopqrstuvwxyz';
length = alphabet.length;
result = input;
i = input.length;
while (i >= 0) {
last = input.charAt(--i);
if (isNaN(last)) {
index = alphabet.indexOf(last.toLowerCase());
if (index === -1) {
next = last;
carry = true;
} else {
next = alphabet.charAt((index + 1) % length);
isUpperCase = last === last.toUpperCase();
if (isUpperCase) {
next = next.toUpperCase();
}
carry = index + 1 >= length;
if (carry && i === 0) {
added = isUpperCase ? 'A' : 'a';
result = added + next + result.slice(1);
break;
}
}
} else {
next = +last + 1;
carry = next > 9;
if (carry) {
next = 0;
}
if (carry && i === 0) {
result = '1' + next + result.slice(1);
break;
}
}
result = result.slice(0, i) + next + result.slice(i + 1);
if (!carry) {
break;
}
}
return result;
};
exports.invert = function(object) {
var key, ret, val;
ret = {};
for (key in object) {
val = object[key];
ret[val] = key;
}
return ret;
};
}).call(this);
},{}],36:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var PDFGradient, PDFLinearGradient, PDFRadialGradient,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
PDFGradient = (function() {
function PDFGradient(doc) {
this.doc = doc;
this.stops = [];
this.embedded = false;
this.transform = [1, 0, 0, 1, 0, 0];
this._colorSpace = 'DeviceRGB';
}
PDFGradient.prototype.stop = function(pos, color, opacity) {
if (opacity == null) {
opacity = 1;
}
opacity = Math.max(0, Math.min(1, opacity));
this.stops.push([pos, this.doc._normalizeColor(color), opacity]);
return this;
};
PDFGradient.prototype.embed = function() {
var bounds, dx, dy, encode, fn, form, grad, group, gstate, i, last, m, m0, m1, m11, m12, m2, m21, m22, m3, m4, m5, name, pattern, resources, sMask, shader, stop, stops, v, _i, _j, _len, _ref, _ref1, _ref2;
if (this.embedded || this.stops.length === 0) {
return;
}
this.embedded = true;
last = this.stops[this.stops.length - 1];
if (last[0] < 1) {
this.stops.push([1, last[1], last[2]]);
}
bounds = [];
encode = [];
stops = [];
for (i = _i = 0, _ref = this.stops.length - 1; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
encode.push(0, 1);
if (i + 2 !== this.stops.length) {
bounds.push(this.stops[i + 1][0]);
}
fn = this.doc.ref({
FunctionType: 2,
Domain: [0, 1],
C0: this.stops[i + 0][1],
C1: this.stops[i + 1][1],
N: 1
});
stops.push(fn);
fn.end();
}
if (stops.length === 1) {
fn = stops[0];
} else {
fn = this.doc.ref({
FunctionType: 3,
Domain: [0, 1],
Functions: stops,
Bounds: bounds,
Encode: encode
});
fn.end();
}
this.id = 'Sh' + (++this.doc._gradCount);
m = this.doc._ctm.slice();
m0 = m[0], m1 = m[1], m2 = m[2], m3 = m[3], m4 = m[4], m5 = m[5];
_ref1 = this.transform, m11 = _ref1[0], m12 = _ref1[1], m21 = _ref1[2], m22 = _ref1[3], dx = _ref1[4], dy = _ref1[5];
m[0] = m0 * m11 + m2 * m12;
m[1] = m1 * m11 + m3 * m12;
m[2] = m0 * m21 + m2 * m22;
m[3] = m1 * m21 + m3 * m22;
m[4] = m0 * dx + m2 * dy + m4;
m[5] = m1 * dx + m3 * dy + m5;
shader = this.shader(fn);
shader.end();
pattern = this.doc.ref({
Type: 'Pattern',
PatternType: 2,
Shading: shader,
Matrix: (function() {
var _j, _len, _results;
_results = [];
for (_j = 0, _len = m.length; _j < _len; _j++) {
v = m[_j];
_results.push(+v.toFixed(5));
}
return _results;
})()
});
this.doc.page.patterns[this.id] = pattern;
pattern.end();
if (this.stops.some(function(stop) {
return stop[2] < 1;
})) {
grad = this.opacityGradient();
grad._colorSpace = 'DeviceGray';
_ref2 = this.stops;
for (_j = 0, _len = _ref2.length; _j < _len; _j++) {
stop = _ref2[_j];
grad.stop(stop[0], [stop[2]]);
}
grad = grad.embed();
group = this.doc.ref({
Type: 'Group',
S: 'Transparency',
CS: 'DeviceGray'
});
group.end();
resources = this.doc.ref({
ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI'],
Shading: {
Sh1: grad.data.Shading
}
});
resources.end();
form = this.doc.ref({
Type: 'XObject',
Subtype: 'Form',
FormType: 1,
BBox: [0, 0, this.doc.page.width, this.doc.page.height],
Group: group,
Resources: resources
});
form.end("/Sh1 sh");
sMask = this.doc.ref({
Type: 'Mask',
S: 'Luminosity',
G: form
});
sMask.end();
gstate = this.doc.ref({
Type: 'ExtGState',
SMask: sMask
});
this.opacity_id = ++this.doc._opacityCount;
name = "Gs" + this.opacity_id;
this.doc.page.ext_gstates[name] = gstate;
gstate.end();
}
return pattern;
};
PDFGradient.prototype.apply = function(op) {
if (!this.embedded) {
this.embed();
}
this.doc.addContent("/" + this.id + " " + op);
if (this.opacity_id) {
this.doc.addContent("/Gs" + this.opacity_id + " gs");
return this.doc._sMasked = true;
}
};
return PDFGradient;
})();
PDFLinearGradient = (function(_super) {
__extends(PDFLinearGradient, _super);
function PDFLinearGradient(doc, x1, y1, x2, y2) {
this.doc = doc;
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
PDFLinearGradient.__super__.constructor.apply(this, arguments);
}
PDFLinearGradient.prototype.shader = function(fn) {
return this.doc.ref({
ShadingType: 2,
ColorSpace: this._colorSpace,
Coords: [this.x1, this.y1, this.x2, this.y2],
Function: fn,
Extend: [true, true]
});
};
PDFLinearGradient.prototype.opacityGradient = function() {
return new PDFLinearGradient(this.doc, this.x1, this.y1, this.x2, this.y2);
};
return PDFLinearGradient;
})(PDFGradient);
PDFRadialGradient = (function(_super) {
__extends(PDFRadialGradient, _super);
function PDFRadialGradient(doc, x1, y1, r1, x2, y2, r2) {
this.doc = doc;
this.x1 = x1;
this.y1 = y1;
this.r1 = r1;
this.x2 = x2;
this.y2 = y2;
this.r2 = r2;
PDFRadialGradient.__super__.constructor.apply(this, arguments);
}
PDFRadialGradient.prototype.shader = function(fn) {
return this.doc.ref({
ShadingType: 3,
ColorSpace: this._colorSpace,
Coords: [this.x1, this.y1, this.r1, this.x2, this.y2, this.r2],
Function: fn,
Extend: [true, true]
});
};
PDFRadialGradient.prototype.opacityGradient = function() {
return new PDFRadialGradient(this.doc, this.x1, this.y1, this.r1, this.x2, this.y2, this.r2);
};
return PDFRadialGradient;
})(PDFGradient);
module.exports = {
PDFGradient: PDFGradient,
PDFLinearGradient: PDFLinearGradient,
PDFRadialGradient: PDFRadialGradient
};
}).call(this);
},{}],37:[function(require,module,exports){
(function (Buffer){
// Generated by CoffeeScript 1.7.1
/*
PDFImage - embeds images in PDF documents
By Devon Govett
*/
(function() {
var Data, JPEG, PDFImage, PNG, fs;
fs = require('fs');
Data = require('./data');
JPEG = require('./image/jpeg');
PNG = require('./image/png');
PDFImage = (function() {
function PDFImage() {}
PDFImage.open = function(src, label) {
var data, match;
if (Buffer.isBuffer(src)) {
data = src;
} else {
if (match = /^data:.+;base64,(.*)$/.exec(src)) {
data = new Buffer(match[1], 'base64');
} else {
data = fs.readFileSync(src);
if (!data) {
return;
}
}
}
if (data[0] === 0xff && data[1] === 0xd8) {
return new JPEG(data, label);
} else if (data[0] === 0x89 && data.toString('ascii', 1, 4) === 'PNG') {
return new PNG(data, label);
} else {
throw new Error('Unknown image format.');
}
};
return PDFImage;
})();
module.exports = PDFImage;
}).call(this);
}).call(this,require("buffer").Buffer)
},{"./data":16,"./image/jpeg":38,"./image/png":39,"buffer":74,"fs":58}],38:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var JPEG, fs,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
fs = require('fs');
JPEG = (function() {
var MARKERS;
MARKERS = [0xFFC0, 0xFFC1, 0xFFC2, 0xFFC3, 0xFFC5, 0xFFC6, 0xFFC7, 0xFFC8, 0xFFC9, 0xFFCA, 0xFFCB, 0xFFCC, 0xFFCD, 0xFFCE, 0xFFCF];
function JPEG(data, label) {
var channels, marker, pos;
this.data = data;
this.label = label;
if (this.data.readUInt16BE(0) !== 0xFFD8) {
throw "SOI not found in JPEG";
}
pos = 2;
while (pos < this.data.length) {
marker = this.data.readUInt16BE(pos);
pos += 2;
if (__indexOf.call(MARKERS, marker) >= 0) {
break;
}
pos += this.data.readUInt16BE(pos);
}
if (__indexOf.call(MARKERS, marker) < 0) {
throw "Invalid JPEG.";
}
pos += 2;
this.bits = this.data[pos++];
this.height = this.data.readUInt16BE(pos);
pos += 2;
this.width = this.data.readUInt16BE(pos);
pos += 2;
channels = this.data[pos++];
this.colorSpace = (function() {
switch (channels) {
case 1:
return 'DeviceGray';
case 3:
return 'DeviceRGB';
case 4:
return 'DeviceCMYK';
}
})();
this.obj = null;
}
JPEG.prototype.embed = function(document) {
if (this.obj) {
return;
}
this.obj = document.ref({
Type: 'XObject',
Subtype: 'Image',
BitsPerComponent: this.bits,
Width: this.width,
Height: this.height,
ColorSpace: this.colorSpace,
Filter: 'DCTDecode'
});
if (this.colorSpace === 'DeviceCMYK') {
this.obj.data['Decode'] = [1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0];
}
this.obj.end(this.data);
return this.data = null;
};
return JPEG;
})();
module.exports = JPEG;
}).call(this);
},{"fs":58}],39:[function(require,module,exports){
(function (Buffer){
// Generated by CoffeeScript 1.7.1
(function() {
var PNG, PNGImage, zlib;
zlib = require('zlib');
PNG = require('png-js');
PNGImage = (function() {
function PNGImage(data, label) {
this.label = label;
this.image = new PNG(data);
this.width = this.image.width;
this.height = this.image.height;
this.imgData = this.image.imgData;
this.obj = null;
}
PNGImage.prototype.embed = function(document) {
var mask, palette, params, rgb, val, x, _i, _len;
this.document = document;
if (this.obj) {
return;
}
this.obj = document.ref({
Type: 'XObject',
Subtype: 'Image',
BitsPerComponent: this.image.bits,
Width: this.width,
Height: this.height,
Filter: 'FlateDecode'
});
if (!this.image.hasAlphaChannel) {
params = document.ref({
Predictor: 15,
Colors: this.image.colors,
BitsPerComponent: this.image.bits,
Columns: this.width
});
this.obj.data['DecodeParms'] = params;
params.end();
}
if (this.image.palette.length === 0) {
this.obj.data['ColorSpace'] = this.image.colorSpace;
} else {
palette = document.ref();
palette.end(new Buffer(this.image.palette));
this.obj.data['ColorSpace'] = ['Indexed', 'DeviceRGB', (this.image.palette.length / 3) - 1, palette];
}
if (this.image.transparency.grayscale) {
val = this.image.transparency.greyscale;
return this.obj.data['Mask'] = [val, val];
} else if (this.image.transparency.rgb) {
rgb = this.image.transparency.rgb;
mask = [];
for (_i = 0, _len = rgb.length; _i < _len; _i++) {
x = rgb[_i];
mask.push(x, x);
}
return this.obj.data['Mask'] = mask;
} else if (this.image.transparency.indexed) {
return this.loadIndexedAlphaChannel();
} else if (this.image.hasAlphaChannel) {
return this.splitAlphaChannel();
} else {
return this.finalize();
}
};
PNGImage.prototype.finalize = function() {
var sMask;
if (this.alphaChannel) {
sMask = this.document.ref({
Type: 'XObject',
Subtype: 'Image',
Height: this.height,
Width: this.width,
BitsPerComponent: 8,
Filter: 'FlateDecode',
ColorSpace: 'DeviceGray',
Decode: [0, 1]
});
sMask.end(this.alphaChannel);
this.obj.data['SMask'] = sMask;
}
this.obj.end(this.imgData);
this.image = null;
return this.imgData = null;
};
PNGImage.prototype.splitAlphaChannel = function() {
return this.image.decodePixels((function(_this) {
return function(pixels) {
var a, alphaChannel, colorByteSize, done, i, imgData, len, p, pixelCount;
colorByteSize = _this.image.colors * _this.image.bits / 8;
pixelCount = _this.width * _this.height;
imgData = new Buffer(pixelCount * colorByteSize);
alphaChannel = new Buffer(pixelCount);
i = p = a = 0;
len = pixels.length;
while (i < len) {
imgData[p++] = pixels[i++];
imgData[p++] = pixels[i++];
imgData[p++] = pixels[i++];
alphaChannel[a++] = pixels[i++];
}
done = 0;
zlib.deflate(imgData, function(err, imgData) {
_this.imgData = imgData;
if (err) {
throw err;
}
if (++done === 2) {
return _this.finalize();
}
});
return zlib.deflate(alphaChannel, function(err, alphaChannel) {
_this.alphaChannel = alphaChannel;
if (err) {
throw err;
}
if (++done === 2) {
return _this.finalize();
}
});
};
})(this));
};
PNGImage.prototype.loadIndexedAlphaChannel = function(fn) {
var transparency;
transparency = this.image.transparency.indexed;
return this.image.decodePixels((function(_this) {
return function(pixels) {
var alphaChannel, i, j, _i, _ref;
alphaChannel = new Buffer(_this.width * _this.height);
i = 0;
for (j = _i = 0, _ref = pixels.length; _i < _ref; j = _i += 1) {
alphaChannel[i++] = transparency[pixels[j]];
}
return zlib.deflate(alphaChannel, function(err, alphaChannel) {
_this.alphaChannel = alphaChannel;
if (err) {
throw err;
}
return _this.finalize();
});
};
})(this));
};
return PNGImage;
})();
module.exports = PNGImage;
}).call(this);
}).call(this,require("buffer").Buffer)
},{"buffer":74,"png-js":56,"zlib":73}],40:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var EventEmitter, LineBreaker, LineWrapper,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
EventEmitter = require('events').EventEmitter;
LineBreaker = require('linebreak');
LineWrapper = (function(_super) {
__extends(LineWrapper, _super);
function LineWrapper(document, options) {
var _ref;
this.document = document;
this.indent = options.indent || 0;
this.characterSpacing = options.characterSpacing || 0;
this.wordSpacing = options.wordSpacing === 0;
this.columns = options.columns || 1;
this.columnGap = (_ref = options.columnGap) != null ? _ref : 18;
this.lineWidth = (options.width - (this.columnGap * (this.columns - 1))) / this.columns;
this.spaceLeft = this.lineWidth;
this.startX = this.document.x;
this.startY = this.document.y;
this.column = 1;
this.ellipsis = options.ellipsis;
this.continuedX = 0;
if (options.height != null) {
this.height = options.height;
this.maxY = this.startY + options.height;
} else {
this.maxY = this.document.page.maxY();
}
this.on('firstLine', (function(_this) {
return function(options) {
var indent;
indent = _this.continuedX || _this.indent;
_this.document.x += indent;
_this.lineWidth -= indent;
return _this.once('line', function() {
_this.document.x -= indent;
_this.lineWidth += indent;
if (options.continued && !_this.continuedX) {
_this.continuedX = _this.indent;
}
if (!options.continued) {
return _this.continuedX = 0;
}
});
};
})(this));
this.on('lastLine', (function(_this) {
return function(options) {
var align;
align = options.align;
if (align === 'justify') {
options.align = 'left';
}
_this.lastLine = true;
return _this.once('line', function() {
_this.document.y += options.paragraphGap || 0;
options.align = align;
return _this.lastLine = false;
});
};
})(this));
}
LineWrapper.prototype.wordWidth = function(word) {
return this.document.widthOfString(word, this) + this.characterSpacing + this.wordSpacing;
};
LineWrapper.prototype.eachWord = function(text, fn) {
var bk, breaker, fbk, l, last, lbk, shouldContinue, w, word, wordWidths;
breaker = new LineBreaker(text);
last = null;
wordWidths = {};
while (bk = breaker.nextBreak()) {
word = text.slice((last != null ? last.position : void 0) || 0, bk.position);
w = wordWidths[word] != null ? wordWidths[word] : wordWidths[word] = this.wordWidth(word);
if (w > this.lineWidth + this.continuedX) {
lbk = last;
fbk = {};
while (word.length) {
l = word.length;
while (w > this.spaceLeft) {
w = this.wordWidth(word.slice(0, --l));
}
fbk.required = l < word.length;
shouldContinue = fn(word.slice(0, l), w, fbk, lbk);
lbk = {
required: false
};
word = word.slice(l);
w = this.wordWidth(word);
if (shouldContinue === false) {
break;
}
}
} else {
shouldContinue = fn(word, w, bk, last);
}
if (shouldContinue === false) {
break;
}
last = bk;
}
};
LineWrapper.prototype.wrap = function(text, options) {
var buffer, emitLine, lc, nextY, textWidth, wc, y;
if (options.indent != null) {
this.indent = options.indent;
}
if (options.characterSpacing != null) {
this.characterSpacing = options.characterSpacing;
}
if (options.wordSpacing != null) {
this.wordSpacing = options.wordSpacing;
}
if (options.ellipsis != null) {
this.ellipsis = options.ellipsis;
}
nextY = this.document.y + this.document.currentLineHeight(true);
if (this.document.y > this.maxY || nextY > this.maxY) {
this.nextSection();
}
buffer = '';
textWidth = 0;
wc = 0;
lc = 0;
y = this.document.y;
emitLine = (function(_this) {
return function() {
options.textWidth = textWidth + _this.wordSpacing * (wc - 1);
options.wordCount = wc;
options.lineWidth = _this.lineWidth;
y = _this.document.y;
_this.emit('line', buffer, options, _this);
return lc++;
};
})(this);
this.emit('sectionStart', options, this);
this.eachWord(text, (function(_this) {
return function(word, w, bk, last) {
var lh, shouldContinue;
if ((last == null) || last.required) {
_this.emit('firstLine', options, _this);
_this.spaceLeft = _this.lineWidth;
}
if (w <= _this.spaceLeft) {
buffer += word;
textWidth += w;
wc++;
}
if (bk.required || w > _this.spaceLeft) {
if (bk.required) {
_this.emit('lastLine', options, _this);
}
lh = _this.document.currentLineHeight(true);
if ((_this.height != null) && _this.ellipsis && _this.document.y + lh * 2 > _this.maxY && _this.column >= _this.columns) {
if (_this.ellipsis === true) {
_this.ellipsis = '…';
}
buffer = buffer.replace(/\s+$/, '');
textWidth = _this.wordWidth(buffer + _this.ellipsis);
while (textWidth > _this.lineWidth) {
buffer = buffer.slice(0, -1).replace(/\s+$/, '');
textWidth = _this.wordWidth(buffer + _this.ellipsis);
}
buffer = buffer + _this.ellipsis;
}
emitLine();
if (_this.document.y + lh > _this.maxY) {
shouldContinue = _this.nextSection();
if (!shouldContinue) {
wc = 0;
buffer = '';
return false;
}
}
if (bk.required) {
if (w > _this.spaceLeft) {
buffer = word;
textWidth = w;
wc = 1;
emitLine();
}
_this.spaceLeft = _this.lineWidth;
buffer = '';
textWidth = 0;
return wc = 0;
} else {
_this.spaceLeft = _this.lineWidth - w;
buffer = word;
textWidth = w;
return wc = 1;
}
} else {
return _this.spaceLeft -= w;
}
};
})(this));
if (wc > 0) {
this.emit('lastLine', options, this);
emitLine();
}
this.emit('sectionEnd', options, this);
if (options.continued === true) {
if (lc > 1) {
this.continuedX = 0;
}
this.continuedX += options.textWidth;
return this.document.y = y;
} else {
return this.document.x = this.startX;
}
};
LineWrapper.prototype.nextSection = function(options) {
var _ref;
this.emit('sectionEnd', options, this);
if (++this.column > this.columns) {
if (this.height != null) {
return false;
}
this.document.addPage();
this.column = 1;
this.startY = this.document.page.margins.top;
this.maxY = this.document.page.maxY();
this.document.x = this.startX;
if (this.document._fillColor) {
(_ref = this.document).fillColor.apply(_ref, this.document._fillColor);
}
this.emit('pageBreak', options, this);
} else {
this.document.x += this.lineWidth + this.columnGap;
this.document.y = this.startY;
this.emit('columnBreak', options, this);
}
this.emit('sectionStart', options, this);
return true;
};
return LineWrapper;
})(EventEmitter);
module.exports = LineWrapper;
}).call(this);
},{"events":78,"linebreak":54}],41:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
module.exports = {
annotate: function(x, y, w, h, options) {
var key, ref, val;
options.Type = 'Annot';
options.Rect = this._convertRect(x, y, w, h);
options.Border = [0, 0, 0];
if (options.Subtype !== 'Link') {
if (options.C == null) {
options.C = this._normalizeColor(options.color || [0, 0, 0]);
}
}
delete options.color;
if (typeof options.Dest === 'string') {
options.Dest = new String(options.Dest);
}
for (key in options) {
val = options[key];
options[key[0].toUpperCase() + key.slice(1)] = val;
}
ref = this.ref(options);
this.page.annotations.push(ref);
ref.end();
return this;
},
note: function(x, y, w, h, contents, options) {
if (options == null) {
options = {};
}
options.Subtype = 'Text';
options.Contents = new String(contents);
options.Name = 'Comment';
if (options.color == null) {
options.color = [243, 223, 92];
}
return this.annotate(x, y, w, h, options);
},
link: function(x, y, w, h, url, options) {
if (options == null) {
options = {};
}
options.Subtype = 'Link';
options.A = this.ref({
S: 'URI',
URI: new String(url)
});
options.A.end();
return this.annotate(x, y, w, h, options);
},
_markup: function(x, y, w, h, options) {
var x1, x2, y1, y2, _ref;
if (options == null) {
options = {};
}
_ref = this._convertRect(x, y, w, h), x1 = _ref[0], y1 = _ref[1], x2 = _ref[2], y2 = _ref[3];
options.QuadPoints = [x1, y2, x2, y2, x1, y1, x2, y1];
options.Contents = new String;
return this.annotate(x, y, w, h, options);
},
highlight: function(x, y, w, h, options) {
if (options == null) {
options = {};
}
options.Subtype = 'Highlight';
if (options.color == null) {
options.color = [241, 238, 148];
}
return this._markup(x, y, w, h, options);
},
underline: function(x, y, w, h, options) {
if (options == null) {
options = {};
}
options.Subtype = 'Underline';
return this._markup(x, y, w, h, options);
},
strike: function(x, y, w, h, options) {
if (options == null) {
options = {};
}
options.Subtype = 'StrikeOut';
return this._markup(x, y, w, h, options);
},
lineAnnotation: function(x1, y1, x2, y2, options) {
if (options == null) {
options = {};
}
options.Subtype = 'Line';
options.Contents = new String;
options.L = [x1, this.page.height - y1, x2, this.page.height - y2];
return this.annotate(x1, y1, x2, y2, options);
},
rectAnnotation: function(x, y, w, h, options) {
if (options == null) {
options = {};
}
options.Subtype = 'Square';
options.Contents = new String;
return this.annotate(x, y, w, h, options);
},
ellipseAnnotation: function(x, y, w, h, options) {
if (options == null) {
options = {};
}
options.Subtype = 'Circle';
options.Contents = new String;
return this.annotate(x, y, w, h, options);
},
textAnnotation: function(x, y, w, h, text, options) {
if (options == null) {
options = {};
}
options.Subtype = 'FreeText';
options.Contents = new String(text);
options.DA = new String;
return this.annotate(x, y, w, h, options);
},
_convertRect: function(x1, y1, w, h) {
var m0, m1, m2, m3, m4, m5, x2, y2, _ref;
y2 = y1;
y1 += h;
x2 = x1 + w;
_ref = this._ctm, m0 = _ref[0], m1 = _ref[1], m2 = _ref[2], m3 = _ref[3], m4 = _ref[4], m5 = _ref[5];
x1 = m0 * x1 + m2 * y1 + m4;
y1 = m1 * x1 + m3 * y1 + m5;
x2 = m0 * x2 + m2 * y2 + m4;
y2 = m1 * x2 + m3 * y2 + m5;
return [x1, y1, x2, y2];
}
};
}).call(this);
},{}],42:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var PDFGradient, PDFLinearGradient, PDFRadialGradient, namedColors, _ref;
_ref = require('../gradient'), PDFGradient = _ref.PDFGradient, PDFLinearGradient = _ref.PDFLinearGradient, PDFRadialGradient = _ref.PDFRadialGradient;
module.exports = {
initColor: function() {
this._opacityRegistry = {};
this._opacityCount = 0;
return this._gradCount = 0;
},
_normalizeColor: function(color) {
var hex, part;
if (color instanceof PDFGradient) {
return color;
}
if (typeof color === 'string') {
if (color.charAt(0) === '#') {
if (color.length === 4) {
color = color.replace(/#([0-9A-F])([0-9A-F])([0-9A-F])/i, "#$1$1$2$2$3$3");
}
hex = parseInt(color.slice(1), 16);
color = [hex >> 16, hex >> 8 & 0xff, hex & 0xff];
} else if (namedColors[color]) {
color = namedColors[color];
}
}
if (Array.isArray(color)) {
if (color.length === 3) {
color = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = color.length; _i < _len; _i++) {
part = color[_i];
_results.push(part / 255);
}
return _results;
})();
} else if (color.length === 4) {
color = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = color.length; _i < _len; _i++) {
part = color[_i];
_results.push(part / 100);
}
return _results;
})();
}
return color;
}
return null;
},
_setColor: function(color, stroke) {
var gstate, name, op, space;
color = this._normalizeColor(color);
if (!color) {
return false;
}
if (this._sMasked) {
gstate = this.ref({
Type: 'ExtGState',
SMask: 'None'
});
gstate.end();
name = "Gs" + (++this._opacityCount);
this.page.ext_gstates[name] = gstate;
this.addContent("/" + name + " gs");
this._sMasked = false;
}
op = stroke ? 'SCN' : 'scn';
if (color instanceof PDFGradient) {
this._setColorSpace('Pattern', stroke);
color.apply(op);
} else {
space = color.length === 4 ? 'DeviceCMYK' : 'DeviceRGB';
this._setColorSpace(space, stroke);
color = color.join(' ');
this.addContent("" + color + " " + op);
}
return true;
},
_setColorSpace: function(space, stroke) {
var op;
op = stroke ? 'CS' : 'cs';
return this.addContent("/" + space + " " + op);
},
fillColor: function(color, opacity) {
var set;
if (opacity == null) {
opacity = 1;
}
set = this._setColor(color, false);
if (set) {
this.fillOpacity(opacity);
}
this._fillColor = [color, opacity];
return this;
},
strokeColor: function(color, opacity) {
var set;
if (opacity == null) {
opacity = 1;
}
set = this._setColor(color, true);
if (set) {
this.strokeOpacity(opacity);
}
return this;
},
opacity: function(opacity) {
this._doOpacity(opacity, opacity);
return this;
},
fillOpacity: function(opacity) {
this._doOpacity(opacity, null);
return this;
},
strokeOpacity: function(opacity) {
this._doOpacity(null, opacity);
return this;
},
_doOpacity: function(fillOpacity, strokeOpacity) {
var dictionary, id, key, name, _ref1;
if (!((fillOpacity != null) || (strokeOpacity != null))) {
return;
}
if (fillOpacity != null) {
fillOpacity = Math.max(0, Math.min(1, fillOpacity));
}
if (strokeOpacity != null) {
strokeOpacity = Math.max(0, Math.min(1, strokeOpacity));
}
key = "" + fillOpacity + "_" + strokeOpacity;
if (this._opacityRegistry[key]) {
_ref1 = this._opacityRegistry[key], dictionary = _ref1[0], name = _ref1[1];
} else {
dictionary = {
Type: 'ExtGState'
};
if (fillOpacity != null) {
dictionary.ca = fillOpacity;
}
if (strokeOpacity != null) {
dictionary.CA = strokeOpacity;
}
dictionary = this.ref(dictionary);
dictionary.end();
id = ++this._opacityCount;
name = "Gs" + id;
this._opacityRegistry[key] = [dictionary, name];
}
this.page.ext_gstates[name] = dictionary;
return this.addContent("/" + name + " gs");
},
linearGradient: function(x1, y1, x2, y2) {
return new PDFLinearGradient(this, x1, y1, x2, y2);
},
radialGradient: function(x1, y1, r1, x2, y2, r2) {
return new PDFRadialGradient(this, x1, y1, r1, x2, y2, r2);
}
};
namedColors = {
aliceblue: [240, 248, 255],
antiquewhite: [250, 235, 215],
aqua: [0, 255, 255],
aquamarine: [127, 255, 212],
azure: [240, 255, 255],
beige: [245, 245, 220],
bisque: [255, 228, 196],
black: [0, 0, 0],
blanchedalmond: [255, 235, 205],
blue: [0, 0, 255],
blueviolet: [138, 43, 226],
brown: [165, 42, 42],
burlywood: [222, 184, 135],
cadetblue: [95, 158, 160],
chartreuse: [127, 255, 0],
chocolate: [210, 105, 30],
coral: [255, 127, 80],
cornflowerblue: [100, 149, 237],
cornsilk: [255, 248, 220],
crimson: [220, 20, 60],
cyan: [0, 255, 255],
darkblue: [0, 0, 139],
darkcyan: [0, 139, 139],
darkgoldenrod: [184, 134, 11],
darkgray: [169, 169, 169],
darkgreen: [0, 100, 0],
darkgrey: [169, 169, 169],
darkkhaki: [189, 183, 107],
darkmagenta: [139, 0, 139],
darkolivegreen: [85, 107, 47],
darkorange: [255, 140, 0],
darkorchid: [153, 50, 204],
darkred: [139, 0, 0],
darksalmon: [233, 150, 122],
darkseagreen: [143, 188, 143],
darkslateblue: [72, 61, 139],
darkslategray: [47, 79, 79],
darkslategrey: [47, 79, 79],
darkturquoise: [0, 206, 209],
darkviolet: [148, 0, 211],
deeppink: [255, 20, 147],
deepskyblue: [0, 191, 255],
dimgray: [105, 105, 105],
dimgrey: [105, 105, 105],
dodgerblue: [30, 144, 255],
firebrick: [178, 34, 34],
floralwhite: [255, 250, 240],
forestgreen: [34, 139, 34],
fuchsia: [255, 0, 255],
gainsboro: [220, 220, 220],
ghostwhite: [248, 248, 255],
gold: [255, 215, 0],
goldenrod: [218, 165, 32],
gray: [128, 128, 128],
grey: [128, 128, 128],
green: [0, 128, 0],
greenyellow: [173, 255, 47],
honeydew: [240, 255, 240],
hotpink: [255, 105, 180],
indianred: [205, 92, 92],
indigo: [75, 0, 130],
ivory: [255, 255, 240],
khaki: [240, 230, 140],
lavender: [230, 230, 250],
lavenderblush: [255, 240, 245],
lawngreen: [124, 252, 0],
lemonchiffon: [255, 250, 205],
lightblue: [173, 216, 230],
lightcoral: [240, 128, 128],
lightcyan: [224, 255, 255],
lightgoldenrodyellow: [250, 250, 210],
lightgray: [211, 211, 211],
lightgreen: [144, 238, 144],
lightgrey: [211, 211, 211],
lightpink: [255, 182, 193],
lightsalmon: [255, 160, 122],
lightseagreen: [32, 178, 170],
lightskyblue: [135, 206, 250],
lightslategray: [119, 136, 153],
lightslategrey: [119, 136, 153],
lightsteelblue: [176, 196, 222],
lightyellow: [255, 255, 224],
lime: [0, 255, 0],
limegreen: [50, 205, 50],
linen: [250, 240, 230],
magenta: [255, 0, 255],
maroon: [128, 0, 0],
mediumaquamarine: [102, 205, 170],
mediumblue: [0, 0, 205],
mediumorchid: [186, 85, 211],
mediumpurple: [147, 112, 219],
mediumseagreen: [60, 179, 113],
mediumslateblue: [123, 104, 238],
mediumspringgreen: [0, 250, 154],
mediumturquoise: [72, 209, 204],
mediumvioletred: [199, 21, 133],
midnightblue: [25, 25, 112],
mintcream: [245, 255, 250],
mistyrose: [255, 228, 225],
moccasin: [255, 228, 181],
navajowhite: [255, 222, 173],
navy: [0, 0, 128],
oldlace: [253, 245, 230],
olive: [128, 128, 0],
olivedrab: [107, 142, 35],
orange: [255, 165, 0],
orangered: [255, 69, 0],
orchid: [218, 112, 214],
palegoldenrod: [238, 232, 170],
palegreen: [152, 251, 152],
paleturquoise: [175, 238, 238],
palevioletred: [219, 112, 147],
papayawhip: [255, 239, 213],
peachpuff: [255, 218, 185],
peru: [205, 133, 63],
pink: [255, 192, 203],
plum: [221, 160, 221],
powderblue: [176, 224, 230],
purple: [128, 0, 128],
red: [255, 0, 0],
rosybrown: [188, 143, 143],
royalblue: [65, 105, 225],
saddlebrown: [139, 69, 19],
salmon: [250, 128, 114],
sandybrown: [244, 164, 96],
seagreen: [46, 139, 87],
seashell: [255, 245, 238],
sienna: [160, 82, 45],
silver: [192, 192, 192],
skyblue: [135, 206, 235],
slateblue: [106, 90, 205],
slategray: [112, 128, 144],
slategrey: [112, 128, 144],
snow: [255, 250, 250],
springgreen: [0, 255, 127],
steelblue: [70, 130, 180],
tan: [210, 180, 140],
teal: [0, 128, 128],
thistle: [216, 191, 216],
tomato: [255, 99, 71],
turquoise: [64, 224, 208],
violet: [238, 130, 238],
wheat: [245, 222, 179],
white: [255, 255, 255],
whitesmoke: [245, 245, 245],
yellow: [255, 255, 0],
yellowgreen: [154, 205, 50]
};
}).call(this);
},{"../gradient":36}],43:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var PDFFont;
PDFFont = require('../font');
module.exports = {
initFonts: function() {
this._fontFamilies = {};
this._fontCount = 0;
this._fontSize = 12;
this._font = null;
this._registeredFonts = {};
return this.font('Helvetica');
},
font: function(src, family, size) {
var cacheKey, font, id, _ref;
if (typeof family === 'number') {
size = family;
family = null;
}
if (typeof src === 'string' && this._registeredFonts[src]) {
cacheKey = src;
_ref = this._registeredFonts[src], src = _ref.src, family = _ref.family;
} else {
cacheKey = family || src;
if (typeof cacheKey !== 'string') {
cacheKey = null;
}
}
if (size != null) {
this.fontSize(size);
}
if (font = this._fontFamilies[cacheKey]) {
this._font = font;
return this;
}
id = 'F' + (++this._fontCount);
this._font = new PDFFont(this, src, family, id);
if (font = this._fontFamilies[this._font.name]) {
this._font = font;
return this;
}
if (cacheKey) {
this._fontFamilies[cacheKey] = this._font;
}
this._fontFamilies[this._font.name] = this._font;
return this;
},
fontSize: function(_fontSize) {
this._fontSize = _fontSize;
return this;
},
currentLineHeight: function(includeGap) {
if (includeGap == null) {
includeGap = false;
}
return this._font.lineHeight(this._fontSize, includeGap);
},
registerFont: function(name, src, family) {
this._registeredFonts[name] = {
src: src,
family: family
};
return this;
}
};
}).call(this);
},{"../font":18}],44:[function(require,module,exports){
(function (Buffer){
// Generated by CoffeeScript 1.7.1
(function() {
var PDFImage;
PDFImage = require('../image');
module.exports = {
initImages: function() {
this._imageRegistry = {};
return this._imageCount = 0;
},
image: function(src, x, y, options) {
var bh, bp, bw, h, hp, image, ip, w, wp, _base, _name, _ref, _ref1, _ref2;
if (options == null) {
options = {};
}
if (typeof x === 'object') {
options = x;
x = null;
}
x = (_ref = x != null ? x : options.x) != null ? _ref : this.x;
y = (_ref1 = y != null ? y : options.y) != null ? _ref1 : this.y;
if (!Buffer.isBuffer(src)) {
image = this._imageRegistry[src];
}
if (!image) {
image = PDFImage.open(src, 'I' + (++this._imageCount));
image.embed(this);
if (!Buffer.isBuffer(src)) {
this._imageRegistry[src] = image;
}
}
if ((_base = this.page.xobjects)[_name = image.label] == null) {
_base[_name] = image.obj;
}
w = options.width || image.width;
h = options.height || image.height;
if (options.width && !options.height) {
wp = w / image.width;
w = image.width * wp;
h = image.height * wp;
} else if (options.height && !options.width) {
hp = h / image.height;
w = image.width * hp;
h = image.height * hp;
} else if (options.scale) {
w = image.width * options.scale;
h = image.height * options.scale;
} else if (options.fit) {
_ref2 = options.fit, bw = _ref2[0], bh = _ref2[1];
bp = bw / bh;
ip = image.width / image.height;
if (ip > bp) {
w = bw;
h = bw / ip;
} else {
h = bh;
w = bh * ip;
}
if (options.align === 'center') {
x = x + bw / 2 - w / 2;
} else if (options.align === 'right') {
x = x + bw - w;
}
if (options.valign === 'center') {
y = y + bh / 2 - h / 2;
} else if (options.valign === 'bottom') {
y = y + bh - h;
}
}
if (this.y === y) {
this.y += h;
}
this.save();
this.transform(w, 0, 0, -h, x, y + h);
this.addContent("/" + image.label + " Do");
this.restore();
return this;
}
};
}).call(this);
}).call(this,require("buffer").Buffer)
},{"../image":37,"buffer":74}],45:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var LineWrapper;
LineWrapper = require('../line_wrapper');
module.exports = {
initText: function() {
this.x = 0;
this.y = 0;
return this._lineGap = 0;
},
lineGap: function(_lineGap) {
this._lineGap = _lineGap;
return this;
},
moveDown: function(lines) {
if (lines == null) {
lines = 1;
}
this.y += this.currentLineHeight(true) * lines + this._lineGap;
return this;
},
moveUp: function(lines) {
if (lines == null) {
lines = 1;
}
this.y -= this.currentLineHeight(true) * lines + this._lineGap;
return this;
},
_text: function(text, x, y, options, lineCallback) {
var line, wrapper, _i, _len, _ref;
options = this._initOptions(x, y, options);
text = '' + text;
if (options.wordSpacing) {
text = text.replace(/\s{2,}/g, ' ');
}
if (options.width) {
wrapper = this._wrapper;
if (!wrapper) {
wrapper = new LineWrapper(this, options);
wrapper.on('line', lineCallback);
}
this._wrapper = options.continued ? wrapper : null;
this._textOptions = options.continued ? options : null;
wrapper.wrap(text, options);
} else {
_ref = text.split('\n');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
line = _ref[_i];
lineCallback(line, options);
}
}
return this;
},
text: function(text, x, y, options) {
return this._text(text, x, y, options, this._line.bind(this));
},
widthOfString: function(string, options) {
if (options == null) {
options = {};
}
return this._font.widthOfString(string, this._fontSize) + (options.characterSpacing || 0) * (string.length - 1);
},
heightOfString: function(text, options) {
var height, lineGap, x, y;
if (options == null) {
options = {};
}
x = this.x, y = this.y;
options = this._initOptions(options);
options.height = Infinity;
lineGap = options.lineGap || this._lineGap || 0;
this._text(text, this.x, this.y, options, (function(_this) {
return function(line, options) {
return _this.y += _this.currentLineHeight(true) + lineGap;
};
})(this));
height = this.y - y;
this.x = x;
this.y = y;
return height;
},
list: function(list, x, y, options, wrapper) {
var flatten, i, indent, itemIndent, items, level, levels, r;
options = this._initOptions(x, y, options);
r = Math.round((this._font.ascender / 1000 * this._fontSize) / 3);
indent = options.textIndent || r * 5;
itemIndent = options.bulletIndent || r * 8;
level = 1;
items = [];
levels = [];
flatten = function(list) {
var i, item, _i, _len, _results;
_results = [];
for (i = _i = 0, _len = list.length; _i < _len; i = ++_i) {
item = list[i];
if (Array.isArray(item)) {
level++;
flatten(item);
_results.push(level--);
} else {
items.push(item);
_results.push(levels.push(level));
}
}
return _results;
};
flatten(list);
wrapper = new LineWrapper(this, options);
wrapper.on('line', this._line.bind(this));
level = 1;
i = 0;
wrapper.on('firstLine', (function(_this) {
return function() {
var diff, l;
if ((l = levels[i++]) !== level) {
diff = itemIndent * (l - level);
_this.x += diff;
wrapper.lineWidth -= diff;
level = l;
}
_this.circle(_this.x - indent + r, _this.y + r + (r / 2), r);
return _this.fill();
};
})(this));
wrapper.on('sectionStart', (function(_this) {
return function() {
var pos;
pos = indent + itemIndent * (level - 1);
_this.x += pos;
return wrapper.lineWidth -= pos;
};
})(this));
wrapper.on('sectionEnd', (function(_this) {
return function() {
var pos;
pos = indent + itemIndent * (level - 1);
_this.x -= pos;
return wrapper.lineWidth += pos;
};
})(this));
wrapper.wrap(items.join('\n'), options);
return this;
},
_initOptions: function(x, y, options) {
var key, margins, val, _ref;
if (x == null) {
x = {};
}
if (options == null) {
options = {};
}
if (typeof x === 'object') {
options = x;
x = null;
}
options = (function() {
var k, opts, v;
opts = {};
for (k in options) {
v = options[k];
opts[k] = v;
}
return opts;
})();
if (this._textOptions) {
_ref = this._textOptions;
for (key in _ref) {
val = _ref[key];
if (key !== 'continued') {
if (options[key] == null) {
options[key] = val;
}
}
}
}
if (x != null) {
this.x = x;
}
if (y != null) {
this.y = y;
}
if (options.lineBreak !== false) {
margins = this.page.margins;
if (options.width == null) {
options.width = this.page.width - this.x - margins.right;
}
}
options.columns || (options.columns = 0);
if (options.columnGap == null) {
options.columnGap = 18;
}
return options;
},
_line: function(text, options, wrapper) {
var lineGap;
if (options == null) {
options = {};
}
this._fragment(text, this.x, this.y, options);
lineGap = options.lineGap || this._lineGap || 0;
if (!wrapper) {
return this.x += this.widthOfString(text);
} else {
return this.y += this.currentLineHeight(true) + lineGap;
}
},
_fragment: function(text, x, y, options) {
var align, characterSpacing, commands, d, encoded, i, lineWidth, lineY, mode, renderedWidth, spaceWidth, textWidth, word, wordSpacing, words, _base, _i, _len, _name;
text = '' + text;
if (text.length === 0) {
return;
}
align = options.align || 'left';
wordSpacing = options.wordSpacing || 0;
characterSpacing = options.characterSpacing || 0;
if (options.width) {
switch (align) {
case 'right':
textWidth = this.widthOfString(text.replace(/\s+$/, ''), options);
x += options.lineWidth - textWidth;
break;
case 'center':
x += options.lineWidth / 2 - options.textWidth / 2;
break;
case 'justify':
words = text.trim().split(/\s+/);
textWidth = this.widthOfString(text.replace(/\s+/g, ''), options);
spaceWidth = this.widthOfString(' ') + characterSpacing;
wordSpacing = Math.max(0, (options.lineWidth - textWidth) / Math.max(1, words.length - 1) - spaceWidth);
}
}
renderedWidth = options.textWidth + (wordSpacing * (options.wordCount - 1)) + (characterSpacing * (text.length - 1));
if (options.link) {
this.link(x, y, renderedWidth, this.currentLineHeight(), options.link);
}
if (options.underline || options.strike) {
this.save();
if (!options.stroke) {
this.strokeColor.apply(this, this._fillColor);
}
lineWidth = this._fontSize < 10 ? 0.5 : Math.floor(this._fontSize / 10);
this.lineWidth(lineWidth);
d = options.underline ? 1 : 2;
lineY = y + this.currentLineHeight() / d;
if (options.underline) {
lineY -= lineWidth;
}
this.moveTo(x, lineY);
this.lineTo(x + renderedWidth, lineY);
this.stroke();
this.restore();
}
this.save();
this.transform(1, 0, 0, -1, 0, this.page.height);
y = this.page.height - y - (this._font.ascender / 1000 * this._fontSize);
if ((_base = this.page.fonts)[_name = this._font.id] == null) {
_base[_name] = this._font.ref();
}
this._font.use(text);
this.addContent("BT");
this.addContent("" + x + " " + y + " Td");
this.addContent("/" + this._font.id + " " + this._fontSize + " Tf");
mode = options.fill && options.stroke ? 2 : options.stroke ? 1 : 0;
if (mode) {
this.addContent("" + mode + " Tr");
}
if (characterSpacing) {
this.addContent("" + characterSpacing + " Tc");
}
if (wordSpacing) {
words = text.trim().split(/\s+/);
wordSpacing += this.widthOfString(' ') + characterSpacing;
wordSpacing *= 1000 / this._fontSize;
commands = [];
for (_i = 0, _len = words.length; _i < _len; _i++) {
word = words[_i];
encoded = this._font.encode(word);
encoded = ((function() {
var _j, _ref, _results;
_results = [];
for (i = _j = 0, _ref = encoded.length; _j < _ref; i = _j += 1) {
_results.push(encoded.charCodeAt(i).toString(16));
}
return _results;
})()).join('');
commands.push("<" + encoded + "> " + (-wordSpacing));
}
this.addContent("[" + (commands.join(' ')) + "] TJ");
} else {
encoded = this._font.encode(text);
encoded = ((function() {
var _j, _ref, _results;
_results = [];
for (i = _j = 0, _ref = encoded.length; _j < _ref; i = _j += 1) {
_results.push(encoded.charCodeAt(i).toString(16));
}
return _results;
})()).join('');
this.addContent("<" + encoded + "> Tj");
}
this.addContent("ET");
return this.restore();
}
};
}).call(this);
},{"../line_wrapper":40}],46:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var KAPPA, SVGPath,
__slice = [].slice;
SVGPath = require('../path');
KAPPA = 4.0 * ((Math.sqrt(2) - 1.0) / 3.0);
module.exports = {
initVector: function() {
this._ctm = [1, 0, 0, 1, 0, 0];
return this._ctmStack = [];
},
save: function() {
this._ctmStack.push(this._ctm.slice());
return this.addContent('q');
},
restore: function() {
this._ctm = this._ctmStack.pop() || [1, 0, 0, 1, 0, 0];
return this.addContent('Q');
},
closePath: function() {
return this.addContent('h');
},
lineWidth: function(w) {
return this.addContent("" + w + " w");
},
_CAP_STYLES: {
BUTT: 0,
ROUND: 1,
SQUARE: 2
},
lineCap: function(c) {
if (typeof c === 'string') {
c = this._CAP_STYLES[c.toUpperCase()];
}
return this.addContent("" + c + " J");
},
_JOIN_STYLES: {
MITER: 0,
ROUND: 1,
BEVEL: 2
},
lineJoin: function(j) {
if (typeof j === 'string') {
j = this._JOIN_STYLES[j.toUpperCase()];
}
return this.addContent("" + j + " j");
},
miterLimit: function(m) {
return this.addContent("" + m + " M");
},
dash: function(length, options) {
var phase, space, _ref;
if (options == null) {
options = {};
}
if (length == null) {
return this;
}
space = (_ref = options.space) != null ? _ref : length;
phase = options.phase || 0;
return this.addContent("[" + length + " " + space + "] " + phase + " d");
},
undash: function() {
return this.addContent("[] 0 d");
},
moveTo: function(x, y) {
return this.addContent("" + x + " " + y + " m");
},
lineTo: function(x, y) {
return this.addContent("" + x + " " + y + " l");
},
bezierCurveTo: function(cp1x, cp1y, cp2x, cp2y, x, y) {
return this.addContent("" + cp1x + " " + cp1y + " " + cp2x + " " + cp2y + " " + x + " " + y + " c");
},
quadraticCurveTo: function(cpx, cpy, x, y) {
return this.addContent("" + cpx + " " + cpy + " " + x + " " + y + " v");
},
rect: function(x, y, w, h) {
return this.addContent("" + x + " " + y + " " + w + " " + h + " re");
},
roundedRect: function(x, y, w, h, r) {
if (r == null) {
r = 0;
}
this.moveTo(x + r, y);
this.lineTo(x + w - r, y);
this.quadraticCurveTo(x + w, y, x + w, y + r);
this.lineTo(x + w, y + h - r);
this.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
this.lineTo(x + r, y + h);
this.quadraticCurveTo(x, y + h, x, y + h - r);
this.lineTo(x, y + r);
return this.quadraticCurveTo(x, y, x + r, y);
},
ellipse: function(x, y, r1, r2) {
var ox, oy, xe, xm, ye, ym;
if (r2 == null) {
r2 = r1;
}
x -= r1;
y -= r2;
ox = r1 * KAPPA;
oy = r2 * KAPPA;
xe = x + r1 * 2;
ye = y + r2 * 2;
xm = x + r1;
ym = y + r2;
this.moveTo(x, ym);
this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
return this.closePath();
},
circle: function(x, y, radius) {
return this.ellipse(x, y, radius);
},
polygon: function() {
var point, points, _i, _len;
points = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
this.moveTo.apply(this, points.shift());
for (_i = 0, _len = points.length; _i < _len; _i++) {
point = points[_i];
this.lineTo.apply(this, point);
}
return this.closePath();
},
path: function(path) {
SVGPath.apply(this, path);
return this;
},
_windingRule: function(rule) {
if (/even-?odd/.test(rule)) {
return '*';
}
return '';
},
fill: function(color, rule) {
if (/(even-?odd)|(non-?zero)/.test(color)) {
rule = color;
color = null;
}
if (color) {
this.fillColor(color);
}
return this.addContent('f' + this._windingRule(rule));
},
stroke: function(color) {
if (color) {
this.strokeColor(color);
}
return this.addContent('S');
},
fillAndStroke: function(fillColor, strokeColor, rule) {
var isFillRule;
if (strokeColor == null) {
strokeColor = fillColor;
}
isFillRule = /(even-?odd)|(non-?zero)/;
if (isFillRule.test(fillColor)) {
rule = fillColor;
fillColor = null;
}
if (isFillRule.test(strokeColor)) {
rule = strokeColor;
strokeColor = fillColor;
}
if (fillColor) {
this.fillColor(fillColor);
this.strokeColor(strokeColor);
}
return this.addContent('B' + this._windingRule(rule));
},
clip: function(rule) {
return this.addContent('W' + this._windingRule(rule) + ' n');
},
transform: function(m11, m12, m21, m22, dx, dy) {
var m, m0, m1, m2, m3, m4, m5, v, values;
m = this._ctm;
m0 = m[0], m1 = m[1], m2 = m[2], m3 = m[3], m4 = m[4], m5 = m[5];
m[0] = m0 * m11 + m2 * m12;
m[1] = m1 * m11 + m3 * m12;
m[2] = m0 * m21 + m2 * m22;
m[3] = m1 * m21 + m3 * m22;
m[4] = m0 * dx + m2 * dy + m4;
m[5] = m1 * dx + m3 * dy + m5;
values = ((function() {
var _i, _len, _ref, _results;
_ref = [m11, m12, m21, m22, dx, dy];
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
v = _ref[_i];
_results.push(+v.toFixed(5));
}
return _results;
})()).join(' ');
return this.addContent("" + values + " cm");
},
translate: function(x, y) {
return this.transform(1, 0, 0, 1, x, y);
},
rotate: function(angle, options) {
var cos, rad, sin, x, x1, y, y1, _ref;
if (options == null) {
options = {};
}
rad = angle * Math.PI / 180;
cos = Math.cos(rad);
sin = Math.sin(rad);
x = y = 0;
if (options.origin != null) {
_ref = options.origin, x = _ref[0], y = _ref[1];
x1 = x * cos - y * sin;
y1 = x * sin + y * cos;
x -= x1;
y -= y1;
}
return this.transform(cos, sin, -sin, cos, x, y);
},
scale: function(xFactor, yFactor, options) {
var x, y, _ref;
if (yFactor == null) {
yFactor = xFactor;
}
if (options == null) {
options = {};
}
if (arguments.length === 2) {
yFactor = xFactor;
options = yFactor;
}
x = y = 0;
if (options.origin != null) {
_ref = options.origin, x = _ref[0], y = _ref[1];
x -= xFactor * x;
y -= yFactor * y;
}
return this.transform(xFactor, 0, 0, yFactor, x, y);
}
};
}).call(this);
},{"../path":49}],47:[function(require,module,exports){
(function (Buffer){
// Generated by CoffeeScript 1.7.1
/*
PDFObject - converts JavaScript types into their corrisponding PDF types.
By Devon Govett
*/
(function() {
var PDFObject, PDFReference;
PDFObject = (function() {
var escapable, escapableRe, pad, swapBytes;
function PDFObject() {}
pad = function(str, length) {
return (Array(length + 1).join('0') + str).slice(-length);
};
escapableRe = /[\n\r\t\b\f\(\)\\]/g;
escapable = {
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
'\b': '\\b',
'\f': '\\f',
'\\': '\\\\',
'(': '\\(',
')': '\\)'
};
swapBytes = function(buff) {
var a, i, l, _i, _ref;
l = buff.length;
if (l & 0x01) {
throw new Error("Buffer length must be even");
} else {
for (i = _i = 0, _ref = l - 1; _i < _ref; i = _i += 2) {
a = buff[i];
buff[i] = buff[i + 1];
buff[i + 1] = a;
}
}
return buff;
};
PDFObject.convert = function(object) {
var e, i, isUnicode, items, key, out, string, val, _i, _ref;
if (typeof object === 'string') {
return '/' + object;
} else if (object instanceof String) {
string = object.replace(escapableRe, function(c) {
return escapable[c];
});
isUnicode = false;
for (i = _i = 0, _ref = string.length; _i < _ref; i = _i += 1) {
if (string.charCodeAt(i) > 0x7f) {
isUnicode = true;
break;
}
}
if (isUnicode) {
string = swapBytes(new Buffer('\ufeff' + string, 'utf16le')).toString('binary');
}
return '(' + string + ')';
} else if (Buffer.isBuffer(object)) {
return '<' + object.toString('hex') + '>';
} else if (object instanceof PDFReference) {
return object.toString();
} else if (object instanceof Date) {
return '(D:' + pad(object.getUTCFullYear(), 4) + pad(object.getUTCMonth(), 2) + pad(object.getUTCDate(), 2) + pad(object.getUTCHours(), 2) + pad(object.getUTCMinutes(), 2) + pad(object.getUTCSeconds(), 2) + 'Z)';
} else if (Array.isArray(object)) {
items = ((function() {
var _j, _len, _results;
_results = [];
for (_j = 0, _len = object.length; _j < _len; _j++) {
e = object[_j];
_results.push(PDFObject.convert(e));
}
return _results;
})()).join(' ');
return '[' + items + ']';
} else if ({}.toString.call(object) === '[object Object]') {
out = ['<<'];
for (key in object) {
val = object[key];
out.push('/' + key + ' ' + PDFObject.convert(val));
}
out.push('>>');
return out.join('\n');
} else {
return '' + object;
}
};
return PDFObject;
})();
module.exports = PDFObject;
PDFReference = require('./reference');
}).call(this);
}).call(this,require("buffer").Buffer)
},{"./reference":50,"buffer":74}],48:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
/*
PDFPage - represents a single page in the PDF document
By Devon Govett
*/
(function() {
var PDFPage;
PDFPage = (function() {
var DEFAULT_MARGINS, SIZES;
function PDFPage(document, options) {
var dimensions;
this.document = document;
if (options == null) {
options = {};
}
this.size = options.size || 'letter';
this.layout = options.layout || 'portrait';
if (typeof options.margin === 'number') {
this.margins = {
top: options.margin,
left: options.margin,
bottom: options.margin,
right: options.margin
};
} else {
this.margins = options.margins || DEFAULT_MARGINS;
}
dimensions = Array.isArray(this.size) ? this.size : SIZES[this.size.toUpperCase()];
this.width = dimensions[this.layout === 'portrait' ? 0 : 1];
this.height = dimensions[this.layout === 'portrait' ? 1 : 0];
this.content = this.document.ref();
this.resources = this.document.ref({
ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI']
});
Object.defineProperties(this, {
fonts: {
get: (function(_this) {
return function() {
var _base;
return (_base = _this.resources.data).Font != null ? _base.Font : _base.Font = {};
};
})(this)
},
xobjects: {
get: (function(_this) {
return function() {
var _base;
return (_base = _this.resources.data).XObject != null ? _base.XObject : _base.XObject = {};
};
})(this)
},
ext_gstates: {
get: (function(_this) {
return function() {
var _base;
return (_base = _this.resources.data).ExtGState != null ? _base.ExtGState : _base.ExtGState = {};
};
})(this)
},
patterns: {
get: (function(_this) {
return function() {
var _base;
return (_base = _this.resources.data).Pattern != null ? _base.Pattern : _base.Pattern = {};
};
})(this)
},
annotations: {
get: (function(_this) {
return function() {
var _base;
return (_base = _this.dictionary.data).Annots != null ? _base.Annots : _base.Annots = [];
};
})(this)
}
});
this.dictionary = this.document.ref({
Type: 'Page',
Parent: this.document._root.data.Pages,
MediaBox: [0, 0, this.width, this.height],
Contents: this.content,
Resources: this.resources
});
}
PDFPage.prototype.maxY = function() {
return this.height - this.margins.bottom;
};
PDFPage.prototype.write = function(chunk) {
return this.content.write(chunk);
};
PDFPage.prototype.end = function() {
this.dictionary.end();
this.resources.end();
return this.content.end();
};
DEFAULT_MARGINS = {
top: 72,
left: 72,
bottom: 72,
right: 72
};
SIZES = {
'4A0': [4767.87, 6740.79],
'2A0': [3370.39, 4767.87],
A0: [2383.94, 3370.39],
A1: [1683.78, 2383.94],
A2: [1190.55, 1683.78],
A3: [841.89, 1190.55],
A4: [595.28, 841.89],
A5: [419.53, 595.28],
A6: [297.64, 419.53],
A7: [209.76, 297.64],
A8: [147.40, 209.76],
A9: [104.88, 147.40],
A10: [73.70, 104.88],
B0: [2834.65, 4008.19],
B1: [2004.09, 2834.65],
B2: [1417.32, 2004.09],
B3: [1000.63, 1417.32],
B4: [708.66, 1000.63],
B5: [498.90, 708.66],
B6: [354.33, 498.90],
B7: [249.45, 354.33],
B8: [175.75, 249.45],
B9: [124.72, 175.75],
B10: [87.87, 124.72],
C0: [2599.37, 3676.54],
C1: [1836.85, 2599.37],
C2: [1298.27, 1836.85],
C3: [918.43, 1298.27],
C4: [649.13, 918.43],
C5: [459.21, 649.13],
C6: [323.15, 459.21],
C7: [229.61, 323.15],
C8: [161.57, 229.61],
C9: [113.39, 161.57],
C10: [79.37, 113.39],
RA0: [2437.80, 3458.27],
RA1: [1729.13, 2437.80],
RA2: [1218.90, 1729.13],
RA3: [864.57, 1218.90],
RA4: [609.45, 864.57],
SRA0: [2551.18, 3628.35],
SRA1: [1814.17, 2551.18],
SRA2: [1275.59, 1814.17],
SRA3: [907.09, 1275.59],
SRA4: [637.80, 907.09],
EXECUTIVE: [521.86, 756.00],
FOLIO: [612.00, 936.00],
LEGAL: [612.00, 1008.00],
LETTER: [612.00, 792.00],
TABLOID: [792.00, 1224.00]
};
return PDFPage;
})();
module.exports = PDFPage;
}).call(this);
},{}],49:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var SVGPath;
SVGPath = (function() {
var apply, arcToSegments, cx, cy, parameters, parse, px, py, runners, segmentToBezier, solveArc, sx, sy;
function SVGPath() {}
SVGPath.apply = function(doc, path) {
var commands;
commands = parse(path);
return apply(commands, doc);
};
parameters = {
A: 7,
a: 7,
C: 6,
c: 6,
H: 1,
h: 1,
L: 2,
l: 2,
M: 2,
m: 2,
Q: 4,
q: 4,
S: 4,
s: 4,
T: 2,
t: 2,
V: 1,
v: 1,
Z: 0,
z: 0
};
parse = function(path) {
var args, c, cmd, curArg, foundDecimal, params, ret, _i, _len;
ret = [];
args = [];
curArg = "";
foundDecimal = false;
params = 0;
for (_i = 0, _len = path.length; _i < _len; _i++) {
c = path[_i];
if (parameters[c] != null) {
params = parameters[c];
if (cmd) {
if (curArg.length > 0) {
args[args.length] = +curArg;
}
ret[ret.length] = {
cmd: cmd,
args: args
};
args = [];
curArg = "";
foundDecimal = false;
}
cmd = c;
} else if ((c === " " || c === ",") || (c === "-" && curArg.length > 0 && curArg[curArg.length - 1] !== 'e') || (c === "." && foundDecimal)) {
if (curArg.length === 0) {
continue;
}
if (args.length === params) {
ret[ret.length] = {
cmd: cmd,
args: args
};
args = [+curArg];
if (cmd === "M") {
cmd = "L";
}
if (cmd === "m") {
cmd = "l";
}
} else {
args[args.length] = +curArg;
}
foundDecimal = c === ".";
curArg = c === '-' || c === '.' ? c : '';
} else {
curArg += c;
if (c === '.') {
foundDecimal = true;
}
}
}
if (curArg.length > 0) {
if (args.length === params) {
ret[ret.length] = {
cmd: cmd,
args: args
};
args = [+curArg];
if (cmd === "M") {
cmd = "L";
}
if (cmd === "m") {
cmd = "l";
}
} else {
args[args.length] = +curArg;
}
}
ret[ret.length] = {
cmd: cmd,
args: args
};
return ret;
};
cx = cy = px = py = sx = sy = 0;
apply = function(commands, doc) {
var c, i, _i, _len, _name;
cx = cy = px = py = sx = sy = 0;
for (i = _i = 0, _len = commands.length; _i < _len; i = ++_i) {
c = commands[i];
if (typeof runners[_name = c.cmd] === "function") {
runners[_name](doc, c.args);
}
}
return cx = cy = px = py = 0;
};
runners = {
M: function(doc, a) {
cx = a[0];
cy = a[1];
px = py = null;
sx = cx;
sy = cy;
return doc.moveTo(cx, cy);
},
m: function(doc, a) {
cx += a[0];
cy += a[1];
px = py = null;
sx = cx;
sy = cy;
return doc.moveTo(cx, cy);
},
C: function(doc, a) {
cx = a[4];
cy = a[5];
px = a[2];
py = a[3];
return doc.bezierCurveTo.apply(doc, a);
},
c: function(doc, a) {
doc.bezierCurveTo(a[0] + cx, a[1] + cy, a[2] + cx, a[3] + cy, a[4] + cx, a[5] + cy);
px = cx + a[2];
py = cy + a[3];
cx += a[4];
return cy += a[5];
},
S: function(doc, a) {
if (px === null) {
px = cx;
py = cy;
}
doc.bezierCurveTo(cx - (px - cx), cy - (py - cy), a[0], a[1], a[2], a[3]);
px = a[0];
py = a[1];
cx = a[2];
return cy = a[3];
},
s: function(doc, a) {
if (px === null) {
px = cx;
py = cy;
}
doc.bezierCurveTo(cx - (px - cx), cy - (py - cy), cx + a[0], cy + a[1], cx + a[2], cy + a[3]);
px = cx + a[0];
py = cy + a[1];
cx += a[2];
return cy += a[3];
},
Q: function(doc, a) {
px = a[0];
py = a[1];
cx = a[2];
cy = a[3];
return doc.quadraticCurveTo(a[0], a[1], cx, cy);
},
q: function(doc, a) {
doc.quadraticCurveTo(a[0] + cx, a[1] + cy, a[2] + cx, a[3] + cy);
px = cx + a[0];
py = cy + a[1];
cx += a[2];
return cy += a[3];
},
T: function(doc, a) {
if (px === null) {
px = cx;
py = cy;
} else {
px = cx - (px - cx);
py = cy - (py - cy);
}
doc.quadraticCurveTo(px, py, a[0], a[1]);
px = cx - (px - cx);
py = cy - (py - cy);
cx = a[0];
return cy = a[1];
},
t: function(doc, a) {
if (px === null) {
px = cx;
py = cy;
} else {
px = cx - (px - cx);
py = cy - (py - cy);
}
doc.quadraticCurveTo(px, py, cx + a[0], cy + a[1]);
cx += a[0];
return cy += a[1];
},
A: function(doc, a) {
solveArc(doc, cx, cy, a);
cx = a[5];
return cy = a[6];
},
a: function(doc, a) {
a[5] += cx;
a[6] += cy;
solveArc(doc, cx, cy, a);
cx = a[5];
return cy = a[6];
},
L: function(doc, a) {
cx = a[0];
cy = a[1];
px = py = null;
return doc.lineTo(cx, cy);
},
l: function(doc, a) {
cx += a[0];
cy += a[1];
px = py = null;
return doc.lineTo(cx, cy);
},
H: function(doc, a) {
cx = a[0];
px = py = null;
return doc.lineTo(cx, cy);
},
h: function(doc, a) {
cx += a[0];
px = py = null;
return doc.lineTo(cx, cy);
},
V: function(doc, a) {
cy = a[0];
px = py = null;
return doc.lineTo(cx, cy);
},
v: function(doc, a) {
cy += a[0];
px = py = null;
return doc.lineTo(cx, cy);
},
Z: function(doc) {
doc.closePath();
cx = sx;
return cy = sy;
},
z: function(doc) {
doc.closePath();
cx = sx;
return cy = sy;
}
};
solveArc = function(doc, x, y, coords) {
var bez, ex, ey, large, rot, rx, ry, seg, segs, sweep, _i, _len, _results;
rx = coords[0], ry = coords[1], rot = coords[2], large = coords[3], sweep = coords[4], ex = coords[5], ey = coords[6];
segs = arcToSegments(ex, ey, rx, ry, large, sweep, rot, x, y);
_results = [];
for (_i = 0, _len = segs.length; _i < _len; _i++) {
seg = segs[_i];
bez = segmentToBezier.apply(null, seg);
_results.push(doc.bezierCurveTo.apply(doc, bez));
}
return _results;
};
arcToSegments = function(x, y, rx, ry, large, sweep, rotateX, ox, oy) {
var a00, a01, a10, a11, cos_th, d, i, pl, result, segments, sfactor, sfactor_sq, sin_th, th, th0, th1, th2, th3, th_arc, x0, x1, xc, y0, y1, yc, _i;
th = rotateX * (Math.PI / 180);
sin_th = Math.sin(th);
cos_th = Math.cos(th);
rx = Math.abs(rx);
ry = Math.abs(ry);
px = cos_th * (ox - x) * 0.5 + sin_th * (oy - y) * 0.5;
py = cos_th * (oy - y) * 0.5 - sin_th * (ox - x) * 0.5;
pl = (px * px) / (rx * rx) + (py * py) / (ry * ry);
if (pl > 1) {
pl = Math.sqrt(pl);
rx *= pl;
ry *= pl;
}
a00 = cos_th / rx;
a01 = sin_th / rx;
a10 = (-sin_th) / ry;
a11 = cos_th / ry;
x0 = a00 * ox + a01 * oy;
y0 = a10 * ox + a11 * oy;
x1 = a00 * x + a01 * y;
y1 = a10 * x + a11 * y;
d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0);
sfactor_sq = 1 / d - 0.25;
if (sfactor_sq < 0) {
sfactor_sq = 0;
}
sfactor = Math.sqrt(sfactor_sq);
if (sweep === large) {
sfactor = -sfactor;
}
xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0);
yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0);
th0 = Math.atan2(y0 - yc, x0 - xc);
th1 = Math.atan2(y1 - yc, x1 - xc);
th_arc = th1 - th0;
if (th_arc < 0 && sweep === 1) {
th_arc += 2 * Math.PI;
} else if (th_arc > 0 && sweep === 0) {
th_arc -= 2 * Math.PI;
}
segments = Math.ceil(Math.abs(th_arc / (Math.PI * 0.5 + 0.001)));
result = [];
for (i = _i = 0; 0 <= segments ? _i < segments : _i > segments; i = 0 <= segments ? ++_i : --_i) {
th2 = th0 + i * th_arc / segments;
th3 = th0 + (i + 1) * th_arc / segments;
result[i] = [xc, yc, th2, th3, rx, ry, sin_th, cos_th];
}
return result;
};
segmentToBezier = function(cx, cy, th0, th1, rx, ry, sin_th, cos_th) {
var a00, a01, a10, a11, t, th_half, x1, x2, x3, y1, y2, y3;
a00 = cos_th * rx;
a01 = -sin_th * ry;
a10 = sin_th * rx;
a11 = cos_th * ry;
th_half = 0.5 * (th1 - th0);
t = (8 / 3) * Math.sin(th_half * 0.5) * Math.sin(th_half * 0.5) / Math.sin(th_half);
x1 = cx + Math.cos(th0) - t * Math.sin(th0);
y1 = cy + Math.sin(th0) + t * Math.cos(th0);
x3 = cx + Math.cos(th1);
y3 = cy + Math.sin(th1);
x2 = x3 + t * Math.sin(th1);
y2 = y3 - t * Math.cos(th1);
return [a00 * x1 + a01 * y1, a10 * x1 + a11 * y1, a00 * x2 + a01 * y2, a10 * x2 + a11 * y2, a00 * x3 + a01 * y3, a10 * x3 + a11 * y3];
};
return SVGPath;
})();
module.exports = SVGPath;
}).call(this);
},{}],50:[function(require,module,exports){
(function (Buffer){
// Generated by CoffeeScript 1.7.1
/*
PDFReference - represents a reference to another object in the PDF object heirarchy
By Devon Govett
*/
(function() {
var PDFObject, PDFReference, zlib,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
zlib = require('zlib');
PDFReference = (function() {
function PDFReference(document, id, data) {
this.document = document;
this.id = id;
this.data = data != null ? data : {};
this.finalize = __bind(this.finalize, this);
this.gen = 0;
this.deflate = null;
this.compress = this.document.compress && !this.data.Filter;
this.uncompressedLength = 0;
this.chunks = [];
}
PDFReference.prototype.initDeflate = function() {
this.data.Filter = 'FlateDecode';
this.deflate = zlib.createDeflate();
this.deflate.on('data', (function(_this) {
return function(chunk) {
_this.chunks.push(chunk);
return _this.data.Length += chunk.length;
};
})(this));
return this.deflate.on('end', this.finalize);
};
PDFReference.prototype.write = function(chunk) {
var _base;
if (!Buffer.isBuffer(chunk)) {
chunk = new Buffer(chunk + '\n', 'binary');
}
this.uncompressedLength += chunk.length;
if ((_base = this.data).Length == null) {
_base.Length = 0;
}
if (this.compress) {
if (!this.deflate) {
this.initDeflate();
}
return this.deflate.write(chunk);
} else {
this.chunks.push(chunk);
return this.data.Length += chunk.length;
}
};
PDFReference.prototype.end = function(chunk) {
if (typeof chunk === 'string' || Buffer.isBuffer(chunk)) {
this.write(chunk);
}
if (this.deflate) {
return this.deflate.end();
} else {
return this.finalize();
}
};
PDFReference.prototype.finalize = function() {
var chunk, _i, _len, _ref;
this.offset = this.document._offset;
this.document._write("" + this.id + " " + this.gen + " obj");
this.document._write(PDFObject.convert(this.data));
if (this.chunks.length) {
this.document._write('stream');
_ref = this.chunks;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
chunk = _ref[_i];
this.document._write(chunk);
}
this.chunks.length = 0;
this.document._write('\nendstream');
}
this.document._write('endobj');
return this.document._refEnd(this);
};
PDFReference.prototype.toString = function() {
return "" + this.id + " " + this.gen + " R";
};
return PDFReference;
})();
module.exports = PDFReference;
PDFObject = require('./object');
}).call(this);
}).call(this,require("buffer").Buffer)
},{"./object":47,"buffer":74,"zlib":73}],51:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
var UnicodeTrie,
__slice = [].slice;
UnicodeTrie = (function() {
var DATA_BLOCK_LENGTH, DATA_GRANULARITY, DATA_MASK, INDEX_1_OFFSET, INDEX_2_BLOCK_LENGTH, INDEX_2_BMP_LENGTH, INDEX_2_MASK, INDEX_SHIFT, LSCP_INDEX_2_LENGTH, LSCP_INDEX_2_OFFSET, OMITTED_BMP_INDEX_1_LENGTH, SHIFT_1, SHIFT_1_2, SHIFT_2, UTF8_2B_INDEX_2_LENGTH, UTF8_2B_INDEX_2_OFFSET;
SHIFT_1 = 6 + 5;
SHIFT_2 = 5;
SHIFT_1_2 = SHIFT_1 - SHIFT_2;
OMITTED_BMP_INDEX_1_LENGTH = 0x10000 >> SHIFT_1;
INDEX_2_BLOCK_LENGTH = 1 << SHIFT_1_2;
INDEX_2_MASK = INDEX_2_BLOCK_LENGTH - 1;
INDEX_SHIFT = 2;
DATA_BLOCK_LENGTH = 1 << SHIFT_2;
DATA_MASK = DATA_BLOCK_LENGTH - 1;
LSCP_INDEX_2_OFFSET = 0x10000 >> SHIFT_2;
LSCP_INDEX_2_LENGTH = 0x400 >> SHIFT_2;
INDEX_2_BMP_LENGTH = LSCP_INDEX_2_OFFSET + LSCP_INDEX_2_LENGTH;
UTF8_2B_INDEX_2_OFFSET = INDEX_2_BMP_LENGTH;
UTF8_2B_INDEX_2_LENGTH = 0x800 >> 6;
INDEX_1_OFFSET = UTF8_2B_INDEX_2_OFFSET + UTF8_2B_INDEX_2_LENGTH;
DATA_GRANULARITY = 1 << INDEX_SHIFT;
function UnicodeTrie(json) {
var _ref, _ref1;
if (json == null) {
json = {};
}
this.data = json.data || [];
this.highStart = (_ref = json.highStart) != null ? _ref : 0;
this.errorValue = (_ref1 = json.errorValue) != null ? _ref1 : -1;
}
UnicodeTrie.prototype.get = function(codePoint) {
var index;
if (codePoint < 0 || codePoint > 0x10ffff) {
return this.errorValue;
}
if (codePoint < 0xd800 || (codePoint > 0xdbff && codePoint <= 0xffff)) {
index = (this.data[codePoint >> SHIFT_2] << INDEX_SHIFT) + (codePoint & DATA_MASK);
return this.data[index];
}
if (codePoint <= 0xffff) {
index = (this.data[LSCP_INDEX_2_OFFSET + ((codePoint - 0xd800) >> SHIFT_2)] << INDEX_SHIFT) + (codePoint & DATA_MASK);
return this.data[index];
}
if (codePoint < this.highStart) {
index = this.data[(INDEX_1_OFFSET - OMITTED_BMP_INDEX_1_LENGTH) + (codePoint >> SHIFT_1)];
index = this.data[index + ((codePoint >> SHIFT_2) & INDEX_2_MASK)];
index = (index << INDEX_SHIFT) + (codePoint & DATA_MASK);
return this.data[index];
}
return this.data[this.data.length - DATA_GRANULARITY];
};
UnicodeTrie.prototype.toJSON = function() {
var res;
res = {
data: __slice.call(this.data),
highStart: this.highStart,
errorValue: this.errorValue
};
return res;
};
return UnicodeTrie;
})();
module.exports = UnicodeTrie;
},{}],52:[function(require,module,exports){
module.exports={"data":[1961,1969,1977,1985,2025,2033,2041,2049,2057,2065,2073,2081,2089,2097,2105,2113,2121,2129,2137,2145,2153,2161,2169,2177,2185,2193,2201,2209,2217,2225,2233,2241,2249,2257,2265,2273,2281,2289,2297,2305,2313,2321,2329,2337,2345,2353,2361,2369,2377,2385,2393,2401,2409,2417,2425,2433,2441,2449,2457,2465,2473,2481,2489,2497,2505,2513,2521,2529,2529,2537,2009,2545,2553,2561,2569,2577,2585,2593,2601,2609,2617,2625,2633,2641,2649,2657,2665,2673,2681,2689,2697,2705,2713,2721,2729,2737,2745,2753,2761,2769,2777,2785,2793,2801,2809,2817,2825,2833,2841,2849,2857,2865,2873,2881,2889,2009,2897,2905,2913,2009,2921,2929,2937,2945,2953,2961,2969,2009,2977,2977,2985,2993,3001,3009,3009,3009,3017,3017,3017,3025,3025,3033,3041,3041,3049,3049,3049,3049,3049,3049,3049,3049,3049,3049,3057,3065,3073,3073,3073,3081,3089,3097,3097,3097,3097,3097,3097,3097,3097,3097,3097,3097,3097,3097,3097,3097,3097,3097,3097,3097,3105,3113,3113,3121,3129,3137,3145,3153,3161,3161,3169,3177,3185,3193,3193,3193,3193,3201,3209,3209,3217,3225,3233,3241,3241,3241,3249,3257,3265,3273,3273,3281,3289,3297,2009,2009,3305,3313,3321,3329,3337,3345,3353,3361,3369,3377,3385,3393,2009,2009,3401,3409,3417,3417,3417,3417,3417,3417,3425,3425,3433,3433,3433,3433,3433,3433,3433,3433,3433,3433,3433,3433,3433,3433,3433,3441,3449,3457,3465,3473,3481,3489,3497,3505,3513,3521,3529,3537,3545,3553,3561,3569,3577,3585,3593,3601,3609,3617,3625,3625,3633,3641,3649,3649,3649,3649,3649,3657,3665,3665,3673,3681,3681,3681,3681,3689,3697,3697,3705,3713,3721,3729,3737,3745,3753,3761,3769,3777,3785,3793,3801,3809,3817,3825,3833,3841,3849,3857,3865,3873,3881,3881,3881,3881,3881,3881,3881,3881,3881,3881,3881,3881,3889,3897,3905,3913,3921,3921,3921,3921,3921,3921,3921,3921,3921,3921,3929,2009,2009,2009,2009,2009,3937,3937,3937,3937,3937,3937,3937,3945,3953,3953,3953,3961,3969,3969,3977,3985,3993,4001,2009,2009,4009,4009,4009,4009,4009,4009,4009,4009,4009,4009,4009,4009,4017,4025,4033,4041,4049,4057,4065,4073,4081,4081,4081,4081,4081,4081,4081,4089,4097,4097,4105,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4113,4121,4121,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4129,4
},{}],53:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var AI, AL, B2, BA, BB, BK, CB, CJ, CL, CM, CP, CR, EX, GL, H2, H3, HL, HY, ID, IN, IS, JL, JT, JV, LF, NL, NS, NU, OP, PO, PR, QU, RI, SA, SG, SP, SY, WJ, XX, ZW;
exports.OP = OP = 0;
exports.CL = CL = 1;
exports.CP = CP = 2;
exports.QU = QU = 3;
exports.GL = GL = 4;
exports.NS = NS = 5;
exports.EX = EX = 6;
exports.SY = SY = 7;
exports.IS = IS = 8;
exports.PR = PR = 9;
exports.PO = PO = 10;
exports.NU = NU = 11;
exports.AL = AL = 12;
exports.HL = HL = 13;
exports.ID = ID = 14;
exports.IN = IN = 15;
exports.HY = HY = 16;
exports.BA = BA = 17;
exports.BB = BB = 18;
exports.B2 = B2 = 19;
exports.ZW = ZW = 20;
exports.CM = CM = 21;
exports.WJ = WJ = 22;
exports.H2 = H2 = 23;
exports.H3 = H3 = 24;
exports.JL = JL = 25;
exports.JV = JV = 26;
exports.JT = JT = 27;
exports.RI = RI = 28;
exports.AI = AI = 29;
exports.BK = BK = 30;
exports.CB = CB = 31;
exports.CJ = CJ = 32;
exports.CR = CR = 33;
exports.LF = LF = 34;
exports.NL = NL = 35;
exports.SA = SA = 36;
exports.SG = SG = 37;
exports.SP = SP = 38;
exports.XX = XX = 39;
}).call(this);
},{}],54:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var AI, AL, BA, BK, CB, CI_BRK, CJ, CP_BRK, CR, DI_BRK, ID, IN_BRK, LF, LineBreaker, NL, NS, PR_BRK, SA, SG, SP, UnicodeTrie, WJ, XX, characterClasses, classTrie, pairTable, _ref, _ref1;
UnicodeTrie = require('unicode-trie');
classTrie = new UnicodeTrie(require('./class_trie.json'));
_ref = require('./classes'), BK = _ref.BK, CR = _ref.CR, LF = _ref.LF, NL = _ref.NL, CB = _ref.CB, BA = _ref.BA, SP = _ref.SP, WJ = _ref.WJ, SP = _ref.SP, BK = _ref.BK, LF = _ref.LF, NL = _ref.NL, AI = _ref.AI, AL = _ref.AL, SA = _ref.SA, SG = _ref.SG, XX = _ref.XX, CJ = _ref.CJ, ID = _ref.ID, NS = _ref.NS, characterClasses = _ref.characterClasses;
_ref1 = require('./pairs'), DI_BRK = _ref1.DI_BRK, IN_BRK = _ref1.IN_BRK, CI_BRK = _ref1.CI_BRK, CP_BRK = _ref1.CP_BRK, PR_BRK = _ref1.PR_BRK, pairTable = _ref1.pairTable;
LineBreaker = (function() {
var Break, mapClass, mapFirst;
function LineBreaker(string) {
this.string = string;
this.pos = 0;
this.lastPos = 0;
this.curClass = null;
this.nextClass = null;
}
LineBreaker.prototype.nextCodePoint = function() {
var code, next;
code = this.string.charCodeAt(this.pos++);
next = this.string.charCodeAt(this.pos);
if ((0xd800 <= code && code <= 0xdbff) && (0xdc00 <= next && next <= 0xdfff)) {
this.pos++;
return ((code - 0xd800) * 0x400) + (next - 0xdc00) + 0x10000;
}
return code;
};
mapClass = function(c) {
switch (c) {
case AI:
return AL;
case SA:
case SG:
case XX:
return AL;
case CJ:
return NS;
default:
return c;
}
};
mapFirst = function(c) {
switch (c) {
case LF:
case NL:
return BK;
case CB:
return BA;
case SP:
return WJ;
default:
return c;
}
};
LineBreaker.prototype.nextCharClass = function(first) {
if (first == null) {
first = false;
}
return mapClass(classTrie.get(this.nextCodePoint()));
};
Break = (function() {
function Break(position, required) {
this.position = position;
this.required = required != null ? required : false;
}
return Break;
})();
LineBreaker.prototype.nextBreak = function() {
var cur, lastClass, shouldBreak;
if (this.curClass == null) {
this.curClass = mapFirst(this.nextCharClass());
}
while (this.pos < this.string.length) {
this.lastPos = this.pos;
lastClass = this.nextClass;
this.nextClass = this.nextCharClass();
if (this.curClass === BK || (this.curClass === CR && this.nextClass !== LF)) {
this.curClass = mapFirst(mapClass(this.nextClass));
return new Break(this.lastPos, true);
}
cur = (function() {
switch (this.nextClass) {
case SP:
return this.curClass;
case BK:
case LF:
case NL:
return BK;
case CR:
return CR;
case CB:
return BA;
}
}).call(this);
if (cur != null) {
this.curClass = cur;
if (this.nextClass === CB) {
return new Break(this.lastPos);
}
continue;
}
shouldBreak = false;
switch (pairTable[this.curClass][this.nextClass]) {
case DI_BRK:
shouldBreak = true;
break;
case IN_BRK:
shouldBreak = lastClass === SP;
break;
case CI_BRK:
shouldBreak = lastClass === SP;
if (!shouldBreak) {
continue;
}
break;
case CP_BRK:
if (lastClass !== SP) {
continue;
}
}
this.curClass = this.nextClass;
if (shouldBreak) {
return new Break(this.lastPos);
}
}
if (this.pos >= this.string.length) {
if (this.lastPos < this.string.length) {
this.lastPos = this.string.length;
return new Break(this.string.length);
} else {
return null;
}
}
};
return LineBreaker;
})();
module.exports = LineBreaker;
}).call(this);
},{"./class_trie.json":52,"./classes":53,"./pairs":55,"unicode-trie":51}],55:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var CI_BRK, CP_BRK, DI_BRK, IN_BRK, PR_BRK;
exports.DI_BRK = DI_BRK = 0;
exports.IN_BRK = IN_BRK = 1;
exports.CI_BRK = CI_BRK = 2;
exports.CP_BRK = CP_BRK = 3;
exports.PR_BRK = PR_BRK = 4;
exports.pairTable = [[PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, CP_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [PR_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, CI_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK], [IN_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, CI_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, IN_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [IN_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK], [IN_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [IN_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [IN_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [IN_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, IN_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, IN_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, DI_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, IN_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, IN_BRK, IN_BRK, DI_BRK, DI_BRK, PR_BRK, CI_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK, DI_BRK], [DI_BRK, PR_BRK, PR_BRK, IN_BRK, DI_BRK, IN_BRK, PR_BRK, PR_BRK, PR_BRK, DI_BRK, DI_BRK, DI_BR
}).call(this);
},{}],56:[function(require,module,exports){
(function (Buffer){
// Generated by CoffeeScript 1.4.0
/*
# MIT LICENSE
# Copyright (c) 2011 Devon Govett
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
# to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function() {
var PNG, fs, zlib;
fs = require('fs');
zlib = require('zlib');
module.exports = PNG = (function() {
PNG.decode = function(path, fn) {
return fs.readFile(path, function(err, file) {
var png;
png = new PNG(file);
return png.decode(function(pixels) {
return fn(pixels);
});
});
};
PNG.load = function(path) {
var file;
file = fs.readFileSync(path);
return new PNG(file);
};
function PNG(data) {
var chunkSize, colors, i, index, key, section, short, text, _i, _j, _ref;
this.data = data;
this.pos = 8;
this.palette = [];
this.imgData = [];
this.transparency = {};
this.text = {};
while (true) {
chunkSize = this.readUInt32();
section = ((function() {
var _i, _results;
_results = [];
for (i = _i = 0; _i < 4; i = ++_i) {
_results.push(String.fromCharCode(this.data[this.pos++]));
}
return _results;
}).call(this)).join('');
switch (section) {
case 'IHDR':
this.width = this.readUInt32();
this.height = this.readUInt32();
this.bits = this.data[this.pos++];
this.colorType = this.data[this.pos++];
this.compressionMethod = this.data[this.pos++];
this.filterMethod = this.data[this.pos++];
this.interlaceMethod = this.data[this.pos++];
break;
case 'PLTE':
this.palette = this.read(chunkSize);
break;
case 'IDAT':
for (i = _i = 0; _i < chunkSize; i = _i += 1) {
this.imgData.push(this.data[this.pos++]);
}
break;
case 'tRNS':
this.transparency = {};
switch (this.colorType) {
case 3:
this.transparency.indexed = this.read(chunkSize);
short = 255 - this.transparency.indexed.length;
if (short > 0) {
for (i = _j = 0; 0 <= short ? _j < short : _j > short; i = 0 <= short ? ++_j : --_j) {
this.transparency.indexed.push(255);
}
}
break;
case 0:
this.transparency.grayscale = this.read(chunkSize)[0];
break;
case 2:
this.transparency.rgb = this.read(chunkSize);
}
break;
case 'tEXt':
text = this.read(chunkSize);
index = text.indexOf(0);
key = String.fromCharCode.apply(String, text.slice(0, index));
this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1));
break;
case 'IEND':
this.colors = (function() {
switch (this.colorType) {
case 0:
case 3:
case 4:
return 1;
case 2:
case 6:
return 3;
}
}).call(this);
this.hasAlphaChannel = (_ref = this.colorType) === 4 || _ref === 6;
colors = this.colors + (this.hasAlphaChannel ? 1 : 0);
this.pixelBitlength = this.bits * colors;
this.colorSpace = (function() {
switch (this.colors) {
case 1:
return 'DeviceGray';
case 3:
return 'DeviceRGB';
}
}).call(this);
this.imgData = new Buffer(this.imgData);
return;
default:
this.pos += chunkSize;
}
this.pos += 4;
if (this.pos > this.data.length) {
throw new Error("Incomplete or corrupt PNG file");
}
}
return;
}
PNG.prototype.read = function(bytes) {
var i, _i, _results;
_results = [];
for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) {
_results.push(this.data[this.pos++]);
}
return _results;
};
PNG.prototype.readUInt32 = function() {
var b1, b2, b3, b4;
b1 = this.data[this.pos++] << 24;
b2 = this.data[this.pos++] << 16;
b3 = this.data[this.pos++] << 8;
b4 = this.data[this.pos++];
return b1 | b2 | b3 | b4;
};
PNG.prototype.readUInt16 = function() {
var b1, b2;
b1 = this.data[this.pos++] << 8;
b2 = this.data[this.pos++];
return b1 | b2;
};
PNG.prototype.decodePixels = function(fn) {
var _this = this;
return zlib.inflate(this.imgData, function(err, data) {
var byte, c, col, i, left, length, p, pa, paeth, pb, pc, pixelBytes, pixels, pos, row, scanlineLength, upper, upperLeft, _i, _j, _k, _l, _m;
if (err) {
throw err;
}
pixelBytes = _this.pixelBitlength / 8;
scanlineLength = pixelBytes * _this.width;
pixels = new Buffer(scanlineLength * _this.height);
length = data.length;
row = 0;
pos = 0;
c = 0;
while (pos < length) {
switch (data[pos++]) {
case 0:
for (i = _i = 0; _i < scanlineLength; i = _i += 1) {
pixels[c++] = data[pos++];
}
break;
case 1:
for (i = _j = 0; _j < scanlineLength; i = _j += 1) {
byte = data[pos++];
left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
pixels[c++] = (byte + left) % 256;
}
break;
case 2:
for (i = _k = 0; _k < scanlineLength; i = _k += 1) {
byte = data[pos++];
col = (i - (i % pixelBytes)) / pixelBytes;
upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
pixels[c++] = (upper + byte) % 256;
}
break;
case 3:
for (i = _l = 0; _l < scanlineLength; i = _l += 1) {
byte = data[pos++];
col = (i - (i % pixelBytes)) / pixelBytes;
left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
pixels[c++] = (byte + Math.floor((left + upper) / 2)) % 256;
}
break;
case 4:
for (i = _m = 0; _m < scanlineLength; i = _m += 1) {
byte = data[pos++];
col = (i - (i % pixelBytes)) / pixelBytes;
left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
if (row === 0) {
upper = upperLeft = 0;
} else {
upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + (i % pixelBytes)];
}
p = left + upper - upperLeft;
pa = Math.abs(p - left);
pb = Math.abs(p - upper);
pc = Math.abs(p - upperLeft);
if (pa <= pb && pa <= pc) {
paeth = left;
} else if (pb <= pc) {
paeth = upper;
} else {
paeth = upperLeft;
}
pixels[c++] = (byte + paeth) % 256;
}
break;
default:
throw new Error("Invalid filter algorithm: " + data[pos - 1]);
}
row++;
}
return fn(pixels);
});
};
PNG.prototype.decodePalette = function() {
var c, i, length, palette, pos, ret, transparency, _i, _ref, _ref1;
palette = this.palette;
transparency = this.transparency.indexed || [];
ret = new Buffer(transparency.length + palette.length);
pos = 0;
length = palette.length;
c = 0;
for (i = _i = 0, _ref = palette.length; _i < _ref; i = _i += 3) {
ret[pos++] = palette[i];
ret[pos++] = palette[i + 1];
ret[pos++] = palette[i + 2];
ret[pos++] = (_ref1 = transparency[c++]) != null ? _ref1 : 255;
}
return ret;
};
PNG.prototype.copyToImageData = function(imageData, pixels) {
var alpha, colors, data, i, input, j, k, length, palette, v, _ref;
colors = this.colors;
palette = null;
alpha = this.hasAlphaChannel;
if (this.palette.length) {
palette = (_ref = this._decodedPalette) != null ? _ref : this._decodedPalette = this.decodePalette();
colors = 4;
alpha = true;
}
data = (imageData != null ? imageData.data : void 0) || imageData;
length = data.length;
input = palette || pixels;
i = j = 0;
if (colors === 1) {
while (i < length) {
k = palette ? pixels[i / 4] * 4 : j;
v = input[k++];
data[i++] = v;
data[i++] = v;
data[i++] = v;
data[i++] = alpha ? input[k++] : 255;
j = k;
}
} else {
while (i < length) {
k = palette ? pixels[i / 4] * 4 : j;
data[i++] = input[k++];
data[i++] = input[k++];
data[i++] = input[k++];
data[i++] = alpha ? input[k++] : 255;
j = k;
}
}
};
PNG.prototype.decode = function(fn) {
var ret,
_this = this;
ret = new Buffer(this.width * this.height * 4);
return this.decodePixels(function(pixels) {
_this.copyToImageData(ret, pixels);
return fn(ret);
});
};
return PNG;
})();
}).call(this);
}).call(this,require("buffer").Buffer)
},{"buffer":74,"fs":58,"zlib":73}],57:[function(require,module,exports){
// Underscore.js 1.8.3
// http://underscorejs.org
// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var
push = ArrayProto.push,
slice = ArrayProto.slice,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind,
nativeCreate = Object.create;
// Naked function reference for surrogate-prototype-swapping.
var Ctor = function(){};
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.8.3';
// Internal function that returns an efficient (for current engines) version
// of the passed-in callback, to be repeatedly applied in other Underscore
// functions.
var optimizeCb = function(func, context, argCount) {
if (context === void 0) return func;
switch (argCount == null ? 3 : argCount) {
case 1: return function(value) {
return func.call(context, value);
};
case 2: return function(value, other) {
return func.call(context, value, other);
};
case 3: return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
};
// A mostly-internal function to generate callbacks that can be applied
// to each element in a collection, returning the desired result — either
// identity, an arbitrary callback, a property matcher, or a property accessor.
var cb = function(value, context, argCount) {
if (value == null) return _.identity;
if (_.isFunction(value)) return optimizeCb(value, context, argCount);
if (_.isObject(value)) return _.matcher(value);
return _.property(value);
};
_.iteratee = function(value, context) {
return cb(value, context, Infinity);
};
// An internal function for creating assigner functions.
var createAssigner = function(keysFunc, undefinedOnly) {
return function(obj) {
var length = arguments.length;
if (length < 2 || obj == null) return obj;
for (var index = 1; index < length; index++) {
var source = arguments[index],
keys = keysFunc(source),
l = keys.length;
for (var i = 0; i < l; i++) {
var key = keys[i];
if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
}
}
return obj;
};
};
// An internal function for creating a new object that inherits from another.
var baseCreate = function(prototype) {
if (!_.isObject(prototype)) return {};
if (nativeCreate) return nativeCreate(prototype);
Ctor.prototype = prototype;
var result = new Ctor;
Ctor.prototype = null;
return result;
};
var property = function(key) {
return function(obj) {
return obj == null ? void 0 : obj[key];
};
};
// Helper for collection methods to determine whether a collection
// should be iterated as an array or as an object
// Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
// Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
var getLength = property('length');
var isArrayLike = function(collection) {
var length = getLength(collection);
return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
};
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles raw objects in addition to array-likes. Treats all
// sparse array-likes as if they were dense.
_.each = _.forEach = function(obj, iteratee, context) {
iteratee = optimizeCb(iteratee, context);
var i, length;
if (isArrayLike(obj)) {
for (i = 0, length = obj.length; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
// Return the results of applying the iteratee to each element.
_.map = _.collect = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length,
results = Array(length);
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
results[index] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
// Create a reducing function iterating left or right.
function createReduce(dir) {
// Optimized iterator function as using arguments.length
// in the main function will deoptimize the, see #1991.
function iterator(obj, iteratee, memo, keys, index, length) {
for (; index >= 0 && index < length; index += dir) {
var currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
}
return function(obj, iteratee, memo, context) {
iteratee = optimizeCb(iteratee, context, 4);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length,
index = dir > 0 ? 0 : length - 1;
// Determine the initial value if none is provided.
if (arguments.length < 3) {
memo = obj[keys ? keys[index] : index];
index += dir;
}
return iterator(obj, iteratee, memo, keys, index, length);
};
}
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`.
_.reduce = _.foldl = _.inject = createReduce(1);
// The right-associative version of reduce, also known as `foldr`.
_.reduceRight = _.foldr = createReduce(-1);
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, predicate, context) {
var key;
if (isArrayLike(obj)) {
key = _.findIndex(obj, predicate, context);
} else {
key = _.findKey(obj, predicate, context);
}
if (key !== void 0 && key !== -1) return obj[key];
};
// Return all the elements that pass a truth test.
// Aliased as `select`.
_.filter = _.select = function(obj, predicate, context) {
var results = [];
predicate = cb(predicate, context);
_.each(obj, function(value, index, list) {
if (predicate(value, index, list)) results.push(value);
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, predicate, context) {
return _.filter(obj, _.negate(cb(predicate)), context);
};
// Determine whether all of the elements match a truth test.
// Aliased as `all`.
_.every = _.all = function(obj, predicate, context) {
predicate = cb(predicate, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length;
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
if (!predicate(obj[currentKey], currentKey, obj)) return false;
}
return true;
};
// Determine if at least one element in the object matches a truth test.
// Aliased as `any`.
_.some = _.any = function(obj, predicate, context) {
predicate = cb(predicate, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length;
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
if (predicate(obj[currentKey], currentKey, obj)) return true;
}
return false;
};
// Determine if the array or object contains a given item (using `===`).
// Aliased as `includes` and `include`.
_.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
if (!isArrayLike(obj)) obj = _.values(obj);
if (typeof fromIndex != 'number' || guard) fromIndex = 0;
return _.indexOf(obj, item, fromIndex) >= 0;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
var func = isFunc ? method : value[method];
return func == null ? func : func.apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, _.property(key));
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs) {
return _.filter(obj, _.matcher(attrs));
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.find(obj, _.matcher(attrs));
};
// Return the maximum element (or element-based computation).
_.max = function(obj, iteratee, context) {
var result = -Infinity, lastComputed = -Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = isArrayLike(obj) ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value > result) {
result = value;
}
}
} else {
iteratee = cb(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iteratee, context) {
var result = Infinity, lastComputed = Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = isArrayLike(obj) ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value < result) {
result = value;
}
}
} else {
iteratee = cb(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed < lastComputed || computed === Infinity && result === Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Shuffle a collection, using the modern version of the
// [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/FisherYates_shuffle).
_.shuffle = function(obj) {
var set = isArrayLike(obj) ? obj : _.values(obj);
var length = set.length;
var shuffled = Array(length);
for (var index = 0, rand; index < length; index++) {
rand = _.random(0, index);
if (rand !== index) shuffled[index] = shuffled[rand];
shuffled[rand] = set[index];
}
return shuffled;
};
// Sample **n** random values from a collection.
// If **n** is not specified, returns a single random element.
// The internal `guard` argument allows it to work with `map`.
_.sample = function(obj, n, guard) {
if (n == null || guard) {
if (!isArrayLike(obj)) obj = _.values(obj);
return obj[_.random(obj.length - 1)];
}
return _.shuffle(obj).slice(0, Math.max(0, n));
};
// Sort the object's values by a criterion produced by an iteratee.
_.sortBy = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value: value,
index: index,
criteria: iteratee(value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index - right.index;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(behavior) {
return function(obj, iteratee, context) {
var result = {};
iteratee = cb(iteratee, context);
_.each(obj, function(value, index) {
var key = iteratee(value, index, obj);
behavior(result, value, key);
});
return result;
};
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = group(function(result, value, key) {
if (_.has(result, key)) result[key].push(value); else result[key] = [value];
});
// Indexes the object's values by a criterion, similar to `groupBy`, but for
// when you know that your index values will be unique.
_.indexBy = group(function(result, value, key) {
result[key] = value;
});
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = group(function(result, value, key) {
if (_.has(result, key)) result[key]++; else result[key] = 1;
});
// Safely create a real, live array from anything iterable.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (isArrayLike(obj)) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return isArrayLike(obj) ? obj.length : _.keys(obj).length;
};
// Split a collection into two arrays: one whose elements all satisfy the given
// predicate, and one whose elements all do not satisfy the predicate.
_.partition = function(obj, predicate, context) {
predicate = cb(predicate, context);
var pass = [], fail = [];
_.each(obj, function(value, key, obj) {
(predicate(value, key, obj) ? pass : fail).push(value);
});
return [pass, fail];
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[0];
return _.initial(array, array.length - n);
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N.
_.initial = function(array, n, guard) {
return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[array.length - 1];
return _.rest(array, Math.max(0, array.length - n));
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, n == null || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, strict, startIndex) {
var output = [], idx = 0;
for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
var value = input[i];
if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
//flatten current level of array or arguments object
if (!shallow) value = flatten(value, shallow, strict);
var j = 0, len = value.length;
output.length += len;
while (j < len) {
output[idx++] = value[j++];
}
} else if (!strict) {
output[idx++] = value;
}
}
return output;
};
// Flatten out an array, either recursively (by default), or just one level.
_.flatten = function(array, shallow) {
return flatten(array, shallow, false);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iteratee, context) {
if (!_.isBoolean(isSorted)) {
context = iteratee;
iteratee = isSorted;
isSorted = false;
}
if (iteratee != null) iteratee = cb(iteratee, context);
var result = [];
var seen = [];
for (var i = 0, length = getLength(array); i < length; i++) {
var value = array[i],
computed = iteratee ? iteratee(value, i, array) : value;
if (isSorted) {
if (!i || seen !== computed) result.push(value);
seen = computed;
} else if (iteratee) {
if (!_.contains(seen, computed)) {
seen.push(computed);
result.push(value);
}
} else if (!_.contains(result, value)) {
result.push(value);
}
}
return result;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(flatten(arguments, true, true));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
var result = [];
var argsLength = arguments.length;
for (var i = 0, length = getLength(array); i < length; i++) {
var item = array[i];
if (_.contains(result, item)) continue;
for (var j = 1; j < argsLength; j++) {
if (!_.contains(arguments[j], item)) break;
}
if (j === argsLength) result.push(item);
}
return result;
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = flatten(arguments, true, true, 1);
return _.filter(array, function(value){
return !_.contains(rest, value);
});
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
return _.unzip(arguments);
};
// Complement of _.zip. Unzip accepts an array of arrays and groups
// each array's elements on shared indices
_.unzip = function(array) {
var length = array && _.max(array, getLength).length || 0;
var result = Array(length);
for (var index = 0; index < length; index++) {
result[index] = _.pluck(array, index);
}
return result;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
var result = {};
for (var i = 0, length = getLength(list); i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// Generator function to create the findIndex and findLastIndex functions
function createPredicateIndexFinder(dir) {
return function(array, predicate, context) {
predicate = cb(predicate, context);
var length = getLength(array);
var index = dir > 0 ? 0 : length - 1;
for (; index >= 0 && index < length; index += dir) {
if (predicate(array[index], index, array)) return index;
}
return -1;
};
}
// Returns the first index on an array-like that passes a predicate test
_.findIndex = createPredicateIndexFinder(1);
_.findLastIndex = createPredicateIndexFinder(-1);
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iteratee, context) {
iteratee = cb(iteratee, context, 1);
var value = iteratee(obj);
var low = 0, high = getLength(array);
while (low < high) {
var mid = Math.floor((low + high) / 2);
if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
}
return low;
};
// Generator function to create the indexOf and lastIndexOf functions
function createIndexFinder(dir, predicateFind, sortedIndex) {
return function(array, item, idx) {
var i = 0, length = getLength(array);
if (typeof idx == 'number') {
if (dir > 0) {
i = idx >= 0 ? idx : Math.max(idx + length, i);
} else {
length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
}
} else if (sortedIndex && idx && length) {
idx = sortedIndex(array, item);
return array[idx] === item ? idx : -1;
}
if (item !== item) {
idx = predicateFind(slice.call(array, i, length), _.isNaN);
return idx >= 0 ? idx + i : -1;
}
for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
if (array[idx] === item) return idx;
}
return -1;
};
}
// Return the position of the first occurrence of an item in an array,
// or -1 if the item is not included in the array.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
_.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (stop == null) {
stop = start || 0;
start = 0;
}
step = step || 1;
var length = Math.max(Math.ceil((stop - start) / step), 0);
var range = Array(length);
for (var idx = 0; idx < length; idx++, start += step) {
range[idx] = start;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Determines whether to execute a function as a constructor
// or a normal function with the provided arguments
var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
var self = baseCreate(sourceFunc.prototype);
var result = sourceFunc.apply(self, args);
if (_.isObject(result)) return result;
return self;
};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
_.bind = function(func, context) {
if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
var args = slice.call(arguments, 2);
var bound = function() {
return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
};
return bound;
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context. _ acts
// as a placeholder, allowing any combination of arguments to be pre-filled.
_.partial = function(func) {
var boundArgs = slice.call(arguments, 1);
var bound = function() {
var position = 0, length = boundArgs.length;
var args = Array(length);
for (var i = 0; i < length; i++) {
args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
}
while (position < arguments.length) args.push(arguments[position++]);
return executeBound(func, bound, this, this, args);
};
return bound;
};
// Bind a number of an object's methods to that object. Remaining arguments
// are the method names to be bound. Useful for ensuring that all callbacks
// defined on an object belong to it.
_.bindAll = function(obj) {
var i, length = arguments.length, key;
if (length <= 1) throw new Error('bindAll must be passed function names');
for (i = 1; i < length; i++) {
key = arguments[i];
obj[key] = _.bind(obj[key], obj);
}
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memoize = function(key) {
var cache = memoize.cache;
var address = '' + (hasher ? hasher.apply(this, arguments) : key);
if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
return cache[address];
};
memoize.cache = {};
return memoize;
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){
return func.apply(null, args);
}, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = _.partial(_.delay, _, 1);
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
_.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = _.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function() {
var last = _.now() - timestamp;
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = _.now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return _.partial(wrapper, func);
};
// Returns a negated version of the passed-in predicate.
_.negate = function(predicate) {
return function() {
return !predicate.apply(this, arguments);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var args = arguments;
var start = args.length - 1;
return function() {
var i = start;
var result = args[start].apply(this, arguments);
while (i--) result = args[i].call(this, result);
return result;
};
};
// Returns a function that will only be executed on and after the Nth call.
_.after = function(times, func) {
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Returns a function that will only be executed up to (but not including) the Nth call.
_.before = function(times, func) {
var memo;
return function() {
if (--times > 0) {
memo = func.apply(this, arguments);
}
if (times <= 1) func = null;
return memo;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = _.partial(_.before, 2);
// Object Functions
// ----------------
// Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
function collectNonEnumProps(obj, keys) {
var nonEnumIdx = nonEnumerableProps.length;
var constructor = obj.constructor;
var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
// Constructor is a special case.
var prop = 'constructor';
if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
while (nonEnumIdx--) {
prop = nonEnumerableProps[nonEnumIdx];
if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
keys.push(prop);
}
}
}
// Retrieve the names of an object's own properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = function(obj) {
if (!_.isObject(obj)) return [];
if (nativeKeys) return nativeKeys(obj);
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys.push(key);
// Ahem, IE < 9.
if (hasEnumBug) collectNonEnumProps(obj, keys);
return keys;
};
// Retrieve all the property names of an object.
_.allKeys = function(obj) {
if (!_.isObject(obj)) return [];
var keys = [];
for (var key in obj) keys.push(key);
// Ahem, IE < 9.
if (hasEnumBug) collectNonEnumProps(obj, keys);
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var values = Array(length);
for (var i = 0; i < length; i++) {
values[i] = obj[keys[i]];
}
return values;
};
// Returns the results of applying the iteratee to each element of the object
// In contrast to _.map it returns an object
_.mapObject = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
var keys = _.keys(obj),
length = keys.length,
results = {},
currentKey;
for (var index = 0; index < length; index++) {
currentKey = keys[index];
results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var pairs = Array(length);
for (var i = 0; i < length; i++) {
pairs[i] = [keys[i], obj[keys[i]]];
}
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
var keys = _.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
result[obj[keys[i]]] = keys[i];
}
return result;
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = createAssigner(_.allKeys);
// Assigns a given object with all the own properties in the passed-in object(s)
// (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
_.extendOwn = _.assign = createAssigner(_.keys);
// Returns the first key on an object that passes a predicate test
_.findKey = function(obj, predicate, context) {
predicate = cb(predicate, context);
var keys = _.keys(obj), key;
for (var i = 0, length = keys.length; i < length; i++) {
key = keys[i];
if (predicate(obj[key], key, obj)) return key;
}
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(object, oiteratee, context) {
var result = {}, obj = object, iteratee, keys;
if (obj == null) return result;
if (_.isFunction(oiteratee)) {
keys = _.allKeys(obj);
iteratee = optimizeCb(oiteratee, context);
} else {
keys = flatten(arguments, false, false, 1);
iteratee = function(value, key, obj) { return key in obj; };
obj = Object(obj);
}
for (var i = 0, length = keys.length; i < length; i++) {
var key = keys[i];
var value = obj[key];
if (iteratee(value, key, obj)) result[key] = value;
}
return result;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj, iteratee, context) {
if (_.isFunction(iteratee)) {
iteratee = _.negate(iteratee);
} else {
var keys = _.map(flatten(arguments, false, false, 1), String);
iteratee = function(value, key) {
return !_.contains(keys, key);
};
}
return _.pick(obj, iteratee, context);
};
// Fill in a given object with default properties.
_.defaults = createAssigner(_.allKeys, true);
// Creates an object that inherits from the given prototype object.
// If additional properties are provided then they will be added to the
// created object.
_.create = function(prototype, props) {
var result = baseCreate(prototype);
if (props) _.extendOwn(result, props);
return result;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Returns whether an object has a given set of `key:value` pairs.
_.isMatch = function(object, attrs) {
var keys = _.keys(attrs), length = keys.length;
if (object == null) return !length;
var obj = Object(object);
for (var i = 0; i < length; i++) {
var key = keys[i];
if (attrs[key] !== obj[key] || !(key in obj)) return false;
}
return true;
};
// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
if (a === b) return a !== 0 || 1 / a === 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className !== toString.call(b)) return false;
switch (className) {
// Strings, numbers, regular expressions, dates, and booleans are compared by value.
case '[object RegExp]':
// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return '' + a === '' + b;
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive.
// Object(NaN) is equivalent to NaN
if (+a !== +a) return +b !== +b;
// An `egal` comparison is performed for other numeric values.
return +a === 0 ? 1 / +a === 1 / b : +a === +b;
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a === +b;
}
var areArrays = className === '[object Array]';
if (!areArrays) {
if (typeof a != 'object' || typeof b != 'object') return false;
// Objects with different constructors are not equivalent, but `Object`s or `Array`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
_.isFunction(bCtor) && bCtor instanceof bCtor)
&& ('constructor' in a && 'constructor' in b)) {
return false;
}
}
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
// Initializing stack of traversed objects.
// It's done here since we only need them for objects and arrays comparison.
aStack = aStack || [];
bStack = bStack || [];
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] === a) return bStack[length] === b;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
// Recursively compare objects and arrays.
if (areArrays) {
// Compare array lengths to determine if a deep comparison is necessary.
length = a.length;
if (length !== b.length) return false;
// Deep compare the contents, ignoring non-numeric properties.
while (length--) {
if (!eq(a[length], b[length], aStack, bStack)) return false;
}
} else {
// Deep compare objects.
var keys = _.keys(a), key;
length = keys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
if (_.keys(b).length !== length) return false;
while (length--) {
// Deep compare each member
key = keys[length];
if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return true;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
return _.keys(obj).length === 0;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
_.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) === '[object ' + name + ']';
};
});
// Define a fallback version of the method in browsers (ahem, IE < 9), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return _.has(obj, 'callee');
};
}
// Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
// IE 11 (#1621), and in Safari 8 (#1929).
if (typeof /./ != 'function' && typeof Int8Array != 'object') {
_.isFunction = function(obj) {
return typeof obj == 'function' || false;
};
}
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj !== +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return obj != null && hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iteratees.
_.identity = function(value) {
return value;
};
// Predicate-generating functions. Often useful outside of Underscore.
_.constant = function(value) {
return function() {
return value;
};
};
_.noop = function(){};
_.property = property;
// Generates a function for a given object that returns a given property.
_.propertyOf = function(obj) {
return obj == null ? function(){} : function(key) {
return obj[key];
};
};
// Returns a predicate for checking whether an object has a given set of
// `key:value` pairs.
_.matcher = _.matches = function(attrs) {
attrs = _.extendOwn({}, attrs);
return function(obj) {
return _.isMatch(obj, attrs);
};
};
// Run a function **n** times.
_.times = function(n, iteratee, context) {
var accum = Array(Math.max(0, n));
iteratee = optimizeCb(iteratee, context, 1);
for (var i = 0; i < n; i++) accum[i] = iteratee(i);
return accum;
};
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
// A (possibly faster) way to get the current timestamp as an integer.
_.now = Date.now || function() {
return new Date().getTime();
};
// List of HTML entities for escaping.
var escapeMap = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#x27;',
'`': '&#x60;'
};
var unescapeMap = _.invert(escapeMap);
// Functions for escaping and unescaping strings to/from HTML interpolation.
var createEscaper = function(map) {
var escaper = function(match) {
return map[match];
};
// Regexes for identifying a key that needs to be escaped
var source = '(?:' + _.keys(map).join('|') + ')';
var testRegexp = RegExp(source);
var replaceRegexp = RegExp(source, 'g');
return function(string) {
string = string == null ? '' : '' + string;
return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
};
};
_.escape = createEscaper(escapeMap);
_.unescape = createEscaper(unescapeMap);
// If the value of the named `property` is a function then invoke it with the
// `object` as context; otherwise, return it.
_.result = function(object, property, fallback) {
var value = object == null ? void 0 : object[property];
if (value === void 0) {
value = fallback;
}
return _.isFunction(value) ? value.call(object) : value;
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
var escapeChar = function(match) {
return '\\' + escapes[match];
};
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
// NB: `oldSettings` only exists for backwards compatibility.
_.template = function(text, settings, oldSettings) {
if (!settings && oldSettings) settings = oldSettings;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset).replace(escaper, escapeChar);
index = offset + match.length;
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
} else if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
} else if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
// Adobe VMs need the match returned to produce the correct offest.
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + 'return __p;\n';
try {
var render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled source as a convenience for precompilation.
var argument = settings.variable || 'obj';
template.source = 'function(' + argument + '){\n' + source + '}';
return template;
};
// Add a "chain" function. Start chaining a wrapped Underscore object.
_.chain = function(obj) {
var instance = _(obj);
instance._chain = true;
return instance;
};
// OOP
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
// Helper function to continue chaining intermediate results.
var result = function(instance, obj) {
return instance._chain ? _(obj).chain() : obj;
};
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
_.each(_.functions(obj), function(name) {
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return result(this, func.apply(_, args));
};
});
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
_.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
var obj = this._wrapped;
method.apply(obj, arguments);
if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
return result(this, obj);
};
});
// Add all accessor Array functions to the wrapper.
_.each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
return result(this, method.apply(this._wrapped, arguments));
};
});
// Extracts the result from a wrapped and chained object.
_.prototype.value = function() {
return this._wrapped;
};
// Provide unwrapping proxy for some methods used in engine operations
// such as arithmetic and JSON stringification.
_.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
_.prototype.toString = function() {
return '' + this._wrapped;
};
// AMD registration happens at the end for compatibility with AMD loaders
// that may not enforce next-turn semantics on modules. Even though general
// practice for AMD registration is to be anonymous, underscore registers
// as a named module because, like jQuery, it is a base library that is
// popular enough to be bundled in a third party lib, but not be part of
// an AMD load request. Those cases could generate an error when an
// anonymous define() is called outside of a loader request.
if (typeof define === 'function' && define.amd) {
define('underscore', [], function() {
return _;
});
}
}.call(this));
},{}],58:[function(require,module,exports){
},{}],59:[function(require,module,exports){
// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// when used in node, this will actually load the util module we depend on
// versus loading the builtin util module as happens otherwise
// this is a bug in node module loading as far as I am concerned
var util = require('util/');
var pSlice = Array.prototype.slice;
var hasOwn = Object.prototype.hasOwnProperty;
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.
var assert = module.exports = ok;
// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
// actual: actual,
// expected: expected })
assert.AssertionError = function AssertionError(options) {
this.name = 'AssertionError';
this.actual = options.actual;
this.expected = options.expected;
this.operator = options.operator;
if (options.message) {
this.message = options.message;
this.generatedMessage = false;
} else {
this.message = getMessage(this);
this.generatedMessage = true;
}
var stackStartFunction = options.stackStartFunction || fail;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, stackStartFunction);
}
else {
// non v8 browsers so we can have a stacktrace
var err = new Error();
if (err.stack) {
var out = err.stack;
// try to strip useless frames
var fn_name = stackStartFunction.name;
var idx = out.indexOf('\n' + fn_name);
if (idx >= 0) {
// once we have located the function frame
// we need to strip out everything before it (and its line)
var next_line = out.indexOf('\n', idx + 1);
out = out.substring(next_line + 1);
}
this.stack = out;
}
}
};
// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);
function replacer(key, value) {
if (util.isUndefined(value)) {
return '' + value;
}
if (util.isNumber(value) && !isFinite(value)) {
return value.toString();
}
if (util.isFunction(value) || util.isRegExp(value)) {
return value.toString();
}
return value;
}
function truncate(s, n) {
if (util.isString(s)) {
return s.length < n ? s : s.slice(0, n);
} else {
return s;
}
}
function getMessage(self) {
return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
self.operator + ' ' +
truncate(JSON.stringify(self.expected, replacer), 128);
}
// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.
// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided. All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.
function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}
// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;
// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.
function ok(value, message) {
if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;
// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);
assert.equal = function equal(actual, expected, message) {
if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};
// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);
assert.notEqual = function notEqual(actual, expected, message) {
if (actual == expected) {
fail(actual, expected, message, '!=', assert.notEqual);
}
};
// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);
assert.deepEqual = function deepEqual(actual, expected, message) {
if (!_deepEqual(actual, expected)) {
fail(actual, expected, message, 'deepEqual', assert.deepEqual);
}
};
function _deepEqual(actual, expected) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (util.isBuffer(actual) && util.isBuffer(expected)) {
if (actual.length != expected.length) return false;
for (var i = 0; i < actual.length; i++) {
if (actual[i] !== expected[i]) return false;
}
return true;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (util.isDate(actual) && util.isDate(expected)) {
return actual.getTime() === expected.getTime();
// 7.3 If the expected value is a RegExp object, the actual value is
// equivalent if it is also a RegExp object with the same source and
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
} else if (util.isRegExp(actual) && util.isRegExp(expected)) {
return actual.source === expected.source &&
actual.global === expected.global &&
actual.multiline === expected.multiline &&
actual.lastIndex === expected.lastIndex &&
actual.ignoreCase === expected.ignoreCase;
// 7.4. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if (!util.isObject(actual) && !util.isObject(expected)) {
return actual == expected;
// 7.5 For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected);
}
}
function isArguments(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
function objEquiv(a, b) {
if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b))
return false;
// an identical 'prototype' property.
if (a.prototype !== b.prototype) return false;
// if one is a primitive, the other must be same
if (util.isPrimitive(a) || util.isPrimitive(b)) {
return a === b;
}
var aIsArgs = isArguments(a),
bIsArgs = isArguments(b);
if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
return false;
if (aIsArgs) {
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b);
}
var ka = objectKeys(a),
kb = objectKeys(b),
key, i;
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!_deepEqual(a[key], b[key])) return false;
}
return true;
}
// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
if (_deepEqual(actual, expected)) {
fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
}
};
// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);
assert.strictEqual = function strictEqual(actual, expected, message) {
if (actual !== expected) {
fail(actual, expected, message, '===', assert.strictEqual);
}
};
// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (actual === expected) {
fail(actual, expected, message, '!==', assert.notStrictEqual);
}
};
function expectedException(actual, expected) {
if (!actual || !expected) {
return false;
}
if (Object.prototype.toString.call(expected) == '[object RegExp]') {
return expected.test(actual);
} else if (actual instanceof expected) {
return true;
} else if (expected.call({}, actual) === true) {
return true;
}
return false;
}
function _throws(shouldThrow, block, expected, message) {
var actual;
if (util.isString(expected)) {
message = expected;
expected = null;
}
try {
block();
} catch (e) {
actual = e;
}
message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
(message ? ' ' + message : '.');
if (shouldThrow && !actual) {
fail(actual, expected, 'Missing expected exception' + message);
}
if (!shouldThrow && expectedException(actual, expected)) {
fail(actual, expected, 'Got unwanted exception' + message);
}
if ((shouldThrow && actual && expected &&
!expectedException(actual, expected)) || (!shouldThrow && actual)) {
throw actual;
}
}
// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);
assert.throws = function(block, /*optional*/error, /*optional*/message) {
_throws.apply(this, [true].concat(pSlice.call(arguments)));
};
// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/message) {
_throws.apply(this, [false].concat(pSlice.call(arguments)));
};
assert.ifError = function(err) { if (err) {throw err;}};
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
if (hasOwn.call(obj, key)) keys.push(key);
}
return keys;
};
},{"util/":97}],60:[function(require,module,exports){
arguments[4][58][0].apply(exports,arguments)
},{"dup":58}],61:[function(require,module,exports){
'use strict';
var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
(typeof Uint16Array !== 'undefined') &&
(typeof Int32Array !== 'undefined');
exports.assign = function (obj /*from1, from2, from3, ...*/) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) { continue; }
if (typeof(source) !== 'object') {
throw new TypeError(source + 'must be non-object');
}
for (var p in source) {
if (source.hasOwnProperty(p)) {
obj[p] = source[p];
}
}
}
return obj;
};
// reduce buffer size, avoiding mem copy
exports.shrinkBuf = function (buf, size) {
if (buf.length === size) { return buf; }
if (buf.subarray) { return buf.subarray(0, size); }
buf.length = size;
return buf;
};
var fnTyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
if (src.subarray && dest.subarray) {
dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
return;
}
// Fallback to ordinary array
for(var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
var i, l, len, pos, chunk, result;
// calculate data length
len = 0;
for (i=0, l=chunks.length; i<l; i++) {
len += chunks[i].length;
}
// join chunks
result = new Uint8Array(len);
pos = 0;
for (i=0, l=chunks.length; i<l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
};
var fnUntyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
for(var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
return [].concat.apply([], chunks);
}
};
// Enable/Disable typed arrays use, for testing
//
exports.setTyped = function (on) {
if (on) {
exports.Buf8 = Uint8Array;
exports.Buf16 = Uint16Array;
exports.Buf32 = Int32Array;
exports.assign(exports, fnTyped);
} else {
exports.Buf8 = Array;
exports.Buf16 = Array;
exports.Buf32 = Array;
exports.assign(exports, fnUntyped);
}
};
exports.setTyped(TYPED_OK);
},{}],62:[function(require,module,exports){
'use strict';
// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It doesn't worth to make additional optimizationa as in original.
// Small size is preferable.
function adler32(adler, buf, len, pos) {
var s1 = (adler & 0xffff) |0
, s2 = ((adler >>> 16) & 0xffff) |0
, n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = (s1 + buf[pos++]) |0;
s2 = (s2 + s1) |0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return (s1 | (s2 << 16)) |0;
}
module.exports = adler32;
},{}],63:[function(require,module,exports){
module.exports = {
/* Allowed flush values; see deflate() and inflate() below for details */
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
//Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8
//Z_NULL: null // Use -1 or null inline, depending on var type
};
},{}],64:[function(require,module,exports){
'use strict';
// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// Use ordinary array, since untyped makes no boost here
function makeTable() {
var c, table = [];
for(var n =0; n < 256; n++){
c = n;
for(var k =0; k < 8; k++){
c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
}
// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable
, end = pos + len;
crc = crc ^ (-1);
for (var i = pos; i < end; i++ ) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}
module.exports = crc32;
},{}],65:[function(require,module,exports){
'use strict';
var utils = require('../utils/common');
var trees = require('./trees');
var adler32 = require('./adler32');
var crc32 = require('./crc32');
var msg = require('./messages');
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
var Z_NO_FLUSH = 0;
var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
//var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
//var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
//var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* compression levels */
//var Z_NO_COMPRESSION = 0;
//var Z_BEST_SPEED = 1;
//var Z_BEST_COMPRESSION = 9;
var Z_DEFAULT_COMPRESSION = -1;
var Z_FILTERED = 1;
var Z_HUFFMAN_ONLY = 2;
var Z_RLE = 3;
var Z_FIXED = 4;
var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
//var Z_BINARY = 0;
//var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/* The deflate compression method */
var Z_DEFLATED = 8;
/*============================================================================*/
var MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_MEM_LEVEL = 8;
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
var PRESET_DICT = 0x20;
var INIT_STATE = 42;
var EXTRA_STATE = 69;
var NAME_STATE = 73;
var COMMENT_STATE = 91;
var HCRC_STATE = 103;
var BUSY_STATE = 113;
var FINISH_STATE = 666;
var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
var BS_BLOCK_DONE = 2; /* block flush performed */
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
function err(strm, errorCode) {
strm.msg = msg[errorCode];
return errorCode;
}
function rank(f) {
return ((f) << 1) - ((f) > 4 ? 9 : 0);
}
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
/* =========================================================================
* Flush as much pending output as possible. All deflate() output goes
* through this function so some applications may wish to modify it
* to avoid allocating a large strm->output buffer and copying into it.
* (See also read_buf()).
*/
function flush_pending(strm) {
var s = strm.state;
//_tr_flush_bits(s);
var len = s.pending;
if (len > strm.avail_out) {
len = strm.avail_out;
}
if (len === 0) { return; }
utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
strm.next_out += len;
s.pending_out += len;
strm.total_out += len;
strm.avail_out -= len;
s.pending -= len;
if (s.pending === 0) {
s.pending_out = 0;
}
}
function flush_block_only (s, last) {
trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
s.block_start = s.strstart;
flush_pending(s.strm);
}
function put_byte(s, b) {
s.pending_buf[s.pending++] = b;
}
/* =========================================================================
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
* IN assertion: the stream state is correct and there is enough room in
* pending_buf.
*/
function putShortMSB(s, b) {
// put_byte(s, (Byte)(b >> 8));
// put_byte(s, (Byte)(b & 0xff));
s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
s.pending_buf[s.pending++] = b & 0xff;
}
/* ===========================================================================
* Read a new buffer from the current input stream, update the adler32
* and total number of bytes read. All deflate() input goes through
* this function so some applications may wish to modify it to avoid
* allocating a large strm->input buffer and copying from it.
* (See also flush_pending()).
*/
function read_buf(strm, buf, start, size) {
var len = strm.avail_in;
if (len > size) { len = size; }
if (len === 0) { return 0; }
strm.avail_in -= len;
utils.arraySet(buf, strm.input, strm.next_in, len, start);
if (strm.state.wrap === 1) {
strm.adler = adler32(strm.adler, buf, len, start);
}
else if (strm.state.wrap === 2) {
strm.adler = crc32(strm.adler, buf, len, start);
}
strm.next_in += len;
strm.total_in += len;
return len;
}
/* ===========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
* OUT assertion: the match length is not greater than s->lookahead.
*/
function longest_match(s, cur_match) {
var chain_length = s.max_chain_length; /* max hash chain length */
var scan = s.strstart; /* current string */
var match; /* matched string */
var len; /* length of current match */
var best_len = s.prev_length; /* best match length so far */
var nice_match = s.nice_match; /* stop if match long enough */
var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
var _win = s.window; // shortcut
var wmask = s.w_mask;
var prev = s.prev;
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
var strend = s.strstart + MAX_MATCH;
var scan_end1 = _win[scan + best_len - 1];
var scan_end = _win[scan + best_len];
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary.
*/
// Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
/* Do not waste too much time if we already have a good match: */
if (s.prev_length >= s.good_match) {
chain_length >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (nice_match > s.lookahead) { nice_match = s.lookahead; }
// Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
do {
// Assert(cur_match < s->strstart, "no future");
match = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2. Note that the checks below
* for insufficient lookahead only occur occasionally for performance
* reasons. Therefore uninitialized memory will be accessed, and
* conditional jumps will be made that depend on those values.
* However the length of the match is limited to the lookahead, so
* the output of deflate is not affected by the uninitialized values.
*/
if (_win[match + best_len] !== scan_end ||
_win[match + best_len - 1] !== scan_end1 ||
_win[match] !== _win[scan] ||
_win[++match] !== _win[scan + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scan += 2;
match++;
// Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
/*jshint noempty:false*/
} while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
scan < strend);
// Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
len = MAX_MATCH - (strend - scan);
scan = strend - MAX_MATCH;
if (len > best_len) {
s.match_start = cur_match;
best_len = len;
if (len >= nice_match) {
break;
}
scan_end1 = _win[scan + best_len - 1];
scan_end = _win[scan + best_len];
}
} while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
if (best_len <= s.lookahead) {
return best_len;
}
return s.lookahead;
}
/* ===========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead.
*
* IN assertion: lookahead < MIN_LOOKAHEAD
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0; reads are
* performed for at least two bytes (required for the zip translate_eol
* option -- not supported here).
*/
function fill_window(s) {
var _w_size = s.w_size;
var p, n, m, more, str;
//Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
do {
more = s.window_size - s.lookahead - s.strstart;
// JS ints have 32 bit, block below not needed
/* Deal with !@#$% 64K limit: */
//if (sizeof(int) <= 2) {
// if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
// more = wsize;
//
// } else if (more == (unsigned)(-1)) {
// /* Very unlikely, but possible on 16 bit machine if
// * strstart == 0 && lookahead == 1 (input done a byte at time)
// */
// more--;
// }
//}
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
s.match_start -= _w_size;
s.strstart -= _w_size;
/* we now have strstart >= MAX_DIST */
s.block_start -= _w_size;
/* Slide the hash table (could be avoided with 32 bit values
at the expense of memory usage). We slide even when level == 0
to keep the hash table consistent if we switch back to level > 0
later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.)
*/
n = s.hash_size;
p = n;
do {
m = s.head[--p];
s.head[p] = (m >= _w_size ? m - _w_size : 0);
} while (--n);
n = _w_size;
p = n;
do {
m = s.prev[--p];
s.prev[p] = (m >= _w_size ? m - _w_size : 0);
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
} while (--n);
more += _w_size;
}
if (s.strm.avail_in === 0) {
break;
}
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
//Assert(more >= 2, "more < 2");
n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
s.lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s.lookahead + s.insert >= MIN_MATCH) {
str = s.strstart - s.insert;
s.ins_h = s.window[str];
/* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call update_hash() MIN_MATCH-3 more times
//#endif
while (s.insert) {
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
s.insert--;
if (s.lookahead + s.insert < MIN_MATCH) {
break;
}
}
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
// if (s.high_water < s.window_size) {
// var curr = s.strstart + s.lookahead;
// var init = 0;
//
// if (s.high_water < curr) {
// /* Previous high water mark below current data -- zero WIN_INIT
// * bytes or up to end of window, whichever is less.
// */
// init = s.window_size - curr;
// if (init > WIN_INIT)
// init = WIN_INIT;
// zmemzero(s->window + curr, (unsigned)init);
// s->high_water = curr + init;
// }
// else if (s->high_water < (ulg)curr + WIN_INIT) {
// /* High water mark at or above current data, but below current data
// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
// * to end of window, whichever is less.
// */
// init = (ulg)curr + WIN_INIT - s->high_water;
// if (init > s->window_size - s->high_water)
// init = s->window_size - s->high_water;
// zmemzero(s->window + s->high_water, (unsigned)init);
// s->high_water += init;
// }
// }
//
// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
// "not enough room for search");
}
/* ===========================================================================
* Copy without compression as much as possible from the input stream, return
* the current block state.
* This function does not insert new strings in the dictionary since
* uncompressible data is probably not useful. This function is used
* only for the level=0 compression option.
* NOTE: this function should be optimized to avoid extra copying from
* window to pending_buf.
*/
function deflate_stored(s, flush) {
/* Stored blocks are limited to 0xffff bytes, pending_buf is limited
* to pending_buf_size, and each stored block has a 5 byte header:
*/
var max_block_size = 0xffff;
if (max_block_size > s.pending_buf_size - 5) {
max_block_size = s.pending_buf_size - 5;
}
/* Copy as much as possible from input to output: */
for (;;) {
/* Fill the window as much as possible: */
if (s.lookahead <= 1) {
//Assert(s->strstart < s->w_size+MAX_DIST(s) ||
// s->block_start >= (long)s->w_size, "slide too late");
// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
// s.block_start >= s.w_size)) {
// throw new Error("slide too late");
// }
fill_window(s);
if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
/* flush the current block */
}
//Assert(s->block_start >= 0L, "block gone");
// if (s.block_start < 0) throw new Error("block gone");
s.strstart += s.lookahead;
s.lookahead = 0;
/* Emit a stored block if pending_buf will be full: */
var max_start = s.block_start + max_block_size;
if (s.strstart === 0 || s.strstart >= max_start) {
/* strstart == 0 is possible when wraparound on 16-bit machine */
s.lookahead = s.strstart - max_start;
s.strstart = max_start;
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
/* Flush if we may have to slide, otherwise block_start may become
* negative and the data will be gone:
*/
if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.strstart > s.block_start) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_NEED_MORE;
}
/* ===========================================================================
* Compress as much as possible from the input stream, return the current
* block state.
* This function does not perform lazy evaluation of matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
function deflate_fast(s, flush) {
var hash_head; /* head of the hash chain */
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break; /* flush the current block */
}
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
}
if (s.match_length >= MIN_MATCH) {
// check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
/*** _tr_tally_dist(s, s.strstart - s.match_start,
s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
s.match_length--; /* string at strstart already in table */
do {
s.strstart++;
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead.
*/
} while (--s.match_length !== 0);
s.strstart++;
} else
{
s.strstart += s.match_length;
s.match_length = 0;
s.ins_h = s.window[s.strstart];
/* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
* matter since it will be recomputed at next deflate call.
*/
}
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s.window[s.strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
function deflate_slow(s, flush) {
var hash_head; /* head of hash chain */
var bflush; /* set if current block must be flushed */
var max_insert;
/* Process the input block. */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
*/
s.prev_length = s.match_length;
s.prev_match = s.match_start;
s.match_length = MIN_MATCH-1;
if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
if (s.match_length <= 5 &&
(s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
s.match_length = MIN_MATCH-1;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
max_insert = s.strstart + s.lookahead - MIN_MATCH;
/* Do not insert strings in hash table beyond this. */
//check_match(s, s.strstart-1, s.prev_match, s.prev_length);
/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
s.prev_length - MIN_MATCH, bflush);***/
bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not
* enough lookahead, the last two strings are not inserted in
* the hash table.
*/
s.lookahead -= s.prev_length-1;
s.prev_length -= 2;
do {
if (++s.strstart <= max_insert) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
} while (--s.prev_length !== 0);
s.match_available = 0;
s.match_length = MIN_MATCH-1;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
} else if (s.match_available) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
if (bflush) {
/*** FLUSH_BLOCK_ONLY(s, 0) ***/
flush_block_only(s, false);
/***/
}
s.strstart++;
s.lookahead--;
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
s.match_available = 1;
s.strstart++;
s.lookahead--;
}
}
//Assert (flush != Z_NO_FLUSH, "no flush?");
if (s.match_available) {
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
s.match_available = 0;
}
s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.)
*/
function deflate_rle(s, flush) {
var bflush; /* set if current block must be flushed */
var prev; /* byte at distance one to match */
var scan, strend; /* scan goes up to strend for length of run */
var _win = s.window;
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the longest run, plus one for the unrolled loop.
*/
if (s.lookahead <= MAX_MATCH) {
fill_window(s);
if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* See how many times the previous byte repeats */
s.match_length = 0;
if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
scan = s.strstart - 1;
prev = _win[scan];
if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
strend = s.strstart + MAX_MATCH;
do {
/*jshint noempty:false*/
} while (prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
scan < strend);
s.match_length = MAX_MATCH - (strend - scan);
if (s.match_length > s.lookahead) {
s.match_length = s.lookahead;
}
}
//Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
}
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (s.match_length >= MIN_MATCH) {
//check_match(s, s.strstart, s.strstart - 1, s.match_length);
/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
s.strstart += s.match_length;
s.match_length = 0;
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.)
*/
function deflate_huff(s, flush) {
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
break; /* flush the current block */
}
}
/* Output a literal byte */
s.match_length = 0;
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
};
var configuration_table;
configuration_table = [
/* good lazy nice chain */
new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
new Config(4, 5, 16, 8, deflate_fast), /* 2 */
new Config(4, 6, 32, 32, deflate_fast), /* 3 */
new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
new Config(8, 16, 32, 32, deflate_slow), /* 5 */
new Config(8, 16, 128, 128, deflate_slow), /* 6 */
new Config(8, 32, 128, 256, deflate_slow), /* 7 */
new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
];
/* ===========================================================================
* Initialize the "longest match" routines for a new zlib stream
*/
function lm_init(s) {
s.window_size = 2 * s.w_size;
/*** CLEAR_HASH(s); ***/
zero(s.head); // Fill with NIL (= 0);
/* Set the default configuration parameters:
*/
s.max_lazy_match = configuration_table[s.level].max_lazy;
s.good_match = configuration_table[s.level].good_length;
s.nice_match = configuration_table[s.level].nice_length;
s.max_chain_length = configuration_table[s.level].max_chain;
s.strstart = 0;
s.block_start = 0;
s.lookahead = 0;
s.insert = 0;
s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0;
s.ins_h = 0;
}
function DeflateState() {
this.strm = null; /* pointer back to this zlib stream */
this.status = 0; /* as the name implies */
this.pending_buf = null; /* output still pending */
this.pending_buf_size = 0; /* size of pending_buf */
this.pending_out = 0; /* next pending byte to output to the stream */
this.pending = 0; /* nb of bytes in the pending buffer */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.gzhead = null; /* gzip header information to write */
this.gzindex = 0; /* where in extra, name, or comment */
this.method = Z_DEFLATED; /* can only be DEFLATED */
this.last_flush = -1; /* value of flush param for previous deflate call */
this.w_size = 0; /* LZ77 window size (32K by default) */
this.w_bits = 0; /* log2(w_size) (8..16) */
this.w_mask = 0; /* w_size - 1 */
this.window = null;
/* Sliding window. Input bytes are read into the second half of the window,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size.
*/
this.window_size = 0;
/* Actual size of window: 2*wSize, except when the user input buffer
* is directly used as sliding window.
*/
this.prev = null;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a window index modulo 32K.
*/
this.head = null; /* Heads of the hash chains or NIL. */
this.ins_h = 0; /* hash index of string to be inserted */
this.hash_size = 0; /* number of elements in hash table */
this.hash_bits = 0; /* log2(hash_size) */
this.hash_mask = 0; /* hash_size-1 */
this.hash_shift = 0;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
this.block_start = 0;
/* Window position at the beginning of the current output block. Gets
* negative when the window is moved backwards.
*/
this.match_length = 0; /* length of best match */
this.prev_match = 0; /* previous match */
this.match_available = 0; /* set if previous match exists */
this.strstart = 0; /* start of string to insert */
this.match_start = 0; /* start of matching string */
this.lookahead = 0; /* number of valid bytes ahead in window */
this.prev_length = 0;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
this.max_chain_length = 0;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
this.max_lazy_match = 0;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
// That's alias to max_lazy_match, don't use directly
//this.max_insert_length = 0;
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
this.level = 0; /* compression level (1..9) */
this.strategy = 0; /* favor or force Huffman coding*/
this.good_match = 0;
/* Use a faster search when the previous match is longer than this */
this.nice_match = 0; /* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to suppress compiler warning */
// struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
// struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
// struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
// Use flat array of DOUBLE size, with interleaved fata,
// because JS does not support effective
this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
zero(this.dyn_ltree);
zero(this.dyn_dtree);
zero(this.bl_tree);
this.l_desc = null; /* desc. for literal tree */
this.d_desc = null; /* desc. for distance tree */
this.bl_desc = null; /* desc. for bit length tree */
//ush bl_count[MAX_BITS+1];
this.bl_count = new utils.Buf16(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
//int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
zero(this.heap);
this.heap_len = 0; /* number of elements in the heap */
this.heap_max = 0; /* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
zero(this.depth);
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
this.l_buf = 0; /* buffer index for literals or lengths */
this.lit_bufsize = 0;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the window so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
this.last_lit = 0; /* running index in l_buf */
this.d_buf = 0;
/* Buffer index for distances. To simplify the code, d_buf and l_buf have
* the same number of elements. To use different lengths, an extra flag
* array would be necessary.
*/
this.opt_len = 0; /* bit length of current block with optimal trees */
this.static_len = 0; /* bit length of current block with static trees */
this.matches = 0; /* number of string matches in current block */
this.insert = 0; /* bytes at end of window left to insert */
this.bi_buf = 0;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
this.bi_valid = 0;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
// Used for window memory init. We safely ignore it for JS. That makes
// sense only for pointers and memory check tools.
//this.high_water = 0;
/* High water mark offset in window for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
}
function deflateResetKeep(strm) {
var s;
if (!strm || !strm.state) {
return err(strm, Z_STREAM_ERROR);
}
strm.total_in = strm.total_out = 0;
strm.data_type = Z_UNKNOWN;
s = strm.state;
s.pending = 0;
s.pending_out = 0;
if (s.wrap < 0) {
s.wrap = -s.wrap;
/* was made negative by deflate(..., Z_FINISH); */
}
s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
strm.adler = (s.wrap === 2) ?
0 // crc32(0, Z_NULL, 0)
:
1; // adler32(0, Z_NULL, 0)
s.last_flush = Z_NO_FLUSH;
trees._tr_init(s);
return Z_OK;
}
function deflateReset(strm) {
var ret = deflateResetKeep(strm);
if (ret === Z_OK) {
lm_init(strm.state);
}
return ret;
}
function deflateSetHeader(strm, head) {
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
strm.state.gzhead = head;
return Z_OK;
}
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
if (!strm) { // === Z_NULL
return Z_STREAM_ERROR;
}
var wrap = 1;
if (level === Z_DEFAULT_COMPRESSION) {
level = 6;
}
if (windowBits < 0) { /* suppress zlib wrapper */
wrap = 0;
windowBits = -windowBits;
}
else if (windowBits > 15) {
wrap = 2; /* write gzip wrapper instead */
windowBits -= 16;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_FIXED) {
return err(strm, Z_STREAM_ERROR);
}
if (windowBits === 8) {
windowBits = 9;
}
/* until 256-byte window bug fixed */
var s = new DeflateState();
strm.state = s;
s.strm = strm;
s.wrap = wrap;
s.gzhead = null;
s.w_bits = windowBits;
s.w_size = 1 << s.w_bits;
s.w_mask = s.w_size - 1;
s.hash_bits = memLevel + 7;
s.hash_size = 1 << s.hash_bits;
s.hash_mask = s.hash_size - 1;
s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
s.window = new utils.Buf8(s.w_size * 2);
s.head = new utils.Buf16(s.hash_size);
s.prev = new utils.Buf16(s.w_size);
// Don't need mem init magic for JS.
//s.high_water = 0; /* nothing written to s->window yet */
s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
s.pending_buf_size = s.lit_bufsize * 4;
s.pending_buf = new utils.Buf8(s.pending_buf_size);
s.d_buf = s.lit_bufsize >> 1;
s.l_buf = (1 + 2) * s.lit_bufsize;
s.level = level;
s.strategy = strategy;
s.method = method;
return deflateReset(strm);
}
function deflateInit(strm, level) {
return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
function deflate(strm, flush) {
var old_flush, s;
var beg, val; // for gzip header write only
if (!strm || !strm.state ||
flush > Z_BLOCK || flush < 0) {
return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
}
s = strm.state;
if (!strm.output ||
(!strm.input && strm.avail_in !== 0) ||
(s.status === FINISH_STATE && flush !== Z_FINISH)) {
return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
}
s.strm = strm; /* just in case */
old_flush = s.last_flush;
s.last_flush = flush;
/* Write the header */
if (s.status === INIT_STATE) {
if (s.wrap === 2) { // GZIP header
strm.adler = 0; //crc32(0L, Z_NULL, 0);
put_byte(s, 31);
put_byte(s, 139);
put_byte(s, 8);
if (!s.gzhead) { // s->gzhead == Z_NULL
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, OS_CODE);
s.status = BUSY_STATE;
}
else {
put_byte(s, (s.gzhead.text ? 1 : 0) +
(s.gzhead.hcrc ? 2 : 0) +
(!s.gzhead.extra ? 0 : 4) +
(!s.gzhead.name ? 0 : 8) +
(!s.gzhead.comment ? 0 : 16)
);
put_byte(s, s.gzhead.time & 0xff);
put_byte(s, (s.gzhead.time >> 8) & 0xff);
put_byte(s, (s.gzhead.time >> 16) & 0xff);
put_byte(s, (s.gzhead.time >> 24) & 0xff);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, s.gzhead.os & 0xff);
if (s.gzhead.extra && s.gzhead.extra.length) {
put_byte(s, s.gzhead.extra.length & 0xff);
put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
}
if (s.gzhead.hcrc) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
}
s.gzindex = 0;
s.status = EXTRA_STATE;
}
}
else // DEFLATE header
{
var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
var level_flags = -1;
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
level_flags = 0;
} else if (s.level < 6) {
level_flags = 1;
} else if (s.level === 6) {
level_flags = 2;
} else {
level_flags = 3;
}
header |= (level_flags << 6);
if (s.strstart !== 0) { header |= PRESET_DICT; }
header += 31 - (header % 31);
s.status = BUSY_STATE;
putShortMSB(s, header);
/* Save the adler32 of the preset dictionary: */
if (s.strstart !== 0) {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
strm.adler = 1; // adler32(0L, Z_NULL, 0);
}
}
//#ifdef GZIP
if (s.status === EXTRA_STATE) {
if (s.gzhead.extra/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
break;
}
}
put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
s.gzindex++;
}
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (s.gzindex === s.gzhead.extra.length) {
s.gzindex = 0;
s.status = NAME_STATE;
}
}
else {
s.status = NAME_STATE;
}
}
if (s.status === NAME_STATE) {
if (s.gzhead.name/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.name.length) {
val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg){
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.gzindex = 0;
s.status = COMMENT_STATE;
}
}
else {
s.status = COMMENT_STATE;
}
}
if (s.status === COMMENT_STATE) {
if (s.gzhead.comment/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.comment.length) {
val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.status = HCRC_STATE;
}
}
else {
s.status = HCRC_STATE;
}
}
if (s.status === HCRC_STATE) {
if (s.gzhead.hcrc) {
if (s.pending + 2 > s.pending_buf_size) {
flush_pending(strm);
}
if (s.pending + 2 <= s.pending_buf_size) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
strm.adler = 0; //crc32(0L, Z_NULL, 0);
s.status = BUSY_STATE;
}
}
else {
s.status = BUSY_STATE;
}
}
//#endif
/* Flush as much pending output as possible */
if (s.pending !== 0) {
flush_pending(strm);
if (strm.avail_out === 0) {
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s.last_flush = -1;
return Z_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUF_ERROR.
*/
} else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
flush !== Z_FINISH) {
return err(strm, Z_BUF_ERROR);
}
/* User must not provide more input after the first FINISH: */
if (s.status === FINISH_STATE && strm.avail_in !== 0) {
return err(strm, Z_BUF_ERROR);
}
/* Start a new block or continue the current one.
*/
if (strm.avail_in !== 0 || s.lookahead !== 0 ||
(flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
(s.strategy === Z_RLE ? deflate_rle(s, flush) :
configuration_table[s.level].func(s, flush));
if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
s.status = FINISH_STATE;
}
if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
if (strm.avail_out === 0) {
s.last_flush = -1;
/* avoid BUF_ERROR next call, see above */
}
return Z_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate === BS_BLOCK_DONE) {
if (flush === Z_PARTIAL_FLUSH) {
trees._tr_align(s);
}
else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
trees._tr_stored_block(s, 0, 0, false);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush === Z_FULL_FLUSH) {
/*** CLEAR_HASH(s); ***/ /* forget history */
zero(s.head); // Fill with NIL (= 0);
if (s.lookahead === 0) {
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
}
}
flush_pending(strm);
if (strm.avail_out === 0) {
s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
return Z_OK;
}
}
}
//Assert(strm->avail_out > 0, "bug2");
//if (strm.avail_out <= 0) { throw new Error("bug2");}
if (flush !== Z_FINISH) { return Z_OK; }
if (s.wrap <= 0) { return Z_STREAM_END; }
/* Write the trailer */
if (s.wrap === 2) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
put_byte(s, (strm.adler >> 16) & 0xff);
put_byte(s, (strm.adler >> 24) & 0xff);
put_byte(s, strm.total_in & 0xff);
put_byte(s, (strm.total_in >> 8) & 0xff);
put_byte(s, (strm.total_in >> 16) & 0xff);
put_byte(s, (strm.total_in >> 24) & 0xff);
}
else
{
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
flush_pending(strm);
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
if (s.wrap > 0) { s.wrap = -s.wrap; }
/* write the trailer only once! */
return s.pending !== 0 ? Z_OK : Z_STREAM_END;
}
function deflateEnd(strm) {
var status;
if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
return Z_STREAM_ERROR;
}
status = strm.state.status;
if (status !== INIT_STATE &&
status !== EXTRA_STATE &&
status !== NAME_STATE &&
status !== COMMENT_STATE &&
status !== HCRC_STATE &&
status !== BUSY_STATE &&
status !== FINISH_STATE
) {
return err(strm, Z_STREAM_ERROR);
}
strm.state = null;
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
}
/* =========================================================================
* Copy the source state to the destination state
*/
//function deflateCopy(dest, source) {
//
//}
exports.deflateInit = deflateInit;
exports.deflateInit2 = deflateInit2;
exports.deflateReset = deflateReset;
exports.deflateResetKeep = deflateResetKeep;
exports.deflateSetHeader = deflateSetHeader;
exports.deflate = deflate;
exports.deflateEnd = deflateEnd;
exports.deflateInfo = 'pako deflate (from Nodeca project)';
/* Not implemented
exports.deflateBound = deflateBound;
exports.deflateCopy = deflateCopy;
exports.deflateSetDictionary = deflateSetDictionary;
exports.deflateParams = deflateParams;
exports.deflatePending = deflatePending;
exports.deflatePrime = deflatePrime;
exports.deflateTune = deflateTune;
*/
},{"../utils/common":61,"./adler32":62,"./crc32":64,"./messages":69,"./trees":70}],66:[function(require,module,exports){
'use strict';
// See state defs from inflate.js
var BAD = 30; /* got a data error -- remain here until reset */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state.mode === LEN
strm.avail_in >= 6
strm.avail_out >= 258
start >= strm.avail_out
state.bits < 8
On return, state.mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm.avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm.avail_out >= 258 for each loop to avoid checking for
output space.
*/
module.exports = function inflate_fast(strm, start) {
var state;
var _in; /* local strm.input */
var last; /* have enough input while in < last */
var _out; /* local strm.output */
var beg; /* inflate()'s initial strm.output */
var end; /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
var dmax; /* maximum distance from zlib header */
//#endif
var wsize; /* window size or zero if not using window */
var whave; /* valid bytes in the window */
var wnext; /* window write index */
var window; /* allocated sliding window, if wsize != 0 */
var hold; /* local strm.hold */
var bits; /* local strm.bits */
var lcode; /* local strm.lencode */
var dcode; /* local strm.distcode */
var lmask; /* mask for first level of length codes */
var dmask; /* mask for first level of distance codes */
var here; /* retrieved table entry */
var op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
var len; /* match length, unused bytes */
var dist; /* match distance */
var from; /* where to copy match from */
var from_source;
var input, output; // JS specific, because we have no pointers
/* copy state to local variables */
state = strm.state;
//here = state.here;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
dmax = state.dmax;
//#endif
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
window = state.window;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
top:
do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
for (;;) { // Goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op === 0) { /* literal */
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
output[_out++] = here & 0xffff/*here.val*/;
}
else if (op & 16) { /* length base */
len = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & ((1 << op) - 1);
hold >>>= op;
bits -= op;
}
//Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
for (;;) { // goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op & 16) { /* distance base */
dist = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
if (dist > dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
//#endif
hold >>>= op;
bits -= op;
//Tracevv((stderr, "inflate: distance %u\n", dist));
op = _out - beg; /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// if (len <= op - whave) {
// do {
// output[_out++] = 0;
// } while (--len);
// continue top;
// }
// len -= op - whave;
// do {
// output[_out++] = 0;
// } while (--op > whave);
// if (op === 0) {
// from = _out - dist;
// do {
// output[_out++] = output[from++];
// } while (--len);
// continue top;
// }
//#endif
}
from = 0; // window index
from_source = window;
if (wnext === 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
output[_out++] = window[from++];
} while (--op);
from = 0;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
output[_out++] = window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
}
else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
}
else {
from = _out - dist; /* copy direct from output */
do { /* minimum length is three */
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
}
else if ((op & 64) === 0) { /* 2nd level distance code */
here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dodist;
}
else {
strm.msg = 'invalid distance code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
}
else if ((op & 64) === 0) { /* 2nd level length code */
here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dolen;
}
else if (op & 32) { /* end-of-block */
//Tracevv((stderr, "inflate: end of block\n"));
state.mode = TYPE;
break top;
}
else {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} while (_in < last && _out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
/* update state and return */
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
state.hold = hold;
state.bits = bits;
return;
};
},{}],67:[function(require,module,exports){
'use strict';
var utils = require('../utils/common');
var adler32 = require('./adler32');
var crc32 = require('./crc32');
var inflate_fast = require('./inffast');
var inflate_table = require('./inftrees');
var CODES = 0;
var LENS = 1;
var DISTS = 2;
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
//var Z_NO_FLUSH = 0;
//var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
//var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* The deflate compression method */
var Z_DEFLATED = 8;
/* STATES ====================================================================*/
/* ===========================================================================*/
var HEAD = 1; /* i: waiting for magic header */
var FLAGS = 2; /* i: waiting for method and flags (gzip) */
var TIME = 3; /* i: waiting for modification time (gzip) */
var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
var EXLEN = 5; /* i: waiting for extra length (gzip) */
var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
var NAME = 7; /* i: waiting for end of file name (gzip) */
var COMMENT = 8; /* i: waiting for end of comment (gzip) */
var HCRC = 9; /* i: waiting for header crc (gzip) */
var DICTID = 10; /* i: waiting for dictionary check value */
var DICT = 11; /* waiting for inflateSetDictionary() call */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
var STORED = 14; /* i: waiting for stored size (length and complement) */
var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
var COPY = 16; /* i/o: waiting for input or output to copy stored block */
var TABLE = 17; /* i: waiting for dynamic block table lengths */
var LENLENS = 18; /* i: waiting for code length code lengths */
var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
var LEN_ = 20; /* i: same as LEN below, but only first time in */
var LEN = 21; /* i: waiting for length/lit/eob code */
var LENEXT = 22; /* i: waiting for length extra bits */
var DIST = 23; /* i: waiting for distance code */
var DISTEXT = 24; /* i: waiting for distance extra bits */
var MATCH = 25; /* o: waiting for output space to copy string */
var LIT = 26; /* o: waiting for output space to write literal */
var CHECK = 27; /* i: waiting for 32-bit check value */
var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
var DONE = 29; /* finished check, done -- remain here until reset */
var BAD = 30; /* got a data error -- remain here until reset */
var MEM = 31; /* got an inflate() memory error -- remain here until reset */
var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
/* ===========================================================================*/
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_WBITS = MAX_WBITS;
function ZSWAP32(q) {
return (((q >>> 24) & 0xff) +
((q >>> 8) & 0xff00) +
((q & 0xff00) << 8) +
((q & 0xff) << 24));
}
function InflateState() {
this.mode = 0; /* current inflate mode */
this.last = false; /* true if processing last block */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.havedict = false; /* true if dictionary provided */
this.flags = 0; /* gzip header method and flags (0 if zlib) */
this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
this.check = 0; /* protected copy of check value */
this.total = 0; /* protected copy of output count */
// TODO: may be {}
this.head = null; /* where to save gzip header information */
/* sliding window */
this.wbits = 0; /* log base 2 of requested window size */
this.wsize = 0; /* window size or zero if not using window */
this.whave = 0; /* valid bytes in the window */
this.wnext = 0; /* window write index */
this.window = null; /* allocated sliding window, if needed */
/* bit accumulator */
this.hold = 0; /* input bit accumulator */
this.bits = 0; /* number of bits in "in" */
/* for string and stored block copying */
this.length = 0; /* literal or length of data to copy */
this.offset = 0; /* distance back to copy string from */
/* for table and code decoding */
this.extra = 0; /* extra bits needed */
/* fixed and dynamic code tables */
this.lencode = null; /* starting table for length/literal codes */
this.distcode = null; /* starting table for distance codes */
this.lenbits = 0; /* index bits for lencode */
this.distbits = 0; /* index bits for distcode */
/* dynamic table building */
this.ncode = 0; /* number of code length code lengths */
this.nlen = 0; /* number of length code lengths */
this.ndist = 0; /* number of distance code lengths */
this.have = 0; /* number of code lengths in lens[] */
this.next = null; /* next available space in codes[] */
this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
this.work = new utils.Buf16(288); /* work area for code table building */
/*
because we don't have pointers in js, we use lencode and distcode directly
as buffers so we don't need codes
*/
//this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
this.distdyn = null; /* dynamic table for distance codes (JS specific) */
this.sane = 0; /* if false, allow invalid distance too far */
this.back = 0; /* bits back of last unprocessed length/lit */
this.was = 0; /* initial length of match */
}
function inflateResetKeep(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
strm.total_in = strm.total_out = state.total = 0;
strm.msg = ''; /*Z_NULL*/
if (state.wrap) { /* to support ill-conceived Java test suite */
strm.adler = state.wrap & 1;
}
state.mode = HEAD;
state.last = 0;
state.havedict = 0;
state.dmax = 32768;
state.head = null/*Z_NULL*/;
state.hold = 0;
state.bits = 0;
//state.lencode = state.distcode = state.next = state.codes;
state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
state.sane = 1;
state.back = -1;
//Tracev((stderr, "inflate: reset\n"));
return Z_OK;
}
function inflateReset(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
state.wsize = 0;
state.whave = 0;
state.wnext = 0;
return inflateResetKeep(strm);
}
function inflateReset2(strm, windowBits) {
var wrap;
var state;
/* get the state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
/* extract wrap request from windowBits parameter */
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
}
else {
wrap = (windowBits >> 4) + 1;
if (windowBits < 48) {
windowBits &= 15;
}
}
/* set number of window bits, free window if different */
if (windowBits && (windowBits < 8 || windowBits > 15)) {
return Z_STREAM_ERROR;
}
if (state.window !== null && state.wbits !== windowBits) {
state.window = null;
}
/* update state and reset the rest of it */
state.wrap = wrap;
state.wbits = windowBits;
return inflateReset(strm);
}
function inflateInit2(strm, windowBits) {
var ret;
var state;
if (!strm) { return Z_STREAM_ERROR; }
//strm.msg = Z_NULL; /* in case we return an error */
state = new InflateState();
//if (state === Z_NULL) return Z_MEM_ERROR;
//Tracev((stderr, "inflate: allocated\n"));
strm.state = state;
state.window = null/*Z_NULL*/;
ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK) {
strm.state = null/*Z_NULL*/;
}
return ret;
}
function inflateInit(strm) {
return inflateInit2(strm, DEF_WBITS);
}
/*
Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h.
If BUILDFIXED is defined, then instead this routine builds the tables the
first time it's called, and returns those tables the first time and
thereafter. This reduces the size of the code by about 2K bytes, in
exchange for a little execution time. However, BUILDFIXED should not be
used for threaded applications, since the rewriting of the tables and virgin
may not be thread-safe.
*/
var virgin = true;
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
function fixedtables(state) {
/* build fixed huffman tables if first call (may not be thread safe) */
if (virgin) {
var sym;
lenfix = new utils.Buf32(512);
distfix = new utils.Buf32(32);
/* literal/length table */
sym = 0;
while (sym < 144) { state.lens[sym++] = 8; }
while (sym < 256) { state.lens[sym++] = 9; }
while (sym < 280) { state.lens[sym++] = 7; }
while (sym < 288) { state.lens[sym++] = 8; }
inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
/* distance table */
sym = 0;
while (sym < 32) { state.lens[sym++] = 5; }
inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
/* do this just once */
virgin = false;
}
state.lencode = lenfix;
state.lenbits = 9;
state.distcode = distfix;
state.distbits = 5;
}
/*
Update the window with the last wsize (normally 32K) bytes written before
returning. If window does not exist yet, create it. This is only called
when a window is already in use, or when output has been written during this
inflate call, but the end of the deflate stream has not been reached yet.
It is also called to create a window for dictionary data when a dictionary
is loaded.
Providing output buffers larger than 32K to inflate() should provide a speed
advantage, since only the last 32K of output is copied to the sliding window
upon return from inflate(), and since all distances after the first 32K of
output will fall in the output data, making match copies simpler and faster.
The advantage may be dependent on the size of the processor's data caches.
*/
function updatewindow(strm, src, end, copy) {
var dist;
var state = strm.state;
/* if it hasn't been done already, allocate space for the window */
if (state.window === null) {
state.wsize = 1 << state.wbits;
state.wnext = 0;
state.whave = 0;
state.window = new utils.Buf8(state.wsize);
}
/* copy state->wsize or less output bytes into the circular window */
if (copy >= state.wsize) {
utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
state.wnext = 0;
state.whave = state.wsize;
}
else {
dist = state.wsize - state.wnext;
if (dist > copy) {
dist = copy;
}
//zmemcpy(state->window + state->wnext, end - copy, dist);
utils.arraySet(state.window,src, end - copy, dist, state.wnext);
copy -= dist;
if (copy) {
//zmemcpy(state->window, end - copy, copy);
utils.arraySet(state.window,src, end - copy, copy, 0);
state.wnext = copy;
state.whave = state.wsize;
}
else {
state.wnext += dist;
if (state.wnext === state.wsize) { state.wnext = 0; }
if (state.whave < state.wsize) { state.whave += dist; }
}
}
return 0;
}
function inflate(strm, flush) {
var state;
var input, output; // input/output buffers
var next; /* next input INDEX */
var put; /* next output INDEX */
var have, left; /* available input and output */
var hold; /* bit buffer */
var bits; /* bits in bit buffer */
var _in, _out; /* save starting available input and output */
var copy; /* number of stored or match bytes to copy */
var from; /* where to copy match bytes from */
var from_source;
var here = 0; /* current decoding table entry */
var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//var last; /* parent table entry */
var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
var len; /* length to copy for repeats, bits to drop */
var ret; /* return code */
var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
var opts;
var n; // temporary var for NEED_BITS
var order = /* permutation of code lengths */
[16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
if (!strm || !strm.state || !strm.output ||
(!strm.input && strm.avail_in !== 0)) {
return Z_STREAM_ERROR;
}
state = strm.state;
if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
_in = have;
_out = left;
ret = Z_OK;
inf_leave: // goto emulation
for (;;) {
switch (state.mode) {
case HEAD:
if (state.wrap === 0) {
state.mode = TYPEDO;
break;
}
//=== NEEDBITS(16);
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
state.check = 0/*crc32(0L, Z_NULL, 0)*/;
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = FLAGS;
break;
}
state.flags = 0; /* expect zlib header */
if (state.head) {
state.head.done = false;
}
if (!(state.wrap & 1) || /* check if zlib header allowed */
(((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
strm.msg = 'incorrect header check';
state.mode = BAD;
break;
}
if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
len = (hold & 0x0f)/*BITS(4)*/ + 8;
if (state.wbits === 0) {
state.wbits = len;
}
else if (len > state.wbits) {
strm.msg = 'invalid window size';
state.mode = BAD;
break;
}
state.dmax = 1 << len;
//Tracev((stderr, "inflate: zlib header ok\n"));
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = hold & 0x200 ? DICTID : TYPE;
//=== INITBITS();
hold = 0;
bits = 0;
//===//
break;
case FLAGS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.flags = hold;
if ((state.flags & 0xff) !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
if (state.flags & 0xe000) {
strm.msg = 'unknown header flags set';
state.mode = BAD;
break;
}
if (state.head) {
state.head.text = ((hold >> 8) & 1);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = TIME;
/* falls through */
case TIME:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.time = hold;
}
if (state.flags & 0x0200) {
//=== CRC4(state.check, hold)
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
hbuf[2] = (hold >>> 16) & 0xff;
hbuf[3] = (hold >>> 24) & 0xff;
state.check = crc32(state.check, hbuf, 4, 0);
//===
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = OS;
/* falls through */
case OS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.xflags = (hold & 0xff);
state.head.os = (hold >> 8);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = EXLEN;
/* falls through */
case EXLEN:
if (state.flags & 0x0400) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length = hold;
if (state.head) {
state.head.extra_len = hold;
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
else if (state.head) {
state.head.extra = null/*Z_NULL*/;
}
state.mode = EXTRA;
/* falls through */
case EXTRA:
if (state.flags & 0x0400) {
copy = state.length;
if (copy > have) { copy = have; }
if (copy) {
if (state.head) {
len = state.head.extra_len - state.length;
if (!state.head.extra) {
// Use untyped array for more conveniend processing later
state.head.extra = new Array(state.head.extra_len);
}
utils.arraySet(
state.head.extra,
input,
next,
// extra field is limited to 65536 bytes
// - no need for additional size check
copy,
/*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
len
);
//zmemcpy(state.head.extra + len, next,
// len + copy > state.head.extra_max ?
// state.head.extra_max - len : copy);
}
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
state.length -= copy;
}
if (state.length) { break inf_leave; }
}
state.length = 0;
state.mode = NAME;
/* falls through */
case NAME:
if (state.flags & 0x0800) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
// TODO: 2 or 1 bytes?
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.name_max*/)) {
state.head.name += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.name = null;
}
state.length = 0;
state.mode = COMMENT;
/* falls through */
case COMMENT:
if (state.flags & 0x1000) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.comm_max*/)) {
state.head.comment += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.comment = null;
}
state.mode = HCRC;
/* falls through */
case HCRC:
if (state.flags & 0x0200) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.check & 0xffff)) {
strm.msg = 'header crc mismatch';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
if (state.head) {
state.head.hcrc = ((state.flags >> 9) & 1);
state.head.done = true;
}
strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
break;
case DICTID:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
strm.adler = state.check = ZSWAP32(hold);
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = DICT;
/* falls through */
case DICT:
if (state.havedict === 0) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
return Z_NEED_DICT;
}
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
/* falls through */
case TYPE:
if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
/* falls through */
case TYPEDO:
if (state.last) {
//--- BYTEBITS() ---//
hold >>>= bits & 7;
bits -= bits & 7;
//---//
state.mode = CHECK;
break;
}
//=== NEEDBITS(3); */
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.last = (hold & 0x01)/*BITS(1)*/;
//--- DROPBITS(1) ---//
hold >>>= 1;
bits -= 1;
//---//
switch ((hold & 0x03)/*BITS(2)*/) {
case 0: /* stored block */
//Tracev((stderr, "inflate: stored block%s\n",
// state.last ? " (last)" : ""));
state.mode = STORED;
break;
case 1: /* fixed block */
fixedtables(state);
//Tracev((stderr, "inflate: fixed codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = LEN_; /* decode codes */
if (flush === Z_TREES) {
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break inf_leave;
}
break;
case 2: /* dynamic block */
//Tracev((stderr, "inflate: dynamic codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = TABLE;
break;
case 3:
strm.msg = 'invalid block type';
state.mode = BAD;
}
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break;
case STORED:
//--- BYTEBITS() ---// /* go to byte boundary */
hold >>>= bits & 7;
bits -= bits & 7;
//---//
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
strm.msg = 'invalid stored block lengths';
state.mode = BAD;
break;
}
state.length = hold & 0xffff;
//Tracev((stderr, "inflate: stored length %u\n",
// state.length));
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = COPY_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case COPY_:
state.mode = COPY;
/* falls through */
case COPY:
copy = state.length;
if (copy) {
if (copy > have) { copy = have; }
if (copy > left) { copy = left; }
if (copy === 0) { break inf_leave; }
//--- zmemcpy(put, next, copy); ---
utils.arraySet(output, input, next, copy, put);
//---//
have -= copy;
next += copy;
left -= copy;
put += copy;
state.length -= copy;
break;
}
//Tracev((stderr, "inflate: stored end\n"));
state.mode = TYPE;
break;
case TABLE:
//=== NEEDBITS(14); */
while (bits < 14) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
//#ifndef PKZIP_BUG_WORKAROUND
if (state.nlen > 286 || state.ndist > 30) {
strm.msg = 'too many length or distance symbols';
state.mode = BAD;
break;
}
//#endif
//Tracev((stderr, "inflate: table sizes ok\n"));
state.have = 0;
state.mode = LENLENS;
/* falls through */
case LENLENS:
while (state.have < state.ncode) {
//=== NEEDBITS(3);
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
while (state.have < 19) {
state.lens[order[state.have++]] = 0;
}
// We have separate tables & no pointers. 2 commented lines below not needed.
//state.next = state.codes;
//state.lencode = state.next;
// Switch to use dynamic table
state.lencode = state.lendyn;
state.lenbits = 7;
opts = {bits: state.lenbits};
ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = 'invalid code lengths set';
state.mode = BAD;
break;
}
//Tracev((stderr, "inflate: code lengths ok\n"));
state.have = 0;
state.mode = CODELENS;
/* falls through */
case CODELENS:
while (state.have < state.nlen + state.ndist) {
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_val < 16) {
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.lens[state.have++] = here_val;
}
else {
if (here_val === 16) {
//=== NEEDBITS(here.bits + 2);
n = here_bits + 2;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
if (state.have === 0) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
len = state.lens[state.have - 1];
copy = 3 + (hold & 0x03);//BITS(2);
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
}
else if (here_val === 17) {
//=== NEEDBITS(here.bits + 3);
n = here_bits + 3;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 3 + (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
else {
//=== NEEDBITS(here.bits + 7);
n = here_bits + 7;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 11 + (hold & 0x7f);//BITS(7);
//--- DROPBITS(7) ---//
hold >>>= 7;
bits -= 7;
//---//
}
if (state.have + copy > state.nlen + state.ndist) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
while (copy--) {
state.lens[state.have++] = len;
}
}
}
/* handle error breaks in while */
if (state.mode === BAD) { break; }
/* check for end-of-block code (better have one) */
if (state.lens[256] === 0) {
strm.msg = 'invalid code -- missing end-of-block';
state.mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state.lenbits = 9;
opts = {bits: state.lenbits};
ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.lenbits = opts.bits;
// state.lencode = state.next;
if (ret) {
strm.msg = 'invalid literal/lengths set';
state.mode = BAD;
break;
}
state.distbits = 6;
//state.distcode.copy(state.codes);
// Switch to use dynamic table
state.distcode = state.distdyn;
opts = {bits: state.distbits};
ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.distbits = opts.bits;
// state.distcode = state.next;
if (ret) {
strm.msg = 'invalid distances set';
state.mode = BAD;
break;
}
//Tracev((stderr, 'inflate: codes ok\n'));
state.mode = LEN_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case LEN_:
state.mode = LEN;
/* falls through */
case LEN:
if (have >= 6 && left >= 258) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
inflate_fast(strm, _out);
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
if (state.mode === TYPE) {
state.back = -1;
}
break;
}
state.back = 0;
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_op && (here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.lencode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
state.length = here_val;
if (here_op === 0) {
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
state.mode = LIT;
break;
}
if (here_op & 32) {
//Tracevv((stderr, "inflate: end of block\n"));
state.back = -1;
state.mode = TYPE;
break;
}
if (here_op & 64) {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break;
}
state.extra = here_op & 15;
state.mode = LENEXT;
/* falls through */
case LENEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//Tracevv((stderr, "inflate: length %u\n", state.length));
state.was = state.length;
state.mode = DIST;
/* falls through */
case DIST:
for (;;) {
here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if ((here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.distcode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
if (here_op & 64) {
strm.msg = 'invalid distance code';
state.mode = BAD;
break;
}
state.offset = here_val;
state.extra = (here_op) & 15;
state.mode = DISTEXT;
/* falls through */
case DISTEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//#ifdef INFLATE_STRICT
if (state.offset > state.dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
//#endif
//Tracevv((stderr, "inflate: distance %u\n", state.offset));
state.mode = MATCH;
/* falls through */
case MATCH:
if (left === 0) { break inf_leave; }
copy = _out - left;
if (state.offset > copy) { /* copy from window */
copy = state.offset - copy;
if (copy > state.whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// Trace((stderr, "inflate.c too far\n"));
// copy -= state.whave;
// if (copy > state.length) { copy = state.length; }
// if (copy > left) { copy = left; }
// left -= copy;
// state.length -= copy;
// do {
// output[put++] = 0;
// } while (--copy);
// if (state.length === 0) { state.mode = LEN; }
// break;
//#endif
}
if (copy > state.wnext) {
copy -= state.wnext;
from = state.wsize - copy;
}
else {
from = state.wnext - copy;
}
if (copy > state.length) { copy = state.length; }
from_source = state.window;
}
else { /* copy from output */
from_source = output;
from = put - state.offset;
copy = state.length;
}
if (copy > left) { copy = left; }
left -= copy;
state.length -= copy;
do {
output[put++] = from_source[from++];
} while (--copy);
if (state.length === 0) { state.mode = LEN; }
break;
case LIT:
if (left === 0) { break inf_leave; }
output[put++] = state.length;
left--;
state.mode = LEN;
break;
case CHECK:
if (state.wrap) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
// Use '|' insdead of '+' to make sure that result is signed
hold |= input[next++] << bits;
bits += 8;
}
//===//
_out -= left;
strm.total_out += _out;
state.total += _out;
if (_out) {
strm.adler = state.check =
/*UPDATE(state.check, put - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
}
_out = left;
// NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
strm.msg = 'incorrect data check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: check matches trailer\n"));
}
state.mode = LENGTH;
/* falls through */
case LENGTH:
if (state.wrap && state.flags) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.total & 0xffffffff)) {
strm.msg = 'incorrect length check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: length matches trailer\n"));
}
state.mode = DONE;
/* falls through */
case DONE:
ret = Z_STREAM_END;
break inf_leave;
case BAD:
ret = Z_DATA_ERROR;
break inf_leave;
case MEM:
return Z_MEM_ERROR;
case SYNC:
/* falls through */
default:
return Z_STREAM_ERROR;
}
}
// inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
/*
Return from inflate(), updating the total counts and the check value.
If there was no progress during the inflate() call, return a buffer
error. Call updatewindow() to create and/or update the window state.
Note: a memory error from inflate() is non-recoverable.
*/
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
(state.mode < CHECK || flush !== Z_FINISH))) {
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
state.mode = MEM;
return Z_MEM_ERROR;
}
}
_in -= strm.avail_in;
_out -= strm.avail_out;
strm.total_in += _in;
strm.total_out += _out;
state.total += _out;
if (state.wrap && _out) {
strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
}
strm.data_type = state.bits + (state.last ? 64 : 0) +
(state.mode === TYPE ? 128 : 0) +
(state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
ret = Z_BUF_ERROR;
}
return ret;
}
function inflateEnd(strm) {
if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
return Z_STREAM_ERROR;
}
var state = strm.state;
if (state.window) {
state.window = null;
}
strm.state = null;
return Z_OK;
}
function inflateGetHeader(strm, head) {
var state;
/* check state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
/* save header structure */
state.head = head;
head.done = false;
return Z_OK;
}
exports.inflateReset = inflateReset;
exports.inflateReset2 = inflateReset2;
exports.inflateResetKeep = inflateResetKeep;
exports.inflateInit = inflateInit;
exports.inflateInit2 = inflateInit2;
exports.inflate = inflate;
exports.inflateEnd = inflateEnd;
exports.inflateGetHeader = inflateGetHeader;
exports.inflateInfo = 'pako inflate (from Nodeca project)';
/* Not implemented
exports.inflateCopy = inflateCopy;
exports.inflateGetDictionary = inflateGetDictionary;
exports.inflateMark = inflateMark;
exports.inflatePrime = inflatePrime;
exports.inflateSetDictionary = inflateSetDictionary;
exports.inflateSync = inflateSync;
exports.inflateSyncPoint = inflateSyncPoint;
exports.inflateUndermine = inflateUndermine;
*/
},{"../utils/common":61,"./adler32":62,"./crc32":64,"./inffast":66,"./inftrees":68}],68:[function(require,module,exports){
'use strict';
var utils = require('../utils/common');
var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var CODES = 0;
var LENS = 1;
var DISTS = 2;
var lbase = [ /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
];
var lext = [ /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
];
var dbase = [ /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0
];
var dext = [ /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64
];
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
{
var bits = opts.bits;
//here = opts.here; /* table entry for duplication */
var len = 0; /* a code's length in bits */
var sym = 0; /* index of code symbols */
var min = 0, max = 0; /* minimum and maximum code lengths */
var root = 0; /* number of index bits for root table */
var curr = 0; /* number of index bits for current table */
var drop = 0; /* code bits to drop for sub-table */
var left = 0; /* number of prefix codes available */
var used = 0; /* code entries in table used */
var huff = 0; /* Huffman code */
var incr; /* for incrementing code, index */
var fill; /* index for replicating entries */
var low; /* low bits for current root entry */
var mask; /* mask for low root bits */
var next; /* next available space in table */
var base = null; /* base value table to use */
var base_index = 0;
// var shoextra; /* extra bits table to use */
var end; /* use base and extra for symbol > end */
var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
var extra = null;
var extra_index = 0;
var here_bits, here_op, here_val;
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0; sym < codes; sym++) {
count[lens[lens_index + sym]]++;
}
/* bound code lengths, force root to be within code lengths */
root = bits;
for (max = MAXBITS; max >= 1; max--) {
if (count[max] !== 0) { break; }
}
if (root > max) {
root = max;
}
if (max === 0) { /* no symbols to code at all */
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
//table.op[opts.table_index] = 64;
//table.bits[opts.table_index] = 1;
//table.val[opts.table_index++] = 0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
opts.bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++) {
if (count[min] !== 0) { break; }
}
if (root < min) {
root = min;
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1;
} /* over-subscribed */
}
if (left > 0 && (type === CODES || max !== 1)) {
return -1; /* incomplete set */
}
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + count[len];
}
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++) {
if (lens[lens_index + sym] !== 0) {
work[offs[lens[lens_index + sym]]++] = sym;
}
}
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
// poor man optimization - use if-else instead of switch,
// to avoid deopts in old v8
if (type === CODES) {
base = extra = work; /* dummy value--not used */
end = 19;
} else if (type === LENS) {
base = lbase;
base_index -= 257;
extra = lext;
extra_index -= 257;
end = 256;
} else { /* DISTS */
base = dbase;
extra = dext;
end = -1;
}
/* initialize opts for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = table_index; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = -1; /* trigger new sub-table when len > root */
used = 1 << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
var i=0;
/* process all codes and make table entries */
for (;;) {
i++;
/* create table entry */
here_bits = len - drop;
if (work[sym] < end) {
here_op = 0;
here_val = work[sym];
}
else if (work[sym] > end) {
here_op = extra[extra_index + work[sym]];
here_val = base[base_index + work[sym]];
}
else {
here_op = 32 + 64; /* end of block */
here_val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1 << (len - drop);
fill = 1 << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
} while (fill !== 0);
/* backwards increment the len-bit code huff */
incr = 1 << (len - 1);
while (huff & incr) {
incr >>= 1;
}
if (incr !== 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
/* go to next symbol, update count, len */
sym++;
if (--count[len] === 0) {
if (len === max) { break; }
len = lens[lens_index + work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) !== low) {
/* if first time, transition to sub-tables */
if (drop === 0) {
drop = root;
}
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) { break; }
curr++;
left <<= 1;
}
/* check for enough space */
used += 1 << curr;
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
/* point entry in root table to sub-table */
low = huff & mask;
/*table.op[low] = curr;
table.bits[low] = root;
table.val[low] = next - opts.table_index;*/
table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff !== 0) {
//table.op[next + huff] = 64; /* invalid code marker */
//table.bits[next + huff] = len - drop;
//table.val[next + huff] = 0;
table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
}
/* set return parameters */
//opts.table_index += used;
opts.bits = root;
return 0;
};
},{"../utils/common":61}],69:[function(require,module,exports){
'use strict';
module.exports = {
'2': 'need dictionary', /* Z_NEED_DICT 2 */
'1': 'stream end', /* Z_STREAM_END 1 */
'0': '', /* Z_OK 0 */
'-1': 'file error', /* Z_ERRNO (-1) */
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
'-3': 'data error', /* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
};
},{}],70:[function(require,module,exports){
'use strict';
var utils = require('../utils/common');
/* Public constants ==========================================================*/
/* ===========================================================================*/
//var Z_FILTERED = 1;
//var Z_HUFFMAN_ONLY = 2;
//var Z_RLE = 3;
var Z_FIXED = 4;
//var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
var Z_BINARY = 0;
var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/*============================================================================*/
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
// From zutil.h
var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES = 2;
/* The three kinds of block type */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
/* The minimum and maximum match lengths */
// From deflate.h
/* ===========================================================================
* Internal compression state.
*/
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var Buf_size = 16;
/* size of bit buffer in bi_buf */
/* ===========================================================================
* Constants
*/
var MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */
var END_BLOCK = 256;
/* end of block literal code */
var REP_3_6 = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
var REPZ_3_10 = 17;
/* repeat a zero length 3-10 times (3 bits of repeat count) */
var REPZ_11_138 = 18;
/* repeat a zero length 11-138 times (7 bits of repeat count) */
var extra_lbits = /* extra bits for each length code */
[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
var extra_dbits = /* extra bits for each distance code */
[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
var extra_blbits = /* extra bits for each bit length code */
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
var bl_order =
[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
// We pre-fill arrays with 0 to avoid uninitialized gaps
var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
var static_ltree = new Array((L_CODES+2) * 2);
zero(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
var static_dtree = new Array(D_CODES * 2);
zero(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
var _dist_code = new Array(DIST_CODE_LEN);
zero(_dist_code);
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
zero(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */
var base_length = new Array(LENGTH_CODES);
zero(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */
var base_dist = new Array(D_CODES);
zero(base_dist);
/* First normalized distance for each code (0 = distance of 1) */
var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
this.static_tree = static_tree; /* static tree or NULL */
this.extra_bits = extra_bits; /* extra bits for each code or NULL */
this.extra_base = extra_base; /* base index for extra_bits */
this.elems = elems; /* max number of elements in the tree */
this.max_length = max_length; /* max bit length for the codes */
// show if `static_tree` has data or dummy - needed for monomorphic objects
this.has_stree = static_tree && static_tree.length;
};
var static_l_desc;
var static_d_desc;
var static_bl_desc;
var TreeDesc = function(dyn_tree, stat_desc) {
this.dyn_tree = dyn_tree; /* the dynamic tree */
this.max_code = 0; /* largest code with non zero frequency */
this.stat_desc = stat_desc; /* the corresponding static tree */
};
function d_code(dist) {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
}
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
function put_short (s, w) {
// put_byte(s, (uch)((w) & 0xff));
// put_byte(s, (uch)((ush)(w) >> 8));
s.pending_buf[s.pending++] = (w) & 0xff;
s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
function send_bits(s, value, length) {
if (s.bi_valid > (Buf_size - length)) {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
put_short(s, s.bi_buf);
s.bi_buf = value >> (Buf_size - s.bi_valid);
s.bi_valid += length - Buf_size;
} else {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
s.bi_valid += length;
}
}
function send_code(s, c, tree) {
send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
function bi_reverse(code, len) {
var res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
function bi_flush(s) {
if (s.bi_valid === 16) {
put_short(s, s.bi_buf);
s.bi_buf = 0;
s.bi_valid = 0;
} else if (s.bi_valid >= 8) {
s.pending_buf[s.pending++] = s.bi_buf & 0xff;
s.bi_buf >>= 8;
s.bi_valid -= 8;
}
}
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
function gen_bitlen(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var max_code = desc.max_code;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var extra = desc.stat_desc.extra_bits;
var base = desc.stat_desc.extra_base;
var max_length = desc.stat_desc.max_length;
var h; /* heap index */
var n, m; /* iterate over the tree elements */
var bits; /* bit length */
var xbits; /* extra bits */
var f; /* frequency */
var overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) {
s.bl_count[bits] = 0;
}
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
n = s.heap[h];
bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n*2 + 1]/*.Len*/ = bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) { continue; } /* not a leaf node */
s.bl_count[bits]++;
xbits = 0;
if (n >= base) {
xbits = extra[n-base];
}
f = tree[n * 2]/*.Freq*/;
s.opt_len += f * (bits + xbits);
if (has_stree) {
s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
}
}
if (overflow === 0) { return; }
// Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length-1;
while (s.bl_count[bits] === 0) { bits--; }
s.bl_count[bits]--; /* move one leaf down the tree */
s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
s.bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits !== 0; bits--) {
n = s.bl_count[bits];
while (n !== 0) {
m = s.heap[--h];
if (m > max_code) { continue; }
if (tree[m*2 + 1]/*.Len*/ !== bits) {
// Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
tree[m*2 + 1]/*.Len*/ = bits;
}
n--;
}
}
}
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
function gen_codes(tree, max_code, bl_count)
// ct_data *tree; /* the tree to decorate */
// int max_code; /* largest code with non zero frequency */
// ushf *bl_count; /* number of codes at each bit length */
{
var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
var code = 0; /* running code value */
var bits; /* bit index */
var n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (code + bl_count[bits-1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
var len = tree[n*2 + 1]/*.Len*/;
if (len === 0) { continue; }
/* Now reverse the bits */
tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
//Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
function tr_static_init() {
var n; /* iterates over tree elements */
var bits; /* bit counter */
var length; /* length value */
var code; /* code value */
var dist; /* distance index */
var bl_count = new Array(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
// do check in _tr_init()
//if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
/*#ifdef NO_INIT_GLOBAL_POINTERS
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
#endif*/
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES-1; code++) {
base_length[code] = length;
for (n = 0; n < (1<<extra_lbits[code]); n++) {
_length_code[length++] = code;
}
}
//Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length-1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0 ; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1<<extra_dbits[code]); n++) {
_dist_code[dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for ( ; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
_dist_code[256 + dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) {
bl_count[bits] = 0;
}
n = 0;
while (n <= 143) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
while (n <= 255) {
static_ltree[n*2 + 1]/*.Len*/ = 9;
n++;
bl_count[9]++;
}
while (n <= 279) {
static_ltree[n*2 + 1]/*.Len*/ = 7;
n++;
bl_count[7]++;
}
while (n <= 287) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes(static_ltree, L_CODES+1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n*2 + 1]/*.Len*/ = 5;
static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
}
// Now data ready and we can init static trees
static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
//static_init_done = true;
}
/* ===========================================================================
* Initialize a new block.
*/
function init_block(s) {
var n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
s.opt_len = s.static_len = 0;
s.last_lit = s.matches = 0;
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
function bi_windup(s)
{
if (s.bi_valid > 8) {
put_short(s, s.bi_buf);
} else if (s.bi_valid > 0) {
//put_byte(s, (Byte)s->bi_buf);
s.pending_buf[s.pending++] = s.bi_buf;
}
s.bi_buf = 0;
s.bi_valid = 0;
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
function copy_block(s, buf, len, header)
//DeflateState *s;
//charf *buf; /* the input data */
//unsigned len; /* its length */
//int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
if (header) {
put_short(s, len);
put_short(s, ~len);
}
// while (len--) {
// put_byte(s, *buf++);
// }
utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
s.pending += len;
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
function smaller(tree, n, m, depth) {
var _n2 = n*2;
var _m2 = m*2;
return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
(tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
}
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
function pqdownheap(s, tree, k)
// deflate_state *s;
// ct_data *tree; /* the tree to restore */
// int k; /* node to move down */
{
var v = s.heap[k];
var j = k << 1; /* left son of k */
while (j <= s.heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s.heap_len &&
smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s.heap[j], s.depth)) { break; }
/* Exchange v with the smallest son */
s.heap[k] = s.heap[j];
k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s.heap[k] = v;
}
// inlined manually
// var SMALLEST = 1;
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
function compress_block(s, ltree, dtree)
// deflate_state *s;
// const ct_data *ltree; /* literal tree */
// const ct_data *dtree; /* distance tree */
{
var dist; /* distance of matched string */
var lc; /* match length or unmatched char (if dist == 0) */
var lx = 0; /* running index in l_buf */
var code; /* the code to send */
var extra; /* number of extra bits to send */
if (s.last_lit !== 0) {
do {
dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
lc = s.pending_buf[s.l_buf + lx];
lx++;
if (dist === 0) {
send_code(s, lc, ltree); /* send a literal byte */
//Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code+LITERALS+1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra !== 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
//Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra !== 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
//Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
// "pendingBuf overflow");
} while (lx < s.last_lit);
}
send_code(s, END_BLOCK, ltree);
}
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
function build_tree(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var elems = desc.stat_desc.elems;
var n, m; /* iterate over heap elements */
var max_code = -1; /* largest code with non zero frequency */
var node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n * 2]/*.Freq*/ !== 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n*2 + 1]/*.Len*/ = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node * 2]/*.Freq*/ = 1;
s.depth[node] = 0;
s.opt_len--;
if (has_stree) {
s.static_len -= stree[node*2 + 1]/*.Len*/;
}
/* node is 0 or 1 so it does not have extra bits */
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
//pqremove(s, tree, n); /* n = node of least frequency */
/*** pqremove ***/
n = s.heap[1/*SMALLEST*/];
s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
pqdownheap(s, tree, 1/*SMALLEST*/);
/***/
m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
s.heap[--s.heap_max] = m;
/* Create a new node father of n and m */
tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
/* and insert the new node in the heap */
s.heap[1/*SMALLEST*/] = node++;
pqdownheap(s, tree, 1/*SMALLEST*/);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, desc);
/* The field len is now set, we can generate the bit codes */
gen_codes(tree, max_code, s.bl_count);
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
function scan_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
s.bl_tree[curlen * 2]/*.Freq*/ += count;
} else if (curlen !== 0) {
if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
s.bl_tree[REP_3_6*2]/*.Freq*/++;
} else if (count <= 10) {
s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
} else {
s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
function send_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
} else if (curlen !== 0) {
if (curlen !== prevlen) {
send_code(s, curlen, s.bl_tree);
count--;
}
//Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s.bl_tree);
send_bits(s, count-3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s.bl_tree);
send_bits(s, count-3, 3);
} else {
send_code(s, REPZ_11_138, s.bl_tree);
send_bits(s, count-11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
function build_bl_tree(s) {
var max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, s.bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
break;
}
}
/* Update opt_len to include the bit length tree and counts */
s.opt_len += 3*(max_blindex+1) + 5+5+4;
//Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
function send_all_trees(s, lcodes, dcodes, blcodes)
// deflate_state *s;
// int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
var rank; /* index in bl_order */
//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
//Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes-1, 5);
send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
//Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
}
//Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
//Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}
/* ===========================================================================
* Check if the data type is TEXT or BINARY, using the following algorithm:
* - TEXT if the two conditions below are satisfied:
* a) There are no non-portable control characters belonging to the
* "black list" (0..6, 14..25, 28..31).
* b) There is at least one printable character belonging to the
* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
* - BINARY otherwise.
* - The following partially-portable control characters form a
* "gray list" that is ignored in this detection algorithm:
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set.
*/
function detect_data_type(s) {
/* black_mask is the bit mask of black-listed bytes
* set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111
*/
var black_mask = 0xf3ffc07f;
var n;
/* Check for non-textual ("black-listed") bytes. */
for (n = 0; n <= 31; n++, black_mask >>>= 1) {
if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
return Z_BINARY;
}
}
/* Check for textual ("white-listed") bytes. */
if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
for (n = 32; n < LITERALS; n++) {
if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
}
/* There are no "black-listed" or "white-listed" bytes:
* this stream either is empty or has tolerated ("gray-listed") bytes only.
*/
return Z_BINARY;
}
var static_init_done = false;
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
function _tr_init(s)
{
if (!static_init_done) {
tr_static_init();
static_init_done = true;
}
s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
s.bi_buf = 0;
s.bi_valid = 0;
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Send a stored block
*/
function _tr_stored_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
copy_block(s, buf, stored_len, true); /* with header */
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
*/
function _tr_align(s) {
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
bi_flush(s);
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
function _tr_flush_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block, or NULL if too old */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
var max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s.level > 0) {
/* Check if the file is binary or text */
if (s.strm.data_type === Z_UNKNOWN) {
s.strm.data_type = detect_data_type(s);
}
/* Construct the literal and distance trees */
build_tree(s, s.l_desc);
// Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
build_tree(s, s.d_desc);
// Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = (s.opt_len+3+7) >>> 3;
static_lenb = (s.static_len+3+7) >>> 3;
// Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
// opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
// s->last_lit));
if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
} else {
// Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
/* 4: two words for the lengths */
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, last);
} else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
compress_block(s, static_ltree, static_dtree);
} else {
send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
compress_block(s, s.dyn_ltree, s.dyn_dtree);
}
// Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (last) {
bi_windup(s);
}
// Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
// s->compressed_len-7*last));
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
function _tr_tally(s, dist, lc)
// deflate_state *s;
// unsigned dist; /* distance of matched string */
// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
//var out_length, in_length, dcode;
s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
s.last_lit++;
if (dist === 0) {
/* lc is the unmatched char */
s.dyn_ltree[lc*2]/*.Freq*/++;
} else {
s.matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
//Assert((ush)dist < (ush)MAX_DIST(s) &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef TRUNCATE_BLOCK
// /* Try to guess if it is profitable to stop the current block here */
// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
// /* Compute an upper bound for the compressed length */
// out_length = s.last_lit*8;
// in_length = s.strstart - s.block_start;
//
// for (dcode = 0; dcode < D_CODES; dcode++) {
// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
// }
// out_length >>>= 3;
// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
// // s->last_lit, in_length, out_length,
// // 100L - out_length*100L/in_length));
// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
// return true;
// }
// }
//#endif
return (s.last_lit === s.lit_bufsize-1);
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
exports._tr_init = _tr_init;
exports._tr_stored_block = _tr_stored_block;
exports._tr_flush_block = _tr_flush_block;
exports._tr_tally = _tr_tally;
exports._tr_align = _tr_align;
},{"../utils/common":61}],71:[function(require,module,exports){
'use strict';
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''/*Z_NULL*/;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2/*Z_UNKNOWN*/;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
module.exports = ZStream;
},{}],72:[function(require,module,exports){
(function (process,Buffer){
var msg = require('pako/lib/zlib/messages');
var zstream = require('pako/lib/zlib/zstream');
var zlib_deflate = require('pako/lib/zlib/deflate.js');
var zlib_inflate = require('pako/lib/zlib/inflate.js');
var constants = require('pako/lib/zlib/constants');
for (var key in constants) {
exports[key] = constants[key];
}
// zlib modes
exports.NONE = 0;
exports.DEFLATE = 1;
exports.INFLATE = 2;
exports.GZIP = 3;
exports.GUNZIP = 4;
exports.DEFLATERAW = 5;
exports.INFLATERAW = 6;
exports.UNZIP = 7;
/**
* Emulate Node's zlib C++ layer for use by the JS layer in index.js
*/
function Zlib(mode) {
if (mode < exports.DEFLATE || mode > exports.UNZIP)
throw new TypeError("Bad argument");
this.mode = mode;
this.init_done = false;
this.write_in_progress = false;
this.pending_close = false;
this.windowBits = 0;
this.level = 0;
this.memLevel = 0;
this.strategy = 0;
this.dictionary = null;
}
Zlib.prototype.init = function(windowBits, level, memLevel, strategy, dictionary) {
this.windowBits = windowBits;
this.level = level;
this.memLevel = memLevel;
this.strategy = strategy;
// dictionary not supported.
if (this.mode === exports.GZIP || this.mode === exports.GUNZIP)
this.windowBits += 16;
if (this.mode === exports.UNZIP)
this.windowBits += 32;
if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW)
this.windowBits = -this.windowBits;
this.strm = new zstream();
switch (this.mode) {
case exports.DEFLATE:
case exports.GZIP:
case exports.DEFLATERAW:
var status = zlib_deflate.deflateInit2(
this.strm,
this.level,
exports.Z_DEFLATED,
this.windowBits,
this.memLevel,
this.strategy
);
break;
case exports.INFLATE:
case exports.GUNZIP:
case exports.INFLATERAW:
case exports.UNZIP:
var status = zlib_inflate.inflateInit2(
this.strm,
this.windowBits
);
break;
default:
throw new Error("Unknown mode " + this.mode);
}
if (status !== exports.Z_OK) {
this._error(status);
return;
}
this.write_in_progress = false;
this.init_done = true;
};
Zlib.prototype.params = function() {
throw new Error("deflateParams Not supported");
};
Zlib.prototype._writeCheck = function() {
if (!this.init_done)
throw new Error("write before init");
if (this.mode === exports.NONE)
throw new Error("already finalized");
if (this.write_in_progress)
throw new Error("write already in progress");
if (this.pending_close)
throw new Error("close is pending");
};
Zlib.prototype.write = function(flush, input, in_off, in_len, out, out_off, out_len) {
this._writeCheck();
this.write_in_progress = true;
var self = this;
process.nextTick(function() {
self.write_in_progress = false;
var res = self._write(flush, input, in_off, in_len, out, out_off, out_len);
self.callback(res[0], res[1]);
if (self.pending_close)
self.close();
});
return this;
};
// set method for Node buffers, used by pako
function bufferSet(data, offset) {
for (var i = 0; i < data.length; i++) {
this[offset + i] = data[i];
}
}
Zlib.prototype.writeSync = function(flush, input, in_off, in_len, out, out_off, out_len) {
this._writeCheck();
return this._write(flush, input, in_off, in_len, out, out_off, out_len);
};
Zlib.prototype._write = function(flush, input, in_off, in_len, out, out_off, out_len) {
this.write_in_progress = true;
if (flush !== exports.Z_NO_FLUSH &&
flush !== exports.Z_PARTIAL_FLUSH &&
flush !== exports.Z_SYNC_FLUSH &&
flush !== exports.Z_FULL_FLUSH &&
flush !== exports.Z_FINISH &&
flush !== exports.Z_BLOCK) {
throw new Error("Invalid flush value");
}
if (input == null) {
input = new Buffer(0);
in_len = 0;
in_off = 0;
}
if (out._set)
out.set = out._set;
else
out.set = bufferSet;
var strm = this.strm;
strm.avail_in = in_len;
strm.input = input;
strm.next_in = in_off;
strm.avail_out = out_len;
strm.output = out;
strm.next_out = out_off;
switch (this.mode) {
case exports.DEFLATE:
case exports.GZIP:
case exports.DEFLATERAW:
var status = zlib_deflate.deflate(strm, flush);
break;
case exports.UNZIP:
case exports.INFLATE:
case exports.GUNZIP:
case exports.INFLATERAW:
var status = zlib_inflate.inflate(strm, flush);
break;
default:
throw new Error("Unknown mode " + this.mode);
}
if (status !== exports.Z_STREAM_END && status !== exports.Z_OK) {
this._error(status);
}
this.write_in_progress = false;
return [strm.avail_in, strm.avail_out];
};
Zlib.prototype.close = function() {
if (this.write_in_progress) {
this.pending_close = true;
return;
}
this.pending_close = false;
if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
zlib_deflate.deflateEnd(this.strm);
} else {
zlib_inflate.inflateEnd(this.strm);
}
this.mode = exports.NONE;
};
Zlib.prototype.reset = function() {
switch (this.mode) {
case exports.DEFLATE:
case exports.DEFLATERAW:
var status = zlib_deflate.deflateReset(this.strm);
break;
case exports.INFLATE:
case exports.INFLATERAW:
var status = zlib_inflate.inflateReset(this.strm);
break;
}
if (status !== exports.Z_OK) {
this._error(status);
}
};
Zlib.prototype._error = function(status) {
this.onerror(msg[status] + ': ' + this.strm.msg, status);
this.write_in_progress = false;
if (this.pending_close)
this.close();
};
exports.Zlib = Zlib;
}).call(this,require('_process'),require("buffer").Buffer)
},{"_process":82,"buffer":74,"pako/lib/zlib/constants":63,"pako/lib/zlib/deflate.js":65,"pako/lib/zlib/inflate.js":67,"pako/lib/zlib/messages":69,"pako/lib/zlib/zstream":71}],73:[function(require,module,exports){
(function (process,Buffer){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var Transform = require('_stream_transform');
var binding = require('./binding');
var util = require('util');
var assert = require('assert').ok;
// zlib doesn't provide these, so kludge them in following the same
// const naming scheme zlib uses.
binding.Z_MIN_WINDOWBITS = 8;
binding.Z_MAX_WINDOWBITS = 15;
binding.Z_DEFAULT_WINDOWBITS = 15;
// fewer than 64 bytes per chunk is stupid.
// technically it could work with as few as 8, but even 64 bytes
// is absurdly low. Usually a MB or more is best.
binding.Z_MIN_CHUNK = 64;
binding.Z_MAX_CHUNK = Infinity;
binding.Z_DEFAULT_CHUNK = (16 * 1024);
binding.Z_MIN_MEMLEVEL = 1;
binding.Z_MAX_MEMLEVEL = 9;
binding.Z_DEFAULT_MEMLEVEL = 8;
binding.Z_MIN_LEVEL = -1;
binding.Z_MAX_LEVEL = 9;
binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
// expose all the zlib constants
Object.keys(binding).forEach(function(k) {
if (k.match(/^Z/)) exports[k] = binding[k];
});
// translation table for return codes.
exports.codes = {
Z_OK: binding.Z_OK,
Z_STREAM_END: binding.Z_STREAM_END,
Z_NEED_DICT: binding.Z_NEED_DICT,
Z_ERRNO: binding.Z_ERRNO,
Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
Z_DATA_ERROR: binding.Z_DATA_ERROR,
Z_MEM_ERROR: binding.Z_MEM_ERROR,
Z_BUF_ERROR: binding.Z_BUF_ERROR,
Z_VERSION_ERROR: binding.Z_VERSION_ERROR
};
Object.keys(exports.codes).forEach(function(k) {
exports.codes[exports.codes[k]] = k;
});
exports.Deflate = Deflate;
exports.Inflate = Inflate;
exports.Gzip = Gzip;
exports.Gunzip = Gunzip;
exports.DeflateRaw = DeflateRaw;
exports.InflateRaw = InflateRaw;
exports.Unzip = Unzip;
exports.createDeflate = function(o) {
return new Deflate(o);
};
exports.createInflate = function(o) {
return new Inflate(o);
};
exports.createDeflateRaw = function(o) {
return new DeflateRaw(o);
};
exports.createInflateRaw = function(o) {
return new InflateRaw(o);
};
exports.createGzip = function(o) {
return new Gzip(o);
};
exports.createGunzip = function(o) {
return new Gunzip(o);
};
exports.createUnzip = function(o) {
return new Unzip(o);
};
// Convenience methods.
// compress/decompress a string or buffer in one step.
exports.deflate = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Deflate(opts), buffer, callback);
};
exports.deflateSync = function(buffer, opts) {
return zlibBufferSync(new Deflate(opts), buffer);
};
exports.gzip = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Gzip(opts), buffer, callback);
};
exports.gzipSync = function(buffer, opts) {
return zlibBufferSync(new Gzip(opts), buffer);
};
exports.deflateRaw = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new DeflateRaw(opts), buffer, callback);
};
exports.deflateRawSync = function(buffer, opts) {
return zlibBufferSync(new DeflateRaw(opts), buffer);
};
exports.unzip = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Unzip(opts), buffer, callback);
};
exports.unzipSync = function(buffer, opts) {
return zlibBufferSync(new Unzip(opts), buffer);
};
exports.inflate = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Inflate(opts), buffer, callback);
};
exports.inflateSync = function(buffer, opts) {
return zlibBufferSync(new Inflate(opts), buffer);
};
exports.gunzip = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Gunzip(opts), buffer, callback);
};
exports.gunzipSync = function(buffer, opts) {
return zlibBufferSync(new Gunzip(opts), buffer);
};
exports.inflateRaw = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new InflateRaw(opts), buffer, callback);
};
exports.inflateRawSync = function(buffer, opts) {
return zlibBufferSync(new InflateRaw(opts), buffer);
};
function zlibBuffer(engine, buffer, callback) {
var buffers = [];
var nread = 0;
engine.on('error', onError);
engine.on('end', onEnd);
engine.end(buffer);
flow();
function flow() {
var chunk;
while (null !== (chunk = engine.read())) {
buffers.push(chunk);
nread += chunk.length;
}
engine.once('readable', flow);
}
function onError(err) {
engine.removeListener('end', onEnd);
engine.removeListener('readable', flow);
callback(err);
}
function onEnd() {
var buf = Buffer.concat(buffers, nread);
buffers = [];
callback(null, buf);
engine.close();
}
}
function zlibBufferSync(engine, buffer) {
if (typeof buffer === 'string')
buffer = new Buffer(buffer);
if (!Buffer.isBuffer(buffer))
throw new TypeError('Not a string or buffer');
var flushFlag = binding.Z_FINISH;
return engine._processChunk(buffer, flushFlag);
}
// generic zlib
// minimal 2-byte header
function Deflate(opts) {
if (!(this instanceof Deflate)) return new Deflate(opts);
Zlib.call(this, opts, binding.DEFLATE);
}
function Inflate(opts) {
if (!(this instanceof Inflate)) return new Inflate(opts);
Zlib.call(this, opts, binding.INFLATE);
}
// gzip - bigger header, same deflate compression
function Gzip(opts) {
if (!(this instanceof Gzip)) return new Gzip(opts);
Zlib.call(this, opts, binding.GZIP);
}
function Gunzip(opts) {
if (!(this instanceof Gunzip)) return new Gunzip(opts);
Zlib.call(this, opts, binding.GUNZIP);
}
// raw - no header
function DeflateRaw(opts) {
if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
Zlib.call(this, opts, binding.DEFLATERAW);
}
function InflateRaw(opts) {
if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
Zlib.call(this, opts, binding.INFLATERAW);
}
// auto-detect header.
function Unzip(opts) {
if (!(this instanceof Unzip)) return new Unzip(opts);
Zlib.call(this, opts, binding.UNZIP);
}
// the Zlib class they all inherit from
// This thing manages the queue of requests, and returns
// true or false if there is anything in the queue when
// you call the .write() method.
function Zlib(opts, mode) {
this._opts = opts = opts || {};
this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
Transform.call(this, opts);
if (opts.flush) {
if (opts.flush !== binding.Z_NO_FLUSH &&
opts.flush !== binding.Z_PARTIAL_FLUSH &&
opts.flush !== binding.Z_SYNC_FLUSH &&
opts.flush !== binding.Z_FULL_FLUSH &&
opts.flush !== binding.Z_FINISH &&
opts.flush !== binding.Z_BLOCK) {
throw new Error('Invalid flush flag: ' + opts.flush);
}
}
this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
if (opts.chunkSize) {
if (opts.chunkSize < exports.Z_MIN_CHUNK ||
opts.chunkSize > exports.Z_MAX_CHUNK) {
throw new Error('Invalid chunk size: ' + opts.chunkSize);
}
}
if (opts.windowBits) {
if (opts.windowBits < exports.Z_MIN_WINDOWBITS ||
opts.windowBits > exports.Z_MAX_WINDOWBITS) {
throw new Error('Invalid windowBits: ' + opts.windowBits);
}
}
if (opts.level) {
if (opts.level < exports.Z_MIN_LEVEL ||
opts.level > exports.Z_MAX_LEVEL) {
throw new Error('Invalid compression level: ' + opts.level);
}
}
if (opts.memLevel) {
if (opts.memLevel < exports.Z_MIN_MEMLEVEL ||
opts.memLevel > exports.Z_MAX_MEMLEVEL) {
throw new Error('Invalid memLevel: ' + opts.memLevel);
}
}
if (opts.strategy) {
if (opts.strategy != exports.Z_FILTERED &&
opts.strategy != exports.Z_HUFFMAN_ONLY &&
opts.strategy != exports.Z_RLE &&
opts.strategy != exports.Z_FIXED &&
opts.strategy != exports.Z_DEFAULT_STRATEGY) {
throw new Error('Invalid strategy: ' + opts.strategy);
}
}
if (opts.dictionary) {
if (!Buffer.isBuffer(opts.dictionary)) {
throw new Error('Invalid dictionary: it should be a Buffer instance');
}
}
this._binding = new binding.Zlib(mode);
var self = this;
this._hadError = false;
this._binding.onerror = function(message, errno) {
// there is no way to cleanly recover.
// continuing only obscures problems.
self._binding = null;
self._hadError = true;
var error = new Error(message);
error.errno = errno;
error.code = exports.codes[errno];
self.emit('error', error);
};
var level = exports.Z_DEFAULT_COMPRESSION;
if (typeof opts.level === 'number') level = opts.level;
var strategy = exports.Z_DEFAULT_STRATEGY;
if (typeof opts.strategy === 'number') strategy = opts.strategy;
this._binding.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS,
level,
opts.memLevel || exports.Z_DEFAULT_MEMLEVEL,
strategy,
opts.dictionary);
this._buffer = new Buffer(this._chunkSize);
this._offset = 0;
this._closed = false;
this._level = level;
this._strategy = strategy;
this.once('end', this.close);
}
util.inherits(Zlib, Transform);
Zlib.prototype.params = function(level, strategy, callback) {
if (level < exports.Z_MIN_LEVEL ||
level > exports.Z_MAX_LEVEL) {
throw new RangeError('Invalid compression level: ' + level);
}
if (strategy != exports.Z_FILTERED &&
strategy != exports.Z_HUFFMAN_ONLY &&
strategy != exports.Z_RLE &&
strategy != exports.Z_FIXED &&
strategy != exports.Z_DEFAULT_STRATEGY) {
throw new TypeError('Invalid strategy: ' + strategy);
}
if (this._level !== level || this._strategy !== strategy) {
var self = this;
this.flush(binding.Z_SYNC_FLUSH, function() {
self._binding.params(level, strategy);
if (!self._hadError) {
self._level = level;
self._strategy = strategy;
if (callback) callback();
}
});
} else {
process.nextTick(callback);
}
};
Zlib.prototype.reset = function() {
return this._binding.reset();
};
// This is the _flush function called by the transform class,
// internally, when the last chunk has been written.
Zlib.prototype._flush = function(callback) {
this._transform(new Buffer(0), '', callback);
};
Zlib.prototype.flush = function(kind, callback) {
var ws = this._writableState;
if (typeof kind === 'function' || (kind === void 0 && !callback)) {
callback = kind;
kind = binding.Z_FULL_FLUSH;
}
if (ws.ended) {
if (callback)
process.nextTick(callback);
} else if (ws.ending) {
if (callback)
this.once('end', callback);
} else if (ws.needDrain) {
var self = this;
this.once('drain', function() {
self.flush(callback);
});
} else {
this._flushFlag = kind;
this.write(new Buffer(0), '', callback);
}
};
Zlib.prototype.close = function(callback) {
if (callback)
process.nextTick(callback);
if (this._closed)
return;
this._closed = true;
this._binding.close();
var self = this;
process.nextTick(function() {
self.emit('close');
});
};
Zlib.prototype._transform = function(chunk, encoding, cb) {
var flushFlag;
var ws = this._writableState;
var ending = ws.ending || ws.ended;
var last = ending && (!chunk || ws.length === chunk.length);
if (!chunk === null && !Buffer.isBuffer(chunk))
return cb(new Error('invalid input'));
// If it's the last chunk, or a final flush, we use the Z_FINISH flush flag.
// If it's explicitly flushing at some other time, then we use
// Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
// goodness.
if (last)
flushFlag = binding.Z_FINISH;
else {
flushFlag = this._flushFlag;
// once we've flushed the last of the queue, stop flushing and
// go back to the normal behavior.
if (chunk.length >= ws.length) {
this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
}
}
var self = this;
this._processChunk(chunk, flushFlag, cb);
};
Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
var availInBefore = chunk && chunk.length;
var availOutBefore = this._chunkSize - this._offset;
var inOff = 0;
var self = this;
var async = typeof cb === 'function';
if (!async) {
var buffers = [];
var nread = 0;
var error;
this.on('error', function(er) {
error = er;
});
do {
var res = this._binding.writeSync(flushFlag,
chunk, // in
inOff, // in_off
availInBefore, // in_len
this._buffer, // out
this._offset, //out_off
availOutBefore); // out_len
} while (!this._hadError && callback(res[0], res[1]));
if (this._hadError) {
throw error;
}
var buf = Buffer.concat(buffers, nread);
this.close();
return buf;
}
var req = this._binding.write(flushFlag,
chunk, // in
inOff, // in_off
availInBefore, // in_len
this._buffer, // out
this._offset, //out_off
availOutBefore); // out_len
req.buffer = chunk;
req.callback = callback;
function callback(availInAfter, availOutAfter) {
if (self._hadError)
return;
var have = availOutBefore - availOutAfter;
assert(have >= 0, 'have should not go down');
if (have > 0) {
var out = self._buffer.slice(self._offset, self._offset + have);
self._offset += have;
// serve some output to the consumer.
if (async) {
self.push(out);
} else {
buffers.push(out);
nread += out.length;
}
}
// exhausted the output buffer, or used all the input create a new one.
if (availOutAfter === 0 || self._offset >= self._chunkSize) {
availOutBefore = self._chunkSize;
self._offset = 0;
self._buffer = new Buffer(self._chunkSize);
}
if (availOutAfter === 0) {
// Not actually done. Need to reprocess.
// Also, update the availInBefore to the availInAfter value,
// so that if we have to hit it a third (fourth, etc.) time,
// it'll have the correct byte counts.
inOff += (availInBefore - availInAfter);
availInBefore = availInAfter;
if (!async)
return true;
var newReq = self._binding.write(flushFlag,
chunk,
inOff,
availInBefore,
self._buffer,
self._offset,
self._chunkSize);
newReq.callback = callback; // this same function
newReq.buffer = chunk;
return;
}
if (!async)
return false;
// finished with the chunk.
cb();
}
};
util.inherits(Deflate, Zlib);
util.inherits(Inflate, Zlib);
util.inherits(Gzip, Zlib);
util.inherits(Gunzip, Zlib);
util.inherits(DeflateRaw, Zlib);
util.inherits(InflateRaw, Zlib);
util.inherits(Unzip, Zlib);
}).call(this,require('_process'),require("buffer").Buffer)
},{"./binding":72,"_process":82,"_stream_transform":92,"assert":59,"buffer":74,"util":97}],74:[function(require,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
var base64 = require('base64-js')
var ieee754 = require('ieee754')
var isArray = require('is-array')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
Buffer.poolSize = 8192 // not used by this implementation
var kMaxLength = 0x3fffffff
var rootParent = {}
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Note:
*
* - Implementation must support adding new properties to `Uint8Array` instances.
* Firefox 4-29 lacked support, fixed in Firefox 30+.
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
*
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will
* get the Object implementation, which is slower but will work correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = (function () {
try {
var buf = new ArrayBuffer(0)
var arr = new Uint8Array(buf)
arr.foo = function () { return 42 }
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
})()
/**
* Class: Buffer
* =============
*
* The Buffer constructor returns instances of `Uint8Array` that are augmented
* with function properties for all the node `Buffer` API functions. We use
* `Uint8Array` so that square bracket notation works as expected -- it returns
* a single octet.
*
* By augmenting the instances, we can avoid modifying the `Uint8Array`
* prototype.
*/
function Buffer (subject, encoding) {
var self = this
if (!(self instanceof Buffer)) return new Buffer(subject, encoding)
var type = typeof subject
var length
if (type === 'number') {
length = +subject
} else if (type === 'string') {
length = Buffer.byteLength(subject, encoding)
} else if (type === 'object' && subject !== null) {
// assume object is array-like
if (subject.type === 'Buffer' && isArray(subject.data)) subject = subject.data
length = +subject.length
} else {
throw new TypeError('must start with number, buffer, array or string')
}
if (length > kMaxLength) {
throw new RangeError('Attempt to allocate Buffer larger than maximum size: 0x' +
kMaxLength.toString(16) + ' bytes')
}
if (length < 0) length = 0
else length >>>= 0 // coerce to uint32
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Preferred: Return an augmented `Uint8Array` instance for best performance
self = Buffer._augment(new Uint8Array(length)) // eslint-disable-line consistent-this
} else {
// Fallback: Return THIS instance of Buffer (created by `new`)
self.length = length
self._isBuffer = true
}
var i
if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
// Speed optimization -- use set if we're copying from a typed array
self._set(subject)
} else if (isArrayish(subject)) {
// Treat array-ish objects as a byte array
if (Buffer.isBuffer(subject)) {
for (i = 0; i < length; i++) {
self[i] = subject.readUInt8(i)
}
} else {
for (i = 0; i < length; i++) {
self[i] = ((subject[i] % 256) + 256) % 256
}
}
} else if (type === 'string') {
self.write(subject, 0, encoding)
} else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT) {
for (i = 0; i < length; i++) {
self[i] = 0
}
}
if (length > 0 && length <= Buffer.poolSize) self.parent = rootParent
return self
}
function SlowBuffer (subject, encoding) {
if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
var buf = new Buffer(subject, encoding)
delete buf.parent
return buf
}
Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {}
if (i !== len) {
x = a[i]
y = b[i]
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'binary':
case 'base64':
case 'raw':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, totalLength) {
if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
if (list.length === 0) {
return new Buffer(0)
} else if (list.length === 1) {
return list[0]
}
var i
if (totalLength === undefined) {
totalLength = 0
for (i = 0; i < list.length; i++) {
totalLength += list[i].length
}
}
var buf = new Buffer(totalLength)
var pos = 0
for (i = 0; i < list.length; i++) {
var item = list[i]
item.copy(buf, pos)
pos += item.length
}
return buf
}
Buffer.byteLength = function byteLength (str, encoding) {
var ret
str = str + ''
switch (encoding || 'utf8') {
case 'ascii':
case 'binary':
case 'raw':
ret = str.length
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = str.length * 2
break
case 'hex':
ret = str.length >>> 1
break
case 'utf8':
case 'utf-8':
ret = utf8ToBytes(str).length
break
case 'base64':
ret = base64ToBytes(str).length
break
default:
ret = str.length
}
return ret
}
// pre-set for values that may exist in the future
Buffer.prototype.length = undefined
Buffer.prototype.parent = undefined
// toString(encoding, start=0, end=buffer.length)
Buffer.prototype.toString = function toString (encoding, start, end) {
var loweredCase = false
start = start >>> 0
end = end === undefined || end === Infinity ? this.length : end >>> 0
if (!encoding) encoding = 'utf8'
if (start < 0) start = 0
if (end > this.length) end = this.length
if (end <= start) return ''
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'binary':
return binarySlice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return 0
return Buffer.compare(this, b)
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
else if (byteOffset < -0x80000000) byteOffset = -0x80000000
byteOffset >>= 0
if (this.length === 0) return -1
if (byteOffset >= this.length) return -1
// Negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
if (typeof val === 'string') {
if (val.length === 0) return -1 // special case: looking for empty string always fails
return String.prototype.indexOf.call(this, val, byteOffset)
}
if (Buffer.isBuffer(val)) {
return arrayIndexOf(this, val, byteOffset)
}
if (typeof val === 'number') {
if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
}
return arrayIndexOf(this, [ val ], byteOffset)
}
function arrayIndexOf (arr, val, byteOffset) {
var foundIndex = -1
for (var i = 0; byteOffset + i < arr.length; i++) {
if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
} else {
foundIndex = -1
}
}
return -1
}
throw new TypeError('val must be string, number or Buffer')
}
// `get` will be removed in Node 0.13+
Buffer.prototype.get = function get (offset) {
console.log('.get() is deprecated. Access using array indexes instead.')
return this.readUInt8(offset)
}
// `set` will be removed in Node 0.13+
Buffer.prototype.set = function set (v, offset) {
console.log('.set() is deprecated. Access using array indexes instead.')
return this.writeUInt8(v, offset)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new Error('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; i++) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(parsed)) throw new Error('Invalid hex string')
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
var charsWritten = blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
return charsWritten
}
function asciiWrite (buf, string, offset, length) {
var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
return charsWritten
}
function binaryWrite (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
return charsWritten
}
function utf16leWrite (buf, string, offset, length) {
var charsWritten = blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
return charsWritten
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Support both (string, offset, length, encoding)
// and the legacy (string, encoding, offset, length)
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length
length = undefined
}
} else { // legacy
var swap = encoding
encoding = offset
offset = length
length = swap
}
offset = Number(offset) || 0
if (length < 0 || offset < 0 || offset > this.length) {
throw new RangeError('attempt to write outside buffer bounds')
}
var remaining = this.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
encoding = String(encoding || 'utf8').toLowerCase()
var ret
switch (encoding) {
case 'hex':
ret = hexWrite(this, string, offset, length)
break
case 'utf8':
case 'utf-8':
ret = utf8Write(this, string, offset, length)
break
case 'ascii':
ret = asciiWrite(this, string, offset, length)
break
case 'binary':
ret = binaryWrite(this, string, offset, length)
break
case 'base64':
ret = base64Write(this, string, offset, length)
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = utf16leWrite(this, string, offset, length)
break
default:
throw new TypeError('Unknown encoding: ' + encoding)
}
return ret
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
var res = ''
var tmp = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
if (buf[i] <= 0x7F) {
res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
tmp = ''
} else {
tmp += '%' + buf[i].toString(16)
}
}
return res + decodeUtf8Char(tmp)
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function binarySlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; i++) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = Buffer._augment(this.subarray(start, end))
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; i++) {
newBuf[i] = this[i + start]
}
}
if (newBuf.length) newBuf.parent = this.parent || this
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
if (value > max || value < min) throw new RangeError('value is out of bounds')
if (offset + ext > buf.length) throw new RangeError('index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) >>> 0 & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) >>> 0 & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = value
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = value
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = value
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkInt(
this, value, offset, byteLength,
Math.pow(2, 8 * byteLength - 1) - 1,
-Math.pow(2, 8 * byteLength - 1)
)
}
var i = 0
var mul = 1
var sub = value < 0 ? 1 : 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkInt(
this, value, offset, byteLength,
Math.pow(2, 8 * byteLength - 1) - 1,
-Math.pow(2, 8 * byteLength - 1)
)
}
var i = byteLength - 1
var mul = 1
var sub = value < 0 ? 1 : 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = value
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = value
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (value > max || value < min) throw new RangeError('value is out of bounds')
if (offset + ext > buf.length) throw new RangeError('index out of range')
if (offset < 0) throw new RangeError('index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, target_start, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (target_start >= target.length) target_start = target.length
if (!target_start) target_start = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (target_start < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - target_start < end - start) {
end = target.length - target_start + start
}
var len = end - start
if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < len; i++) {
target[i + target_start] = this[i + start]
}
} else {
target._set(this.subarray(start, start + len), target_start)
}
return len
}
// fill(value, start=0, end=buffer.length)
Buffer.prototype.fill = function fill (value, start, end) {
if (!value) value = 0
if (!start) start = 0
if (!end) end = this.length
if (end < start) throw new RangeError('end < start')
// Fill 0 bytes; we're done
if (end === start) return
if (this.length === 0) return
if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
var i
if (typeof value === 'number') {
for (i = start; i < end; i++) {
this[i] = value
}
} else {
var bytes = utf8ToBytes(value.toString())
var len = bytes.length
for (i = start; i < end; i++) {
this[i] = bytes[i % len]
}
}
return this
}
/**
* Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
* Added in Node 0.12. Only available in browsers that support ArrayBuffer.
*/
Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
if (typeof Uint8Array !== 'undefined') {
if (Buffer.TYPED_ARRAY_SUPPORT) {
return (new Buffer(this)).buffer
} else {
var buf = new Uint8Array(this.length)
for (var i = 0, len = buf.length; i < len; i += 1) {
buf[i] = this[i]
}
return buf.buffer
}
} else {
throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
}
}
// HELPER FUNCTIONS
// ================
var BP = Buffer.prototype
/**
* Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
*/
Buffer._augment = function _augment (arr) {
arr.constructor = Buffer
arr._isBuffer = true
// save reference to original Uint8Array set method before overwriting
arr._set = arr.set
// deprecated, will be removed in node 0.13+
arr.get = BP.get
arr.set = BP.set
arr.write = BP.write
arr.toString = BP.toString
arr.toLocaleString = BP.toString
arr.toJSON = BP.toJSON
arr.equals = BP.equals
arr.compare = BP.compare
arr.indexOf = BP.indexOf
arr.copy = BP.copy
arr.slice = BP.slice
arr.readUIntLE = BP.readUIntLE
arr.readUIntBE = BP.readUIntBE
arr.readUInt8 = BP.readUInt8
arr.readUInt16LE = BP.readUInt16LE
arr.readUInt16BE = BP.readUInt16BE
arr.readUInt32LE = BP.readUInt32LE
arr.readUInt32BE = BP.readUInt32BE
arr.readIntLE = BP.readIntLE
arr.readIntBE = BP.readIntBE
arr.readInt8 = BP.readInt8
arr.readInt16LE = BP.readInt16LE
arr.readInt16BE = BP.readInt16BE
arr.readInt32LE = BP.readInt32LE
arr.readInt32BE = BP.readInt32BE
arr.readFloatLE = BP.readFloatLE
arr.readFloatBE = BP.readFloatBE
arr.readDoubleLE = BP.readDoubleLE
arr.readDoubleBE = BP.readDoubleBE
arr.writeUInt8 = BP.writeUInt8
arr.writeUIntLE = BP.writeUIntLE
arr.writeUIntBE = BP.writeUIntBE
arr.writeUInt16LE = BP.writeUInt16LE
arr.writeUInt16BE = BP.writeUInt16BE
arr.writeUInt32LE = BP.writeUInt32LE
arr.writeUInt32BE = BP.writeUInt32BE
arr.writeIntLE = BP.writeIntLE
arr.writeIntBE = BP.writeIntBE
arr.writeInt8 = BP.writeInt8
arr.writeInt16LE = BP.writeInt16LE
arr.writeInt16BE = BP.writeInt16BE
arr.writeInt32LE = BP.writeInt32LE
arr.writeInt32BE = BP.writeInt32BE
arr.writeFloatLE = BP.writeFloatLE
arr.writeFloatBE = BP.writeFloatBE
arr.writeDoubleLE = BP.writeDoubleLE
arr.writeDoubleBE = BP.writeDoubleBE
arr.fill = BP.fill
arr.inspect = BP.inspect
arr.toArrayBuffer = BP.toArrayBuffer
return arr
}
var INVALID_BASE64_RE = /[^+\/0-9A-z\-]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function isArrayish (subject) {
return isArray(subject) || Buffer.isBuffer(subject) ||
subject && typeof subject === 'object' &&
typeof subject.length === 'number'
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
var i = 0
for (; i < length; i++) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (leadSurrogate) {
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
} else {
// valid surrogate pair
codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
leadSurrogate = null
}
} else {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else {
// valid lead
leadSurrogate = codePoint
continue
}
}
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = null
}
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x200000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; i++) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; i++) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
function decodeUtf8Char (str) {
try {
return decodeURIComponent(str)
} catch (err) {
return String.fromCharCode(0xFFFD) // UTF 8 invalid char
}
}
},{"base64-js":75,"ieee754":76,"is-array":77}],75:[function(require,module,exports){
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
;(function (exports) {
'use strict';
var Arr = (typeof Uint8Array !== 'undefined')
? Uint8Array
: Array
var PLUS = '+'.charCodeAt(0)
var SLASH = '/'.charCodeAt(0)
var NUMBER = '0'.charCodeAt(0)
var LOWER = 'a'.charCodeAt(0)
var UPPER = 'A'.charCodeAt(0)
var PLUS_URL_SAFE = '-'.charCodeAt(0)
var SLASH_URL_SAFE = '_'.charCodeAt(0)
function decode (elt) {
var code = elt.charCodeAt(0)
if (code === PLUS ||
code === PLUS_URL_SAFE)
return 62 // '+'
if (code === SLASH ||
code === SLASH_URL_SAFE)
return 63 // '/'
if (code < NUMBER)
return -1 //no match
if (code < NUMBER + 10)
return code - NUMBER + 26 + 26
if (code < UPPER + 26)
return code - UPPER
if (code < LOWER + 26)
return code - LOWER + 26
}
function b64ToByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
if (b64.length % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
var len = b64.length
placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
// base64 is 4/3 + up to two characters of the original data
arr = new Arr(b64.length * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? b64.length - 4 : b64.length
var L = 0
function push (v) {
arr[L++] = v
}
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
push((tmp & 0xFF0000) >> 16)
push((tmp & 0xFF00) >> 8)
push(tmp & 0xFF)
}
if (placeHolders === 2) {
tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
push(tmp & 0xFF)
} else if (placeHolders === 1) {
tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
push((tmp >> 8) & 0xFF)
push(tmp & 0xFF)
}
return arr
}
function uint8ToBase64 (uint8) {
var i,
extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
output = "",
temp, length
function encode (num) {
return lookup.charAt(num)
}
function tripletToBase64 (num) {
return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
}
// go through the array every three bytes, we'll deal with trailing stuff later
for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output += tripletToBase64(temp)
}
// pad the end with zeros, but make sure to not forget the extra bytes
switch (extraBytes) {
case 1:
temp = uint8[uint8.length - 1]
output += encode(temp >> 2)
output += encode((temp << 4) & 0x3F)
output += '=='
break
case 2:
temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
output += encode(temp >> 10)
output += encode((temp >> 4) & 0x3F)
output += encode((temp << 2) & 0x3F)
output += '='
break
}
return output
}
exports.toByteArray = b64ToByteArray
exports.fromByteArray = uint8ToBase64
}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
},{}],76:[function(require,module,exports){
exports.read = function(buffer, offset, isLE, mLen, nBytes) {
var e, m,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
nBits = -7,
i = isLE ? (nBytes - 1) : 0,
d = isLE ? -1 : 1,
s = buffer[offset + i];
i += d;
e = s & ((1 << (-nBits)) - 1);
s >>= (-nBits);
nBits += eLen;
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
m = e & ((1 << (-nBits)) - 1);
e >>= (-nBits);
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity);
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};
exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
i = isLE ? 0 : (nBytes - 1),
d = isLE ? 1 : -1,
s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
value = Math.abs(value);
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value) / Math.LN2);
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * Math.pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
e = (e << mLen) | m;
eLen += mLen;
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
buffer[offset + i - d] |= s * 128;
};
},{}],77:[function(require,module,exports){
/**
* isArray
*/
var isArray = Array.isArray;
/**
* toString
*/
var str = Object.prototype.toString;
/**
* Whether or not the given `val`
* is an array.
*
* example:
*
* isArray([]);
* // > true
* isArray(arguments);
* // > false
* isArray('');
* // > false
*
* @param {mixed} val
* @return {bool}
*/
module.exports = isArray || function (val) {
return !! val && '[object Array]' == str.call(val);
};
},{}],78:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
handler.apply(this, args);
}
} else if (isObject(handler)) {
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
var m;
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.listenerCount = function(emitter, type) {
var ret;
if (!emitter._events || !emitter._events[type])
ret = 0;
else if (isFunction(emitter._events[type]))
ret = 1;
else
ret = emitter._events[type].length;
return ret;
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],79:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],80:[function(require,module,exports){
module.exports = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
},{}],81:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
return splitPathRe.exec(filename).slice(1);
};
// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
return !!p;
}), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(filter(path.split('/'), function(p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function(path) {
return path.charAt(0) === '/';
};
// posix version
exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(filter(paths, function(p, index) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
};
// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function(path) {
var result = splitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
exports.basename = function(path, ext) {
var f = splitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function(path) {
return splitPath(path)[3];
};
function filter (xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b'
? function (str, start, len) { return str.substr(start, len) }
: function (str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
}
;
}).call(this,require('_process'))
},{"_process":82}],82:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
function drainQueue() {
if (draining) {
return;
}
draining = true;
var currentQueue;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
var i = -1;
while (++i < len) {
currentQueue[i]();
}
len = queue.length;
}
draining = false;
}
process.nextTick = function (fun) {
queue.push(fun);
if (!draining) {
setTimeout(drainQueue, 0);
}
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],83:[function(require,module,exports){
module.exports = require("./lib/_stream_duplex.js")
},{"./lib/_stream_duplex.js":84}],84:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
module.exports = Duplex;
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
/*</replacement>*/
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
util.inherits(Duplex, Readable);
forEach(objectKeys(Writable.prototype), function(method) {
if (!Duplex.prototype[method])
Duplex.prototype[method] = Writable.prototype[method];
});
function Duplex(options) {
if (!(this instanceof Duplex))
return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false)
this.readable = false;
if (options && options.writable === false)
this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false)
this.allowHalfOpen = false;
this.once('end', onend);
}
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended)
return;
// no more data can be written.
// But allow more writes to happen in this tick.
process.nextTick(this.end.bind(this));
}
function forEach (xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
}).call(this,require('_process'))
},{"./_stream_readable":86,"./_stream_writable":88,"_process":82,"core-util-is":89,"inherits":79}],85:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
module.exports = PassThrough;
var Transform = require('./_stream_transform');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough))
return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function(chunk, encoding, cb) {
cb(null, chunk);
};
},{"./_stream_transform":87,"core-util-is":89,"inherits":79}],86:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
module.exports = Readable;
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
Readable.ReadableState = ReadableState;
var EE = require('events').EventEmitter;
/*<replacement>*/
if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
var Stream = require('stream');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var StringDecoder;
/*<replacement>*/
var debug = require('util');
if (debug && debug.debuglog) {
debug = debug.debuglog('stream');
} else {
debug = function () {};
}
/*</replacement>*/
util.inherits(Readable, Stream);
function ReadableState(options, stream) {
var Duplex = require('./_stream_duplex');
options = options || {};
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var defaultHwm = options.objectMode ? 16 : 16 * 1024;
this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.buffer = [];
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex)
this.objectMode = this.objectMode || !!options.readableObjectMode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// when piping, we only care about 'readable' events that happen
// after read()ing all the bytes and not getting any pushback.
this.ranOut = false;
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder)
StringDecoder = require('string_decoder/').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
var Duplex = require('./_stream_duplex');
if (!(this instanceof Readable))
return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
Stream.call(this);
}
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function(chunk, encoding) {
var state = this._readableState;
if (util.isString(chunk) && !state.objectMode) {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = new Buffer(chunk, encoding);
encoding = '';
}
}
return readableAddChunk(this, state, chunk, encoding, false);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function(chunk) {
var state = this._readableState;
return readableAddChunk(this, state, chunk, '', true);
};
function readableAddChunk(stream, state, chunk, encoding, addToFront) {
var er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (util.isNullOrUndefined(chunk)) {
state.reading = false;
if (!state.ended)
onEofChunk(stream, state);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (state.ended && !addToFront) {
var e = new Error('stream.push() after EOF');
stream.emit('error', e);
} else if (state.endEmitted && addToFront) {
var e = new Error('stream.unshift() after end event');
stream.emit('error', e);
} else {
if (state.decoder && !addToFront && !encoding)
chunk = state.decoder.write(chunk);
if (!addToFront)
state.reading = false;
// if we want the data now, just emit it.
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront)
state.buffer.unshift(chunk);
else
state.buffer.push(chunk);
if (state.needReadable)
emitReadable(stream);
}
maybeReadMore(stream, state);
}
} else if (!addToFront) {
state.reading = false;
}
return needMoreData(state);
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended &&
(state.needReadable ||
state.length < state.highWaterMark ||
state.length === 0);
}
// backwards compatibility.
Readable.prototype.setEncoding = function(enc) {
if (!StringDecoder)
StringDecoder = require('string_decoder/').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 128MB
var MAX_HWM = 0x800000;
function roundUpToNextPowerOf2(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2
n--;
for (var p = 1; p < 32; p <<= 1) n |= n >> p;
n++;
}
return n;
}
function howMuchToRead(n, state) {
if (state.length === 0 && state.ended)
return 0;
if (state.objectMode)
return n === 0 ? 0 : 1;
if (isNaN(n) || util.isNull(n)) {
// only flow one buffer at a time
if (state.flowing && state.buffer.length)
return state.buffer[0].length;
else
return state.length;
}
if (n <= 0)
return 0;
// If we're asking for more than the target buffer level,
// then raise the water mark. Bump up to the next highest
// power of 2, to prevent increasing it excessively in tiny
// amounts.
if (n > state.highWaterMark)
state.highWaterMark = roundUpToNextPowerOf2(n);
// don't have that much. return null, unless we've ended.
if (n > state.length) {
if (!state.ended) {
state.needReadable = true;
return 0;
} else
return state.length;
}
return n;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function(n) {
debug('read', n);
var state = this._readableState;
var nOrig = n;
if (!util.isNumber(n) || n > 0)
state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 &&
state.needReadable &&
(state.length >= state.highWaterMark || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended)
endReadable(this);
else
emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0)
endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
}
if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0)
state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
}
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (doRead && !state.reading)
n = howMuchToRead(nOrig, state);
var ret;
if (n > 0)
ret = fromList(n, state);
else
ret = null;
if (util.isNull(ret)) {
state.needReadable = true;
n = 0;
}
state.length -= n;
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (state.length === 0 && !state.ended)
state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended && state.length === 0)
endReadable(this);
if (!util.isNull(ret))
this.emit('data', ret);
return ret;
};
function chunkInvalid(state, chunk) {
var er = null;
if (!util.isBuffer(chunk) &&
!util.isString(chunk) &&
!util.isNullOrUndefined(chunk) &&
!state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
function onEofChunk(stream, state) {
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// emit 'readable' now to make sure it gets picked up.
emitReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
if (state.sync)
process.nextTick(function() {
emitReadable_(stream);
});
else
emitReadable_(stream);
}
}
function emitReadable_(stream) {
debug('emit readable');
stream.emit('readable');
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
process.nextTick(function() {
maybeReadMore_(stream, state);
});
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended &&
state.length < state.highWaterMark) {
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;
else
len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function(n) {
this.emit('error', new Error('not implemented'));
};
Readable.prototype.pipe = function(dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
dest !== process.stdout &&
dest !== process.stderr;
var endFn = doEnd ? onend : cleanup;
if (state.endEmitted)
process.nextTick(endFn);
else
src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable) {
debug('onunpipe');
if (readable === src) {
cleanup();
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', cleanup);
src.removeListener('data', ondata);
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain &&
(!dest._writableState || dest._writableState.needDrain))
ondrain();
}
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
var ret = dest.write(chunk);
if (false === ret) {
debug('false write response, pause',
src._readableState.awaitDrain);
src._readableState.awaitDrain++;
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EE.listenerCount(dest, 'error') === 0)
dest.emit('error', er);
}
// This is a brutally ugly hack to make sure that our error handler
// is attached before any userland ones. NEVER DO THIS.
if (!dest._events || !dest._events.error)
dest.on('error', onerror);
else if (isArray(dest._events.error))
dest._events.error.unshift(onerror);
else
dest._events.error = [onerror, dest._events.error];
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function() {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain)
state.awaitDrain--;
if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function(dest) {
var state = this._readableState;
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0)
return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes)
return this;
if (!dest)
dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest)
dest.emit('unpipe', this);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var i = 0; i < len; i++)
dests[i].emit('unpipe', this);
return this;
}
// try to find the right one.
var i = indexOf(state.pipes, dest);
if (i === -1)
return this;
state.pipes.splice(i, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1)
state.pipes = state.pipes[0];
dest.emit('unpipe', this);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function(ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
// If listening to data, and it has not explicitly been paused,
// then call resume to start the flow of data on the next tick.
if (ev === 'data' && false !== this._readableState.flowing) {
this.resume();
}
if (ev === 'readable' && this.readable) {
var state = this._readableState;
if (!state.readableListening) {
state.readableListening = true;
state.emittedReadable = false;
state.needReadable = true;
if (!state.reading) {
var self = this;
process.nextTick(function() {
debug('readable nexttick read 0');
self.read(0);
});
} else if (state.length) {
emitReadable(this, state);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function() {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
state.flowing = true;
if (!state.reading) {
debug('resume read 0');
this.read(0);
}
resume(this, state);
}
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
process.nextTick(function() {
resume_(stream, state);
});
}
}
function resume_(stream, state) {
state.resumeScheduled = false;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading)
stream.read(0);
}
Readable.prototype.pause = function() {
debug('call pause flowing=%j', this._readableState.flowing);
if (false !== this._readableState.flowing) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
if (state.flowing) {
do {
var chunk = stream.read();
} while (null !== chunk && state.flowing);
}
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function(stream) {
var state = this._readableState;
var paused = false;
var self = this;
stream.on('end', function() {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length)
self.push(chunk);
}
self.push(null);
});
stream.on('data', function(chunk) {
debug('wrapped data');
if (state.decoder)
chunk = state.decoder.write(chunk);
if (!chunk || !state.objectMode && !chunk.length)
return;
var ret = self.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
this[i] = function(method) { return function() {
return stream[method].apply(stream, arguments);
}}(i);
}
}
// proxy certain important events.
var events = ['error', 'close', 'destroy', 'pause', 'resume'];
forEach(events, function(ev) {
stream.on(ev, self.emit.bind(self, ev));
});
// when we try to consume some more bytes, simply unpause the
// underlying stream.
self._read = function(n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return self;
};
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
function fromList(n, state) {
var list = state.buffer;
var length = state.length;
var stringMode = !!state.decoder;
var objectMode = !!state.objectMode;
var ret;
// nothing in the list, definitely empty.
if (list.length === 0)
return null;
if (length === 0)
ret = null;
else if (objectMode)
ret = list.shift();
else if (!n || n >= length) {
// read it all, truncate the array.
if (stringMode)
ret = list.join('');
else
ret = Buffer.concat(list, length);
list.length = 0;
} else {
// read just some of it.
if (n < list[0].length) {
// just take a part of the first list item.
// slice is the same for buffers and strings.
var buf = list[0];
ret = buf.slice(0, n);
list[0] = buf.slice(n);
} else if (n === list[0].length) {
// first list is a perfect match
ret = list.shift();
} else {
// complex case.
// we have enough to cover it, but it spans past the first buffer.
if (stringMode)
ret = '';
else
ret = new Buffer(n);
var c = 0;
for (var i = 0, l = list.length; i < l && c < n; i++) {
var buf = list[0];
var cpy = Math.min(n - c, buf.length);
if (stringMode)
ret += buf.slice(0, cpy);
else
buf.copy(ret, c, 0, cpy);
if (cpy < buf.length)
list[0] = buf.slice(cpy);
else
list.shift();
c += cpy;
}
}
}
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0)
throw new Error('endReadable called on non-empty stream');
if (!state.endEmitted) {
state.ended = true;
process.nextTick(function() {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
});
}
}
function forEach (xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
function indexOf (xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
}).call(this,require('_process'))
},{"./_stream_duplex":84,"_process":82,"buffer":74,"core-util-is":89,"events":78,"inherits":79,"isarray":80,"stream":94,"string_decoder/":95,"util":60}],87:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
module.exports = Transform;
var Duplex = require('./_stream_duplex');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(Transform, Duplex);
function TransformState(options, stream) {
this.afterTransform = function(er, data) {
return afterTransform(stream, er, data);
};
this.needTransform = false;
this.transforming = false;
this.writecb = null;
this.writechunk = null;
}
function afterTransform(stream, er, data) {
var ts = stream._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb)
return stream.emit('error', new Error('no writecb in Transform class'));
ts.writechunk = null;
ts.writecb = null;
if (!util.isNullOrUndefined(data))
stream.push(data);
if (cb)
cb(er);
var rs = stream._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
stream._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform))
return new Transform(options);
Duplex.call(this, options);
this._transformState = new TransformState(options, this);
// when the writable side finishes, then flush out anything remaining.
var stream = this;
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
this.once('prefinish', function() {
if (util.isFunction(this._flush))
this._flush(function(er) {
done(stream, er);
});
else
done(stream);
});
}
Transform.prototype.push = function(chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function(chunk, encoding, cb) {
throw new Error('not implemented');
};
Transform.prototype._write = function(chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform ||
rs.needReadable ||
rs.length < rs.highWaterMark)
this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function(n) {
var ts = this._transformState;
if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
function done(stream, er) {
if (er)
return stream.emit('error', er);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
var ws = stream._writableState;
var ts = stream._transformState;
if (ws.length)
throw new Error('calling transform done when ws.length != 0');
if (ts.transforming)
throw new Error('calling transform done when still transforming');
return stream.push(null);
}
},{"./_stream_duplex":84,"core-util-is":89,"inherits":79}],88:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, cb), and it'll handle all
// the drain event emission and buffering.
module.exports = Writable;
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var Stream = require('stream');
util.inherits(Writable, Stream);
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
}
function WritableState(options, stream) {
var Duplex = require('./_stream_duplex');
options = options || {};
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var defaultHwm = options.objectMode ? 16 : 16 * 1024;
this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex)
this.objectMode = this.objectMode || !!options.writableObjectMode;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function(er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.buffer = [];
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
}
function Writable(options) {
var Duplex = require('./_stream_duplex');
// Writable ctor is applied to Duplexes, though they're not
// instanceof Writable, they're instanceof Readable.
if (!(this instanceof Writable) && !(this instanceof Duplex))
return new Writable(options);
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function() {
this.emit('error', new Error('Cannot pipe. Not readable.'));
};
function writeAfterEnd(stream, state, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
}
// If we get something that is not a buffer, string, null, or undefined,
// and we're not in objectMode, then that's an error.
// Otherwise stream chunks are all considered to be of length=1, and the
// watermarks determine how many objects to keep in the buffer, rather than
// how many bytes or characters.
function validChunk(stream, state, chunk, cb) {
var valid = true;
if (!util.isBuffer(chunk) &&
!util.isString(chunk) &&
!util.isNullOrUndefined(chunk) &&
!state.objectMode) {
var er = new TypeError('Invalid non-string/buffer chunk');
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
valid = false;
}
return valid;
}
Writable.prototype.write = function(chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
if (util.isFunction(encoding)) {
cb = encoding;
encoding = null;
}
if (util.isBuffer(chunk))
encoding = 'buffer';
else if (!encoding)
encoding = state.defaultEncoding;
if (!util.isFunction(cb))
cb = function() {};
if (state.ended)
writeAfterEnd(this, state, cb);
else if (validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function() {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function() {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing &&
!state.corked &&
!state.finished &&
!state.bufferProcessing &&
state.buffer.length)
clearBuffer(this, state);
}
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode &&
state.decodeStrings !== false &&
util.isString(chunk)) {
chunk = new Buffer(chunk, encoding);
}
return chunk;
}
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding);
if (util.isBuffer(chunk))
encoding = 'buffer';
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret)
state.needDrain = true;
if (state.writing || state.corked)
state.buffer.push(new WriteReq(chunk, encoding, cb));
else
doWrite(stream, state, false, len, chunk, encoding, cb);
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev)
stream._writev(chunk, state.onwrite);
else
stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
if (sync)
process.nextTick(function() {
state.pendingcb--;
cb(er);
});
else {
state.pendingcb--;
cb(er);
}
stream._writableState.errorEmitted = true;
stream.emit('error', er);
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er)
onwriteError(stream, state, sync, er, cb);
else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(stream, state);
if (!finished &&
!state.corked &&
!state.bufferProcessing &&
state.buffer.length) {
clearBuffer(stream, state);
}
if (sync) {
process.nextTick(function() {
afterWrite(stream, state, finished, cb);
});
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished)
onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
if (stream._writev && state.buffer.length > 1) {
// Fast case, write everything using _writev()
var cbs = [];
for (var c = 0; c < state.buffer.length; c++)
cbs.push(state.buffer[c].callback);
// count the one we are adding, as well.
// TODO(isaacs) clean this up
state.pendingcb++;
doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
for (var i = 0; i < cbs.length; i++) {
state.pendingcb--;
cbs[i](err);
}
});
// Clear buffer
state.buffer = [];
} else {
// Slow case, write chunks one-by-one
for (var c = 0; c < state.buffer.length; c++) {
var entry = state.buffer[c];
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
c++;
break;
}
}
if (c < state.buffer.length)
state.buffer = state.buffer.slice(c);
else
state.buffer.length = 0;
}
state.bufferProcessing = false;
}
Writable.prototype._write = function(chunk, encoding, cb) {
cb(new Error('not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function(chunk, encoding, cb) {
var state = this._writableState;
if (util.isFunction(chunk)) {
cb = chunk;
chunk = null;
encoding = null;
} else if (util.isFunction(encoding)) {
cb = encoding;
encoding = null;
}
if (!util.isNullOrUndefined(chunk))
this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished)
endWritable(this, state, cb);
};
function needFinish(stream, state) {
return (state.ending &&
state.length === 0 &&
!state.finished &&
!state.writing);
}
function prefinish(stream, state) {
if (!state.prefinished) {
state.prefinished = true;
stream.emit('prefinish');
}
}
function finishMaybe(stream, state) {
var need = needFinish(stream, state);
if (need) {
if (state.pendingcb === 0) {
prefinish(stream, state);
state.finished = true;
stream.emit('finish');
} else
prefinish(stream, state);
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished)
process.nextTick(cb);
else
stream.once('finish', cb);
}
state.ended = true;
}
}).call(this,require('_process'))
},{"./_stream_duplex":84,"_process":82,"buffer":74,"core-util-is":89,"inherits":79,"stream":94}],89:[function(require,module,exports){
(function (Buffer){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
function isBuffer(arg) {
return Buffer.isBuffer(arg);
}
exports.isBuffer = isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this,require("buffer").Buffer)
},{"buffer":74}],90:[function(require,module,exports){
module.exports = require("./lib/_stream_passthrough.js")
},{"./lib/_stream_passthrough.js":85}],91:[function(require,module,exports){
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = require('stream');
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
},{"./lib/_stream_duplex.js":84,"./lib/_stream_passthrough.js":85,"./lib/_stream_readable.js":86,"./lib/_stream_transform.js":87,"./lib/_stream_writable.js":88,"stream":94}],92:[function(require,module,exports){
module.exports = require("./lib/_stream_transform.js")
},{"./lib/_stream_transform.js":87}],93:[function(require,module,exports){
module.exports = require("./lib/_stream_writable.js")
},{"./lib/_stream_writable.js":88}],94:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
module.exports = Stream;
var EE = require('events').EventEmitter;
var inherits = require('inherits');
inherits(Stream, EE);
Stream.Readable = require('readable-stream/readable.js');
Stream.Writable = require('readable-stream/writable.js');
Stream.Duplex = require('readable-stream/duplex.js');
Stream.Transform = require('readable-stream/transform.js');
Stream.PassThrough = require('readable-stream/passthrough.js');
// Backwards-compat with node 0.4.x
Stream.Stream = Stream;
// old-style streams. Note that the pipe method (the only relevant
// part of this class) is overridden in the Readable class.
function Stream() {
EE.call(this);
}
Stream.prototype.pipe = function(dest, options) {
var source = this;
function ondata(chunk) {
if (dest.writable) {
if (false === dest.write(chunk) && source.pause) {
source.pause();
}
}
}
source.on('data', ondata);
function ondrain() {
if (source.readable && source.resume) {
source.resume();
}
}
dest.on('drain', ondrain);
// If the 'end' option is not supplied, dest.end() will be called when
// source gets the 'end' or 'close' events. Only dest.end() once.
if (!dest._isStdio && (!options || options.end !== false)) {
source.on('end', onend);
source.on('close', onclose);
}
var didOnEnd = false;
function onend() {
if (didOnEnd) return;
didOnEnd = true;
dest.end();
}
function onclose() {
if (didOnEnd) return;
didOnEnd = true;
if (typeof dest.destroy === 'function') dest.destroy();
}
// don't leave dangling pipes when there are errors.
function onerror(er) {
cleanup();
if (EE.listenerCount(this, 'error') === 0) {
throw er; // Unhandled stream error in pipe.
}
}
source.on('error', onerror);
dest.on('error', onerror);
// remove all the event listeners that were added.
function cleanup() {
source.removeListener('data', ondata);
dest.removeListener('drain', ondrain);
source.removeListener('end', onend);
source.removeListener('close', onclose);
source.removeListener('error', onerror);
dest.removeListener('error', onerror);
source.removeListener('end', cleanup);
source.removeListener('close', cleanup);
dest.removeListener('close', cleanup);
}
source.on('end', cleanup);
source.on('close', cleanup);
dest.on('close', cleanup);
dest.emit('pipe', source);
// Allow for unix-like usage: A.pipe(B).pipe(C)
return dest;
};
},{"events":78,"inherits":79,"readable-stream/duplex.js":83,"readable-stream/passthrough.js":90,"readable-stream/readable.js":91,"readable-stream/transform.js":92,"readable-stream/writable.js":93}],95:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var Buffer = require('buffer').Buffer;
var isBufferEncoding = Buffer.isEncoding
|| function(encoding) {
switch (encoding && encoding.toLowerCase()) {
case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
default: return false;
}
}
function assertEncoding(encoding) {
if (encoding && !isBufferEncoding(encoding)) {
throw new Error('Unknown encoding: ' + encoding);
}
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters. CESU-8 is handled as part of the UTF-8 encoding.
//
// @TODO Handling all encodings inside a single object makes it very difficult
// to reason about this code, so it should be split up in the future.
// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
// points as used by CESU-8.
var StringDecoder = exports.StringDecoder = function(encoding) {
this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
assertEncoding(encoding);
switch (this.encoding) {
case 'utf8':
// CESU-8 represents each of Surrogate Pair by 3-bytes
this.surrogateSize = 3;
break;
case 'ucs2':
case 'utf16le':
// UTF-16 represents each of Surrogate Pair by 2-bytes
this.surrogateSize = 2;
this.detectIncompleteChar = utf16DetectIncompleteChar;
break;
case 'base64':
// Base-64 stores 3 bytes in 4 chars, and pads the remainder.
this.surrogateSize = 3;
this.detectIncompleteChar = base64DetectIncompleteChar;
break;
default:
this.write = passThroughWrite;
return;
}
// Enough space to store all bytes of a single character. UTF-8 needs 4
// bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
this.charBuffer = new Buffer(6);
// Number of bytes received for the current incomplete multi-byte character.
this.charReceived = 0;
// Number of bytes expected for the current incomplete multi-byte character.
this.charLength = 0;
};
// write decodes the given buffer and returns it as JS string that is
// guaranteed to not contain any partial multi-byte characters. Any partial
// character found at the end of the buffer is buffered up, and will be
// returned when calling write again with the remaining bytes.
//
// Note: Converting a Buffer containing an orphan surrogate to a String
// currently works, but converting a String to a Buffer (via `new Buffer`, or
// Buffer#write) will replace incomplete surrogates with the unicode
// replacement character. See https://codereview.chromium.org/121173009/ .
StringDecoder.prototype.write = function(buffer) {
var charStr = '';
// if our last write ended with an incomplete multibyte character
while (this.charLength) {
// determine how many remaining bytes this buffer has to offer for this char
var available = (buffer.length >= this.charLength - this.charReceived) ?
this.charLength - this.charReceived :
buffer.length;
// add the new bytes to the char buffer
buffer.copy(this.charBuffer, this.charReceived, 0, available);
this.charReceived += available;
if (this.charReceived < this.charLength) {
// still not enough chars in this buffer? wait for more ...
return '';
}
// remove bytes belonging to the current character from the buffer
buffer = buffer.slice(available, buffer.length);
// get the character that was split
charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
var charCode = charStr.charCodeAt(charStr.length - 1);
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
this.charLength += this.surrogateSize;
charStr = '';
continue;
}
this.charReceived = this.charLength = 0;
// if there are no more bytes in this buffer, just emit our char
if (buffer.length === 0) {
return charStr;
}
break;
}
// determine and set charLength / charReceived
this.detectIncompleteChar(buffer);
var end = buffer.length;
if (this.charLength) {
// buffer the incomplete character bytes we got
buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
end -= this.charReceived;
}
charStr += buffer.toString(this.encoding, 0, end);
var end = charStr.length - 1;
var charCode = charStr.charCodeAt(end);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
var size = this.surrogateSize;
this.charLength += size;
this.charReceived += size;
this.charBuffer.copy(this.charBuffer, size, 0, size);
buffer.copy(this.charBuffer, 0, 0, size);
return charStr.substring(0, end);
}
// or just emit the charStr
return charStr;
};
// detectIncompleteChar determines if there is an incomplete UTF-8 character at
// the end of the given buffer. If so, it sets this.charLength to the byte
// length that character, and sets this.charReceived to the number of bytes
// that are available for this character.
StringDecoder.prototype.detectIncompleteChar = function(buffer) {
// determine how many bytes we have to check at the end of this buffer
var i = (buffer.length >= 3) ? 3 : buffer.length;
// Figure out if one of the last i bytes of our buffer announces an
// incomplete char.
for (; i > 0; i--) {
var c = buffer[buffer.length - i];
// See http://en.wikipedia.org/wiki/UTF-8#Description
// 110XXXXX
if (i == 1 && c >> 5 == 0x06) {
this.charLength = 2;
break;
}
// 1110XXXX
if (i <= 2 && c >> 4 == 0x0E) {
this.charLength = 3;
break;
}
// 11110XXX
if (i <= 3 && c >> 3 == 0x1E) {
this.charLength = 4;
break;
}
}
this.charReceived = i;
};
StringDecoder.prototype.end = function(buffer) {
var res = '';
if (buffer && buffer.length)
res = this.write(buffer);
if (this.charReceived) {
var cr = this.charReceived;
var buf = this.charBuffer;
var enc = this.encoding;
res += buf.slice(0, cr).toString(enc);
}
return res;
};
function passThroughWrite(buffer) {
return buffer.toString(this.encoding);
}
function utf16DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 2;
this.charLength = this.charReceived ? 2 : 0;
}
function base64DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 3;
this.charLength = this.charReceived ? 3 : 0;
}
},{"buffer":74}],96:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],97:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":96,"_process":82,"inherits":79}],98:[function(require,module,exports){
var indexOf = require('indexof');
var Object_keys = function (obj) {
if (Object.keys) return Object.keys(obj)
else {
var res = [];
for (var key in obj) res.push(key)
return res;
}
};
var forEach = function (xs, fn) {
if (xs.forEach) return xs.forEach(fn)
else for (var i = 0; i < xs.length; i++) {
fn(xs[i], i, xs);
}
};
var defineProp = (function() {
try {
Object.defineProperty({}, '_', {});
return function(obj, name, value) {
Object.defineProperty(obj, name, {
writable: true,
enumerable: false,
configurable: true,
value: value
})
};
} catch(e) {
return function(obj, name, value) {
obj[name] = value;
};
}
}());
var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function',
'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError',
'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError',
'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape',
'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape'];
function Context() {}
Context.prototype = {};
var Script = exports.Script = function NodeScript (code) {
if (!(this instanceof Script)) return new Script(code);
this.code = code;
};
Script.prototype.runInContext = function (context) {
if (!(context instanceof Context)) {
throw new TypeError("needs a 'context' argument.");
}
var iframe = document.createElement('iframe');
if (!iframe.style) iframe.style = {};
iframe.style.display = 'none';
document.body.appendChild(iframe);
var win = iframe.contentWindow;
var wEval = win.eval, wExecScript = win.execScript;
if (!wEval && wExecScript) {
// win.eval() magically appears when this is called in IE:
wExecScript.call(win, 'null');
wEval = win.eval;
}
forEach(Object_keys(context), function (key) {
win[key] = context[key];
});
forEach(globals, function (key) {
if (context[key]) {
win[key] = context[key];
}
});
var winKeys = Object_keys(win);
var res = wEval.call(win, this.code);
forEach(Object_keys(win), function (key) {
// Avoid copying circular objects like `top` and `window` by only
// updating existing context properties or new properties in the `win`
// that was only introduced after the eval.
if (key in context || indexOf(winKeys, key) === -1) {
context[key] = win[key];
}
});
forEach(globals, function (key) {
if (!(key in context)) {
defineProp(context, key, win[key]);
}
});
document.body.removeChild(iframe);
return res;
};
Script.prototype.runInThisContext = function () {
return eval(this.code); // maybe...
};
Script.prototype.runInNewContext = function (context) {
var ctx = Script.createContext(context);
var res = this.runInContext(ctx);
forEach(Object_keys(ctx), function (key) {
context[key] = ctx[key];
});
return res;
};
forEach(Object_keys(Script.prototype), function (name) {
exports[name] = Script[name] = function (code) {
var s = Script(code);
return s[name].apply(s, [].slice.call(arguments, 1));
};
});
exports.createScript = function (code) {
return exports.Script(code);
};
exports.createContext = Script.createContext = function (context) {
var copy = new Context();
if(typeof context === 'object') {
forEach(Object_keys(context), function (key) {
copy[key] = context[key];
});
}
return copy;
};
},{"indexof":99}],99:[function(require,module,exports){
var indexOf = [].indexOf;
module.exports = function(arr, obj){
if (indexOf) return arr.indexOf(obj);
for (var i = 0; i < arr.length; ++i) {
if (arr[i] === obj) return i;
}
return -1;
};
},{}]},{},[1]);