magica
Version:
ImageMagick for browser and Node.js, easy setup, high level API and Command Line Interface, including WASM binary for an easy setup.
1 lines • 947 kB
JavaScript
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.magica=f()}})((function(){var define,module,exports;return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,(function(r){var n=e[i][1][r];return o(n||r)}),p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r}()({1:[function(require,module,exports){(function(Buffer){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});const assert_1=require("assert");const cross_fetch_1=__importDefault(require("cross-fetch"));const fs_1=require("fs");const misc_utils_of_mine_generic_1=require("misc-utils-of-mine-generic");const html_1=require("../image/html");const imageCompare_1=require("../image/imageCompare");const imageInfo_1=require("../image/imageInfo");const imageUtil_1=require("../image/imageUtil");const magickLoaded_1=require("../imageMagick/magickLoaded");const run_1=require("../main/run");const options_1=require("../options");const base64_1=require("../util/base64");const fileUtil_1=require("../util/fileUtil");const protected_1=require("./protected");class File{constructor(name,content,isProtected=false,url,width,height){this.name=name;this.content=content;this.url=url;this.width=width;this.height=height;if(isProtected){protected_1.protectFile(name)}}infoOne(){return __awaiter(this,void 0,void 0,(function*(){var i=yield this.info();if(!i||!i.length){throw new Error("Expected image info extract to work")}return i[0]}))}info(){return new Promise(resolve=>{if(this._info){resolve(this._info)}else{imageInfo_1.imageInfo(this).then(data=>{this._info=(data||[]).map(i=>i.image);resolve(this._info)})}})}size(){return __awaiter(this,void 0,void 0,(function*(){if(this.width&&this.height){return{width:this.width,height:this.height}}var i=yield this.infoOne();this.width=i.geometry?i.geometry.width:this.width;this.height=i.geometry?i.geometry.height:this.height;return{width:this.width||0,height:this.height||0}}))}widthXHeight(){return __awaiter(this,void 0,void 0,(function*(){if(this.width&&this.height){return`${this.width}x${this.height}`}var s=yield this.size();return`${s.width}x${s.height}`}))}mimeType(){return __awaiter(this,void 0,void 0,(function*(){var i=yield this.infoOne();return i.mimeType}))}pixel(x,y){return __awaiter(this,void 0,void 0,(function*(){if(this._pixels){return imageUtil_1.rgbaToString(this._pixels[imageUtil_1.coordsToIndex(this.width,x,y)])}return yield imageUtil_1.imagePixelColor(this,x,y)}))}rgba(x,y){return __awaiter(this,void 0,void 0,(function*(){yield this.pixelCalculate();return this._pixels[imageUtil_1.coordsToIndex(this.width,x,y)]}))}pixelCalculate(){return __awaiter(this,void 0,void 0,(function*(){this._pixels=yield imageUtil_1.getPixels(this)}))}asDataUrl(mime){return __awaiter(this,void 0,void 0,(function*(){return File.toDataUrl(this,mime)}))}asBase64(file){return File.toBase64(file)}equals(file){return __awaiter(this,void 0,void 0,(function*(){return yield imageCompare_1.imageCompare(this,file)}))}asArrayBuffer(){return __awaiter(this,void 0,void 0,(function*(){return this.content.buffer}))}asHTMLImageData(){return __awaiter(this,void 0,void 0,(function*(){var d=yield this.asRGBAImageData();return new ImageData(d.data,d.width,d.height)}))}asRGBAImageData(){return __awaiter(this,void 0,void 0,(function*(){var size=yield this.size();var{outputFiles:outputFiles}=this.name.endsWith(".rgba")&&this.width&&this.height?{outputFiles:[this]}:yield run_1.run({script:`convert ${yield this.sizeDepthArgs()} '${this.name}[0]' ${yield this.sizeDepthArgs(false)} output.rgba`,inputFiles:[this]});return{data:new Uint8ClampedArray(outputFiles[0].content.buffer),width:size.width,height:size.height}}))}sizeDepthArgs(onlyIfRGBA=true){return __awaiter(this,void 0,void 0,(function*(){return File.getSizeDepthArgs(this,onlyIfRGBA)}))}static getSizeDepthArgs(f,onlyIfRGBA=true){return __awaiter(this,void 0,void 0,(function*(){return!onlyIfRGBA||f.name.endsWith(".rgba")?`-size ${yield f.widthXHeight()} -depth 8`:""}))}static toDataUrl(file,mime){return __awaiter(this,void 0,void 0,(function*(){return yield html_1.toDataUrl(file,mime)}))}static fromUrl(url,o={}){return __awaiter(this,void 0,void 0,(function*(){try{const response=yield cross_fetch_1.default(url,o);return new File(o.name||misc_utils_of_mine_generic_1.getFileNameFromUrl(url),new Uint8ClampedArray(yield response.arrayBuffer()),o.protected,url)}catch(error){console.error(error);return undefined}}))}static fromArrayBuffer(b,o={}){return __awaiter(this,void 0,void 0,(function*(){const f=new File(o.name||"unknown",new Uint8ClampedArray(b),o.protected);if(!o.name){const info=yield f.infoOne();return new File(info.format?"unammed."+info.format.toLowerCase():"unknown",f.content,o.protected)}return f}))}static fromFile(f,o={}){if(!misc_utils_of_mine_generic_1.isNode()){throw new Error("File.readFile() called in the browser.")}try{return new File(o.name||misc_utils_of_mine_generic_1.basename(f),new Uint8ClampedArray(fs_1.readFileSync(f)),o.protected)}catch(error){console.error(error);return undefined}}static asString(f){return String.fromCharCode.apply(null,f.content)}static toBase64(file){return base64_1.arrayBufferToBase64(file.content.buffer)}static fromBase64(base64,name){return new File(name,Buffer.from(Base64.decode(base64),"base64"))}static fromDataUrl(dataUrl,name){return File.fromBase64(base64_1.urlToBase64(dataUrl),name)}static fromHtmlFileInputElement(el){return Promise.all(Array.from(el.files).map(file=>new Promise((resolve,reject)=>{var reader=new FileReader;reader.addEventListener("loadend",e=>resolve(new File(file.name,new Uint8ClampedArray(reader.result))));reader.readAsArrayBuffer(file)})))}static resolveOne(files,options={protected:false}){return __awaiter(this,void 0,void 0,(function*(){var a=yield File.resolve(files,options);return a.length>0?a[0]:undefined}))}static resolve(files,options={protected:false}){return __awaiter(this,void 0,void 0,(function*(){var fs=misc_utils_of_mine_generic_1.asArray(files||[]).filter(misc_utils_of_mine_generic_1.notUndefined);var result=yield misc_utils_of_mine_generic_1.serial(fs.map(f=>()=>__awaiter(this,void 0,void 0,(function*(){if(typeof f==="string"){if(misc_utils_of_mine_generic_1.isNode()&&fs_1.existsSync(f)){return yield File.fromFile(f,options)}else{return yield File.fromUrl(f,options)}}else{assert_1.ok(ArrayBuffer.isView(f.content));return f}}))));return result.filter(misc_utils_of_mine_generic_1.notUndefined).map(File.asFile)}))}static isFile(f){return!!f&&!!f.name&&!!f.content&&typeof f.constructor!=="undefined"&&!!f.size&&!!f.infoOne}static asFile(f){return File.isFile(f)?f:typeof f==="string"?fileUtil_1.readFile(f,magickLoaded_1.getFS()):new File(f.name,f.content)}static asPath(f){return typeof f==="string"?f:f.name}static fromRGBAImageData(d,name="img.rgba"){return new File(name,d.data,undefined,undefined,d.width,d.height)}static fromHTMLImageData(d,name="img.rgba"){return File.fromRGBAImageData(d,name)}static fileExists(f){return __awaiter(this,void 0,void 0,(function*(){const{FS:FS}=yield magickLoaded_1.magickLoaded;FS.chdir(options_1.getOption("emscriptenNodeFsRoot"));return fileUtil_1.isDir(File.asPath(f),FS)||fileUtil_1.isFile(File.asPath(f),FS)}))}}exports.File=File;File.equals=(a,b)=>File.asPath(a)!==File.asPath(b)}).call(this,require("buffer").Buffer)},{"../image/html":3,"../image/imageCompare":4,"../image/imageInfo":5,"../image/imageUtil":6,"../imageMagick/magickLoaded":11,"../main/run":16,"../options":20,"../util/base64":21,"../util/fileUtil":22,"./protected":2,assert:43,buffer:80,"cross-fetch":88,fs:78,"misc-utils-of-mine-generic":160}],2:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});const fileUtil_1=require("../util/fileUtil");function protectFile(f,protect=true){protectedFiles[fileUtil_1.getFilePath(f)]=protect}exports.protectFile=protectFile;function isProtectedFile(f){return protectedFiles[fileUtil_1.getFilePath(f)]}exports.isProtectedFile=isProtectedFile;const protectedFiles={}},{"../util/fileUtil":22}],3:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:true});const misc_utils_of_mine_generic_1=require("misc-utils-of-mine-generic");const file_1=require("../file/file");function toDataUrl(o,mime){return __awaiter(this,void 0,void 0,(function*(){mime=mime||(yield o.mimeType());return"data:"+mime+";"+o.name+";base64,"+file_1.File.toBase64(o)}))}exports.toDataUrl=toDataUrl;function toDataUrlSync(o,mime=`image/${misc_utils_of_mine_generic_1.getFileExtension(o.name)}`){return`data:${mime};base64,${btoa(o.content.reduce((data,byte)=>data+String.fromCharCode(byte),""))}`}exports.toDataUrlSync=toDataUrlSync;function loadHtmlImageElement(o,el,forceDataUrl=false){return __awaiter(this,void 0,void 0,(function*(){var img=el||new Image;if(!forceDataUrl&&o.url){img.src=o.url}else{img.src=yield o.asDataUrl()}return img}))}exports.loadHtmlImageElement=loadHtmlImageElement;function loadHtmlCanvasElement(f,ctx,dx=0,dy=0,dirtyX=undefined,dirtyY=undefined,dirtyWidth=undefined,dirtyHeight=undefined){return __awaiter(this,void 0,void 0,(function*(){var d=yield f.asHTMLImageData();if(typeof dirtyX==="undefined"||typeof dirtyY==="undefined"||typeof dirtyWidth==="undefined"||typeof dirtyHeight==="undefined"){ctx.putImageData(d,dx,dy)}else{ctx.putImageData(d,dx,dy,dirtyX,dirtyY,dirtyWidth,dirtyHeight)}}))}exports.loadHtmlCanvasElement=loadHtmlCanvasElement},{"../file/file":1,"misc-utils-of-mine-generic":160}],4:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:true});const file_1=require("../file/file");const main_1=require("../main/main");function imageCompare(img1,img2,fuzz=.015){return __awaiter(this,void 0,void 0,(function*(){if(!img1||!img2){return false}const identical=yield imageCompareNumber(img1,img2);return identical<=fuzz}))}exports.imageCompare=imageCompare;function imageCompareNumber(img1,img2){return __awaiter(this,void 0,void 0,(function*(){const result=yield main_1.main({inputFiles:[img1,img2],command:["convert",img1.name,img2.name,"-resize","256x256^!","-metric","RMSE","-format","%[distortion]","-compare","info:info.txt"]});const n=file_1.File.asString(result.outputFiles[0]);return parseFloat(n)}))}exports.imageCompareNumber=imageCompareNumber},{"../file/file":1,"../main/main":15}],5:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:true});const assert_1=require("assert");const misc_utils_of_mine_generic_1=require("misc-utils-of-mine-generic");const file_1=require("../file/file");const main_1=require("../main/main");function imageInfo(img){return __awaiter(this,void 0,void 0,(function*(){if(!img){return Promise.resolve([])}var files=yield Promise.all(misc_utils_of_mine_generic_1.asArray(img).map(img=>__awaiter(this,void 0,void 0,(function*(){return typeof img==="string"?yield file_1.File.resolve(img):[img]}))));const r=yield main_1.main({inputFiles:files.flat().filter(misc_utils_of_mine_generic_1.notUndefined),command:["convert",...misc_utils_of_mine_generic_1.asArray(img).map(img=>typeof img==="string"?img:img.name),"imgInfo.json"]});assert_1.equal(r.outputFiles.length,1);const s=file_1.File.asString(r.outputFiles[0]);const obj=JSON.parse(s);return obj}))}exports.imageInfo=imageInfo},{"../file/file":1,"../main/main":15,assert:43,"misc-utils-of-mine-generic":160}],6:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:true});const misc_utils_of_mine_generic_1=require("misc-utils-of-mine-generic");const file_1=require("../file/file");const main_1=require("../main/main");function getRgbaPixel(f,x,y){const i=coordsToIndex(f.width,x,y);const c=f.content;return{r:c[i],g:c[i+1],b:c[i+2],a:c[i+3]}}exports.getRgbaPixel=getRgbaPixel;function coordsToIndex(width,x,y){return(width*y+x)*4}exports.coordsToIndex=coordsToIndex;function getPixels(f){return __awaiter(this,void 0,void 0,(function*(){var data=yield f.asRGBAImageData();var pixels=[];for(let y=0;y<data.height;y++){for(let x=0;x<data.width;x++){pixels.push(getRgbaPixel(f,x,y))}}return pixels}))}exports.getPixels=getPixels;function imagePixelColor(img,x,y){return __awaiter(this,void 0,void 0,(function*(){if(!img){return}var f=file_1.File.asFile(img);if(isRgbaImage(f)){const c=getRgbaPixel(f,x,y);return rgbaToString(c)}else{const{outputFiles:outputFiles}=yield main_1.main({inputFiles:[img],command:`convert ${img.name} -format %[pixel:p{${x},${y}}] info:info.txt`});return(yield file_1.File.asString(outputFiles[0]))||undefined}}))}exports.imagePixelColor=imagePixelColor;function rgbaToString(c){return`rgba(${c.r},${c.g},${c.b},${c.a})`}exports.rgbaToString=rgbaToString;function isRgbaImage(f){return f.name.endsWith("rgba")&&f.width&&f.content instanceof Uint8ClampedArray}exports.isRgbaImage=isRgbaImage;function colorCount(img){return __awaiter(this,void 0,void 0,(function*(){if(!img){return}const{outputFiles:outputFiles}=yield main_1.main({inputFiles:[img],command:`convert ${img.name} -unique-colors -format %w info:info.txt`});var s=yield file_1.File.asString(outputFiles[0]);return parseInt(s)||undefined}))}exports.colorCount=colorCount;function parseConvertVerbose(stdout){var r=/([^=]+)=>([^\s]+)\s+([a-zA-Z0-9]+)\s+([^=]+)=>([^\s]+)/;var r2=/([^=]+)=>([^\s]+)\s+([a-zA-Z0-9]+)\s+([^\s]+)/;return stdout.map(l=>r.exec(l)||r2.exec(l)).filter(misc_utils_of_mine_generic_1.notFalsy).map(m=>{var a=m[4].split("x");var b=m[Math.min(m.length-1,6)].split("x");return{inputName:m[1],outputName:m[2],inputFormat:m[3].toLowerCase(),inputSize:{width:parseInt(a[0]),height:parseInt(a[1])},outputSize:{width:parseInt(b[0]),height:parseInt(b[1])}}})}exports.parseConvertVerbose=parseConvertVerbose},{"../file/file":1,"../main/main":15,"misc-utils-of-mine-generic":160}],7:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:true});const misc_utils_of_mine_generic_1=require("misc-utils-of-mine-generic");const main_1=require("../main/main");const imageInfo_1=require("./imageInfo");function getConfigureFolders(){return __awaiter(this,void 0,void 0,(function*(){const result=yield main_1.main({command:`convert -debug configure rose: info:`});const contains=`Searching for configure file:`;const folders=result.stderr.filter(line=>line.includes(contains)).map(line=>line.substring(line.indexOf(contains)+contains.length,line.length)).map(s=>s.replace(/\/\//g,"/")).map(s=>s.substring(0,s.lastIndexOf("/"))).map(s=>s.replace(/"/g,"").trim());return folders}))}exports.getConfigureFolders=getConfigureFolders;let listConfigure_;function listConfigure(){return __awaiter(this,void 0,void 0,(function*(){if(!listConfigure_){const result=yield main_1.main({command:`convert -list configure`});const delegatesS=result.stderr.find(l=>l.trim().toLowerCase().startsWith("delegates"));const delegates=delegatesS?delegatesS.split(/\s+/).splice(1):[];const featuresS=result.stderr.find(l=>l.trim().toLowerCase().startsWith("features"));const features=featuresS?featuresS.split(/\s+/).splice(1):[];listConfigure_={delegates:delegates,features:features}}return listConfigure_}))}exports.listConfigure=listConfigure;function listFormat(){return __awaiter(this,void 0,void 0,(function*(){if(!formats){const result=yield main_1.main({command:`convert -list format`});var r=/^\s*([^\s]+)\s+([^\s]+)\s+(.+)$/g;formats=result.stdout.slice(2).map(s=>r.exec(s)).filter(misc_utils_of_mine_generic_1.notFalsy).filter(r=>r[1]!=="See").map(r=>({name:r[1],flags:r[2],description:r[3]}))}return formats}))}exports.listFormat=listFormat;let formats;exports.knownSupportedReadWriteImageFormats=["jpg","png","psd","tiff","xcf","gif","bmp","tga","miff","ico","dcm","xpm","pcx","fits","ppm","pgm","pfm","mng","hdr","dds","otb","txt","psb"];exports.knownSupportedWriteOnlyImageFormats=["ps","pdf","epdf","svg","djvu"];exports.knownSupportedReadOnlyImageFormats=["mat"];let builtInImages;const names=["rose:","logo:","wizard:","granite:","netscape:"];function imageBuiltIn(builtIn){return __awaiter(this,void 0,void 0,(function*(){if(!builtInImages){builtInImages=yield misc_utils_of_mine_generic_1.serial(names.map(name=>()=>__awaiter(this,void 0,void 0,(function*(){const info=yield imageInfo_1.imageInfo(name);const{outputFiles:outputFiles}=yield main_1.main({command:`convert ${name} ${`output1.${info[0].image.format.toLowerCase()}`}`,inputFiles:[]});outputFiles[0].name=name;return outputFiles[0]}))))}return builtIn?builtInImages.filter(i=>i.name===builtIn):builtInImages}))}exports.imageBuiltIn=imageBuiltIn},{"../main/main":15,"./imageInfo":5,"misc-utils-of-mine-generic":160}],8:[function(require,module,exports){(function(process,Buffer,__dirname){const{magickLoaded:magickLoaded,pushStdout:pushStdout,pushStderr:pushStderr,getOptions:getOptions,moduleLocateFile:moduleLocateFile,isNode:isNode}=require("../magickLoaded");const{nodeFsLocalRoot:nodeFsLocalRoot,emscriptenNodeFsRoot:emscriptenNodeFsRoot,debug:debug,disableNodeFs:disableNodeFs}=getOptions();Module=typeof Module==="undefined"?{}:Module;Object.assign(Module,{noExitRuntime:true,noInitialRun:true,logReadFiles:debug,print:pushStdout,printErr:pushStderr,preRun:function(){debug&&console.log("Module.preRun. isNode: ",isNode());if(!FS.isDir(emscriptenNodeFsRoot)){FS.mkdir(emscriptenNodeFsRoot)}if(isNode()&&!disableNodeFs){if(!require("f"+"s").existsSync(nodeFsLocalRoot)){require("f"+"s").mkdirSync(nodeFsLocalRoot,{recursive:true})}debug&&console.log(`Mounting local folder "${nodeFsLocalRoot}" as emscripten root folder "${emscriptenNodeFsRoot}".`);FS.mount(NODEFS,{root:nodeFsLocalRoot},emscriptenNodeFsRoot)}debug&&console.log("Module.preRun <-- exiting")},onRuntimeInitialized:function(){debug&&console.log("Emscripten Module.onRuntimeInitialized ");magickLoaded.resolve({FS:FS,main:require("../createMain").createMain(Module,FS)})},onAbort:function(what){console.error("onAbort",what);console.trace()},locateFile:moduleLocateFile});var Module=typeof Module!=="undefined"?Module:{};var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}Module["arguments"]=[];Module["thisProgram"]="./this.program";Module["quit"]=function(status,toThrow){throw toThrow};Module["preRun"]=[];Module["postRun"]=[];var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof require==="function"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}else{return scriptDirectory+path}}if(ENVIRONMENT_IS_NODE){scriptDirectory=__dirname+"/";var nodeFS;var nodePath;Module["read"]=function shell_read(filename,binary){var ret;if(!nodeFS)nodeFS=require("fs");if(!nodePath)nodePath=require("path");filename=nodePath["normalize"](filename);ret=nodeFS["readFileSync"](filename);return binary?ret:ret.toString()};Module["readBinary"]=function readBinary(filename){var ret=Module["read"](filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process["argv"].length>1){Module["thisProgram"]=process["argv"][1].replace(/\\/g,"/")}Module["arguments"]=process["argv"].slice(2);if(typeof module!=="undefined"){module["exports"]=Module}process["on"]("unhandledRejection",abort);Module["quit"]=function(status){process["exit"](status)};Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_SHELL){if(typeof read!="undefined"){Module["read"]=function shell_read(f){return read(f)}}Module["readBinary"]=function readBinary(f){var data;if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}data=read(f,"binary");assert(typeof data==="object");return data};if(typeof scriptArgs!="undefined"){Module["arguments"]=scriptArgs}else if(typeof arguments!="undefined"){Module["arguments"]=arguments}if(typeof quit==="function"){Module["quit"]=function(status){quit(status)}}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(document.currentScript){scriptDirectory=document.currentScript.src}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf("/")+1)}else{scriptDirectory=""}Module["read"]=function shell_read(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){Module["readBinary"]=function readBinary(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}Module["readAsync"]=function readAsync(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function xhr_onload(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)};Module["setWindowTitle"]=function(title){document.title=title}}else{}var out=Module["print"]||(typeof console!=="undefined"?console.log.bind(console):typeof print!=="undefined"?print:null);var err=Module["printErr"]||(typeof printErr!=="undefined"?printErr:typeof console!=="undefined"&&console.warn.bind(console)||out);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=undefined;function dynamicAlloc(size){var ret=HEAP32[DYNAMICTOP_PTR>>2];var end=ret+size+15&-16;if(end<=_emscripten_get_heap_size()){HEAP32[DYNAMICTOP_PTR>>2]=end}else{var success=_emscripten_resize_heap(end);if(!success)return 0}return ret}function getNativeTypeSize(type){switch(type){case"i1":case"i8":return 1;case"i16":return 2;case"i32":return 4;case"i64":return 8;case"float":return 4;case"double":return 8;default:{if(type[type.length-1]==="*"){return 4}else if(type[0]==="i"){var bits=parseInt(type.substr(1));assert(bits%8===0,"getNativeTypeSize invalid bits "+bits+", type "+type);return bits/8}else{return 0}}}}var asm2wasmImports={"f64-rem":function(x,y){return x%y},debugger:function(){debugger}};var functionPointers=new Array(0);var tempRet0=0;var setTempRet0=function(value){tempRet0=value};var getTempRet0=function(){return tempRet0};if(typeof WebAssembly!=="object"){err("no native wasm support detected")}var wasmMemory;var wasmTable;var ABORT=false;var EXITSTATUS=0;function assert(condition,text){if(!condition){abort("Assertion failed: "+text)}}function setValue(ptr,value,type,noSafe){type=type||"i8";if(type.charAt(type.length-1)==="*")type="i32";switch(type){case"i1":HEAP8[ptr>>0]=value;break;case"i8":HEAP8[ptr>>0]=value;break;case"i16":HEAP16[ptr>>1]=value;break;case"i32":HEAP32[ptr>>2]=value;break;case"i64":tempI64=[value>>>0,(tempDouble=value,+Math_abs(tempDouble)>=1?tempDouble>0?(Math_min(+Math_floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math_ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[ptr>>2]=tempI64[0],HEAP32[ptr+4>>2]=tempI64[1];break;case"float":HEAPF32[ptr>>2]=value;break;case"double":HEAPF64[ptr>>3]=value;break;default:abort("invalid type for setValue: "+type)}}var ALLOC_NORMAL=0;var ALLOC_NONE=3;function allocate(slab,types,allocator,ptr){var zeroinit,size;if(typeof slab==="number"){zeroinit=true;size=slab}else{zeroinit=false;size=slab.length}var singleType=typeof types==="string"?types:null;var ret;if(allocator==ALLOC_NONE){ret=ptr}else{ret=[_malloc,stackAlloc,dynamicAlloc][allocator](Math.max(size,singleType?1:types.length))}if(zeroinit){var stop;ptr=ret;assert((ret&3)==0);stop=ret+(size&~3);for(;ptr<stop;ptr+=4){HEAP32[ptr>>2]=0}stop=ret+size;while(ptr<stop){HEAP8[ptr++>>0]=0}return ret}if(singleType==="i8"){if(slab.subarray||slab.slice){HEAPU8.set(slab,ret)}else{HEAPU8.set(new Uint8Array(slab),ret)}return ret}var i=0,type,typeSize,previousType;while(i<size){var curr=slab[i];type=singleType||types[i];if(type===0){i++;continue}if(type=="i64")type="i32";setValue(ret+i,curr,type);if(previousType!==type){typeSize=getNativeTypeSize(type);previousType=type}i+=typeSize}return ret}function getMemory(size){if(!runtimeInitialized)return dynamicAlloc(size);return _malloc(size)}var UTF8Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(u8Array,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(u8Array[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&u8Array.subarray&&UTF8Decoder){return UTF8Decoder.decode(u8Array.subarray(idx,endPtr))}else{var str="";while(idx<endPtr){var u0=u8Array[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=u8Array[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=u8Array[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|u8Array[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,outU8Array,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;outU8Array[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;outU8Array[outIdx++]=192|u>>6;outU8Array[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;outU8Array[outIdx++]=224|u>>12;outU8Array[outIdx++]=128|u>>6&63;outU8Array[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;outU8Array[outIdx++]=240|u>>18;outU8Array[outIdx++]=128|u>>12&63;outU8Array[outIdx++]=128|u>>6&63;outU8Array[outIdx++]=128|u&63}}outU8Array[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127)++len;else if(u<=2047)len+=2;else if(u<=65535)len+=3;else len+=4}return len}var UTF16Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf-16le"):undefined;function allocateUTF8(str){var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8Array(str,HEAP8,ret,size);return ret}function allocateUTF8OnStack(str){var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8Array(str,HEAP8,ret,size);return ret}function writeArrayToMemory(array,buffer){HEAP8.set(array,buffer)}function writeAsciiToMemory(str,buffer,dontAddNull){for(var i=0;i<str.length;++i){HEAP8[buffer++>>0]=str.charCodeAt(i)}if(!dontAddNull)HEAP8[buffer>>0]=0}function demangle(func){return func}function demangleAll(text){var regex=/__Z[\w\d_]+/g;return text.replace(regex,(function(x){var y=demangle(x);return x===y?x:y+" ["+x+"]"}))}function jsStackTrace(){var err=new Error;if(!err.stack){try{throw new Error(0)}catch(e){err=e}if(!err.stack){return"(no stack trace available)"}}return err.stack.toString()}function stackTrace(){var js=jsStackTrace();if(Module["extraStackTrace"])js+="\n"+Module["extraStackTrace"]();return demangleAll(js)}var PAGE_SIZE=16384;var WASM_PAGE_SIZE=65536;function alignUp(x,multiple){if(x%multiple>0){x+=multiple-x%multiple}return x}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferViews(){Module["HEAP8"]=HEAP8=new Int8Array(buffer);Module["HEAP16"]=HEAP16=new Int16Array(buffer);Module["HEAP32"]=HEAP32=new Int32Array(buffer);Module["HEAPU8"]=HEAPU8=new Uint8Array(buffer);Module["HEAPU16"]=HEAPU16=new Uint16Array(buffer);Module["HEAPU32"]=HEAPU32=new Uint32Array(buffer);Module["HEAPF32"]=HEAPF32=new Float32Array(buffer);Module["HEAPF64"]=HEAPF64=new Float64Array(buffer)}var DYNAMIC_BASE=6646336,DYNAMICTOP_PTR=1403424;var TOTAL_STACK=5242880;var INITIAL_TOTAL_MEMORY=Module["TOTAL_MEMORY"]||16777216;if(INITIAL_TOTAL_MEMORY<TOTAL_STACK)err("TOTAL_MEMORY should be larger than TOTAL_STACK, was "+INITIAL_TOTAL_MEMORY+"! (TOTAL_STACK="+TOTAL_STACK+")");if(Module["buffer"]){buffer=Module["buffer"]}else{if(typeof WebAssembly==="object"&&typeof WebAssembly.Memory==="function"){wasmMemory=new WebAssembly.Memory({initial:INITIAL_TOTAL_MEMORY/WASM_PAGE_SIZE});buffer=wasmMemory.buffer}else{buffer=new ArrayBuffer(INITIAL_TOTAL_MEMORY)}}updateGlobalBufferViews();HEAP32[DYNAMICTOP_PTR>>2]=DYNAMIC_BASE;function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback();continue}var func=callback.func;if(typeof func==="number"){if(callback.arg===undefined){Module["dynCall_v"](func)}else{Module["dynCall_vi"](func,callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeExited=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function ensureInitRuntime(){if(runtimeInitialized)return;runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.init.initialized)FS.init();TTY.init();callRuntimeCallbacks(__ATINIT__)}function preMain(){FS.ignorePermissions=false;callRuntimeCallbacks(__ATMAIN__)}function exitRuntime(){runtimeExited=true}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var Math_abs=Math.abs;var Math_ceil=Math.ceil;var Math_floor=Math.floor;var Math_min=Math.min;var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function getUniqueRunDependency(id){return id}function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["preloadedImages"]={};Module["preloadedAudios"]={};var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return String.prototype.startsWith?filename.startsWith(dataURIPrefix):filename.indexOf(dataURIPrefix)===0}var wasmBinaryFile="magick.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(){try{if(Module["wasmBinary"]){return new Uint8Array(Module["wasmBinary"])}if(Module["readBinary"]){return Module["readBinary"](wasmBinaryFile)}else{throw"both async and sync fetching of the wasm failed"}}catch(err){abort(err)}}function getBinaryPromise(){if(!Module["wasmBinary"]&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&typeof fetch==="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then((function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()})).catch((function(){return getBinary()}))}return new Promise((function(resolve,reject){resolve(getBinary())}))}function createWasm(env){var info={env:env,global:{NaN:NaN,Infinity:Infinity},"global.Math":Math,asm2wasm:asm2wasmImports};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");if(Module["instantiateWasm"]){try{return Module["instantiateWasm"](info,receiveInstance)}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}function receiveInstantiatedSource(output){receiveInstance(output["instance"])}function instantiateArrayBuffer(receiver){getBinaryPromise().then((function(binary){return WebAssembly.instantiate(binary,info)})).then(receiver,(function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)}))}if(!Module["wasmBinary"]&&typeof WebAssembly.instantiateStreaming==="function"&&!isDataURI(wasmBinaryFile)&&typeof fetch==="function"){WebAssembly.instantiateStreaming(fetch(wasmBinaryFile,{credentials:"same-origin"}),info).then(receiveInstantiatedSource,(function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");instantiateArrayBuffer(receiveInstantiatedSource)}))}else{instantiateArrayBuffer(receiveInstantiatedSource)}return{}}Module["asm"]=function(global,env,providedBuffer){env["memory"]=wasmMemory;env["table"]=wasmTable=new WebAssembly.Table({initial:5443,maximum:5443,element:"anyfunc"});env["__memory_base"]=1024;env["__table_base"]=0;var exports=createWasm(env);return exports};__ATINIT__.push({func:function(){___emscripten_environ_constructor()}});function ___assert_fail(condition,filename,line,func){abort("Assertion failed: "+UTF8ToString(condition)+", at: "+[filename?UTF8ToString(filename):"unknown filename",line,func?UTF8ToString(func):"unknown function"])}var ENV={};function ___buildEnvironment(environ){var MAX_ENV_VALUES=64;var TOTAL_ENV_SIZE=1024;var poolPtr;var envPtr;if(!___buildEnvironment.called){___buildEnvironment.called=true;ENV["USER"]=ENV["LOGNAME"]="web_user";ENV["PATH"]="/";ENV["PWD"]="/";ENV["HOME"]="/home/web_user";ENV["LANG"]="C.UTF-8";ENV["_"]=Module["thisProgram"];poolPtr=getMemory(TOTAL_ENV_SIZE);envPtr=getMemory(MAX_ENV_VALUES*4);HEAP32[envPtr>>2]=poolPtr;HEAP32[environ>>2]=envPtr}else{envPtr=HEAP32[environ>>2];poolPtr=HEAP32[envPtr>>2]}var strings=[];var totalSize=0;for(var key in ENV){if(typeof ENV[key]==="string"){var line=key+"="+ENV[key];strings.push(line);totalSize+=line.length}}if(totalSize>TOTAL_ENV_SIZE){throw new Error("Environment size exceeded TOTAL_ENV_SIZE!")}var ptrSize=4;for(var i=0;i<strings.length;i++){var line=strings[i];writeAsciiToMemory(line,poolPtr);HEAP32[envPtr+i*ptrSize>>2]=poolPtr;poolPtr+=line.length+1}HEAP32[envPtr+strings.length*ptrSize>>2]=0}function _emscripten_get_now(){abort()}function _emscripten_get_now_is_monotonic(){return 0||ENVIRONMENT_IS_NODE||typeof dateNow!=="undefined"||typeof performance==="object"&&performance&&typeof performance["now"]==="function"}function ___setErrNo(value){if(Module["___errno_location"])HEAP32[Module["___errno_location"]()>>2]=value;return value}function _clock_gettime(clk_id,tp){var now;if(clk_id===0){now=Date.now()}else if(clk_id===1&&_emscripten_get_now_is_monotonic()){now=_emscripten_get_now()}else{___setErrNo(22);return-1}HEAP32[tp>>2]=now/1e3|0;HEAP32[tp+4>>2]=now%1e3*1e3*1e3|0;return 0}function ___clock_gettime(a0,a1){return _clock_gettime(a0,a1)}function ___cxa_allocate_exception(size){return _malloc(size)}function ___cxa_free_exception(ptr){try{return _free(ptr)}catch(e){}}var EXCEPTIONS={last:0,caught:[],infos:{},deAdjust:function(adjusted){if(!adjusted||EXCEPTIONS.infos[adjusted])return adjusted;for(var key in EXCEPTIONS.infos){var ptr=+key;var adj=EXCEPTIONS.infos[ptr].adjusted;var len=adj.length;for(var i=0;i<len;i++){if(adj[i]===adjusted){return ptr}}}return adjusted},addRef:function(ptr){if(!ptr)return;var info=EXCEPTIONS.infos[ptr];info.refcount++},decRef:function(ptr){if(!ptr)return;var info=EXCEPTIONS.infos[ptr];assert(info.refcount>0);info.refcount--;if(info.refcount===0&&!info.rethrown){if(info.destructor){Module["dynCall_vi"](info.destructor,ptr)}delete EXCEPTIONS.infos[ptr];___cxa_free_exception(ptr)}},clearRef:function(ptr){if(!ptr)return;var info=EXCEPTIONS.infos[ptr];info.refcount=0}};function ___cxa_pure_virtual(){ABORT=true;throw"Pure virtual function called!"}function ___cxa_throw(ptr,type,destructor){EXCEPTIONS.infos[ptr]={ptr:ptr,adjusted:[ptr],type:type,destructor:destructor,refcount:0,caught:false,rethrown:false};EXCEPTIONS.last=ptr;if(!("uncaught_exception"in __ZSt18uncaught_exceptionv)){__ZSt18uncaught_exceptionv.uncaught_exception=1}else{__ZSt18uncaught_exceptionv.uncaught_exception++}throw ptr}function ___cxa_uncaught_exception(){return!!__ZSt18uncaught_exceptionv.uncaught_exception}function ___lock(){}function ___map_file(pathname,size){___setErrNo(1);return-1}var PATH={splitPath:function(filename){var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:function(parts,allowAboveRoot){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(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:function(path){var isAbsolute=path.charAt(0)==="/",trailingSlash=path.substr(-1)==="/";path=PATH.normalizeArray(path.split("/").filter((function(p){return!!p})),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:function(path){var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir},basename:function(path){if(path==="/")return"/";var lastSlash=path.lastIndexOf("/");if(lastSlash===-1)return path;return path.substr(lastSlash+1)},extname:function(path){return PATH.splitPath(path)[3]},join:function(){var paths=Array.prototype.slice.call(arguments,0);return PATH.normalize(paths.join("/"))},join2:function(l,r){return PATH.normalize(l+"/"+r)}};var PATH_FS={resolve:function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:FS.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter((function(p){return!!p})),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:function(from,to){from=PATH_FS.resolve(from).substr(1);to=PATH_FS.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("/")}};var TTY={ttys:[],init:function(){},shutdown:function(){},register:function(dev,ops){TTY.ttys[dev]={input:[],output:[],ops:ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open:function(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(19)}stream.tty=tty;stream.seekable=false},close:function(stream){stream.tty.ops.flush(stream.tty)},flush:function(stream){stream.tty.ops.flush(stream.tty)},read:function(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(6)}var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(5)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(11)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.timestamp=Date.now()}return bytesRead},write:function(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char){throw new FS.ErrnoError(6)}try{for(var i=0;i<length;i++){stream.tty.ops.put_char(stream.tty,buffer[offset+i])}}catch(e){throw new FS.ErrnoError(5)}if(length){stream.node.timestamp=Date.now()}return i}},default_tty_ops:{get_char:function(tty){if(!tty.input.length){var result=null;if(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=new Buffer(BUFSIZE);var bytesRead=0;var isPosixPlatform=process.platform!="win32";var fd=process.stdin.fd;if(isPosixPlatform){var usingDevice=false;try{fd=fs.openSync("/dev/stdin","r");usingDevice=true}catch(e){}}try{bytesRead=fs.readSync(fd,buf,0,BUFSIZE,null)}catch(e){if(e.toString().indexOf("EOF")!=-1)bytesRead=0;else throw e}if(usingDevice){fs.closeSync(fd)}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}else{result=null}}else if(typeof window!="undefined"&&typeof window.prompt=="function"){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else if(typeof readline=="function"){result=readline();if(result!==null){result+="\n"}}if(!result){return null}tty.input=intArrayFromString(result,true)}return tty.input.shift()},put_char:function(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},flush:function(tty){if(tty.output&&tty.output.length>0){out(UTF8ArrayToString(tty.output,0));tty.output=[]}}},default_tty1_ops:{put_char:function(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},flush:function(tty){if(tty.output&&tty.output.length>0){err(UTF8ArrayToString(tty.output,0));tty.output=[]}}}};var MEMFS={ops_table:null,mount:function(mount){return MEMFS.createNode(null,"/",16384|511,0)},createNode:function(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(1)}if(!MEMFS.ops_table){MEMFS.ops_table={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}}}var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.timestamp=Date.now();if(parent){parent.contents[name]=node}return node},getFileDataAsRegularArray:function(node){if(node.contents&&node.contents.subarray){var arr=[];for(var i=0;i<node.usedBytes;++i)arr.push(node.contents[i]);return arr}return node.contents},getFileDataAsTypedArray:function(node){if(!node.contents)return new Uint8Array;if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage:function(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<CAPACITY_DOUBLING_MAX?2:1.125)|0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0);return},resizeFileStorage:function(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0;return}if(!node.contents||node.contents.subarray){var oldContents=node.contents;node.contents=new Uint8Array(new ArrayBuffer(newSize));if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize;return}if(!node.contents)node.contents=[];if(node.contents.length>newSize)node.contents.length=newSize;else while(node.contents.length<newSize)node.contents.push(0);node.usedBytes=newSize},node_ops:{getattr:function(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.timestamp);attr.mtime=new Date(node.timestamp);attr.ctime=new Date(node.timestamp);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr:function(node,attr){if(attr.mode!==undefined){node.mode=attr.mode}if(attr.timestamp!==undefined){node.timestamp=attr.timestamp}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup:function(parent,name){throw FS.genericErrors[2]},mknod:function(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename:function(old_node,new_dir,new_name){if(FS.isDir(old_node.mode)){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){for(var i in new_node.contents){throw new FS.ErrnoError(39)}}}dele