diff --git a/.gitignore b/.gitignore
new file mode 100644
index 000000000..37e6cd6a8
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+/node_modules/
+.env
+/testFiles/
+/ignore/
+*.code-workspace
\ No newline at end of file
diff --git a/CONTRIBUTE.md b/CONTRIBUTE.md
new file mode 100644
index 000000000..460783c61
--- /dev/null
+++ b/CONTRIBUTE.md
@@ -0,0 +1,30 @@
+# Contribute
+
+This file should introduce you with the concepts and tools used in this project.
+
+## PDF Library Docs
+- [pdf-lib](https://pdf-lib.js.org) - js
+- [pdfcpu](https://pdfcpu.io) - go-wasm
+
+## Adding a PDF Function
+
+In order to add a PDF-Function there are several files that need to be changed. If the function is on the backend only, or on only on the frontend, you just need to add it to one of the locations. If it is available on both, you need to update both locations.
+Dependency Injection is used to accomodate for different imports across platforms.
+
+Backend functions can have different implementations than their frontend counterparts if neccesary. Otherwise they can just link to their frontend implementation.
+
+Registering functions will also pass them their dependencies for the specific target platform (Node, Browser)
+
+### Backend
+
+[Register Functions](/functions.js)\
+[Functions Folder](/functions/)
+
+Examples that go in the node-functions folder: server-side-only functions, different implementation for backend
+
+### Frontend
+
+[Register Functions](/public/functions.js)\
+[Functions Folder](/public/functions/)
+
+Examples that go in the browser-functions folder: client-side-only functions, shared functions
diff --git a/README.md b/README.md
new file mode 100644
index 000000000..a9a7f6292
--- /dev/null
+++ b/README.md
@@ -0,0 +1,137 @@
+# StirlingPDF rewrite
+
+This is the development repository for the new StirlingPDF backend. With the power of JS, WASM & GO this will provide almost all functionality SPDF can do currently directly on the client. For automation purposes this will still provide an API to automate your workflows.
+
+## Try the new API!
+
+[](https://documenter.getpostman.com/view/30633786/2s9YRB1Wto)
+
+## Understanding Workflows
+
+Workflows define how to apply operations to a PDF, including their order and relations with eachother.
+
+Workflows can be created via the web-ui and then exported or, if you want to brag a bit, you can create the JSON object yourself.
+
+### Basics
+
+To create your own, you have to understand a few key features first. You can also look at more examples our github repository.
+
+``` json
+{
+ "outputOptions": {
+ "zip": false
+ },
+ "operations": [
+ {
+ "type": "extract",
+ "values": {
+ "pagesToExtractArray": [0, 2]
+ },
+ "operations": []
+ }
+ ]
+}
+```
+
+The workflow above will extract the first (p\[0\]) and third (p\[2\]) page of the document.
+
+You can also nest workflows like this:
+
+``` json
+{
+ "outputOptions": {
+ "zip": false
+ },
+ "operations": [
+ {
+ "type": "extract",
+ "values": {
+ "pagesToExtractArray": [0, 2]
+ },
+ "operations": [
+ {
+ "type": "impose",
+ "values": {
+ "nup": 2, // 2 pages of the input document will be put on one page of the output document.
+ "format": "A4L" // A4L -> The page size of the Ouput will be an A4 in Landscape. You can also use other paper formats and "P" for portrait output.
+ },
+ "operations": []
+ }
+ ]
+ }
+ ]
+}
+```
+
+If you look at it closely, you will see that the extract operation has another nested operation of the type impose. This workflow will produce a PDF with the 1st and 2nd page of the input on one single page.
+
+### Advanced
+
+If that is not enought for you usecase, there is also the possibility to connect operations with eachother.
+
+You can also do different operations to produce two different output PDFs from one input.
+
+If you are interested in learning about this, take a look at the Example workflows provided in the repository, ask on the discord, or wait for me to finish this documentation.
+
+## Features
+
+### New
+
+- [x] Client side PDF-Manipulation
+- [x] Workflows
+- [ ] Stateful UI
+- [ ] Node based editing of them
+- [ ] Propper auth using passportjs
+
+### Functions
+
+Current functions of spdf and their progress in this repo.
+
+- [x] Merge
+- [x] Split
+- [x] Rotate
+- [x] Multi-Page-Layout
+- [x] Adjust page size/scale
+- [ ] Organize
+- [ ] Change Metadata
+- [ ] Add Watermark
+
+
+
+- [ ] Remove Pages
+- [ ] Remove Blank Pages
+- [ ] Detect/Split Scanned photos
+
+
+
+- [ ] Repair
+- [ ] Compress
+- [ ] Flatten
+- [ ] Compare/Diff
+
+
+
+- [ ] Sign
+- [ ] Sign with Certificate
+- [ ] Add Password
+- [ ] Remove Password
+- [ ] Change Permissions
+
+
+
+- [ ] Image to PDF
+- [ ] Add image
+- [ ] Extract Images
+- [ ] PDF to Image
+- [ ] OCR
+
+
+
+- [ ] Convert file to PDF
+- [ ] PDF to Text/RTF
+- [ ] PDF to HTML
+- [ ] PDF to XML
+
+## Contribute
+
+For initial instructions look at [CONTRIBUTE.md](./CONTRIBUTE.md)
\ No newline at end of file
diff --git a/functions.js b/functions.js
new file mode 100644
index 000000000..c6260f4ab
--- /dev/null
+++ b/functions.js
@@ -0,0 +1,38 @@
+import PDFLib from 'pdf-lib';
+import * as pdfcpuWraopper from "./public/wasm/pdfcpu-wrapper-node.js";
+
+import { extractPages as dependantExtractPages } from "./public/functions/extractPages.js";
+import { impose as dependantImpose } from './public/functions/impose.js';
+import { mergePDFs as dependantMergePDFs } from './public/functions/mergePDFs.js';
+import { rotatePages as dependantRotatePages } from './public/functions/rotatePages.js';
+import { scaleContent as dependantScaleContent} from './public/functions/scaleContent.js';
+import { scalePage as dependantScalePage } from './public/functions/scalePage.js';
+import { splitPDF as dependantSplitPDF } from './public/functions/splitPDF.js';
+
+export async function extractPages(snapshot, pagesToExtractArray) {
+ return dependantExtractPages(snapshot, pagesToExtractArray, PDFLib);
+}
+
+export async function impose(snapshot, nup, format) {
+ return dependantImpose(snapshot, nup, format, pdfcpuWraopper);
+}
+
+export async function mergePDFs(snapshots) {
+ return dependantMergePDFs(snapshots, PDFLib);
+}
+
+export async function rotatePages(snapshot, rotation) {
+ return dependantRotatePages(snapshot, rotation, PDFLib);
+}
+
+export async function scaleContent(snapshot, scaleFactor) {
+ return dependantScaleContent(snapshot, scaleFactor, PDFLib);
+}
+
+export async function scalePage(snapshot, pageSize) {
+ return dependantScalePage(snapshot, pageSize, PDFLib);
+}
+
+export async function splitPDF(snapshot, splitAfterPageArray) {
+ return dependantSplitPDF(snapshot, splitAfterPageArray, PDFLib);
+}
\ No newline at end of file
diff --git a/index.js b/index.js
new file mode 100644
index 000000000..cf6c87add
--- /dev/null
+++ b/index.js
@@ -0,0 +1,20 @@
+
+import api from './routes/api/index.js';
+
+import express from 'express';
+const app = express();
+const PORT = 8080;
+
+// Static Middleware
+app.use(express.static('./public'));
+
+app.get('/', function (req, res, next) { // TODO: Use EJS?
+ res.render('home.ejs');
+});
+
+app.use("/api/", api);
+
+app.listen(PORT, function (err) {
+ if (err) console.log(err);
+ console.log(`http://localhost:${PORT}`);
+});
\ No newline at end of file
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 000000000..cee0c2a9b
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,842 @@
+{
+ "name": "pdfjs",
+ "version": "1.0.0",
+ "lockfileVersion": 1,
+ "requires": true,
+ "dependencies": {
+ "@pdf-lib/standard-fonts": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/@pdf-lib/standard-fonts/-/standard-fonts-1.0.0.tgz",
+ "integrity": "sha512-hU30BK9IUN/su0Mn9VdlVKsWBS6GyhVfqjwl1FjZN4TxP6cCw0jP2w7V3Hf5uX7M0AZJ16vey9yE0ny7Sa59ZA==",
+ "requires": {
+ "pako": "^1.0.6"
+ }
+ },
+ "@pdf-lib/upng": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@pdf-lib/upng/-/upng-1.0.1.tgz",
+ "integrity": "sha512-dQK2FUMQtowVP00mtIksrlZhdFXQZPC+taih1q4CvPZ5vqdxR/LKBaFg0oAfzd1GlHZXXSPdQfzQnt+ViGvEIQ==",
+ "requires": {
+ "pako": "^1.0.10"
+ }
+ },
+ "@wasmer/wasmfs": {
+ "version": "0.12.0",
+ "resolved": "https://registry.npmjs.org/@wasmer/wasmfs/-/wasmfs-0.12.0.tgz",
+ "integrity": "sha512-m1ftchyQ1DfSenm5XbbdGIpb6KJHH5z0gODo3IZr6lATkj4WXfX/UeBTZ0aG9YVShBp+kHLdUHvOkqjy6p/GWw==",
+ "requires": {
+ "memfs": "3.0.4",
+ "pako": "^1.0.11",
+ "tar-stream": "^2.1.0"
+ }
+ },
+ "accepts": {
+ "version": "1.3.8",
+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
+ "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
+ "requires": {
+ "mime-types": "~2.1.34",
+ "negotiator": "0.6.3"
+ }
+ },
+ "archiver": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/archiver/-/archiver-6.0.1.tgz",
+ "integrity": "sha512-CXGy4poOLBKptiZH//VlWdFuUC1RESbdZjGjILwBuZ73P7WkAUN0htfSfBq/7k6FRFlpu7bg4JOkj1vU9G6jcQ==",
+ "requires": {
+ "archiver-utils": "^4.0.1",
+ "async": "^3.2.4",
+ "buffer-crc32": "^0.2.1",
+ "readable-stream": "^3.6.0",
+ "readdir-glob": "^1.1.2",
+ "tar-stream": "^3.0.0",
+ "zip-stream": "^5.0.1"
+ },
+ "dependencies": {
+ "tar-stream": {
+ "version": "3.1.6",
+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.1.6.tgz",
+ "integrity": "sha512-B/UyjYwPpMBv+PaFSWAmtYjwdrlEaZQEhMIBFNC5oEG8lpiW8XjcSdmEaClj28ArfKScKHs2nshz3k2le6crsg==",
+ "requires": {
+ "b4a": "^1.6.4",
+ "fast-fifo": "^1.2.0",
+ "streamx": "^2.15.0"
+ }
+ }
+ }
+ },
+ "archiver-utils": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-4.0.1.tgz",
+ "integrity": "sha512-Q4Q99idbvzmgCTEAAhi32BkOyq8iVI5EwdO0PmBDSGIzzjYNdcFn7Q7k3OzbLy4kLUPXfJtG6fO2RjftXbobBg==",
+ "requires": {
+ "glob": "^8.0.0",
+ "graceful-fs": "^4.2.0",
+ "lazystream": "^1.0.0",
+ "lodash": "^4.17.15",
+ "normalize-path": "^3.0.0",
+ "readable-stream": "^3.6.0"
+ }
+ },
+ "array-flatten": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
+ "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg=="
+ },
+ "async": {
+ "version": "3.2.4",
+ "resolved": "https://registry.npmjs.org/async/-/async-3.2.4.tgz",
+ "integrity": "sha512-iAB+JbDEGXhyIUavoDl9WP/Jj106Kz9DEn1DPgYw5ruDn0e3Wgi3sKFm55sASdGBNOQB8F59d9qQ7deqrHA8wQ=="
+ },
+ "b4a": {
+ "version": "1.6.4",
+ "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.6.4.tgz",
+ "integrity": "sha512-fpWrvyVHEKyeEvbKZTVOeZF3VSKKWtJxFIxX/jaVPf+cLbGUSitjb49pHLqPV2BUNNZ0LcoeEGfE/YCpyDYHIw=="
+ },
+ "balanced-match": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="
+ },
+ "base64-js": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="
+ },
+ "bl": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
+ "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
+ "requires": {
+ "buffer": "^5.5.0",
+ "inherits": "^2.0.4",
+ "readable-stream": "^3.4.0"
+ }
+ },
+ "body-parser": {
+ "version": "1.20.1",
+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz",
+ "integrity": "sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==",
+ "requires": {
+ "bytes": "3.1.2",
+ "content-type": "~1.0.4",
+ "debug": "2.6.9",
+ "depd": "2.0.0",
+ "destroy": "1.2.0",
+ "http-errors": "2.0.0",
+ "iconv-lite": "0.4.24",
+ "on-finished": "2.4.1",
+ "qs": "6.11.0",
+ "raw-body": "2.5.1",
+ "type-is": "~1.6.18",
+ "unpipe": "1.0.0"
+ }
+ },
+ "brace-expansion": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz",
+ "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==",
+ "requires": {
+ "balanced-match": "^1.0.0"
+ }
+ },
+ "buffer": {
+ "version": "5.7.1",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
+ "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
+ "requires": {
+ "base64-js": "^1.3.1",
+ "ieee754": "^1.1.13"
+ }
+ },
+ "buffer-crc32": {
+ "version": "0.2.13",
+ "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz",
+ "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="
+ },
+ "busboy": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
+ "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
+ "requires": {
+ "streamsearch": "^1.1.0"
+ }
+ },
+ "bytes": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="
+ },
+ "call-bind": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz",
+ "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==",
+ "requires": {
+ "function-bind": "^1.1.1",
+ "get-intrinsic": "^1.0.2"
+ }
+ },
+ "compress-commons": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/compress-commons/-/compress-commons-5.0.1.tgz",
+ "integrity": "sha512-MPh//1cERdLtqwO3pOFLeXtpuai0Y2WCd5AhtKxznqM7WtaMYaOEMSgn45d9D10sIHSfIKE603HlOp8OPGrvag==",
+ "requires": {
+ "crc-32": "^1.2.0",
+ "crc32-stream": "^5.0.0",
+ "normalize-path": "^3.0.0",
+ "readable-stream": "^3.6.0"
+ }
+ },
+ "content-disposition": {
+ "version": "0.5.4",
+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
+ "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
+ "requires": {
+ "safe-buffer": "5.2.1"
+ }
+ },
+ "content-type": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="
+ },
+ "cookie": {
+ "version": "0.5.0",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz",
+ "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw=="
+ },
+ "cookie-signature": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
+ "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ=="
+ },
+ "core-util-is": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
+ "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="
+ },
+ "crc-32": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz",
+ "integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ=="
+ },
+ "crc32-stream": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/crc32-stream/-/crc32-stream-5.0.0.tgz",
+ "integrity": "sha512-B0EPa1UK+qnpBZpG+7FgPCu0J2ETLpXq09o9BkLkEAhdB6Z61Qo4pJ3JYu0c+Qi+/SAL7QThqnzS06pmSSyZaw==",
+ "requires": {
+ "crc-32": "^1.2.0",
+ "readable-stream": "^3.4.0"
+ }
+ },
+ "debug": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+ "requires": {
+ "ms": "2.0.0"
+ }
+ },
+ "depd": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="
+ },
+ "destroy": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
+ "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg=="
+ },
+ "ee-first": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="
+ },
+ "encodeurl": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
+ "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w=="
+ },
+ "end-of-stream": {
+ "version": "1.4.4",
+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz",
+ "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==",
+ "requires": {
+ "once": "^1.4.0"
+ }
+ },
+ "escape-html": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="
+ },
+ "etag": {
+ "version": "1.8.1",
+ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="
+ },
+ "express": {
+ "version": "4.18.2",
+ "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz",
+ "integrity": "sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==",
+ "requires": {
+ "accepts": "~1.3.8",
+ "array-flatten": "1.1.1",
+ "body-parser": "1.20.1",
+ "content-disposition": "0.5.4",
+ "content-type": "~1.0.4",
+ "cookie": "0.5.0",
+ "cookie-signature": "1.0.6",
+ "debug": "2.6.9",
+ "depd": "2.0.0",
+ "encodeurl": "~1.0.2",
+ "escape-html": "~1.0.3",
+ "etag": "~1.8.1",
+ "finalhandler": "1.2.0",
+ "fresh": "0.5.2",
+ "http-errors": "2.0.0",
+ "merge-descriptors": "1.0.1",
+ "methods": "~1.1.2",
+ "on-finished": "2.4.1",
+ "parseurl": "~1.3.3",
+ "path-to-regexp": "0.1.7",
+ "proxy-addr": "~2.0.7",
+ "qs": "6.11.0",
+ "range-parser": "~1.2.1",
+ "safe-buffer": "5.2.1",
+ "send": "0.18.0",
+ "serve-static": "1.15.0",
+ "setprototypeof": "1.2.0",
+ "statuses": "2.0.1",
+ "type-is": "~1.6.18",
+ "utils-merge": "1.0.1",
+ "vary": "~1.1.2"
+ }
+ },
+ "express-fileupload": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/express-fileupload/-/express-fileupload-1.4.1.tgz",
+ "integrity": "sha512-9F6SkbxbEOA9cYOBZ8tnn238jL+bGfacQuUO/JqPWp5t+piUcoDcESvKwAXsQV7IHGxmI5bMj3QxMWOKOIsMCg==",
+ "requires": {
+ "busboy": "^1.6.0"
+ }
+ },
+ "fast-extend": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/fast-extend/-/fast-extend-1.0.2.tgz",
+ "integrity": "sha512-XXA9RmlPatkFKUzqVZAFth18R4Wo+Xug/S+C7YlYA3xrXwfPlW3dqNwOb4hvQo7wZJ2cNDYhrYuPzVOfHy5/uQ=="
+ },
+ "fast-fifo": {
+ "version": "1.3.2",
+ "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz",
+ "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ=="
+ },
+ "finalhandler": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz",
+ "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==",
+ "requires": {
+ "debug": "2.6.9",
+ "encodeurl": "~1.0.2",
+ "escape-html": "~1.0.3",
+ "on-finished": "2.4.1",
+ "parseurl": "~1.3.3",
+ "statuses": "2.0.1",
+ "unpipe": "~1.0.0"
+ }
+ },
+ "forwarded": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="
+ },
+ "fresh": {
+ "version": "0.5.2",
+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
+ "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q=="
+ },
+ "fs-constants": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
+ "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="
+ },
+ "fs-monkey": {
+ "version": "0.3.3",
+ "resolved": "https://registry.npmjs.org/fs-monkey/-/fs-monkey-0.3.3.tgz",
+ "integrity": "sha512-FNUvuTAJ3CqCQb5ELn+qCbGR/Zllhf2HtwsdAtBi59s1WeCjKMT81fHcSu7dwIskqGVK+MmOrb7VOBlq3/SItw=="
+ },
+ "fs.realpath": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
+ "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw=="
+ },
+ "function-bind": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="
+ },
+ "get-intrinsic": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.1.tgz",
+ "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==",
+ "requires": {
+ "function-bind": "^1.1.1",
+ "has": "^1.0.3",
+ "has-proto": "^1.0.1",
+ "has-symbols": "^1.0.3"
+ }
+ },
+ "glob": {
+ "version": "8.1.0",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-8.1.0.tgz",
+ "integrity": "sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ==",
+ "requires": {
+ "fs.realpath": "^1.0.0",
+ "inflight": "^1.0.4",
+ "inherits": "2",
+ "minimatch": "^5.0.1",
+ "once": "^1.3.0"
+ }
+ },
+ "graceful-fs": {
+ "version": "4.2.11",
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="
+ },
+ "has": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/has/-/has-1.0.4.tgz",
+ "integrity": "sha512-qdSAmqLF6209RFj4VVItywPMbm3vWylknmB3nvNiUIs72xAimcM8nVYxYr7ncvZq5qzk9MKIZR8ijqD/1QuYjQ=="
+ },
+ "has-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.1.tgz",
+ "integrity": "sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg=="
+ },
+ "has-symbols": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz",
+ "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A=="
+ },
+ "http-errors": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
+ "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==",
+ "requires": {
+ "depd": "2.0.0",
+ "inherits": "2.0.4",
+ "setprototypeof": "1.2.0",
+ "statuses": "2.0.1",
+ "toidentifier": "1.0.1"
+ }
+ },
+ "iconv-lite": {
+ "version": "0.4.24",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
+ "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
+ "requires": {
+ "safer-buffer": ">= 2.1.2 < 3"
+ }
+ },
+ "ieee754": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="
+ },
+ "inflight": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
+ "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
+ "requires": {
+ "once": "^1.3.0",
+ "wrappy": "1"
+ }
+ },
+ "inherits": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
+ },
+ "ipaddr.js": {
+ "version": "1.9.1",
+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="
+ },
+ "isarray": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
+ "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="
+ },
+ "lazystream": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/lazystream/-/lazystream-1.0.1.tgz",
+ "integrity": "sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw==",
+ "requires": {
+ "readable-stream": "^2.0.5"
+ },
+ "dependencies": {
+ "readable-stream": {
+ "version": "2.3.8",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
+ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
+ "requires": {
+ "core-util-is": "~1.0.0",
+ "inherits": "~2.0.3",
+ "isarray": "~1.0.0",
+ "process-nextick-args": "~2.0.0",
+ "safe-buffer": "~5.1.1",
+ "string_decoder": "~1.1.1",
+ "util-deprecate": "~1.0.1"
+ }
+ },
+ "safe-buffer": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
+ "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
+ },
+ "string_decoder": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
+ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
+ "requires": {
+ "safe-buffer": "~5.1.0"
+ }
+ }
+ }
+ },
+ "lodash": {
+ "version": "4.17.21",
+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
+ "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="
+ },
+ "media-typer": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
+ "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ=="
+ },
+ "memfs": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/memfs/-/memfs-3.0.4.tgz",
+ "integrity": "sha512-OcZEzwX9E5AoY8SXjuAvw0DbIAYwUzV/I236I8Pqvrlv7sL/Y0E9aRCon05DhaV8pg1b32uxj76RgW0s5xjHBA==",
+ "requires": {
+ "fast-extend": "1.0.2",
+ "fs-monkey": "0.3.3"
+ }
+ },
+ "merge-descriptors": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz",
+ "integrity": "sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w=="
+ },
+ "methods": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
+ "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w=="
+ },
+ "mime": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
+ "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg=="
+ },
+ "mime-db": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="
+ },
+ "mime-types": {
+ "version": "2.1.35",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+ "requires": {
+ "mime-db": "1.52.0"
+ }
+ },
+ "minimatch": {
+ "version": "5.1.6",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz",
+ "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==",
+ "requires": {
+ "brace-expansion": "^2.0.1"
+ }
+ },
+ "ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="
+ },
+ "negotiator": {
+ "version": "0.6.3",
+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
+ "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg=="
+ },
+ "normalize-path": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
+ "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA=="
+ },
+ "object-inspect": {
+ "version": "1.13.0",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.0.tgz",
+ "integrity": "sha512-HQ4J+ic8hKrgIt3mqk6cVOVrW2ozL4KdvHlqpBv9vDYWx9ysAgENAdvy4FoGF+KFdhR7nQTNm5J0ctAeOwn+3g=="
+ },
+ "on-finished": {
+ "version": "2.4.1",
+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
+ "requires": {
+ "ee-first": "1.1.1"
+ }
+ },
+ "once": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+ "requires": {
+ "wrappy": "1"
+ }
+ },
+ "pako": {
+ "version": "1.0.11",
+ "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
+ "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw=="
+ },
+ "parseurl": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="
+ },
+ "path-to-regexp": {
+ "version": "0.1.7",
+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
+ "integrity": "sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ=="
+ },
+ "pdf-lib": {
+ "version": "1.17.1",
+ "resolved": "https://registry.npmjs.org/pdf-lib/-/pdf-lib-1.17.1.tgz",
+ "integrity": "sha512-V/mpyJAoTsN4cnP31vc0wfNA1+p20evqqnap0KLoRUN0Yk/p3wN52DOEsL4oBFcLdb76hlpKPtzJIgo67j/XLw==",
+ "requires": {
+ "@pdf-lib/standard-fonts": "^1.0.0",
+ "@pdf-lib/upng": "^1.0.1",
+ "pako": "^1.0.11",
+ "tslib": "^1.11.1"
+ }
+ },
+ "process-nextick-args": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
+ "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="
+ },
+ "proxy-addr": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
+ "requires": {
+ "forwarded": "0.2.0",
+ "ipaddr.js": "1.9.1"
+ }
+ },
+ "qs": {
+ "version": "6.11.0",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz",
+ "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==",
+ "requires": {
+ "side-channel": "^1.0.4"
+ }
+ },
+ "queue-tick": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/queue-tick/-/queue-tick-1.0.1.tgz",
+ "integrity": "sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag=="
+ },
+ "range-parser": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
+ "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="
+ },
+ "raw-body": {
+ "version": "2.5.1",
+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz",
+ "integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==",
+ "requires": {
+ "bytes": "3.1.2",
+ "http-errors": "2.0.0",
+ "iconv-lite": "0.4.24",
+ "unpipe": "1.0.0"
+ }
+ },
+ "readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "requires": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ }
+ },
+ "readdir-glob": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/readdir-glob/-/readdir-glob-1.1.3.tgz",
+ "integrity": "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA==",
+ "requires": {
+ "minimatch": "^5.1.0"
+ }
+ },
+ "safe-buffer": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="
+ },
+ "safer-buffer": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
+ },
+ "send": {
+ "version": "0.18.0",
+ "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz",
+ "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==",
+ "requires": {
+ "debug": "2.6.9",
+ "depd": "2.0.0",
+ "destroy": "1.2.0",
+ "encodeurl": "~1.0.2",
+ "escape-html": "~1.0.3",
+ "etag": "~1.8.1",
+ "fresh": "0.5.2",
+ "http-errors": "2.0.0",
+ "mime": "1.6.0",
+ "ms": "2.1.3",
+ "on-finished": "2.4.1",
+ "range-parser": "~1.2.1",
+ "statuses": "2.0.1"
+ },
+ "dependencies": {
+ "ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
+ }
+ }
+ },
+ "serve-static": {
+ "version": "1.15.0",
+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz",
+ "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==",
+ "requires": {
+ "encodeurl": "~1.0.2",
+ "escape-html": "~1.0.3",
+ "parseurl": "~1.3.3",
+ "send": "0.18.0"
+ }
+ },
+ "setprototypeof": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="
+ },
+ "side-channel": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz",
+ "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==",
+ "requires": {
+ "call-bind": "^1.0.0",
+ "get-intrinsic": "^1.0.2",
+ "object-inspect": "^1.9.0"
+ }
+ },
+ "statuses": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
+ "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ=="
+ },
+ "streamsearch": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
+ "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg=="
+ },
+ "streamx": {
+ "version": "2.15.1",
+ "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.15.1.tgz",
+ "integrity": "sha512-fQMzy2O/Q47rgwErk/eGeLu/roaFWV0jVsogDmrszM9uIw8L5OA+t+V93MgYlufNptfjmYR1tOMWhei/Eh7TQA==",
+ "requires": {
+ "fast-fifo": "^1.1.0",
+ "queue-tick": "^1.0.1"
+ }
+ },
+ "string_decoder": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
+ "requires": {
+ "safe-buffer": "~5.2.0"
+ }
+ },
+ "tar-stream": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
+ "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
+ "requires": {
+ "bl": "^4.0.3",
+ "end-of-stream": "^1.4.1",
+ "fs-constants": "^1.0.0",
+ "inherits": "^2.0.3",
+ "readable-stream": "^3.1.1"
+ }
+ },
+ "toidentifier": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="
+ },
+ "tslib": {
+ "version": "1.14.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",
+ "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="
+ },
+ "type-is": {
+ "version": "1.6.18",
+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
+ "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
+ "requires": {
+ "media-typer": "0.3.0",
+ "mime-types": "~2.1.24"
+ }
+ },
+ "unpipe": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
+ "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="
+ },
+ "util-deprecate": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="
+ },
+ "utils-merge": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
+ "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA=="
+ },
+ "vary": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="
+ },
+ "wrappy": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
+ },
+ "zip-stream": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/zip-stream/-/zip-stream-5.0.1.tgz",
+ "integrity": "sha512-UfZ0oa0C8LI58wJ+moL46BDIMgCQbnsb+2PoiJYtonhBsMh2bq1eRBVkvjfVsqbEHd9/EgKPUuL9saSSsec8OA==",
+ "requires": {
+ "archiver-utils": "^4.0.1",
+ "compress-commons": "^5.0.1",
+ "readable-stream": "^3.6.0"
+ }
+ }
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 000000000..0c554ac6a
--- /dev/null
+++ b/package.json
@@ -0,0 +1,19 @@
+{
+ "name": "pdfjs",
+ "version": "1.0.0",
+ "description": "",
+ "main": "index.js",
+ "scripts": {
+ "test": "node ."
+ },
+ "author": "",
+ "license": "ISC",
+ "dependencies": {
+ "@wasmer/wasmfs": "^0.12.0",
+ "archiver": "^6.0.1",
+ "express": "^4.18.2",
+ "express-fileupload": "^1.4.1",
+ "pdf-lib": "^1.17.1"
+ },
+ "type": "module"
+}
diff --git a/public/exampleWorkflows.js b/public/exampleWorkflows.js
new file mode 100644
index 000000000..f13b9ad83
--- /dev/null
+++ b/public/exampleWorkflows.js
@@ -0,0 +1,139 @@
+// JSON Representation of this Node Tree:
+// https://discord.com/channels/1068636748814483718/1099390571493195898/1118192754103693483
+// https://cdn.discordapp.com/attachments/1099390571493195898/1118192753759764520/image.png?ex=6537dba7&is=652566a7&hm=dc46820ef7c34bc37424794966c5f66f93ba0e15a740742c364d47d31ea119a9&
+export const discordWorkflow = {
+ outputOptions: {
+ zip: false
+ },
+ operations: [
+ {
+ type: "extract",
+ values: { "index": "1" },
+ operations: [
+ {
+ type: "removeObjects",
+ values: { "objectNames": "photo, josh" },
+ operations: [
+ {
+ type: "wait",
+ values: { "id": 1 }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ type: "extract",
+ values: { "index": "2-5" },
+ operations: [
+ {
+ type: "fillField",
+ values: { "objectName": "name", "inputValue": "Josh" },
+ operations: [
+ {
+ type: "wait",
+ values: { "id": 1 }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ type: "done", // This gets called when the other merge-ops with the same id finish.
+ values: { "id": 1 },
+ operations: [
+ {
+ type: "merge",
+ values: {},
+ operations: []
+ }
+ ]
+ },
+ {
+ type: "extractImages",
+ values: {},
+ operations: []
+ },
+ {
+ type: "merge",
+ values: {},
+ operations: [
+ {
+ type: "transform",
+ values: { "scale": "2x", "rotation": "90deg" },
+ operations: []
+ }
+ ]
+ }
+ ]
+}
+
+// This will merge all input files into one giant document
+export const mergeOnly = {
+ outputOptions: {
+ zip: false
+ },
+ operations: [
+ {
+ type: "merge",
+ values: {},
+ operations: []
+ }
+ ]
+}
+
+// Extract Pages and store them in a new document
+export const extractOnly = {
+ outputOptions: {
+ zip: false
+ },
+ operations: [
+ {
+ type: "extract",
+ values: { "pagesToExtractArray": [0, 2] },
+ operations: []
+ }
+ ]
+}
+
+// Split a document up into multiple documents
+export const splitOnly = {
+ outputOptions: {
+ zip: false
+ },
+ operations: [
+ {
+ type: "split",
+ values: { "pagesToSplitAfterArray": [2, 10] },
+ operations: []
+ }
+ ]
+}
+
+// Split a document up into multiple documents
+export const rotateOnly = {
+ outputOptions: {
+ zip: false
+ },
+ operations: [
+ {
+ type: "rotate",
+ values: { "rotation": -90 },
+ operations: []
+ }
+ ]
+}
+
+// Split a document up into multiple documents
+export const imposeOnly = {
+ outputOptions: {
+ zip: false
+ },
+ operations: [
+ {
+ type: "impose",
+ values: { "nup": 2, "format": "A4L" },
+ operations: []
+ }
+ ]
+}
\ No newline at end of file
diff --git a/public/functions.js b/public/functions.js
new file mode 100644
index 000000000..ad7ae00ee
--- /dev/null
+++ b/public/functions.js
@@ -0,0 +1,38 @@
+// PDFLib gets importet via index.html script-tag
+import * as pdfcpuWraopper from "./wasm/pdfcpu-wrapper-browser.js";
+
+import { extractPages as dependantExtractPages } from "./functions/extractPages.js";
+import { impose as dependantImpose } from './functions/impose.js';
+import { mergePDFs as dependantMergePDFs } from './functions/mergePDFs.js';
+import { rotatePages as dependantRotatePages } from './functions/rotatePages.js';
+import { scaleContent as dependantScaleContent} from './functions/scaleContent.js';
+import { scalePage as dependantScalePage } from './functions/scalePage.js';
+import { splitPDF as dependantSplitPDF } from './functions/splitPDF.js';
+
+export async function extractPages(snapshot, pagesToExtractArray) {
+ return dependantExtractPages(snapshot, pagesToExtractArray, PDFLib);
+}
+
+export async function impose(snapshot, nup, format) {
+ return dependantImpose(snapshot, nup, format, pdfcpuWraopper);
+}
+
+export async function mergePDFs(snapshots) {
+ return dependantMergePDFs(snapshots, PDFLib);
+}
+
+export async function rotatePages(snapshot, rotation) {
+ return dependantRotatePages(snapshot, rotation, PDFLib);
+}
+
+export async function scaleContent(snapshot, scaleFactor) {
+ return dependantScaleContent(snapshot, scaleFactor, PDFLib);
+}
+
+export async function scalePage(snapshot, pageSize) {
+ return dependantScalePage(snapshot, pageSize, PDFLib);
+}
+
+export async function splitPDF(snapshot, splitAfterPageArray) {
+ return dependantSplitPDF(snapshot, splitAfterPageArray, PDFLib);
+}
\ No newline at end of file
diff --git a/public/functions/extractPages.js b/public/functions/extractPages.js
new file mode 100644
index 000000000..20dee1503
--- /dev/null
+++ b/public/functions/extractPages.js
@@ -0,0 +1,23 @@
+export async function extractPages(snapshot, pagesToExtractArray, PDFLib) {
+ const pdfDoc = await PDFLib.PDFDocument.load(snapshot)
+
+ // TODO: invent a better format for pagesToExtractArray and convert it.
+ return createSubDocument(pdfDoc, pagesToExtractArray, PDFLib);
+};
+
+export async function createSubDocument(pdfDoc, pagesToExtractArray, PDFLib) {
+ const subDocument = await PDFLib.PDFDocument.create();
+
+ // Check that array max number is not larger pdf pages number
+ if(Math.max(...pagesToExtractArray) >= pdfDoc.getPageCount()) {
+ throw new Error(`The PDF document only has ${pdfDoc.getPageCount()} pages and you tried to extract page ${Math.max(...pagesToExtractArray)}`);
+ }
+
+ const copiedPages = await subDocument.copyPages(pdfDoc, pagesToExtractArray);
+
+ for (let i = 0; i < copiedPages.length; i++) {
+ subDocument.addPage(copiedPages[i]);
+ }
+
+ return subDocument.save();
+}
\ No newline at end of file
diff --git a/public/functions/impose.js b/public/functions/impose.js
new file mode 100644
index 000000000..894e44bd4
--- /dev/null
+++ b/public/functions/impose.js
@@ -0,0 +1,12 @@
+export async function impose(snapshot, nup, format, pdfcpuWraopper) {
+ return await pdfcpuWraopper.oneToOne([
+ "pdfcpu.wasm",
+ "nup",
+ "-c",
+ "disable",
+ 'f:' + format,
+ "/output.pdf",
+ String(nup),
+ "input.pdf",
+ ], snapshot);
+}
\ No newline at end of file
diff --git a/public/functions/mergePDFs.js b/public/functions/mergePDFs.js
new file mode 100644
index 000000000..109efc66c
--- /dev/null
+++ b/public/functions/mergePDFs.js
@@ -0,0 +1,13 @@
+export const mergePDFs = async (snapshots, PDFLib) => {
+
+ const mergedPdf = await PDFLib.PDFDocument.create();
+
+ for (let i = 0; i < snapshots.length; i++) {
+ const pdfToMerge = await PDFLib.PDFDocument.load(snapshots[i]);
+
+ const copiedPages = await mergedPdf.copyPages(pdfToMerge, pdfToMerge.getPageIndices());
+ copiedPages.forEach((page) => mergedPdf.addPage(page));
+ }
+
+ return mergedPdf.save();
+};
\ No newline at end of file
diff --git a/public/functions/rotatePages.js b/public/functions/rotatePages.js
new file mode 100644
index 000000000..c42b28862
--- /dev/null
+++ b/public/functions/rotatePages.js
@@ -0,0 +1,16 @@
+export async function rotatePages (snapshot, rotation, PDFLib) {
+ // Load the original PDF file
+ const pdfDoc = await PDFLib.PDFDocument.load(snapshot, {
+ parseSpeed: PDFLib.ParseSpeeds.Fastest,
+ });
+
+ const pages = pdfDoc.getPages();
+
+ pages.forEach(page => {
+ // Change page size
+ page.setRotation(PDFLib.degrees(rotation))
+ });
+
+ // Serialize the modified document
+ return pdfDoc.save();
+};
\ No newline at end of file
diff --git a/public/functions/scaleContent.js b/public/functions/scaleContent.js
new file mode 100644
index 000000000..52847af90
--- /dev/null
+++ b/public/functions/scaleContent.js
@@ -0,0 +1,27 @@
+export async function scaleContent(snapshot, scaleFactor, PDFLib) {
+ // Load the original PDF file
+ const pdfDoc = await PDFLib.PDFDocument.load(snapshot, {
+ parseSpeed: PDFLib.ParseSpeeds.Fastest,
+ });
+
+ const pages = pdfDoc.getPages();
+
+ pages.forEach(page => {
+ const width = page.getWidth();
+ const height = page.getHeight();
+
+ // Scale content
+ page.scaleContent(scaleFactor, scaleFactor);
+ const scaled_diff = {
+ width: Math.round(width - scaleFactor * width),
+ height: Math.round(height - scaleFactor * height),
+ };
+
+ // Center content in new page format
+ page.translateContent(Math.round(scaled_diff.width / 2), Math.round(scaled_diff.height / 2));
+
+ });
+
+ // Serialize the modified document
+ return pdfDoc.save();
+};
\ No newline at end of file
diff --git a/public/functions/scalePage.js b/public/functions/scalePage.js
new file mode 100644
index 000000000..3696280f7
--- /dev/null
+++ b/public/functions/scalePage.js
@@ -0,0 +1,29 @@
+export async function scalePage(snapshot, pageSize, PDFLib) {
+ // Load the original PDF file
+ const pdfDoc = await PDFLib.PDFDocument.load(snapshot, {
+ parseSpeed: PDFLib.ParseSpeeds.Fastest,
+ });
+
+ const new_size = pageSize;
+
+ const pages = pdfDoc.getPages();
+
+ pages.forEach(page => {
+ // Change page size
+ page.setSize(new_size.width, new_size.height);
+ });
+
+ // Serialize the modified document
+ return pdfDoc.save();
+};
+
+export const PageSize = {
+ a4: {
+ width: 594.96,
+ height: 841.92
+ },
+ letter: {
+ width: 612,
+ height: 792
+ }
+};
\ No newline at end of file
diff --git a/public/functions/splitPDF.js b/public/functions/splitPDF.js
new file mode 100644
index 000000000..dac378ce1
--- /dev/null
+++ b/public/functions/splitPDF.js
@@ -0,0 +1,24 @@
+import { createSubDocument } from "./extractPages.js";
+
+export async function splitPDF(snapshot, splitAfterPageArray, PDFLib) {
+ const pdfDoc = await PDFLib.PDFDocument.load(snapshot)
+
+ const numberOfPages = pdfDoc.getPages().length;
+
+ let pagesArray = [];
+ let splitAfter = splitAfterPageArray.shift();
+ const subDocuments = [];
+
+ for (let i = 0; i < numberOfPages; i++) {
+ if(i > splitAfter && pagesArray.length > 0) {
+ subDocuments.push(await createSubDocument(pdfDoc, pagesArray, PDFLib));
+ splitAfter = splitAfterPageArray.shift();
+ pagesArray = [];
+ }
+ pagesArray.push(i);
+ }
+ subDocuments.push(await createSubDocument(pdfDoc, pagesArray, PDFLib));
+ pagesArray = [];
+
+ return subDocuments;
+};
\ No newline at end of file
diff --git a/public/index.css b/public/index.css
new file mode 100644
index 000000000..e69de29bb
diff --git a/public/index.html b/public/index.html
new file mode 100644
index 000000000..f1cf9669c
--- /dev/null
+++ b/public/index.html
@@ -0,0 +1,33 @@
+
+
+
+
+
+ Document
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/public/index.js b/public/index.js
new file mode 100644
index 000000000..55709d10d
--- /dev/null
+++ b/public/index.js
@@ -0,0 +1,43 @@
+import { scaleContent } from "./functions/scaleContent.js";
+import { scalePage, PageSize } from "./functions/scalePage.js";
+import * as exampleWorkflows from "./exampleWorkflows.js";
+import { traverseOperations } from "./traverseOperations.js";
+import * as Functions from "./functions.js";
+
+(async (workflow) => {
+ const pdfFileInput = document.getElementById('pdfFile');
+ const doneButton = document.getElementById("doneButton");
+
+ doneButton.addEventListener('click', async (e) => {
+ console.log("Starting...");
+
+ const files = Array.from(pdfFileInput.files);
+ console.log(files);
+ const inputs = await Promise.all(files.map(async file => {
+ return {
+ originalFileName: file.name.replace(/\.[^/.]+$/, ""),
+ fileName: file.name.replace(/\.[^/.]+$/, ""),
+ buffer: new Uint8Array(await file.arrayBuffer())
+ }
+ }));
+ console.log(inputs);
+
+ const traverse = traverseOperations(workflow.operations, inputs, Functions);
+
+ let pdfResults;
+ let iteration;
+ while (true) {
+ iteration = await traverse.next();
+ if (iteration.done) {
+ pdfResults = iteration.value;
+ console.log(`data: processing done\n\n`);
+ break;
+ }
+ console.log(`data: ${iteration.value}\n\n`);
+ }
+
+ pdfResults.forEach(result => {
+ download(result.buffer, result.fileName, "application/pdf");
+ });
+ });
+})(exampleWorkflows.imposeOnly);
\ No newline at end of file
diff --git a/public/organizeWaitOperations.js b/public/organizeWaitOperations.js
new file mode 100644
index 000000000..c994502af
--- /dev/null
+++ b/public/organizeWaitOperations.js
@@ -0,0 +1,43 @@
+
+export function organizeWaitOperations(operations) {
+
+ // Initialize an object to store the counts and associated "done" operations
+ const waitCounts = {};
+ const doneOperations = {};
+
+ // Function to count "type: wait" operations and associate "done" operations per id
+ function countWaitOperationsAndDone(operations) {
+ for (const operation of operations) {
+ if (operation.type === "wait") {
+ const id = operation.values.id;
+ if (id in waitCounts) {
+ waitCounts[id]++;
+ } else {
+ waitCounts[id] = 1;
+ }
+ }
+ if (operation.type === "done") {
+ const id = operation.values.id;
+ doneOperations[id] = operation;
+ }
+ if (operation.operations) {
+ countWaitOperationsAndDone(operation.operations);
+ }
+ }
+ }
+
+ // Start counting and associating from the root operations
+ countWaitOperationsAndDone(operations);
+
+ // Combine counts and associated "done" operations
+ const result = {};
+ for (const id in waitCounts) {
+ result[id] = {
+ waitCount: waitCounts[id],
+ doneOperation: doneOperations[id],
+ input: []
+ };
+ }
+ return result;
+}
+
diff --git a/public/traverseOperations.js b/public/traverseOperations.js
new file mode 100644
index 000000000..c9a0c455a
--- /dev/null
+++ b/public/traverseOperations.js
@@ -0,0 +1,133 @@
+import { organizeWaitOperations } from "./organizeWaitOperations.js";
+
+export async function * traverseOperations(operations, input, Functions) {
+ const waitOperations = organizeWaitOperations(operations);
+ let results = [];
+ yield* nextOperation(operations, input);
+ console.log("Done2");
+ return results;
+
+ async function * nextOperation(operations, input) {
+ if(Array.isArray(operations) && operations.length == 0) { // isEmpty
+ if(Array.isArray(input)) {
+ console.log("operation done: " + input[0].fileName + input.length > 1 ? "+" : "");
+ results = results.concat(input);
+ return;
+ }
+ else {
+ console.log("operation done: " + input.fileName);
+ results.push(input);
+ return;
+ }
+ }
+
+ for (let i = 0; i < operations.length; i++) {
+ yield* computeOperation(operations[i], structuredClone(input));
+ }
+ }
+
+ async function * computeOperation(operation, input) {
+ yield "Starting: " + operation.type;
+ switch (operation.type) {
+ case "done": // Skip this, because it is a valid node.
+ break;
+ case "wait":
+ const waitOperation = waitOperations[operation.values.id];
+
+ if(Array.isArray(input)) {
+ waitOperation.input.concat(input); // TODO: May have unexpected concequences. Needs further testing!
+ }
+ else {
+ waitOperation.input.push(input);
+ }
+
+ waitOperation.waitCount--;
+ if(waitOperation.waitCount == 0) {
+ yield* nextOperation(waitOperation.doneOperation.operations, waitOperation.input);
+ }
+ break;
+ case "extract":
+ yield* nToN(input, operation, async (input) => {
+ input.fileName += "_extractedPages";
+ input.buffer = await Functions.extractPages(input.buffer, operation.values["pagesToExtractArray"]);
+ });
+ break;
+ case "impose":
+ yield* nToN(input, operation, async (input) => {
+ input.fileName += "_imposed";
+ input.buffer = await Functions.impose(input.buffer, operation.values["nup"], operation.values["format"]);
+ });
+ break;
+ case "merge":
+ yield* nToOne(input, operation, async (inputs) => {
+ return {
+ originalFileName: inputs.map(input => input.originalFileName).join("_and_"),
+ fileName: inputs.map(input => input.fileName).join("_and_") + "_merged",
+ buffer: await Functions.mergePDFs(inputs.map(input => input.buffer))
+ }
+ });
+ break;
+ case "rotate":
+ yield* nToN(input, operation, async (input) => {
+ input.fileName += "_turned";
+ input.buffer = await Functions.rotatePages(input.buffer, operation.values["rotation"]);
+ });
+ break;
+ case "split":
+ // TODO: A split might break the done condition, it may count multiple times. Needs further testing!
+ yield* oneToN(input, operation, async (input) => {
+ const splitResult = await Functions.splitPDF(input.buffer, operation.values["pagesToSplitAfterArray"]);
+
+ const splits = [];
+ for (let j = 0; j < splitResult.length; j++) {
+ splits.push({
+ originalFileName: input.originalFileName,
+ fileName: input.fileName + "_split" + j,
+ buffer: splitResult[j]
+ })
+ }
+
+ input = splits;
+ });
+ break;
+ default:
+ throw new Error(`${operation.type} not implemented yet.`);
+ break;
+ }
+ }
+
+ async function * nToOne(inputs, operation, callback) {
+ if(!Array.isArray(inputs)) {
+ inputs = [inputs];
+ }
+
+ inputs = await callback(inputs);
+ yield* nextOperation(operation.operations, inputs);
+ }
+
+ async function * oneToN(input, operation, callback) {
+ if(Array.isArray(input)) {
+ for (let i = 0; i < input.length; i++) {
+ await callback(input[i]);
+ }
+ yield* nextOperation(operation.operations, input);
+ }
+ else {
+ await callback(input);
+ yield* nextOperation(operation.operations, input);
+ }
+ }
+
+ async function * nToN(input, operation, callback) {
+ if(Array.isArray(input)) {
+ for (let i = 0; i < input.length; i++) {
+ await callback(input[i]);
+ }
+ yield* nextOperation(operation.operations, input);
+ }
+ else {
+ await callback(input);
+ yield* nextOperation(operation.operations, input);
+ }
+ }
+}
\ No newline at end of file
diff --git a/public/wasm/browserfs.min.js b/public/wasm/browserfs.min.js
new file mode 100644
index 000000000..a9eca25ca
--- /dev/null
+++ b/public/wasm/browserfs.min.js
@@ -0,0 +1,8 @@
+!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.BrowserFS=e():t.BrowserFS=e()}(this,function(){return function(t){function e(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,e),i.l=!0,i.exports}var n={};return e.m=t,e.c=n,e.d=function(t,n,r){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:r})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=19)}([function(t,e,n){"use strict";function r(t){if(!(this instanceof r))return new r(t);u.call(this,t),f.call(this,t),t&&!1===t.readable&&(this.readable=!1),t&&!1===t.writable&&(this.writable=!1),this.allowHalfOpen=!0,t&&!1===t.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",i)}function i(){this.allowHalfOpen||this._writableState.ended||s(o,this)}function o(t){t.end()}var s=n(7),a=Object.keys||function(t){var e=[];for(var n in t)e.push(n);return e};t.exports=r;var c=n(3);c.inherits=n(1);var u=n(14),f=n(12);c.inherits(r,u);for(var h=a(f.prototype),p=0;pK)throw new RangeError("Invalid typed array length");var e=new Uint8Array(t);return e.__proto__=i.prototype,e}function i(t,e,n){if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return c(t)}return o(t,e,n)}function o(t,e,n){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return H(t)?h(t,e,n):"string"==typeof t?u(t,e):p(t)}function s(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function a(t,e,n){return s(t),t<=0?r(t):void 0!==e?"string"==typeof n?r(t).fill(e,n):r(t).fill(e):r(t)}function c(t){return s(t),r(t<0?0:0|l(t))}function u(t,e){if("string"==typeof e&&""!==e||(e="utf8"),!i.isEncoding(e))throw new TypeError('"encoding" must be a valid string encoding');var n=0|y(t,e),o=r(n),s=o.write(t,e);return s!==n&&(o=o.slice(0,s)),o}function f(t){for(var e=t.length<0?0:0|l(t.length),n=r(e),i=0;i=K)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+K.toString(16)+" bytes");return 0|t}function d(t){return+t!=t&&(t=0),i.alloc(+t)}function y(t,e){if(i.isBuffer(t))return t.length;if(Z(t)||H(t))return t.byteLength;"string"!=typeof t&&(t=""+t);var n=t.length;if(0===n)return 0;for(var r=!1;;)switch(e){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return B(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return V(t).length;default:if(r)return B(t).length;e=(""+e).toLowerCase(),r=!0}}function g(t,e,n){var r=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if(n>>>=0,e>>>=0,n<=e)return"";for(t||(t="utf8");;)switch(t){case"hex":return L(this,e,n);case"utf8":case"utf-8":return F(this,e,n);case"ascii":return R(this,e,n);case"latin1":case"binary":return T(this,e,n);case"base64":return O(this,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,e,n);default:if(r)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),r=!0}}function _(t,e,n){var r=t[e];t[e]=t[n],t[n]=r}function m(t,e,n,r,o){if(0===t.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,Y(n)&&(n=o?0:t.length-1),n<0&&(n=t.length+n),n>=t.length){if(o)return-1;n=t.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof e&&(e=i.from(e,r)),i.isBuffer(e))return 0===e.length?-1:w(t,e,n,r,o);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,e,n):Uint8Array.prototype.lastIndexOf.call(t,e,n):w(t,[e],n,r,o);throw new TypeError("val must be string, number or Buffer")}function w(t,e,n,r,i){function o(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}var s=1,a=t.length,c=e.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(t.length<2||e.length<2)return-1;s=2,a/=2,c/=2,n/=2}var u;if(i){var f=-1;for(u=n;ua&&(n=a-c),u=n;u>=0;u--){for(var h=!0,p=0;pi&&(r=i):r=i;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var s=0;s239?4:o>223?3:o>191?2:1;if(i+a<=n){var c,u,f,h;switch(a){case 1:o<128&&(s=o);break;case 2:c=t[i+1],128==(192&c)&&(h=(31&o)<<6|63&c)>127&&(s=h);break;case 3:c=t[i+1],u=t[i+2],128==(192&c)&&128==(192&u)&&(h=(15&o)<<12|(63&c)<<6|63&u)>2047&&(h<55296||h>57343)&&(s=h);break;case 4:c=t[i+1],u=t[i+2],f=t[i+3],128==(192&c)&&128==(192&u)&&128==(192&f)&&(h=(15&o)<<18|(63&c)<<12|(63&u)<<6|63&f)>65535&&h<1114112&&(s=h)}}null===s?(s=65533,a=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|1023&s),r.push(s),i+=a}return N(r)}function N(t){var e=t.length;if(e<=G)return String.fromCharCode.apply(String,t);for(var n="",r=0;rr)&&(n=r);for(var i="",o=e;on)throw new RangeError("Trying to access beyond buffer length")}function A(t,e,n,r,o,s){if(!i.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>o||et.length)throw new RangeError("Index out of range")}function P(t,e,n,r,i,o){if(n+r>t.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function C(t,e,n,r,i){return e=+e,n>>>=0,i||P(t,e,n,4,3.4028234663852886e38,-3.4028234663852886e38),J.write(t,e,n,r,23,4),n+4}function U(t,e,n,r,i){return e=+e,n>>>=0,i||P(t,e,n,8,1.7976931348623157e308,-1.7976931348623157e308),J.write(t,e,n,r,52,8),n+8}function M(t){if(t=t.trim().replace(Q,""),t.length<2)return"";for(;t.length%4!=0;)t+="=";return t}function j(t){return t<16?"0"+t.toString(16):t.toString(16)}function B(t,e){e=e||1/0;for(var n,r=t.length,i=null,o=[],s=0;s55295&&n<57344){if(!i){if(n>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===r){(e-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(e-=3)>-1&&o.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((e-=1)<0)break;o.push(n)}else if(n<2048){if((e-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((e-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function z(t){for(var e=[],n=0;n>8,i=n%256,o.push(i),o.push(r);return o}function V(t){return X.toByteArray(M(t))}function W(t,e,n,r){for(var i=0;i=e.length||i>=t.length);++i)e[i+n]=t[i];return i}function H(t){return t instanceof ArrayBuffer||null!=t&&null!=t.constructor&&"ArrayBuffer"===t.constructor.name&&"number"==typeof t.byteLength}function Z(t){return"function"==typeof ArrayBuffer.isView&&ArrayBuffer.isView(t)}function Y(t){return t!==t}/*!
+ * The buffer module from node.js, for the browser.
+ *
+ * @author Feross Aboukhadijeh
+ * @license MIT
+ */
+var X=n(20),J=n(21);e.Buffer=i,e.SlowBuffer=d,e.INSPECT_MAX_BYTES=50;var K=2147483647;e.kMaxLength=K,i.TYPED_ARRAY_SUPPORT=function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()}catch(t){return!1}}(),i.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),"undefined"!=typeof Symbol&&Symbol.species&&i[Symbol.species]===i&&Object.defineProperty(i,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),i.poolSize=8192,i.from=function(t,e,n){return o(t,e,n)},i.prototype.__proto__=Uint8Array.prototype,i.__proto__=Uint8Array,i.alloc=function(t,e,n){return a(t,e,n)},i.allocUnsafe=function(t){return c(t)},i.allocUnsafeSlow=function(t){return c(t)},i.isBuffer=function(t){return null!=t&&!0===t._isBuffer},i.compare=function(t,e){if(!i.isBuffer(t)||!i.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var n=t.length,r=e.length,o=0,s=Math.min(n,r);o0&&(t=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(t+=" ... ")),""},i.prototype.compare=function(t,e,n,r,o){if(!i.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===n&&(n=t?t.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),e<0||n>t.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&e>=n)return 0;if(r>=o)return-1;if(e>=n)return 1;if(e>>>=0,n>>>=0,r>>>=0,o>>>=0,this===t)return 0;for(var s=o-r,a=n-e,c=Math.min(s,a),u=this.slice(r,o),f=t.slice(e,n),h=0;h>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var i=this.length-e;if((void 0===n||n>i)&&(n=i),t.length>0&&(n<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return v(this,t,e,n);case"utf8":case"utf-8":return b(this,t,e,n);case"ascii":return S(this,t,e,n);case"latin1":case"binary":return E(this,t,e,n);case"base64":return k(this,t,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,t,e,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var G=4096;i.prototype.slice=function(t,e){var n=this.length;t=~~t,e=void 0===e?n:~~e,t<0?(t+=n)<0&&(t=0):t>n&&(t=n),e<0?(e+=n)<0&&(e=0):e>n&&(e=n),e>>=0,e>>>=0,n||D(t,e,this.length);for(var r=this[t],i=1,o=0;++o>>=0,e>>>=0,n||D(t,e,this.length);for(var r=this[t+--e],i=1;e>0&&(i*=256);)r+=this[t+--e]*i;return r},i.prototype.readUInt8=function(t,e){return t>>>=0,e||D(t,1,this.length),this[t]},i.prototype.readUInt16LE=function(t,e){return t>>>=0,e||D(t,2,this.length),this[t]|this[t+1]<<8},i.prototype.readUInt16BE=function(t,e){return t>>>=0,e||D(t,2,this.length),this[t]<<8|this[t+1]},i.prototype.readUInt32LE=function(t,e){return t>>>=0,e||D(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},i.prototype.readUInt32BE=function(t,e){return t>>>=0,e||D(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},i.prototype.readIntLE=function(t,e,n){t>>>=0,e>>>=0,n||D(t,e,this.length);for(var r=this[t],i=1,o=0;++o=i&&(r-=Math.pow(2,8*e)),r},i.prototype.readIntBE=function(t,e,n){t>>>=0,e>>>=0,n||D(t,e,this.length);for(var r=e,i=1,o=this[t+--r];r>0&&(i*=256);)o+=this[t+--r]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*e)),o},i.prototype.readInt8=function(t,e){return t>>>=0,e||D(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},i.prototype.readInt16LE=function(t,e){t>>>=0,e||D(t,2,this.length);var n=this[t]|this[t+1]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt16BE=function(t,e){t>>>=0,e||D(t,2,this.length);var n=this[t+1]|this[t]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt32LE=function(t,e){return t>>>=0,e||D(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},i.prototype.readInt32BE=function(t,e){return t>>>=0,e||D(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},i.prototype.readFloatLE=function(t,e){return t>>>=0,e||D(t,4,this.length),J.read(this,t,!0,23,4)},i.prototype.readFloatBE=function(t,e){return t>>>=0,e||D(t,4,this.length),J.read(this,t,!1,23,4)},i.prototype.readDoubleLE=function(t,e){return t>>>=0,e||D(t,8,this.length),J.read(this,t,!0,52,8)},i.prototype.readDoubleBE=function(t,e){return t>>>=0,e||D(t,8,this.length),J.read(this,t,!1,52,8)},i.prototype.writeUIntLE=function(t,e,n,r){if(t=+t,e>>>=0,n>>>=0,!r){A(this,t,e,n,Math.pow(2,8*n)-1,0)}var i=1,o=0;for(this[e]=255&t;++o>>=0,n>>>=0,!r){A(this,t,e,n,Math.pow(2,8*n)-1,0)}var i=n-1,o=1;for(this[e+i]=255&t;--i>=0&&(o*=256);)this[e+i]=t/o&255;return e+n},i.prototype.writeUInt8=function(t,e,n){return t=+t,e>>>=0,n||A(this,t,e,1,255,0),this[e]=255&t,e+1},i.prototype.writeUInt16LE=function(t,e,n){return t=+t,e>>>=0,n||A(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},i.prototype.writeUInt16BE=function(t,e,n){return t=+t,e>>>=0,n||A(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},i.prototype.writeUInt32LE=function(t,e,n){return t=+t,e>>>=0,n||A(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},i.prototype.writeUInt32BE=function(t,e,n){return t=+t,e>>>=0,n||A(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},i.prototype.writeIntLE=function(t,e,n,r){if(t=+t,e>>>=0,!r){var i=Math.pow(2,8*n-1);A(this,t,e,n,i-1,-i)}var o=0,s=1,a=0;for(this[e]=255&t;++o>0)-a&255;return e+n},i.prototype.writeIntBE=function(t,e,n,r){if(t=+t,e>>>=0,!r){var i=Math.pow(2,8*n-1);A(this,t,e,n,i-1,-i)}var o=n-1,s=1,a=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===a&&0!==this[e+o+1]&&(a=1),this[e+o]=(t/s>>0)-a&255;return e+n},i.prototype.writeInt8=function(t,e,n){return t=+t,e>>>=0,n||A(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},i.prototype.writeInt16LE=function(t,e,n){return t=+t,e>>>=0,n||A(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},i.prototype.writeInt16BE=function(t,e,n){return t=+t,e>>>=0,n||A(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},i.prototype.writeInt32LE=function(t,e,n){return t=+t,e>>>=0,n||A(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},i.prototype.writeInt32BE=function(t,e,n){return t=+t,e>>>=0,n||A(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},i.prototype.writeFloatLE=function(t,e,n){return C(this,t,e,!0,n)},i.prototype.writeFloatBE=function(t,e,n){return C(this,t,e,!1,n)},i.prototype.writeDoubleLE=function(t,e,n){return U(this,t,e,!0,n)},i.prototype.writeDoubleBE=function(t,e,n){return U(this,t,e,!1,n)},i.prototype.copy=function(t,e,n,r){if(n||(n=0),r||0===r||(r=this.length),e>=t.length&&(e=t.length),e||(e=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),t.length-e=0;--i)t[i+e]=this[i+n];else if(o<1e3)for(i=0;i>>=0,n=void 0===n?this.length:n>>>0,t||(t=0);var s;if("number"==typeof t)for(s=e;s0&&this._events[t].length>i&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){function n(){this.removeListener(t,n),i||(i=!0,e.apply(this,arguments))}if(!r(e))throw TypeError("listener must be a function");var i=!1;return n.listener=e,this.on(t,n),this},n.prototype.removeListener=function(t,e){var n,i,s,a;if(!r(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(n=this._events[t],s=n.length,i=-1,n===e||r(n.listener)&&n.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(n)){for(a=s;a-- >0;)if(n[a]===e||n[a].listener&&n[a].listener===e){i=a;break}if(i<0)return this;1===n.length?(n.length=0,delete this._events[t]):n.splice(i,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[t],r(n))this.removeListener(t,n);else if(n)for(;n.length;)this.removeListener(t,n[n.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){return this._events&&this._events[t]?r(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(r(e))return 1;if(e)return e.length}return 0},n.listenerCount=function(t,e){return t.listenerCount(e)}},function(t,e,n){"use strict";(function(e){function n(t,n,r,i){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var o,s,a=arguments.length;switch(a){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick(function(){t.call(null,n)});case 3:return e.nextTick(function(){t.call(null,n,r)});case 4:return e.nextTick(function(){t.call(null,n,r,i)});default:for(o=new Array(a-1),s=0;s-1?setImmediate:F;u.WritableState=c;var T=n(3);T.inherits=n(1);var L={deprecate:n(28)},x=n(15),D=n(11).Buffer,A=r.Uint8Array||function(){},P=n(16);T.inherits(u,x),c.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(c.prototype,"buffer",{get:L.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}();var C;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(C=Function.prototype[Symbol.hasInstance],Object.defineProperty(u,Symbol.hasInstance,{value:function(t){return!!C.call(this,t)||t&&t._writableState instanceof c}})):C=function(t){return t instanceof this},u.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},u.prototype.write=function(t,e,n){var r=this._writableState,i=!1,c=s(t)&&!r.objectMode;return c&&!D.isBuffer(t)&&(t=o(t)),"function"==typeof e&&(n=e,e=null),c?e="buffer":e||(e=r.defaultEncoding),"function"!=typeof n&&(n=a),r.ended?f(this,n):(c||h(this,r,t,n))&&(r.pendingcb++,i=l(this,r,c,t,e,n)),i},u.prototype.cork=function(){this._writableState.corked++},u.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,t.writing||t.corked||t.finished||t.bufferProcessing||!t.bufferedRequest||v(this,t))},u.prototype.setDefaultEncoding=function(t){if("string"==typeof t&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},u.prototype._write=function(t,e,n){n(new Error("_write() is not implemented"))},u.prototype._writev=null,u.prototype.end=function(t,e,n){var r=this._writableState;"function"==typeof t?(n=t,t=null,e=null):"function"==typeof e&&(n=e,e=null),null!==t&&void 0!==t&&this.write(t,e),r.corked&&(r.corked=1,this.uncork()),r.ending||r.finished||I(this,r,n)},Object.defineProperty(u.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),u.prototype.destroy=P.destroy,u.prototype._undestroy=P.undestroy,u.prototype._destroy=function(t,e){this.end(),e(t)}}).call(e,n(2),n(5))},function(t,e,n){"use strict";(function(e){function n(t){var e=r.exec(t);return e.shift(),e}var r=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,i=function(){function t(){}return t.normalize=function(e){""===e&&(e=".");var n=e.charAt(0)===t.sep;e=t._removeDuplicateSeps(e);for(var r=e.split(t.sep),i=[],o=0;o0&&".."!==i[0])?i.pop():i.push(s))}if(!n&&i.length<2)switch(i.length){case 1:""===i[0]&&i.unshift(".");break;default:i.push(".")}return e=i.join(t.sep),n&&e.charAt(0)!==t.sep&&(e=t.sep+e),e},t.join=function(){for(var e=[],n=0;n1&&a.charAt(a.length-1)===t.sep)return a.substr(0,a.length-1);if(a.charAt(0)!==t.sep){"."!==a.charAt(0)||1!==a.length&&a.charAt(1)!==t.sep||(a=1===a.length?"":a.substr(2));var c=e.cwd();a=""!==a?this.normalize(c+("/"!==c?t.sep:"")+a):c}return a},t.relative=function(e,n){var r;e=t.resolve(e),n=t.resolve(n);var i=e.split(t.sep),o=n.split(t.sep);o.shift(),i.shift();var s=0,a=[];for(r=0;ri.length&&(s=i.length);var c="";for(r=0;r1&&c.charAt(c.length-1)===t.sep&&(c=c.substr(0,c.length-1)),c},t.dirname=function(e){e=t._removeDuplicateSeps(e);var n=e.charAt(0)===t.sep,r=e.split(t.sep);return""===r.pop()&&r.length>0&&r.pop(),r.length>1||1===r.length&&!n?r.join(t.sep):n?t.sep:"."},t.basename=function(e,n){if(void 0===n&&(n=""),""===e)return e;e=t.normalize(e);var r=e.split(t.sep),i=r[r.length-1];if(""===i&&r.length>1)return r[r.length-2];if(n.length>0){if(i.substr(i.length-n.length)===n)return i.substr(0,i.length-n.length)}return i},t.extname=function(e){e=t.normalize(e);var n=e.split(t.sep);if(e=n.pop(),""===e&&n.length>0&&(e=n.pop()),".."===e)return"";var r=e.lastIndexOf(".");return-1===r||0===r?"":e.substr(r)},t.isAbsolute=function(e){return e.length>0&&e.charAt(0)===t.sep},t._makeLong=function(t){return t},t.parse=function(t){var e=n(t);return{root:e[0],dir:e[0]+e[1].slice(0,-1),base:e[2],ext:e[3],name:e[2].slice(0,e[2].length-e[3].length)}},t.format=function(e){if(null===e||"object"!=typeof e)throw new TypeError("Parameter 'pathObject' must be an object, not "+typeof e);if("string"!=typeof(e.root||""))throw new TypeError("'pathObject.root' must be a string or undefined, not "+typeof e.root);return(e.dir?e.dir+t.sep:"")+(e.base||"")},t._removeDuplicateSeps=function(t){return t=t.replace(this._replaceRegex,this.sep)},t.sep="/",t._replaceRegex=new RegExp("//+","g"),t.delimiter=":",t.posix=t,t.win32=t,t}();t.exports=i}).call(e,n(2))},function(t,e,n){"use strict";(function(e,r){function i(t){return U.from(t)}function o(t){return U.isBuffer(t)||t instanceof M}function s(t,e,n){if("function"==typeof t.prependListener)return t.prependListener(e,n);t._events&&t._events[e]?A(t._events[e])?t._events[e].unshift(n):t._events[e]=[n,t._events[e]]:t.on(e,n)}function a(t,e){D=D||n(0),t=t||{},this.objectMode=!!t.objectMode,e instanceof D&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var r=t.highWaterMark,i=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new V,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(q||(q=n(17).StringDecoder),this.decoder=new q(t.encoding),this.encoding=t.encoding)}function c(t){if(D=D||n(0),!(this instanceof c))return new c(t);this._readableState=new a(t,this),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),C.call(this)}function u(t,e,n,r,o){var s=t._readableState;if(null===e)s.reading=!1,y(t,s);else{var a;o||(a=h(s,e)),a?t.emit("error",a):s.objectMode||e&&e.length>0?("string"==typeof e||s.objectMode||Object.getPrototypeOf(e)===U.prototype||(e=i(e)),r?s.endEmitted?t.emit("error",new Error("stream.unshift() after end event")):f(t,s,e,!0):s.ended?t.emit("error",new Error("stream.push() after EOF")):(s.reading=!1,s.decoder&&!n?(e=s.decoder.write(e),s.objectMode||0!==e.length?f(t,s,e,!1):m(t,s)):f(t,s,e,!1))):r||(s.reading=!1)}return p(s)}function f(t,e,n,r){e.flowing&&0===e.length&&!e.sync?(t.emit("data",n),t.read(0)):(e.length+=e.objectMode?1:n.length,r?e.buffer.unshift(n):e.buffer.push(n),e.needReadable&&g(t)),m(t,e)}function h(t,e){var n;return o(e)||"string"==typeof e||void 0===e||t.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function p(t){return!t.ended&&(t.needReadable||t.length=Z?t=Z:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}function d(t,e){return t<=0||0===e.length&&e.ended?0:e.objectMode?1:t!==t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=l(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function y(t,e){if(!e.ended){if(e.decoder){var n=e.decoder.end();n&&n.length&&(e.buffer.push(n),e.length+=e.objectMode?1:n.length)}e.ended=!0,g(t)}}function g(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(z("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?x(_,t):_(t))}function _(t){z("emit readable"),t.emit("readable"),k(t)}function m(t,e){e.readingMore||(e.readingMore=!0,x(w,t,e))}function w(t,e){for(var n=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length=e.length?(n=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):n=O(t,e.buffer,e.decoder),n}function O(t,e,n){var r;return to.length?o.length:t;if(s===o.length?i+=o:i+=o.slice(0,t),0===(t-=s)){s===o.length?(++r,n.next?e.head=n.next:e.head=e.tail=null):(e.head=n,n.data=o.slice(s));break}++r}return e.length-=r,i}function N(t,e){var n=U.allocUnsafe(t),r=e.head,i=1;for(r.data.copy(n),t-=r.data.length;r=r.next;){var o=r.data,s=t>o.length?o.length:t;if(o.copy(n,n.length-t,0,s),0===(t-=s)){s===o.length?(++i,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=o.slice(s));break}++i}return e.length-=i,n}function R(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,x(T,e,t))}function T(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function L(t,e){for(var n=0,r=t.length;n=e.highWaterMark||e.ended))return z("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?R(this):g(this),null;if(0===(t=d(t,e))&&e.ended)return 0===e.length&&R(this),null;var r=e.needReadable;z("need readable",r),(0===e.length||e.length-t0?I(t,e):null,null===i?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),n!==t&&e.ended&&R(this)),null!==i&&this.emit("data",i),i},c.prototype._read=function(t){this.emit("error",new Error("_read() is not implemented"))},c.prototype.pipe=function(t,e){function n(t,e){z("onunpipe"),t===p&&e&&!1===e.hasUnpiped&&(e.hasUnpiped=!0,o())}function i(){z("onend"),t.end()}function o(){z("cleanup"),t.removeListener("close",u),t.removeListener("finish",f),t.removeListener("drain",g),t.removeListener("error",c),t.removeListener("unpipe",n),p.removeListener("end",i),p.removeListener("end",h),p.removeListener("data",a),_=!0,!l.awaitDrain||t._writableState&&!t._writableState.needDrain||g()}function a(e){z("ondata"),m=!1,!1!==t.write(e)||m||((1===l.pipesCount&&l.pipes===t||l.pipesCount>1&&-1!==L(l.pipes,t))&&!_&&(z("false write response, pause",p._readableState.awaitDrain),p._readableState.awaitDrain++,m=!0),p.pause())}function c(e){z("onerror",e),h(),t.removeListener("error",c),0===P(t,"error")&&t.emit("error",e)}function u(){t.removeListener("finish",f),h()}function f(){z("onfinish"),t.removeListener("close",u),h()}function h(){z("unpipe"),p.unpipe(t)}var p=this,l=this._readableState;switch(l.pipesCount){case 0:l.pipes=t;break;case 1:l.pipes=[l.pipes,t];break;default:l.pipes.push(t)}l.pipesCount+=1,z("pipe count=%d opts=%j",l.pipesCount,e);var d=(!e||!1!==e.end)&&t!==r.stdout&&t!==r.stderr,y=d?i:h;l.endEmitted?x(y):p.once("end",y),t.on("unpipe",n);var g=v(p);t.on("drain",g);var _=!1,m=!1;return p.on("data",a),s(t,"error",c),t.once("close",u),t.once("finish",f),t.emit("pipe",p),l.flowing||(z("pipe resume"),p.resume()),t},c.prototype.unpipe=function(t){var e=this._readableState,n={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,n),this);if(!t){var r=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o=this.charLength-this.charReceived?this.charLength-this.charReceived:t.length;if(t.copy(this.charBuffer,this.charReceived,0,n),this.charReceived+=n,this.charReceived=55296&&r<=56319)){if(this.charReceived=this.charLength=0,0===t.length)return e;break}this.charLength+=this.surrogateSize,e=""}this.detectIncompleteChar(t);var i=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-this.charReceived,i),i-=this.charReceived),e+=t.toString(this.encoding,0,i);var i=e.length-1,r=e.charCodeAt(i);if(r>=55296&&r<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),t.copy(this.charBuffer,0,0,o),e.substring(0,i)}return e},u.prototype.detectIncompleteChar=function(t){for(var e=t.length>=3?3:t.length;e>0;e--){var n=t[t.length-e];if(1==e&&n>>5==6){this.charLength=2;break}if(e<=2&&n>>4==14){this.charLength=3;break}if(e<=3&&n>>3==30){this.charLength=4;break}}this.charReceived=e},u.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var n=this.charReceived,r=this.charBuffer,i=this.encoding;e+=r.slice(0,n).toString(i)}return e}},function(t,e,n){"use strict";function r(t){this.afterTransform=function(e,n){return i(t,e,n)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function i(t,e,n){var r=t._transformState;r.transforming=!1;var i=r.writecb;if(!i)return t.emit("error",new Error("write callback called multiple times"));r.writechunk=null,r.writecb=null,null!==n&&void 0!==n&&t.push(n),i(e);var o=t._readableState;o.reading=!1,(o.needReadable||o.length=0)throw new ke(we.EINVAL,"Path must be a string without null bytes.");if(""===t)throw new ke(we.EINVAL,"Path must not be empty.");return be.resolve(t)}function f(t,e,n,r){switch(typeof t){case"object":return{encoding:void 0!==t.encoding?t.encoding:e,flag:void 0!==t.flag?t.flag:n,mode:a(t.mode,r)};case"string":return{encoding:t,flag:n,mode:r};default:return{encoding:e,flag:n,mode:r}}}function h(){}function p(t,e,n,r,i){return tn?n+1:t+1:r===i?e:e+1}function l(t,e){if(t===e)return 0;if(t.length>e.length){var n=t;t=e,e=n}for(var r=t.length,i=e.length;r>0&&t.charCodeAt(r-1)===e.charCodeAt(i-1);)r--,i--;for(var o=0;oS?S+1:I+1:E===s[r+k]?u:u+1,u=I}}return S}function d(t,e,n){t&&console.warn("["+e+"] Direct file system constructor usage is deprecated for this file system, and will be removed in the next major version. Please use the '"+e+".Create("+JSON.stringify(n)+", callback)' method instead. See https://github.com/jvilk/BrowserFS/issues/176 for more details.")}function y(){throw new Error("BFS has reached an impossible code path; please file a bug.")}function g(t,e,n){n.existsSync(t)||(g(be.dirname(t),e,n),n.mkdirSync(t,e))}function _(t){var e=m(t),n=e.byteOffset,r=e.byteLength;return 0===n&&r===e.buffer.byteLength?e.buffer:e.buffer.slice(n,n+r)}function m(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function w(e){return e instanceof t?e:e instanceof Uint8Array?v(e):t.from(e)}function v(e){return e instanceof t?e:0===e.byteOffset&&e.byteLength===e.buffer.byteLength?b(e.buffer):t.from(e.buffer,e.byteOffset,e.byteLength)}function b(e){return t.from(e)}function S(t,e,n){if(void 0===e&&(e=0),void 0===n&&(n=t.length),e<0||n<0||n>t.length||e>n)throw new TypeError("Invalid slice bounds on buffer of length "+t.length+": ["+e+", "+n+"]");if(0===t.length)return E();var r=m(t),i=t[0],o=(i+1)%255;return t[0]=o,r[0]===o?(r[0]=i,v(r.slice(e,n))):(t[0]=i,v(r.subarray(e,n)))}function E(){return Ce||(Ce=t.alloc(0))}function k(e,n){t.isBuffer(e)?n():n(new ke(we.EINVAL,"option must be a Buffer."))}function I(t,e,n){function r(t){a||(t&&(a=!0,n(t)),0===--s&&c&&n())}var i=t.Options,o=t.Name,s=0,a=!1,c=!1;for(var u in i){var f=function(t){if(i.hasOwnProperty(t)){var c=i[t],u=e[t];if(void 0===u||null===u){if(!c.optional){var f=Object.keys(e).filter(function(t){return!(t in i)}).map(function(e){return{str:e,distance:l(t,e)}}).filter(function(t){return t.distance<5}).sort(function(t,e){return t.distance-e.distance});return a?{}:(a=!0,{v:n(new ke(we.EINVAL,"["+o+"] Required option '"+t+"' not provided."+(f.length>0?" You provided unrecognized option '"+f[0].str+"'; perhaps you meant to type '"+t+"'.":"")+"\nOption description: "+c.description))})}}else{if(!(Array.isArray(c.type)?-1!==c.type.indexOf(typeof u):typeof u===c.type))return a?{}:(a=!0,{v:n(new ke(we.EINVAL,"["+o+"] Value provided for option "+t+" is not the proper type. Expected "+(Array.isArray(c.type)?"one of {"+c.type.join(", ")+"}":c.type)+", but received "+typeof u+"\nOption description: "+c.description))});c.validator&&(s++,c.validator(u,r))}}}(u);if(f)return f.v}c=!0,0!==s||a||n()}function O(t){return"/"===t?"":t}function F(t){var e=t.error;if(e[".tag"])return e;if(e.error){var n=e.error;return n[".tag"]?n:n.reason&&n.reason[".tag"]?n.reason:n}if("string"==typeof e)try{var r=JSON.parse(e);if(r.error&&r.error.reason&&r.error.reason[".tag"])return r.error.reason}catch(t){}return e}function N(t){if(t.user_message)return t.user_message.text;if(t.error_summary)return t.error_summary;if("string"==typeof t.error)return t.error;if("object"==typeof t.error)return N(t.error);throw new Error("Dropbox's servers gave us a garbage error message: "+JSON.stringify(t))}function R(t,e,n){switch(t[".tag"]){case"malformed_path":return new ke(we.EBADF,n,e);case"not_found":return ke.ENOENT(e);case"not_file":return ke.EISDIR(e);case"not_folder":return ke.ENOTDIR(e);case"restricted_content":return ke.EPERM(e);case"other":default:return new ke(we.EIO,n,e)}}function T(t,e,n){switch(t[".tag"]){case"malformed_path":case"disallowed_name":return new ke(we.EBADF,n,e);case"conflict":case"no_write_permission":case"team_folder":return ke.EPERM(e);case"insufficient_space":return new ke(we.ENOSPC,n);case"other":default:return new ke(we.EIO,n,e)}}function L(t,e,n){var r={path:O(e)};t.filesDeleteV2(r).then(function(){n()}).catch(function(r){var i=F(r);switch(i[".tag"]){case"path_lookup":n(R(i.path_lookup,e,N(r)));break;case"path_write":n(T(i.path_write,e,N(r)));break;case"too_many_write_operations":setTimeout(function(){return L(t,e,n)},500+300*Math.random());break;case"other":default:n(new ke(we.EIO,N(r),e))}})}function x(t,e,n){var r=F(t);switch(r[".tag"]){case"path":n(R(r.path,e,N(t)));break;case"other":default:n(new ke(we.EIO,N(t),e))}}function D(t,e,n,r,i){var o=n.entries.map(function(t){return t.path_display}).filter(function(t){return!!t}),s=r.concat(o);if(n.has_more){var a={cursor:n.cursor};t.filesListFolderContinue(a).then(function(n){D(t,e,n,s,i)}).catch(function(t){x(t,e,i)})}else i(null,s)}function A(t,e){void 0===e&&(e="");for(var n=t.errno,r=t.node,i=[];r&&(i.unshift(r.name),r!==r.parent);)r=r.parent;return new ke(n,Se[n],i.length>0?"/"+i.join("/"):e)}function P(t,e){if(null!==e&&"object"==typeof e){var n=e,r=n.path;r&&(r="/"+be.relative(t,r),n.message=n.message.replace(n.path,r),n.path=r)}return e}function C(t,e){return"function"==typeof e?function(n){arguments.length>0&&(arguments[0]=P(t,n)),e.apply(null,arguments)}:e}function U(t,e,n){return"Sync"!==t.slice(t.length-4)?function(){return arguments.length>0&&(e&&(arguments[0]=be.join(this._folder,arguments[0])),n&&(arguments[1]=be.join(this._folder,arguments[1])),arguments[arguments.length-1]=C(this._folder,arguments[arguments.length-1])),this._wrapped[t].apply(this._wrapped,arguments)}:function(){try{return e&&(arguments[0]=be.join(this._folder,arguments[0])),n&&(arguments[1]=be.join(this._folder,arguments[1])),this._wrapped[t].apply(this._wrapped,arguments)}catch(t){throw P(this._folder,t)}}}function M(t,e){e|=0;for(var n=Math.max(t.length-e,0),r=Array(n),i=0;i-1&&t%1==0&&t<=Tn}function G(t){return null!=t&&K(t.length)&&!J(t)}function Q(){}function $(t){return function(){if(null!==t){var e=t;t=null,e.apply(this,arguments)}}}function tt(t,e){for(var n=-1,r=Array(t);++n-1&&t%1==0&&t0&&t[0]instanceof ke&&e.standardizeError(t[0],o.path,i),s.apply(null,t)}}return o.fs[t].apply(o.fs,n)}}function Lt(t){return 146|t}function xt(t){return Oe.getFileFlag(t)}function Dt(t){return{type:Xr.API_ERROR,errorData:zt(t.writeToBuffer())}}function At(t){return ke.fromBuffer(qt(t.errorData))}function Pt(t){return{type:Xr.ERROR,name:t.name,message:t.message,stack:t.stack}}function Ct(t){var e=Je[t.name];"function"!=typeof e&&(e=Error);var n=new e(t.message);return n.stack=t.stack,n}function Ut(t){return{type:Xr.STATS,statsData:zt(t.toBuffer())}}function Mt(t){return Ne.fromBuffer(qt(t.statsData))}function jt(t){return{type:Xr.FILEFLAG,flagStr:t.getFlagString()}}function Bt(t){return Oe.getFileFlag(t.flagStr)}function zt(t){return _(t)}function qt(t){return b(t)}function Vt(t){return{type:Xr.BUFFER,data:zt(t)}}function Wt(t){return qt(t.data)}function Ht(t){return t&&"object"==typeof t&&t.hasOwnProperty("browserfsMessage")&&t.browserfsMessage}function Zt(t){return t&&"object"==typeof t&&t.hasOwnProperty("browserfsMessage")&&t.browserfsMessage}function Yt(e,n,r){var i=new XMLHttpRequest;i.open("GET",e,!0);var o=!0;switch(n){case"buffer":i.responseType="arraybuffer";break;case"json":try{i.responseType="json",o="json"===i.responseType}catch(t){o=!1}break;default:return r(new ke(we.EINVAL,"Invalid download type: "+n))}i.onreadystatechange=function(e){if(4===i.readyState){if(200!==i.status)return r(new ke(we.EIO,"XHR error: response returned code "+i.status));switch(n){case"buffer":return r(null,i.response?t.from(i.response):E());case"json":return o?r(null,i.response):r(null,JSON.parse(i.responseText))}}},i.send()}function Xt(e,n){var r=new XMLHttpRequest;r.open("GET",e,!1);var i=null,o=null;if(r.overrideMimeType("text/plain; charset=x-user-defined"),r.onreadystatechange=function(e){if(4===r.readyState){if(200!==r.status)return void(o=new ke(we.EIO,"XHR error: response returned code "+r.status));switch(n){case"buffer":var s=r.responseText;i=t.alloc(s.length);for(var a=0;a>5&15)-1,i=1980+(e>>9),o=31&t,s=t>>5&63,a=t>>11;return new Date(i,r,n,a,s,o)}function se(t,e,n,r){return 0===r?"":e?t.toString("utf8",n,n+r):ai.byte2str(t.slice(n,n+r))}function ae(t,e,n){return t.toString("ascii",e,e+n).trim()}function ce(t,e,n){if(1===n)return String.fromCharCode(t[e]);for(var r=Math.floor(n/2),i=new Array(r),o=0;othis._buffer.length){var n=t.alloc(e-this._buffer.length,0);return this.writeSync(n,0,n.length,this._buffer.length),void(this._flag.isSynchronous()&&xe.getRootFS().supportsSynch()&&this.syncSync())}this._stat.size=e;var r=t.alloc(e);this._buffer.copy(r,0,0,e),this._buffer=r,this._flag.isSynchronous()&&xe.getRootFS().supportsSynch()&&this.syncSync()},n.prototype.write=function(t,e,n,r,i){try{i(null,this.writeSync(t,e,n,r),t)}catch(t){i(t)}},n.prototype.writeSync=function(e,n,r,i){if(this._dirty=!0,void 0!==i&&null!==i||(i=this.getPos()),!this._flag.isWriteable())throw new ke(we.EPERM,"File not opened with a writeable mode.");var o=i+r;if(o>this._stat.size&&(this._stat.size=o,o>this._buffer.length)){var s=t.alloc(o);this._buffer.copy(s),this._buffer=s}var a=e.copy(this._buffer,i,n,n+r);return this._stat.mtime=new Date,this._flag.isSynchronous()?(this.syncSync(),a):(this.setPos(i+a),a)},n.prototype.read=function(t,e,n,r,i){try{i(null,this.readSync(t,e,n,r),t)}catch(t){i(t)}},n.prototype.readSync=function(t,e,n,r){if(!this._flag.isReadable())throw new ke(we.EPERM,"File not opened with a readable mode.");void 0!==r&&null!==r||(r=this.getPos()),r+n>this._stat.size&&(n=this._stat.size-r);var i=this._buffer.copy(t,e,r,r+n);return this._stat.atime=new Date,this._pos=r+n,i},n.prototype.chmod=function(t,e){try{this.chmodSync(t),e()}catch(t){e(t)}},n.prototype.chmodSync=function(t){if(!this._fs.supportsProps())throw new ke(we.ENOTSUP);this._dirty=!0,this._stat.chmod(t),this.syncSync()},n.prototype.isDirty=function(){return this._dirty},n.prototype.resetDirty=function(){this._dirty=!1},n}(Ve),He=function(t){function e(e,n,r,i,o){t.call(this,e,n,r,i,o)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.sync=function(t){t()},e.prototype.syncSync=function(){},e.prototype.close=function(t){t()},e.prototype.closeSync=function(){},e}(We),Ze=function(t){function e(e,n,r,i,o){t.call(this,e,n,r,i,o)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.syncSync=function(){this.isDirty()&&(this._fs._syncSync(this),this.resetDirty())},e.prototype.closeSync=function(){this.syncSync()},e}(We),Ye=function(t){function e(e,n){t.call(this),this._queue=[],this._queueRunning=!1,this._isInitialized=!1,this._initializeCallbacks=[],this._sync=e,this._async=n}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){try{var r=new e(t.sync,t.async);r._initialize(function(t){t?n(t):n(null,r)})}catch(t){n(t)}},e.isAvailable=function(){return!0},e.prototype.getName=function(){return e.Name},e.prototype._syncSync=function(t){this._sync.writeFileSync(t.getPath(),t.getBuffer(),null,Oe.getFileFlag("w"),t.getStats().mode),this.enqueueOp({apiMethod:"writeFile",arguments:[t.getPath(),t.getBuffer(),null,t.getFlag(),t.getStats().mode]})},e.prototype.isReadOnly=function(){return!1},e.prototype.supportsSynch=function(){return!0},e.prototype.supportsLinks=function(){return!1},e.prototype.supportsProps=function(){return this._sync.supportsProps()&&this._async.supportsProps()},e.prototype.renameSync=function(t,e){this._sync.renameSync(t,e),this.enqueueOp({apiMethod:"rename",arguments:[t,e]})},e.prototype.statSync=function(t,e){return this._sync.statSync(t,e)},e.prototype.openSync=function(t,e,n){return this._sync.openSync(t,e,n).closeSync(),new Ze(this,t,e,this._sync.statSync(t,!1),this._sync.readFileSync(t,null,Oe.getFileFlag("r")))},e.prototype.unlinkSync=function(t){this._sync.unlinkSync(t),this.enqueueOp({apiMethod:"unlink",arguments:[t]})},e.prototype.rmdirSync=function(t){this._sync.rmdirSync(t),this.enqueueOp({apiMethod:"rmdir",arguments:[t]})},e.prototype.mkdirSync=function(t,e){this._sync.mkdirSync(t,e),this.enqueueOp({apiMethod:"mkdir",arguments:[t,e]})},e.prototype.readdirSync=function(t){return this._sync.readdirSync(t)},e.prototype.existsSync=function(t){return this._sync.existsSync(t)},e.prototype.chmodSync=function(t,e,n){this._sync.chmodSync(t,e,n),this.enqueueOp({apiMethod:"chmod",arguments:[t,e,n]})},e.prototype.chownSync=function(t,e,n,r){this._sync.chownSync(t,e,n,r),this.enqueueOp({apiMethod:"chown",arguments:[t,e,n,r]})},e.prototype.utimesSync=function(t,e,n){this._sync.utimesSync(t,e,n),this.enqueueOp({apiMethod:"utimes",arguments:[t,e,n]})},e.prototype._initialize=function(t){var e=this,n=this._initializeCallbacks,r=function(t){e._isInitialized=!t,e._initializeCallbacks=[],n.forEach(function(e){return e(t)})};if(this._isInitialized)t();else if(1===n.push(t)){var i=function(t,n,r){"/"!==t&&e._sync.mkdirSync(t,n),e._async.readdir(t,function(e,n){function i(e){e?r(e):o0){var r=e._queue.shift(),i=r.arguments;i.push(n),e._async[r.apiMethod].apply(e._async,i)}else e._queueRunning=!1};n()}},e}(qe);Ye.Name="AsyncMirror",Ye.Options={sync:{type:"object",description:"The synchronous file system to mirror the asynchronous file system to.",validator:function(t,e){t&&"function"==typeof t.supportsSynch&&t.supportsSynch()?e():e(new ke(we.EINVAL,"'sync' option must be a file system that supports synchronous operations"))}},async:{type:"object",description:"The asynchronous file system to mirror."}};var Xe,Je="undefined"!=typeof window?window:"undefined"!=typeof self?self:r;if("undefined"!=typeof setImmediate)Xe=setImmediate;else{var Ke=Je,Ge=[];if(function(){if(void 0!==Ke.importScripts||!Ke.postMessage)return!1;var t=!0,e=Ke.onmessage;return Ke.onmessage=function(){t=!1},Ke.postMessage("","*"),Ke.onmessage=e,t}()){Xe=function(t){Ge.push(t),Ke.postMessage("zero-timeout-message","*")};var Qe=function(t){if(t.source===self&&"zero-timeout-message"===t.data&&(t.stopPropagation?t.stopPropagation():t.cancelBubble=!0,Ge.length>0)){return Ge.shift()()}};Ke.addEventListener?Ke.addEventListener("message",Qe,!0):Ke.attachEvent("onmessage",Qe)}else if(Ke.MessageChannel){var $e=new Ke.MessageChannel;$e.port1.onmessage=function(t){if(Ge.length>0)return Ge.shift()()},Xe=function(t){Ge.push(t),$e.port2.postMessage("")}}else Xe=function(t){return setTimeout(t,0)}}var tn=Xe,en=function(t){function e(e,n,r,i,o){t.call(this,e,n,r,i,o)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.sync=function(t){this._fs._syncFile(this.getPath(),this.getBuffer(),t)},e.prototype.close=function(t){this.sync(t)},e}(We),nn=function(e){function n(t){e.call(this),this._client=t}return e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.Create=function(t,e){e(null,new n(t.client))},n.isAvailable=function(){return"undefined"!=typeof Dropbox},n.prototype.getName=function(){return n.Name},n.prototype.isReadOnly=function(){return!1},n.prototype.supportsSymlinks=function(){return!1},n.prototype.supportsProps=function(){return!1},n.prototype.supportsSynch=function(){return!1},n.prototype.empty=function(t){var e=this;this.readdir("/",function(n,r){if(r){var i=function(n){0===r.length?t():L(e._client,r.shift(),i)};i()}else t(n)})},n.prototype.rename=function(t,e,n){var r=this;this.stat(e,!1,function(i,o){var s=function(){var i={from_path:O(t),to_path:O(e)};r._client.filesMoveV2(i).then(function(){return n()}).catch(function(r){var i=F(r);switch(i[".tag"]){case"from_lookup":n(R(i.from_lookup,t,N(r)));break;case"from_write":n(T(i.from_write,t,N(r)));break;case"to":n(T(i.to,e,N(r)));break;case"cant_copy_shared_folder":case"cant_nest_shared_folder":n(new ke(we.EPERM,N(r),t));break;case"cant_move_folder_into_itself":case"duplicated_or_nested_paths":n(new ke(we.EBADF,N(r),t));break;case"too_many_files":n(new ke(we.ENOSPC,N(r),t));break;case"other":default:n(new ke(we.EIO,N(r),t))}})};i?s():t===e?i?n(ke.ENOENT(e)):n():o&&o.isDirectory()?n(ke.EISDIR(e)):r.unlink(e,function(t){t?n(t):s()})})},n.prototype.stat=function(t,e,n){if("/"===t)return void tn(function(){n(null,new Ne(Fe.DIRECTORY,4096))});var r={path:O(t)};this._client.filesGetMetadata(r).then(function(e){switch(e[".tag"]){case"file":var r=e;n(null,new Ne(Fe.FILE,r.size));break;case"folder":n(null,new Ne(Fe.DIRECTORY,4096));break;case"deleted":n(ke.ENOENT(t))}}).catch(function(e){var r=F(e);switch(r[".tag"]){case"path":n(R(r.path,t,N(e)));break;default:n(new ke(we.EIO,N(e),t))}})},n.prototype.openFile=function(t,e,n){var r=this,i={path:O(t)};this._client.filesDownload(i).then(function(i){var o=i.fileBlob,s=new FileReader;s.onload=function(){var i=s.result;n(null,new en(r,t,e,new Ne(Fe.FILE,i.byteLength),b(i)))},s.readAsArrayBuffer(o)}).catch(function(e){var r=F(e);switch(r[".tag"]){case"path":n(R(r.path,t,N(e)));break;case"other":default:n(new ke(we.EIO,N(e),t))}})},n.prototype.createFile=function(e,n,r,i){var o=this,s=t.alloc(0),a=new Blob([_(s)],{type:"octet/stream"}),c={contents:a,path:O(e)};this._client.filesUpload(c).then(function(t){i(null,new en(o,e,n,new Ne(Fe.FILE,0),s))}).catch(function(t){var s=F(t);switch(s[".tag"]){case"path":i(T(s.path.reason,e,N(t)));break;case"too_many_write_operations":setTimeout(function(){return o.createFile(e,n,r,i)},500+300*Math.random());break;case"other":default:i(new ke(we.EIO,N(t),e))}})},n.prototype.unlink=function(t,e){var n=this;this.stat(t,!1,function(r,i){i?i.isDirectory()?e(ke.EISDIR(t)):L(n._client,t,e):e(r)})},n.prototype.rmdir=function(t,e){var n=this;this.readdir(t,function(r,i){i?i.length>0?e(ke.ENOTEMPTY(t)):L(n._client,t,e):e(r)})},n.prototype.mkdir=function(t,e,n){var r=this,i=be.dirname(t);this.stat(i,!1,function(o,s){if(o)n(o);else if(s&&!s.isDirectory())n(ke.ENOTDIR(i));else{var a={path:O(t)};r._client.filesCreateFolderV2(a).then(function(){return n()}).catch(function(i){"too_many_write_operations"===F(i)[".tag"]?setTimeout(function(){return r.mkdir(t,e,n)},500+300*Math.random()):n(T(F(i).path,t,N(i)))})}})},n.prototype.readdir=function(t,e){var n=this,r={path:O(t)};this._client.filesListFolder(r).then(function(r){D(n._client,t,r,[],e)}).catch(function(n){x(n,t,e)})},n.prototype._syncFile=function(t,e,n){var r=this,i=new Blob([_(e)],{type:"octet/stream"}),o={contents:i,path:O(t),mode:{".tag":"overwrite"}};this._client.filesUpload(o).then(function(){n()}).catch(function(i){var o=F(i);switch(o[".tag"]){case"path":n(T(o.path.reason,t,N(i)));break;case"too_many_write_operations":setTimeout(function(){return r._syncFile(t,e,n)},500+300*Math.random());break;case"other":default:n(new ke(we.EIO,N(i),t))}})},n}(ze);nn.Name="DropboxV2",nn.Options={client:{type:"object",description:"An *authenticated* Dropbox client. Must be from the 2.5.x JS SDK."}};var rn=function(t){function e(e,n,r,i){t.call(this),this._fs=e,this._FS=n,this._path=r,this._stream=i}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getPos=function(){},e.prototype.close=function(t){var e=null;try{this.closeSync()}catch(t){e=t}finally{t(e)}},e.prototype.closeSync=function(){try{this._FS.close(this._stream)}catch(t){throw A(t,this._path)}},e.prototype.stat=function(t){try{t(null,this.statSync())}catch(e){t(e)}},e.prototype.statSync=function(){try{return this._fs.statSync(this._path,!1)}catch(t){throw A(t,this._path)}},e.prototype.truncate=function(t,e){var n=null;try{this.truncateSync(t)}catch(t){n=t}finally{e(n)}},e.prototype.truncateSync=function(t){try{this._FS.ftruncate(this._stream.fd,t)}catch(t){throw A(t,this._path)}},e.prototype.write=function(t,e,n,r,i){try{i(null,this.writeSync(t,e,n,r),t)}catch(t){i(t)}},e.prototype.writeSync=function(t,e,n,r){try{var i=m(t),o=null===r?void 0:r;return this._FS.write(this._stream,i,e,n,o)}catch(t){throw A(t,this._path)}},e.prototype.read=function(t,e,n,r,i){try{i(null,this.readSync(t,e,n,r),t)}catch(t){i(t)}},e.prototype.readSync=function(t,e,n,r){try{var i=m(t),o=null===r?void 0:r;return this._FS.read(this._stream,i,e,n,o)}catch(t){throw A(t,this._path)}},e.prototype.sync=function(t){t()},e.prototype.syncSync=function(){},e.prototype.chown=function(t,e,n){var r=null;try{this.chownSync(t,e)}catch(t){r=t}finally{n(r)}},e.prototype.chownSync=function(t,e){try{this._FS.fchown(this._stream.fd,t,e)}catch(t){throw A(t,this._path)}},e.prototype.chmod=function(t,e){var n=null;try{this.chmodSync(t)}catch(t){n=t}finally{e(n)}},e.prototype.chmodSync=function(t){try{this._FS.fchmod(this._stream.fd,t)}catch(t){throw A(t,this._path)}},e.prototype.utimes=function(t,e,n){var r=null;try{this.utimesSync(t,e)}catch(t){r=t}finally{n(r)}},e.prototype.utimesSync=function(t,e){this._fs.utimesSync(this._path,t,e)},e}(Ve),on=function(e){function n(t){e.call(this),this._FS=t}return e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.Create=function(t,e){e(null,new n(t.FS))},n.isAvailable=function(){return!0},n.prototype.getName=function(){return this._FS.DB_NAME()},n.prototype.isReadOnly=function(){return!1},n.prototype.supportsLinks=function(){return!0},n.prototype.supportsProps=function(){return!0},n.prototype.supportsSynch=function(){return!0},n.prototype.renameSync=function(t,e){try{this._FS.rename(t,e)}catch(n){throw n.errno===we.ENOENT?A(n,this.existsSync(t)?e:t):A(n)}},n.prototype.statSync=function(t,e){try{var n=e?this._FS.lstat(t):this._FS.stat(t),r=this.modeToFileType(n.mode);return new Ne(r,n.size,n.mode,n.atime,n.mtime,n.ctime)}catch(e){throw A(e,t)}},n.prototype.openSync=function(t,e,n){try{var r=this._FS.open(t,e.getFlagString(),n);if(this._FS.isDir(r.node.mode))throw this._FS.close(r),ke.EISDIR(t);return new rn(this,this._FS,t,r)}catch(e){throw A(e,t)}},n.prototype.unlinkSync=function(t){try{this._FS.unlink(t)}catch(e){throw A(e,t)}},n.prototype.rmdirSync=function(t){try{this._FS.rmdir(t)}catch(e){throw A(e,t)}},n.prototype.mkdirSync=function(t,e){try{this._FS.mkdir(t,e)}catch(e){throw A(e,t)}},n.prototype.readdirSync=function(t){try{return this._FS.readdir(t).filter(function(t){return"."!==t&&".."!==t})}catch(e){throw A(e,t)}},n.prototype.truncateSync=function(t,e){try{this._FS.truncate(t,e)}catch(e){throw A(e,t)}},n.prototype.readFileSync=function(t,e,n){try{var r=this._FS.readFile(t,{flags:n.getFlagString()}),i=v(r);return e?i.toString(e):i}catch(e){throw A(e,t)}},n.prototype.writeFileSync=function(e,n,r,i,o){try{r&&(n=t.from(n,r));var s=m(n);this._FS.writeFile(e,s,{flags:i.getFlagString(),encoding:"binary"}),this._FS.chmod(e,o)}catch(t){throw A(t,e)}},n.prototype.chmodSync=function(t,e,n){try{e?this._FS.lchmod(t,n):this._FS.chmod(t,n)}catch(e){throw A(e,t)}},n.prototype.chownSync=function(t,e,n,r){try{e?this._FS.lchown(t,n,r):this._FS.chown(t,n,r)}catch(e){throw A(e,t)}},n.prototype.symlinkSync=function(t,e,n){try{this._FS.symlink(t,e)}catch(t){throw A(t)}},n.prototype.readlinkSync=function(t){try{return this._FS.readlink(t)}catch(e){throw A(e,t)}},n.prototype.utimesSync=function(t,e,n){try{this._FS.utime(t,e.getTime(),n.getTime())}catch(e){throw A(e,t)}},n.prototype.modeToFileType=function(t){if(this._FS.isDir(t))return Fe.DIRECTORY;if(this._FS.isFile(t))return Fe.FILE;if(this._FS.isLink(t))return Fe.SYMLINK;throw ke.EPERM("Invalid mode: "+t)},n}(qe);on.Name="EmscriptenFileSystem",on.Options={FS:{type:"object",description:"The Emscripten file system to use (the `FS` variable)"}};var sn=function(t){function e(e,n){t.call(this),this._folder=e,this._wrapped=n}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){var r=new e(t.folder,t.wrapped);r._initialize(function(t){t?n(t):n(null,r)})},e.isAvailable=function(){return!0},e.prototype.getName=function(){return this._wrapped.getName()},e.prototype.isReadOnly=function(){return this._wrapped.isReadOnly()},e.prototype.supportsProps=function(){return this._wrapped.supportsProps()},e.prototype.supportsSynch=function(){return this._wrapped.supportsSynch()},e.prototype.supportsLinks=function(){return!1},e.prototype._initialize=function(t){var e=this;this._wrapped.exists(this._folder,function(n){n?t():e._wrapped.isReadOnly()?t(ke.ENOENT(e._folder)):e._wrapped.mkdir(e._folder,511,t)})},e}(ze);sn.Name="FolderAdapter",sn.Options={folder:{type:"string",description:"The folder to use as the root directory"},wrapped:{type:"object",description:"The file system to wrap"}},["diskSpace","stat","statSync","open","openSync","unlink","unlinkSync","rmdir","rmdirSync","mkdir","mkdirSync","readdir","readdirSync","exists","existsSync","realpath","realpathSync","truncate","truncateSync","readFile","readFileSync","writeFile","writeFileSync","appendFile","appendFileSync","chmod","chmodSync","chown","chownSync","utimes","utimesSync","readlink","readlinkSync"].forEach(function(t){sn.prototype[t]=U(t,!0,!1)}),["rename","renameSync","link","linkSync","symlink","symlinkSync"].forEach(function(t){sn.prototype[t]=U(t,!0,!0)});var an,cn=function(t){return function(){var e=M(arguments),n=e.pop();t.call(this,e,n)}},un="function"==typeof setImmediate&&setImmediate,fn="object"==typeof i&&"function"==typeof i.nextTick;an=un?setImmediate:fn?i.nextTick:B;var hn=function(t){return function(e){var n=M(arguments,1);t(function(){e.apply(null,n)})}}(an),pn="function"==typeof Symbol,ln="object"==typeof r&&r&&r.Object===Object&&r,dn="object"==typeof self&&self&&self.Object===Object&&self,yn=ln||dn||Function("return this")(),gn=yn.Symbol,_n=Object.prototype,mn=_n.hasOwnProperty,wn=_n.toString,vn=gn?gn.toStringTag:void 0,bn=Object.prototype,Sn=bn.toString,En="[object Null]",kn="[object Undefined]",In=gn?gn.toStringTag:void 0,On="[object AsyncFunction]",Fn="[object Function]",Nn="[object GeneratorFunction]",Rn="[object Proxy]",Tn=9007199254740991,Ln={},xn="function"==typeof Symbol&&Symbol.iterator,Dn=function(t){return xn&&t[xn]&&t[xn]()},An="[object Arguments]",Pn=Object.prototype,Cn=Pn.hasOwnProperty,Un=Pn.propertyIsEnumerable,Mn=nt(function(){return arguments}())?nt:function(t){return et(t)&&Cn.call(t,"callee")&&!Un.call(t,"callee")},jn=Array.isArray,Bn="object"==typeof e&&e&&!e.nodeType&&e,zn=Bn&&"object"==typeof o&&o&&!o.nodeType&&o,qn=zn&&zn.exports===Bn,Vn=qn?yn.Buffer:void 0,Wn=Vn?Vn.isBuffer:void 0,Hn=Wn||rt,Zn=9007199254740991,Yn=/^(?:0|[1-9]\d*)$/,Xn={};Xn["[object Float32Array]"]=Xn["[object Float64Array]"]=Xn["[object Int8Array]"]=Xn["[object Int16Array]"]=Xn["[object Int32Array]"]=Xn["[object Uint8Array]"]=Xn["[object Uint8ClampedArray]"]=Xn["[object Uint16Array]"]=Xn["[object Uint32Array]"]=!0,Xn["[object Arguments]"]=Xn["[object Array]"]=Xn["[object ArrayBuffer]"]=Xn["[object Boolean]"]=Xn["[object DataView]"]=Xn["[object Date]"]=Xn["[object Error]"]=Xn["[object Function]"]=Xn["[object Map]"]=Xn["[object Number]"]=Xn["[object Object]"]=Xn["[object RegExp]"]=Xn["[object Set]"]=Xn["[object String]"]=Xn["[object WeakMap]"]=!1;var Jn="object"==typeof e&&e&&!e.nodeType&&e,Kn=Jn&&"object"==typeof o&&o&&!o.nodeType&&o,Gn=Kn&&Kn.exports===Jn,Qn=Gn&&ln.process,$n=function(){try{return Qn&&Qn.binding&&Qn.binding("util")}catch(t){}}(),tr=$n&&$n.isTypedArray,er=tr?function(t){return function(e){return t(e)}}(tr):ot,nr=Object.prototype,rr=nr.hasOwnProperty,ir=Object.prototype,or=function(t,e){return function(n){return t(e(n))}}(Object.keys,Object),sr=Object.prototype,ar=sr.hasOwnProperty,cr=function(t,e){return function(n,r,i){return t(n,e,r,i)}}(gt,1/0),ur=function(t,e,n){(G(t)?_t:cr)(t,H(e),n)},fr=(function(t){}(),"[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]"),hr="(?:\\ud83c[\\udde6-\\uddff]){2}",pr="[\\ud800-\\udbff][\\udc00-\\udfff]",lr="(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?";["[^\\ud800-\\udfff]",hr,pr].join("|"),["[^\\ud800-\\udfff]"+fr+"?",fr,hr,pr,"[\\ud800-\\udfff]"].join("|");fn?i.nextTick:un&&setImmediate;var dr=(Math.ceil,Math.max,Je.webkitRequestFileSystem||Je.requestFileSystem||null),yr=function(t){function e(e,n,r,i,o,s){t.call(this,e,r,i,o,s),this._entry=n}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.sync=function(t){var e=this;if(!this.isDirty())return t();this._entry.createWriter(function(n){var r=e.getBuffer(),i=new Blob([_(r)]),o=i.size;n.onwriteend=function(r){n.onwriteend=null,n.onerror=null,n.truncate(o),e.resetDirty(),t()},n.onerror=function(n){t(Et(n,e.getPath(),!1))},n.write(i)})},e.prototype.close=function(t){this.sync(t)},e}(We),gr=function(t){function e(e,n){void 0===e&&(e=5),void 0===n&&(n=Je.PERSISTENT),t.call(this),this.size=1048576*e,this.type=n}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){var r=new e(t.size,t.type);r._allocate(function(t){return t?n(t):n(null,r)})},e.isAvailable=function(){return!!dr},e.prototype.getName=function(){return e.Name},e.prototype.isReadOnly=function(){return!1},e.prototype.supportsSymlinks=function(){return!1},e.prototype.supportsProps=function(){return!1},e.prototype.supportsSynch=function(){return!1},e.prototype.empty=function(t){this._readdir("/",function(e,n){if(e)t(e);else{var r=function(n){e?t(e):t()};wt(n,function(t,e){var n=function(){e()},r=function(n){e(Et(n,t.fullPath,!t.isDirectory))};vt(t)?t.removeRecursively(n,r):t.remove(n,r)},r)}})},e.prototype.rename=function(t,e,n){var r=this,i=2,o=0,s=this.fs.root,a=t,c=function(t){--i<=0&&n(Et(t,a,!1))},u=function(i){return 2==++o?n(new ke(we.EINVAL,"Something was identified as both a file and a directory. This should never happen.")):t===e?n():(a=be.dirname(e),void s.getDirectory(a,{},function(o){a=be.basename(e),i.moveTo(o,a,function(t){n()},function(o){i.isDirectory?(a=e,r.unlink(e,function(i){i?c(o):r.rename(t,e,n)})):c(o)})},c))};s.getFile(t,{},u,c),s.getDirectory(t,{},u,c)},e.prototype.stat=function(t,e,n){var r=this,i={create:!1},o=function(t){var e=function(t){var e=new Ne(Fe.FILE,t.size);n(null,e)};t.file(e,a)},s=function(t){var e=new Ne(Fe.DIRECTORY,4096);n(null,e)},a=function(e){n(Et(e,t,!1))},c=function(){r.fs.root.getDirectory(t,i,s,a)};this.fs.root.getFile(t,i,o,c)},e.prototype.open=function(t,e,n,r){var i=this,o=function(n){r("InvalidModificationError"===n.name&&e.isExclusive()?ke.EEXIST(t):Et(n,t,!1))};this.fs.root.getFile(t,{create:e.pathNotExistsAction()===Ee.CREATE_FILE,exclusive:e.isExclusive()},function(n){n.file(function(s){var a=new FileReader;a.onloadend=function(o){var c=i._makeFile(t,n,e,s,a.result);r(null,c)},a.onerror=function(t){o(a.error)},a.readAsArrayBuffer(s)},o)},o)},e.prototype.unlink=function(t,e){this._remove(t,e,!0)},e.prototype.rmdir=function(t,e){var n=this;this.readdir(t,function(r,i){r?e(r):i.length>0?e(ke.ENOTEMPTY(t)):n._remove(t,e,!1)})},e.prototype.mkdir=function(t,e,n){var r={create:!0,exclusive:!0},i=function(t){n()},o=function(e){n(Et(e,t,!0))};this.fs.root.getDirectory(t,r,i,o)},e.prototype.readdir=function(t,e){this._readdir(t,function(t,n){if(!n)return e(t);for(var r=[],i=0,o=n;i0)throw ke.ENOTEMPTY(t);this.removeEntry(t,!0)},n.prototype.mkdirSync=function(e,n){var r=this.store.beginTransaction("readwrite"),i=t.from("{}");this.commitNewFile(r,e,Fe.DIRECTORY,n,i)},n.prototype.readdirSync=function(t){var e=this.store.beginTransaction("readonly");return Object.keys(this.getDirListing(e,t,this.findINode(e,t)))},n.prototype._syncSync=function(t,e,n){var r=this.store.beginTransaction("readwrite"),i=this._findINode(r,be.dirname(t),be.basename(t)),o=this.getINode(r,t,i),s=o.update(n);try{r.put(o.id,e,!0),s&&r.put(i,o.toBuffer(),!0)}catch(t){throw r.abort(),t}r.commit()},n.prototype.makeRootDirectory=function(){var t=this.store.beginTransaction("readwrite");if(void 0===t.get("/")){var e=(new Date).getTime(),n=new _r(It(),4096,511|Fe.DIRECTORY,e,e,e);t.put(n.id,kt(),!1),t.put("/",n.toBuffer(),!1),t.commit()}},n.prototype._findINode=function(t,e,n){var r=this,i=function(i){var o=r.getDirListing(t,e,i);if(o[n])return o[n];throw ke.ENOENT(be.resolve(e,n))};return"/"===e?""===n?"/":i(this.getINode(t,e,"/")):i(this.getINode(t,e+be.sep+n,this._findINode(t,be.dirname(e),be.basename(e))))},n.prototype.findINode=function(t,e){return this.getINode(t,e,this._findINode(t,be.dirname(e),be.basename(e)))},n.prototype.getINode=function(t,e,n){var r=t.get(n);if(void 0===r)throw ke.ENOENT(e);return _r.fromBuffer(r)},n.prototype.getDirListing=function(t,e,n){if(!n.isDirectory())throw ke.ENOTDIR(e);var r=t.get(n.id);if(void 0===r)throw ke.ENOENT(e);return JSON.parse(r.toString())},n.prototype.addNewNode=function(t,e){for(var n;;)try{return n=It(),t.put(n,e,!1),n}catch(t){}throw new ke(we.EIO,"Unable to commit data to key-value store.")},n.prototype.commitNewFile=function(e,n,r,i,o){var s=be.dirname(n),a=be.basename(n),c=this.findINode(e,s),u=this.getDirListing(e,s,c),f=(new Date).getTime();if("/"===n)throw ke.EEXIST(n);if(u[a])throw ke.EEXIST(n);var h;try{var p=this.addNewNode(e,o);h=new _r(p,o.length,i|r,f,f,f);var l=this.addNewNode(e,h.toBuffer());u[a]=l,e.put(c.id,t.from(JSON.stringify(u)),!0)}catch(t){throw e.abort(),t}return e.commit(),h},n.prototype.removeEntry=function(e,n){var r=this.store.beginTransaction("readwrite"),i=be.dirname(e),o=this.findINode(r,i),s=this.getDirListing(r,i,o),a=be.basename(e);if(!s[a])throw ke.ENOENT(e);var c=s[a];delete s[a];var u=this.getINode(r,e,c);if(!n&&u.isDirectory())throw ke.EISDIR(e);if(n&&!u.isDirectory())throw ke.ENOTDIR(e);try{r.del(u.id),r.del(c),r.put(o.id,t.from(JSON.stringify(s)),!0)}catch(t){throw r.abort(),t}r.commit()},n}(qe),Sr=function(t){function e(e,n,r,i,o){t.call(this,e,n,r,i,o)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.sync=function(t){var e=this;this.isDirty()?this._fs._sync(this.getPath(),this.getBuffer(),this.getStats(),function(n){n||e.resetDirty(),t(n)}):t()},e.prototype.close=function(t){this.sync(t)},e}(We),Er=function(e){function n(){e.apply(this,arguments)}return e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.isAvailable=function(){return!0},n.prototype.init=function(t,e){this.store=t,this.makeRootDirectory(e)},n.prototype.getName=function(){return this.store.name()},n.prototype.isReadOnly=function(){return!1},n.prototype.supportsSymlinks=function(){return!1},n.prototype.supportsProps=function(){return!1},n.prototype.supportsSynch=function(){return!1},n.prototype.empty=function(t){var e=this;this.store.clear(function(n){Ot(n,t)&&e.makeRootDirectory(t)})},n.prototype.rename=function(e,n,r){var i=this,o=this.store.beginTransaction("readwrite"),s=be.dirname(e),a=be.basename(e),c=be.dirname(n),u=be.basename(n),f={},h={},p=!1;if(0===(c+"/").indexOf(e+"/"))return r(new ke(we.EBUSY,s));var l=function(){if(!p&&h.hasOwnProperty(s)&&h.hasOwnProperty(c)){var l=h[s],d=f[s],y=h[c],g=f[c];if(l[a]){var _=l[a];delete l[a];var m=function(){y[u]=_,o.put(d.id,t.from(JSON.stringify(l)),!0,function(e){Ft(e,o,r)&&(s===c?o.commit(r):o.put(g.id,t.from(JSON.stringify(y)),!0,function(t){Ft(t,o,r)&&o.commit(r)}))})};y[u]?i.getINode(o,n,y[u],function(t,e){Ft(t,o,r)&&(e.isFile()?o.del(e.id,function(t){Ft(t,o,r)&&o.del(y[u],function(t){Ft(t,o,r)&&m()})}):o.abort(function(t){r(ke.EPERM(n))}))}):m()}else r(ke.ENOENT(e))}},d=function(t){i.findINodeAndDirListing(o,t,function(e,n,i){e?p||(p=!0,o.abort(function(){r(e)})):(f[t]=n,h[t]=i,l())})};d(s),s!==c&&d(c)},n.prototype.stat=function(t,e,n){var r=this.store.beginTransaction("readonly");this.findINode(r,t,function(t,e){Ot(t,n)&&n(null,e.toStats())})},n.prototype.createFile=function(t,e,n,r){var i=this,o=this.store.beginTransaction("readwrite"),s=E();this.commitNewFile(o,t,Fe.FILE,n,s,function(n,o){Ot(n,r)&&r(null,new Sr(i,t,e,o.toStats(),s))})},n.prototype.openFile=function(t,e,n){var r=this,i=this.store.beginTransaction("readonly");this.findINode(i,t,function(o,s){Ot(o,n)&&i.get(s.id,function(i,o){Ot(i,n)&&(void 0===o?n(ke.ENOENT(t)):n(null,new Sr(r,t,e,s.toStats(),o)))})})},n.prototype.unlink=function(t,e){this.removeEntry(t,!1,e)},n.prototype.rmdir=function(t,e){var n=this;this.readdir(t,function(r,i){r?e(r):i.length>0?e(ke.ENOTEMPTY(t)):n.removeEntry(t,!0,e)})},n.prototype.mkdir=function(e,n,r){var i=this.store.beginTransaction("readwrite"),o=t.from("{}");this.commitNewFile(i,e,Fe.DIRECTORY,n,o,r)},n.prototype.readdir=function(t,e){var n=this,r=this.store.beginTransaction("readonly");this.findINode(r,t,function(i,o){Ot(i,e)&&n.getDirListing(r,t,o,function(t,n){Ot(t,e)&&e(null,Object.keys(n))})})},n.prototype._sync=function(t,e,n,r){var i=this,o=this.store.beginTransaction("readwrite");this._findINode(o,be.dirname(t),be.basename(t),function(s,a){Ft(s,o,r)&&i.getINode(o,t,a,function(t,i){if(Ft(t,o,r)){var s=i.update(n);o.put(i.id,e,!0,function(t){Ft(t,o,r)&&(s?o.put(a,i.toBuffer(),!0,function(t){Ft(t,o,r)&&o.commit(r)}):o.commit(r))})}})})},n.prototype.makeRootDirectory=function(t){var e=this.store.beginTransaction("readwrite");e.get("/",function(n,r){if(n||void 0===r){var i=(new Date).getTime(),o=new _r(It(),4096,511|Fe.DIRECTORY,i,i,i);e.put(o.id,kt(),!1,function(n){Ft(n,e,t)&&e.put("/",o.toBuffer(),!1,function(n){n?e.abort(function(){t(n)}):e.commit(t)})})}else e.commit(t)})},n.prototype._findINode=function(t,e,n,r){var i=this,o=function(t,i,o){t?r(t):o[n]?r(null,o[n]):r(ke.ENOENT(be.resolve(e,n)))};"/"===e?""===n?r(null,"/"):this.getINode(t,e,"/",function(n,s){Ot(n,r)&&i.getDirListing(t,e,s,function(t,e){o(t,0,e)})}):this.findINodeAndDirListing(t,e,o)},n.prototype.findINode=function(t,e,n){var r=this;this._findINode(t,be.dirname(e),be.basename(e),function(i,o){Ot(i,n)&&r.getINode(t,e,o,n)})},n.prototype.getINode=function(t,e,n,r){t.get(n,function(t,n){Ot(t,r)&&(void 0===n?r(ke.ENOENT(e)):r(null,_r.fromBuffer(n)))})},n.prototype.getDirListing=function(t,e,n,r){n.isDirectory()?t.get(n.id,function(t,n){if(Ot(t,r))try{r(null,JSON.parse(n.toString()))}catch(t){r(ke.ENOENT(e))}}):r(ke.ENOTDIR(e))},n.prototype.findINodeAndDirListing=function(t,e,n){var r=this;this.findINode(t,e,function(i,o){Ot(i,n)&&r.getDirListing(t,e,o,function(t,e){Ot(t,n)&&n(null,o,e)})})},n.prototype.addNewNode=function(t,e,n){var r,i=0,o=function(){5==++i?n(new ke(we.EIO,"Unable to commit data to key-value store.")):(r=It(),t.put(r,e,!1,function(t,e){t||!e?o():n(null,r)}))};o()},n.prototype.commitNewFile=function(e,n,r,i,o,s){var a=this,c=be.dirname(n),u=be.basename(n),f=(new Date).getTime();if("/"===n)return s(ke.EEXIST(n));this.findINodeAndDirListing(e,c,function(c,h,p){Ft(c,e,s)&&(p[u]?e.abort(function(){s(ke.EEXIST(n))}):a.addNewNode(e,o,function(n,c){if(Ft(n,e,s)){var l=new _r(c,o.length,i|r,f,f,f);a.addNewNode(e,l.toBuffer(),function(n,r){Ft(n,e,s)&&(p[u]=r,e.put(h.id,t.from(JSON.stringify(p)),!0,function(t){Ft(t,e,s)&&e.commit(function(t){Ft(t,e,s)&&s(null,l)})}))})}}))})},n.prototype.removeEntry=function(e,n,r){var i=this,o=this.store.beginTransaction("readwrite"),s=be.dirname(e),a=be.basename(e);this.findINodeAndDirListing(o,s,function(s,c,u){if(Ft(s,o,r))if(u[a]){var f=u[a];delete u[a],i.getINode(o,e,f,function(i,s){Ft(i,o,r)&&(!n&&s.isDirectory()?o.abort(function(){r(ke.EISDIR(e))}):n&&!s.isDirectory()?o.abort(function(){r(ke.ENOTDIR(e))}):o.del(s.id,function(e){Ft(e,o,r)&&o.del(f,function(e){Ft(e,o,r)&&o.put(c.id,t.from(JSON.stringify(u)),!0,function(t){Ft(t,o,r)&&o.commit(r)})})}))})}else o.abort(function(){r(ke.ENOENT(e))})})},n}(ze),kr=function(){this.store={}};kr.prototype.name=function(){return Ir.Name},kr.prototype.clear=function(){this.store={}},kr.prototype.beginTransaction=function(t){return new wr(this)},kr.prototype.get=function(t){return this.store[t]},kr.prototype.put=function(t,e,n){return!(!n&&this.store.hasOwnProperty(t))&&(this.store[t]=e,!0)},kr.prototype.del=function(t){delete this.store[t]};var Ir=function(t){function e(){t.call(this,{store:new kr})}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){n(null,new e)},e}(br);Ir.Name="InMemory",Ir.Options={};var Or=Je.indexedDB||Je.mozIndexedDB||Je.webkitIndexedDB||Je.msIndexedDB,Fr=function(t,e){this.tx=t,this.store=e};Fr.prototype.get=function(t,e){try{var n=this.store.get(t);n.onerror=Rt(e),n.onsuccess=function(t){var n=t.target.result;void 0===n?e(null,n):e(null,b(n))}}catch(t){e(Nt(t))}};var Nr=function(t){function e(e,n){t.call(this,e,n)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.put=function(t,e,n,r){try{var i,o=_(e);i=n?this.store.put(o,t):this.store.add(o,t),i.onerror=Rt(r),i.onsuccess=function(t){r(null,!0)}}catch(t){r(Nt(t))}},e.prototype.del=function(t,e){try{var n=this.store.delete(t);n.onerror=Rt(e),n.onsuccess=function(t){e()}}catch(t){e(Nt(t))}},e.prototype.commit=function(t){setTimeout(t,0)},e.prototype.abort=function(t){var e=null;try{this.tx.abort()}catch(t){e=Nt(t)}finally{t(e)}},e}(Fr),Rr=function(t,e){this.db=t,this.storeName=e};Rr.Create=function(t,e){var n=Or.open(t,1);n.onupgradeneeded=function(e){var n=e.target.result;n.objectStoreNames.contains(t)&&n.deleteObjectStore(t),n.createObjectStore(t)},n.onsuccess=function(n){e(null,new Rr(n.target.result,t))},n.onerror=Rt(e,we.EACCES)},Rr.prototype.name=function(){return Tr.Name+" - "+this.storeName},Rr.prototype.clear=function(t){try{var e=this.db.transaction(this.storeName,"readwrite"),n=e.objectStore(this.storeName),r=n.clear();r.onsuccess=function(e){setTimeout(t,0)},r.onerror=Rt(t)}catch(e){t(Nt(e))}},Rr.prototype.beginTransaction=function(t){void 0===t&&(t="readonly");var e=this.db.transaction(this.storeName,t),n=e.objectStore(this.storeName);if("readwrite"===t)return new Nr(e,n);if("readonly"===t)return new Fr(e,n);throw new ke(we.EINVAL,"Invalid transaction type.")};var Tr=function(t){function e(e){t.call(this),this.store=e}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){Rr.Create(t.storeName?t.storeName:"browserfs",function(t,r){r?n(null,new e(r)):n(t)})},e.isAvailable=function(){try{return void 0!==Or&&null!==Or.open("__browserfs_test__")}catch(t){return!1}},e}(Er);Tr.Name="IndexedDB",Tr.Options={storeName:{type:"string",optional:!0,description:"The name of this file system. You can have multiple IndexedDB file systems operating at once, but each must have a different name."}};var Lr,xr=!1;try{Je.localStorage.setItem("__test__",String.fromCharCode(55296)),xr=Je.localStorage.getItem("__test__")===String.fromCharCode(55296)}catch(t){xr=!1}Lr=xr?"binary_string":"binary_string_ie",t.isEncoding(Lr)||(Lr="base64");var Dr=function(){};Dr.prototype.name=function(){return Ar.Name},Dr.prototype.clear=function(){Je.localStorage.clear()},Dr.prototype.beginTransaction=function(t){return new wr(this)},Dr.prototype.get=function(e){try{var n=Je.localStorage.getItem(e);if(null!==n)return t.from(n,Lr)}catch(t){}},Dr.prototype.put=function(t,e,n){try{return!(!n&&null!==Je.localStorage.getItem(t))&&(Je.localStorage.setItem(t,e.toString(Lr)),!0)}catch(t){throw new ke(we.ENOSPC,"LocalStorage is full.")}},Dr.prototype.del=function(t){try{Je.localStorage.removeItem(t)}catch(e){throw new ke(we.EIO,"Unable to delete key "+t+": "+e)}};var Ar=function(t){function e(){t.call(this,{store:new Dr})}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){n(null,new e)},e.isAvailable=function(){return void 0!==Je.localStorage},e}(br);Ar.Name="LocalStorage",Ar.Options={};var Pr=function(t){function e(e){t.call(this),this.mountList=[],this.mntMap={},this.rootFs=e}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){Ir.Create({},function(r,i){if(i){var o=new e(i);try{Object.keys(t).forEach(function(e){o.mount(e,t[e])})}catch(r){return n(r)}n(null,o)}else n(r)})},e.isAvailable=function(){return!0},e.prototype.mount=function(t,e){if("/"!==t[0]&&(t="/"+t),t=be.resolve(t),this.mntMap[t])throw new ke(we.EINVAL,"Mount point "+t+" is already taken.");g(t,511,this.rootFs),this.mntMap[t]=e,this.mountList.push(t),this.mountList=this.mountList.sort(function(t,e){return e.length-t.length})},e.prototype.umount=function(t){var e=this;if("/"!==t[0]&&(t="/"+t),t=be.resolve(t),!this.mntMap[t])throw new ke(we.EINVAL,"Mount point "+t+" is already unmounted.");for(delete this.mntMap[t],this.mountList.splice(this.mountList.indexOf(t),1);"/"!==t&&0===e.rootFs.readdirSync(t).length;)e.rootFs.rmdirSync(t),t=be.dirname(t)},e.prototype._getFs=function(t){for(var e=this,n=this.mountList,r=n.length,i=0;i1?o.length:0),""===t&&(t="/"),{fs:e.mntMap[o],path:t}}return{fs:this.rootFs,path:t}},e.prototype.getName=function(){return e.Name},e.prototype.diskSpace=function(t,e){e(0,0)},e.prototype.isReadOnly=function(){return!1},e.prototype.supportsLinks=function(){return!1},e.prototype.supportsProps=function(){return!1},e.prototype.supportsSynch=function(){return!0},e.prototype.standardizeError=function(t,e,n){var r=t.message.indexOf(e);return-1!==r&&(t.message=t.message.substr(0,r)+n+t.message.substr(r+e.length),t.path=n),t},e.prototype.rename=function(t,e,n){var r=this,i=this._getFs(t),o=this._getFs(e);return i.fs===o.fs?i.fs.rename(i.path,o.path,function(s){s&&r.standardizeError(r.standardizeError(s,i.path,t),o.path,e),n(s)}):xe.readFile(t,function(r,i){if(r)return n(r);xe.writeFile(e,i,function(e){if(e)return n(e);xe.unlink(t,n)})})},e.prototype.renameSync=function(t,e){var n=this._getFs(t),r=this._getFs(e);if(n.fs===r.fs)try{return n.fs.renameSync(n.path,r.path)}catch(i){throw this.standardizeError(this.standardizeError(i,n.path,t),r.path,e),i}var i=xe.readFileSync(t);return xe.writeFileSync(e,i),xe.unlinkSync(t)},e.prototype.readdirSync=function(t){var e=this._getFs(t),n=null;if(e.fs!==this.rootFs)try{n=this.rootFs.readdirSync(t)}catch(t){}try{var r=e.fs.readdirSync(e.path);return null===n?r:r.concat(n.filter(function(t){return-1===r.indexOf(t)}))}catch(r){if(null===n)throw this.standardizeError(r,e.path,t);return n}},e.prototype.readdir=function(t,e){var n=this,r=this._getFs(t);r.fs.readdir(r.path,function(i,o){if(r.fs!==n.rootFs)try{var s=n.rootFs.readdirSync(t);o=o?o.concat(s.filter(function(t){return-1===o.indexOf(t)})):s}catch(o){if(i)return e(n.standardizeError(i,r.path,t))}else if(i)return e(n.standardizeError(i,r.path,t));e(null,o)})},e.prototype.rmdirSync=function(t){var e=this._getFs(t);if(this._containsMountPt(t))throw ke.ENOTEMPTY(t);try{e.fs.rmdirSync(e.path)}catch(n){throw this.standardizeError(n,e.path,t)}},e.prototype.rmdir=function(t,e){var n=this,r=this._getFs(t);this._containsMountPt(t)?e(ke.ENOTEMPTY(t)):r.fs.rmdir(r.path,function(i){e(i?n.standardizeError(i,r.path,t):null)})},e.prototype._containsMountPt=function(t){for(var e=this.mountList,n=e.length,r=0;r=t.length&&i.slice(0,t.length)===t)return!0}return!1},e}(ze);Pr.Name="MountableFileSystem",Pr.Options={};for(var Cr=[["exists","unlink","readlink"],["stat","mkdir","realpath","truncate"],["open","readFile","chmod","utimes"],["chown"],["writeFile","appendFile"]],Ur=0;Ur"},Vr.prototype.getFSUnlocked=function(){return this._fs},Vr.prototype.diskSpace=function(t,e){this._fs.diskSpace(t,e)},Vr.prototype.isReadOnly=function(){return this._fs.isReadOnly()},Vr.prototype.supportsLinks=function(){return this._fs.supportsLinks()},Vr.prototype.supportsProps=function(){return this._fs.supportsProps()},Vr.prototype.supportsSynch=function(){return this._fs.supportsSynch()},Vr.prototype.rename=function(t,e,n){var r=this;this._mu.lock(function(){r._fs.rename(t,e,function(t){r._mu.unlock(),n(t)})})},Vr.prototype.renameSync=function(t,e){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.renameSync(t,e)},Vr.prototype.stat=function(t,e,n){var r=this;this._mu.lock(function(){r._fs.stat(t,e,function(t,e){r._mu.unlock(),n(t,e)})})},Vr.prototype.statSync=function(t,e){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.statSync(t,e)},Vr.prototype.open=function(t,e,n,r){var i=this;this._mu.lock(function(){i._fs.open(t,e,n,function(t,e){i._mu.unlock(),r(t,e)})})},Vr.prototype.openSync=function(t,e,n){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.openSync(t,e,n)},Vr.prototype.unlink=function(t,e){var n=this;this._mu.lock(function(){n._fs.unlink(t,function(t){n._mu.unlock(),e(t)})})},Vr.prototype.unlinkSync=function(t){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.unlinkSync(t)},Vr.prototype.rmdir=function(t,e){var n=this;this._mu.lock(function(){n._fs.rmdir(t,function(t){n._mu.unlock(),e(t)})})},Vr.prototype.rmdirSync=function(t){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.rmdirSync(t)},Vr.prototype.mkdir=function(t,e,n){var r=this;this._mu.lock(function(){r._fs.mkdir(t,e,function(t){r._mu.unlock(),n(t)})})},Vr.prototype.mkdirSync=function(t,e){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.mkdirSync(t,e)},Vr.prototype.readdir=function(t,e){var n=this;this._mu.lock(function(){n._fs.readdir(t,function(t,r){n._mu.unlock(),e(t,r)})})},Vr.prototype.readdirSync=function(t){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.readdirSync(t)},Vr.prototype.exists=function(t,e){var n=this;this._mu.lock(function(){n._fs.exists(t,function(t){n._mu.unlock(),e(t)})})},Vr.prototype.existsSync=function(t){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.existsSync(t)},Vr.prototype.realpath=function(t,e,n){var r=this;this._mu.lock(function(){r._fs.realpath(t,e,function(t,e){r._mu.unlock(),n(t,e)})})},Vr.prototype.realpathSync=function(t,e){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.realpathSync(t,e)},Vr.prototype.truncate=function(t,e,n){var r=this;this._mu.lock(function(){r._fs.truncate(t,e,function(t){r._mu.unlock(),n(t)})})},Vr.prototype.truncateSync=function(t,e){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.truncateSync(t,e)},Vr.prototype.readFile=function(t,e,n,r){var i=this;this._mu.lock(function(){i._fs.readFile(t,e,n,function(t,e){i._mu.unlock(),r(t,e)})})},Vr.prototype.readFileSync=function(t,e,n){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.readFileSync(t,e,n)},Vr.prototype.writeFile=function(t,e,n,r,i,o){var s=this;this._mu.lock(function(){s._fs.writeFile(t,e,n,r,i,function(t){s._mu.unlock(),o(t)})})},Vr.prototype.writeFileSync=function(t,e,n,r,i){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.writeFileSync(t,e,n,r,i)},Vr.prototype.appendFile=function(t,e,n,r,i,o){var s=this;this._mu.lock(function(){s._fs.appendFile(t,e,n,r,i,function(t){s._mu.unlock(),o(t)})})},Vr.prototype.appendFileSync=function(t,e,n,r,i){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.appendFileSync(t,e,n,r,i)},Vr.prototype.chmod=function(t,e,n,r){var i=this;this._mu.lock(function(){i._fs.chmod(t,e,n,function(t){i._mu.unlock(),r(t)})})},Vr.prototype.chmodSync=function(t,e,n){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.chmodSync(t,e,n)},Vr.prototype.chown=function(t,e,n,r,i){var o=this;this._mu.lock(function(){o._fs.chown(t,e,n,r,function(t){o._mu.unlock(),i(t)})})},Vr.prototype.chownSync=function(t,e,n,r){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.chownSync(t,e,n,r)},Vr.prototype.utimes=function(t,e,n,r){var i=this;this._mu.lock(function(){i._fs.utimes(t,e,n,function(t){i._mu.unlock(),r(t)})})},Vr.prototype.utimesSync=function(t,e,n){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.utimesSync(t,e,n)},Vr.prototype.link=function(t,e,n){var r=this;this._mu.lock(function(){r._fs.link(t,e,function(t){r._mu.unlock(),n(t)})})},Vr.prototype.linkSync=function(t,e){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.linkSync(t,e)},Vr.prototype.symlink=function(t,e,n,r){var i=this;this._mu.lock(function(){i._fs.symlink(t,e,n,function(t){i._mu.unlock(),r(t)})})},Vr.prototype.symlinkSync=function(t,e,n){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.symlinkSync(t,e,n)},Vr.prototype.readlink=function(t,e){var n=this;this._mu.lock(function(){n._fs.readlink(t,function(t,r){n._mu.unlock(),e(t,r)})})},Vr.prototype.readlinkSync=function(t){if(this._mu.isLocked())throw new Error("invalid sync call");return this._fs.readlinkSync(t)};var Wr="/.deletedFiles.log",Hr=function(t){function e(e,n,r,i,o){t.call(this,e,n,r,i,o)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.sync=function(t){var e=this;if(!this.isDirty())return void t(null);this._fs._syncAsync(this,function(n){e.resetDirty(),t(n)})},e.prototype.syncSync=function(){this.isDirty()&&(this._fs._syncSync(this),this.resetDirty())},e.prototype.close=function(t){this.sync(t)},e.prototype.closeSync=function(){this.syncSync()},e}(We),Zr=function(t){function e(e,n){if(t.call(this),this._isInitialized=!1,this._initializeCallbacks=[],this._deletedFiles={},this._deleteLog="",this._deleteLogUpdatePending=!1,this._deleteLogUpdateNeeded=!1,this._deleteLogError=null,this._writable=e,this._readable=n,this._writable.isReadOnly())throw new ke(we.EINVAL,"Writable file system must be writable.")}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.isAvailable=function(){return!0},e.prototype.getOverlayedFileSystems=function(){return{readable:this._readable,writable:this._writable}},e.prototype._syncAsync=function(t,e){var n=this;this.createParentDirectoriesAsync(t.getPath(),function(r){if(r)return e(r);n._writable.writeFile(t.getPath(),t.getBuffer(),null,xt("w"),t.getStats().mode,e)})},e.prototype._syncSync=function(t){this.createParentDirectories(t.getPath()),this._writable.writeFileSync(t.getPath(),t.getBuffer(),null,xt("w"),t.getStats().mode)},e.prototype.getName=function(){return Yr.Name},e.prototype._initialize=function(t){var e=this,n=this._initializeCallbacks,r=function(t){e._isInitialized=!t,e._initializeCallbacks=[],n.forEach(function(e){return e(t)})};if(this._isInitialized)return t();n.push(t),1===n.length&&this._writable.readFile(Wr,"utf8",xt("r"),function(t,n){if(t){if(t.errno!==we.ENOENT)return r(t)}else e._deleteLog=n;e._reparseDeletionLog(),r()})},e.prototype.isReadOnly=function(){return!1},e.prototype.supportsSynch=function(){return this._readable.supportsSynch()&&this._writable.supportsSynch()},e.prototype.supportsLinks=function(){return!1},e.prototype.supportsProps=function(){return this._readable.supportsProps()&&this._writable.supportsProps()},e.prototype.getDeletionLog=function(){return this._deleteLog},e.prototype.restoreDeletionLog=function(t){this._deleteLog=t,this._reparseDeletionLog(),this.updateLog("")},e.prototype.rename=function(t,e,n){var r=this;if(this.checkInitAsync(n)&&!this.checkPathAsync(t,n)&&!this.checkPathAsync(e,n))return t===Wr||e===Wr?n(ke.EPERM("Cannot rename deletion log.")):t===e?n():void this.stat(t,!1,function(i,o){return i?n(i):r.stat(e,!1,function(i,s){function a(r){var i=r.shift();if(!i)return n();var o=be.resolve(t,i),s=be.resolve(e,i);c.rename(o,s,function(t){if(t)return n(t);a(r)})}var c=r,u=511;if(o.isDirectory()){if(i)return i.errno!==we.ENOENT?n(i):r._writable.exists(t,function(i){if(i)return r._writable.rename(t,e,n);r._writable.mkdir(e,u,function(e){if(e)return n(e);r._readable.readdir(t,function(t,e){if(t)return n();a(e)})})});if(u=s.mode,!s.isDirectory())return n(ke.ENOTDIR(e));r.readdir(e,function(i,o){if(o&&o.length)return n(ke.ENOTEMPTY(e));r._readable.readdir(t,function(t,e){if(t)return n();a(e)})})}if(s&&s.isDirectory())return n(ke.EISDIR(e));r.readFile(t,null,xt("r"),function(i,s){return i?n(i):r.writeFile(e,s,null,xt("w"),o.mode,function(e){return e?n(e):r.unlink(t,n)})})})})},e.prototype.renameSync=function(t,e){var n=this;if(this.checkInitialized(),this.checkPath(t),this.checkPath(e),t===Wr||e===Wr)throw ke.EPERM("Cannot rename deletion log.");var r=this.statSync(t,!1);if(r.isDirectory()){if(t===e)return;var i=511;if(this.existsSync(e)){var o=this.statSync(e,!1);if(i=o.mode,!o.isDirectory())throw ke.ENOTDIR(e);if(this.readdirSync(e).length>0)throw ke.ENOTEMPTY(e)}this._writable.existsSync(t)?this._writable.renameSync(t,e):this._writable.existsSync(e)||this._writable.mkdirSync(e,i),this._readable.existsSync(t)&&this._readable.readdirSync(t).forEach(function(r){n.renameSync(be.resolve(t,r),be.resolve(e,r))})}else{if(this.existsSync(e)&&this.statSync(e,!1).isDirectory())throw ke.EISDIR(e);this.writeFileSync(e,this.readFileSync(t,null,xt("r")),null,xt("w"),r.mode)}t!==e&&this.existsSync(t)&&this.unlinkSync(t)},e.prototype.stat=function(t,e,n){var r=this;this.checkInitAsync(n)&&this._writable.stat(t,e,function(i,o){i&&i.errno===we.ENOENT?(r._deletedFiles[t]&&n(ke.ENOENT(t)),r._readable.stat(t,e,function(t,e){e&&(e=Ne.clone(e),e.mode=Lt(e.mode)),n(t,e)})):n(i,o)})},e.prototype.statSync=function(t,e){this.checkInitialized();try{return this._writable.statSync(t,e)}catch(r){if(this._deletedFiles[t])throw ke.ENOENT(t);var n=Ne.clone(this._readable.statSync(t,e));return n.mode=Lt(n.mode),n}},e.prototype.open=function(t,e,n,r){var i=this;this.checkInitAsync(r)&&!this.checkPathAsync(t,r)&&this.stat(t,!1,function(o,s){if(s)switch(e.pathExistsAction()){case Ee.TRUNCATE_FILE:return i.createParentDirectoriesAsync(t,function(o){if(o)return r(o);i._writable.open(t,e,n,r)});case Ee.NOP:return i._writable.exists(t,function(o){o?i._writable.open(t,e,n,r):(s=Ne.clone(s),s.mode=n,i._readable.readFile(t,null,xt("r"),function(n,o){if(n)return r(n);-1===s.size&&(s.size=o.length);var a=new Hr(i,t,e,s,o);r(null,a)}))});default:return r(ke.EEXIST(t))}else switch(e.pathNotExistsAction()){case Ee.CREATE_FILE:return i.createParentDirectoriesAsync(t,function(o){return o?r(o):i._writable.open(t,e,n,r)});default:return r(ke.ENOENT(t))}})},e.prototype.openSync=function(t,e,n){if(this.checkInitialized(),this.checkPath(t),t===Wr)throw ke.EPERM("Cannot open deletion log.");if(this.existsSync(t))switch(e.pathExistsAction()){case Ee.TRUNCATE_FILE:return this.createParentDirectories(t),this._writable.openSync(t,e,n);case Ee.NOP:if(this._writable.existsSync(t))return this._writable.openSync(t,e,n);var r=this._readable.readFileSync(t,null,xt("r")),i=Ne.clone(this._readable.statSync(t,!1));return i.mode=n,new Hr(this,t,e,i,r);default:throw ke.EEXIST(t)}else switch(e.pathNotExistsAction()){case Ee.CREATE_FILE:return this.createParentDirectories(t),this._writable.openSync(t,e,n);default:throw ke.ENOENT(t)}},e.prototype.unlink=function(t,e){var n=this;this.checkInitAsync(e)&&!this.checkPathAsync(t,e)&&this.exists(t,function(r){if(!r)return e(ke.ENOENT(t));n._writable.exists(t,function(r){if(r)return n._writable.unlink(t,function(r){if(r)return e(r);n.exists(t,function(r){r&&n.deletePath(t),e(null)})});n.deletePath(t),e(null)})})},e.prototype.unlinkSync=function(t){if(this.checkInitialized(),this.checkPath(t),!this.existsSync(t))throw ke.ENOENT(t);this._writable.existsSync(t)&&this._writable.unlinkSync(t),this.existsSync(t)&&this.deletePath(t)},e.prototype.rmdir=function(t,e){var n=this;if(this.checkInitAsync(e)){var r=function(){n.readdir(t,function(r,i){return r?e(r):i.length?e(ke.ENOTEMPTY(t)):(n.deletePath(t),void e(null))})};this.exists(t,function(i){if(!i)return e(ke.ENOENT(t));n._writable.exists(t,function(i){i?n._writable.rmdir(t,function(i){if(i)return e(i);n._readable.exists(t,function(t){t?r():e()})}):r()})})}},e.prototype.rmdirSync=function(t){if(this.checkInitialized(),!this.existsSync(t))throw ke.ENOENT(t);if(this._writable.existsSync(t)&&this._writable.rmdirSync(t),this.existsSync(t)){if(this.readdirSync(t).length>0)throw ke.ENOTEMPTY(t);this.deletePath(t)}},e.prototype.mkdir=function(t,e,n){var r=this;this.checkInitAsync(n)&&this.exists(t,function(i){if(i)return n(ke.EEXIST(t));r.createParentDirectoriesAsync(t,function(i){if(i)return n(i);r._writable.mkdir(t,e,n)})})},e.prototype.mkdirSync=function(t,e){if(this.checkInitialized(),this.existsSync(t))throw ke.EEXIST(t);this.createParentDirectories(t),this._writable.mkdirSync(t,e)},e.prototype.readdir=function(t,e){var n=this;this.checkInitAsync(e)&&this.stat(t,!1,function(r,i){return r?e(r):i.isDirectory()?void n._writable.readdir(t,function(r,i){if(r&&"ENOENT"!==r.code)return e(r);!r&&i||(i=[]),n._readable.readdir(t,function(r,o){!r&&o||(o=[]);var s={},a=i.concat(o.filter(function(e){return!n._deletedFiles[t+"/"+e]})).filter(function(t){var e=!s[t];return s[t]=!0,e});e(null,a)})}):e(ke.ENOTDIR(t))})},e.prototype.readdirSync=function(t){var e=this;if(this.checkInitialized(),!this.statSync(t,!1).isDirectory())throw ke.ENOTDIR(t);var n=[];try{n=n.concat(this._writable.readdirSync(t))}catch(t){}try{n=n.concat(this._readable.readdirSync(t).filter(function(n){return!e._deletedFiles[t+"/"+n]}))}catch(t){}var r={};return n.filter(function(t){var e=!r[t];return r[t]=!0,e})},e.prototype.exists=function(t,e){var n=this;this.checkInitialized(),this._writable.exists(t,function(r){if(r)return e(!0);n._readable.exists(t,function(r){e(r&&!0!==n._deletedFiles[t])})})},e.prototype.existsSync=function(t){return this.checkInitialized(),this._writable.existsSync(t)||this._readable.existsSync(t)&&!0!==this._deletedFiles[t]},e.prototype.chmod=function(t,e,n,r){var i=this;this.checkInitAsync(r)&&this.operateOnWritableAsync(t,function(o){if(o)return r(o);i._writable.chmod(t,e,n,r)})},e.prototype.chmodSync=function(t,e,n){var r=this;this.checkInitialized(),this.operateOnWritable(t,function(){r._writable.chmodSync(t,e,n)})},e.prototype.chown=function(t,e,n,r,i){var o=this;this.checkInitAsync(i)&&this.operateOnWritableAsync(t,function(s){if(s)return i(s);o._writable.chown(t,e,n,r,i)})},e.prototype.chownSync=function(t,e,n,r){var i=this;this.checkInitialized(),this.operateOnWritable(t,function(){i._writable.chownSync(t,e,n,r)})},e.prototype.utimes=function(t,e,n,r){var i=this;this.checkInitAsync(r)&&this.operateOnWritableAsync(t,function(o){if(o)return r(o);i._writable.utimes(t,e,n,r)})},e.prototype.utimesSync=function(t,e,n){var r=this;this.checkInitialized(),this.operateOnWritable(t,function(){r._writable.utimesSync(t,e,n)})},e.prototype.deletePath=function(t){this._deletedFiles[t]=!0,this.updateLog("d"+t+"\n")},e.prototype.updateLog=function(t){var e=this;this._deleteLog+=t,this._deleteLogUpdatePending?this._deleteLogUpdateNeeded=!0:(this._deleteLogUpdatePending=!0,this._writable.writeFile(Wr,this._deleteLog,"utf8",Oe.getFileFlag("w"),420,function(t){e._deleteLogUpdatePending=!1,t?e._deleteLogError=t:e._deleteLogUpdateNeeded&&(e._deleteLogUpdateNeeded=!1,e.updateLog(""))}))},e.prototype._reparseDeletionLog=function(){var t=this;this._deletedFiles={},this._deleteLog.split("\n").forEach(function(e){t._deletedFiles[e.slice(1)]="d"===e.slice(0,1)})},e.prototype.checkInitialized=function(){if(!this._isInitialized)throw new ke(we.EPERM,"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it.");if(null!==this._deleteLogError){var t=this._deleteLogError;throw this._deleteLogError=null,t}},e.prototype.checkInitAsync=function(t){if(!this._isInitialized)return t(new ke(we.EPERM,"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it.")),!1;if(null!==this._deleteLogError){var e=this._deleteLogError;return this._deleteLogError=null,t(e),!1}return!0},e.prototype.checkPath=function(t){if(t===Wr)throw ke.EPERM(t)},e.prototype.checkPathAsync=function(t,e){return t===Wr&&(e(ke.EPERM(t)),!0)},e.prototype.createParentDirectoriesAsync=function(t,e){function n(t,e){t?(o.push(i),i=be.dirname(i),s._writable.stat(i,!1,n)):r()}function r(){if(!o.length)return e();var t=o.pop();s._readable.stat(t,!1,function(n,i){if(!i)return e();s._writable.mkdir(t,i.mode,function(t){if(t)return e(t);r()})})}var i=be.dirname(t),o=[],s=this;this._writable.stat(i,!1,n)},e.prototype.createParentDirectories=function(t){for(var e=this,n=be.dirname(t),r=[];!this._writable.existsSync(n);)r.push(n),n=be.dirname(n);r=r.reverse(),r.forEach(function(t){e._writable.mkdirSync(t,e.statSync(t,!1).mode)})},e.prototype.operateOnWritable=function(t,e){if(!this.existsSync(t))throw ke.ENOENT(t);this._writable.existsSync(t)||this.copyToWritable(t),e()},e.prototype.operateOnWritableAsync=function(t,e){var n=this;this.exists(t,function(r){if(!r)return e(ke.ENOENT(t));n._writable.exists(t,function(r){if(!r)return n.copyToWritableAsync(t,e);e()})})},e.prototype.copyToWritable=function(t){var e=this.statSync(t,!1);e.isDirectory()?this._writable.mkdirSync(t,e.mode):this.writeFileSync(t,this._readable.readFileSync(t,null,xt("r")),null,xt("w"),this.statSync(t,!1).mode)},e.prototype.copyToWritableAsync=function(t,e){var n=this;this.stat(t,!1,function(r,i){return r?e(r):i.isDirectory()?n._writable.mkdir(t,i.mode,e):void n._readable.readFile(t,null,xt("r"),function(r,o){if(r)return e(r);n.writeFile(t,o,null,xt("w"),i.mode,e)})})},e}(ze),Yr=function(t){function e(e,n){t.call(this,new Zr(e,n))}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){try{var r=new e(t.writable,t.readable);r._initialize(function(t){n(t,r)})}catch(t){n(t)}},e.isAvailable=function(){return Zr.isAvailable()},e.prototype.getOverlayedFileSystems=function(){return t.prototype.getFSUnlocked.call(this).getOverlayedFileSystems()},e.prototype.unwrap=function(){return t.prototype.getFSUnlocked.call(this)},e.prototype._initialize=function(e){t.prototype.getFSUnlocked.call(this)._initialize(e)},e}(Vr);Yr.Name="OverlayFS",Yr.Options={writable:{type:"object",description:"The file system to write modified files to."},readable:{type:"object",description:"The file system that initially populates this file system."}};var Xr;!function(t){t[t.CB=0]="CB",t[t.FD=1]="FD",t[t.API_ERROR=2]="API_ERROR",t[t.STATS=3]="STATS",t[t.PROBE=4]="PROBE",t[t.FILEFLAG=5]="FILEFLAG",t[t.BUFFER=6]="BUFFER",t[t.ERROR=7]="ERROR"}(Xr||(Xr={}));var Jr=function(){this._callbacks={},this._nextId=0};Jr.prototype.toRemoteArg=function(t){var e=this._nextId++;return this._callbacks[e]=t,{type:Xr.CB,id:e}},Jr.prototype.toLocalArg=function(t){var e=this._callbacks[t];return delete this._callbacks[t],e};var Kr=function(){this._fileDescriptors={},this._nextId=0};Kr.prototype.toRemoteArg=function(e,n,r,i){var o,s,a=this._nextId++;this._fileDescriptors[a]=e,e.stat(function(c,u){c?i(c):(s=zt(u.toBuffer()),r.isReadable()?e.read(t.alloc(u.size),0,u.size,0,function(t,e,c){t?i(t):(o=zt(c),i(null,{type:Xr.FD,id:a,data:o,stat:s,path:n,flag:r.getFlagString()}))}):i(null,{type:Xr.FD,id:a,data:new ArrayBuffer(0),stat:s,path:n,flag:r.getFlagString()}))})},Kr.prototype.applyFdAPIRequest=function(t,e){var n=this,r=t.args[0];this._applyFdChanges(r,function(i,o){i?e(i):o[t.method](function(i){"close"===t.method&&delete n._fileDescriptors[r.id],e(i)})})},Kr.prototype._applyFdChanges=function(t,e){var n=this._fileDescriptors[t.id],r=qt(t.data),i=Ne.fromBuffer(qt(t.stat)),o=Oe.getFileFlag(t.flag);o.isWriteable()?n.write(r,0,r.length,o.isAppendable()?n.getPos():0,function(t){function s(){n.stat(function(t,r){t?e(t):r.mode!==i.mode?n.chmod(i.mode,function(t){e(t,n)}):e(t,n)})}t?e(t):o.isAppendable()?s():n.truncate(r.length,function(){s()})}):e(null,n)};var Gr=function(t){function e(e,n,r,i,o,s){t.call(this,e,n,r,i,s),this._remoteFdId=o}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getRemoteFdId=function(){return this._remoteFdId},e.prototype.toRemoteArg=function(){return{type:Xr.FD,id:this._remoteFdId,data:zt(this.getBuffer()),stat:zt(this.getStats().toBuffer()),path:this.getPath(),flag:this.getFlag().getFlagString()}},e.prototype.sync=function(t){this._syncClose("sync",t)},e.prototype.close=function(t){this._syncClose("close",t)},e.prototype._syncClose=function(t,e){var n=this;this.isDirty()?this._fs.syncClose(t,this,function(t){t||n.resetDirty(),e(t)}):e()},e}(We),Qr=function(e){function n(t){var n=this;e.call(this),this._callbackConverter=new Jr,this._isInitialized=!1,this._isReadOnly=!1,this._supportLinks=!1,this._supportProps=!1,this._worker=t,this._worker.addEventListener("message",function(t){var e=t.data;if(Zt(e)){var r,i=e.args,o=new Array(i.length);for(r=0;r0&&(u=-1,s={browserfsMessage:!0,cbId:o,args:[Dt(t)]},e.postMessage(s))}var i,s,a=arguments,c=new Array(arguments.length),u=arguments.length;for(i=0;i0;){var i=void 0,o=r.pop(),s=o[0],a=o[1],c=o[2];for(var u in a)if(a.hasOwnProperty(u)){var f=a[u],h=s+"/"+u;f?(e._index[h]=i=new oi,r.push([h,f,i])):i=new ii(new Ne(Fe.FILE,-1,365)),c&&(c._ls[u]=i)}}return e},ri.prototype.fileIterator=function(t){var e=this;for(var n in e._index)if(e._index.hasOwnProperty(n))for(var r=e._index[n],i=r.getListing(),o=0,s=i;o0&&"/"!==n.charAt(n.length-1)&&(n+="/"),this.prefixUrl=n,this._index=ri.fromListing(e),!ni||r&&$r?(this._requestFileAsyncInternal=ti,this._requestFileSizeAsyncInternal=Qt):(this._requestFileAsyncInternal=$t,this._requestFileSizeAsyncInternal=te),$r?(this._requestFileSyncInternal=ei,this._requestFileSizeSyncInternal=Gt):(this._requestFileSyncInternal=ie,this._requestFileSizeSyncInternal=ie)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){void 0===t.index&&(t.index="index.json"),"string"==typeof t.index?ti(t.index,"json",function(r,i){r?n(r):n(null,new e(i,t.baseUrl))}):n(null,new e(t.index,t.baseUrl))},e.isAvailable=function(){return $r||ni},e.prototype.empty=function(){this._index.fileIterator(function(t){t.fileData=null})},e.prototype.getName=function(){return e.Name},e.prototype.diskSpace=function(t,e){e(0,0)},e.prototype.isReadOnly=function(){return!0},e.prototype.supportsLinks=function(){return!1},e.prototype.supportsProps=function(){return!1},e.prototype.supportsSynch=function(){return $r},e.prototype.preloadFile=function(t,e){var n=this._index.getInode(t);if(!ee(n))throw ke.EISDIR(t);if(null===n)throw ke.ENOENT(t);var r=n.getData();r.size=e.length,r.fileData=e},e.prototype.stat=function(t,e,n){var r=this._index.getInode(t);if(null===r)return n(ke.ENOENT(t));var i;ee(r)?(i=r.getData(),i.size<0?this._requestFileSizeAsync(t,function(t,e){if(t)return n(t);i.size=e,n(null,Ne.clone(i))}):n(null,Ne.clone(i))):ne(r)?(i=r.getStats(),n(null,i)):n(ke.FileError(we.EINVAL,t))},e.prototype.statSync=function(t,e){var n=this._index.getInode(t);if(null===n)throw ke.ENOENT(t);var r;if(ee(n))r=n.getData(),r.size<0&&(r.size=this._requestFileSizeSync(t));else{if(!ne(n))throw ke.FileError(we.EINVAL,t);r=n.getStats()}return r},e.prototype.open=function(t,e,n,r){if(e.isWriteable())return r(new ke(we.EPERM,t));var i=this,o=this._index.getInode(t);if(null===o)return r(ke.ENOENT(t));if(!ee(o))return r(ke.EISDIR(t));var s=o.getData();switch(e.pathExistsAction()){case Ee.THROW_EXCEPTION:case Ee.TRUNCATE_FILE:return r(ke.EEXIST(t));case Ee.NOP:if(s.fileData)return r(null,new He(i,t,e,Ne.clone(s),s.fileData));this._requestFileAsync(t,"buffer",function(n,o){return n?r(n):(s.size=o.length,s.fileData=o,r(null,new He(i,t,e,Ne.clone(s),o)))});break;default:return r(new ke(we.EINVAL,"Invalid FileMode object."))}},e.prototype.openSync=function(t,e,n){if(e.isWriteable())throw new ke(we.EPERM,t);var r=this._index.getInode(t);if(null===r)throw ke.ENOENT(t);if(!ee(r))throw ke.EISDIR(t);var i=r.getData();switch(e.pathExistsAction()){case Ee.THROW_EXCEPTION:case Ee.TRUNCATE_FILE:throw ke.EEXIST(t);case Ee.NOP:if(i.fileData)return new He(this,t,e,Ne.clone(i),i.fileData);var o=this._requestFileSync(t,"buffer");return i.size=o.length,i.fileData=o,new He(this,t,e,Ne.clone(i),o);default:throw new ke(we.EINVAL,"Invalid FileMode object.")}},e.prototype.readdir=function(t,e){try{e(null,this.readdirSync(t))}catch(t){e(t)}},e.prototype.readdirSync=function(t){var e=this._index.getInode(t);if(null===e)throw ke.ENOENT(t);if(ne(e))return e.getListing();throw ke.ENOTDIR(t)},e.prototype.readFile=function(t,e,n,r){var i=r;this.open(t,n,420,function(t,n){if(t)return r(t);r=function(t,e){n.close(function(n){return t||(t=n),i(t,e)})};var o=n,s=o.getBuffer();null===e?r(t,S(s)):re(s,e,r)})},e.prototype.readFileSync=function(t,e,n){var r=this.openSync(t,n,420);try{var i=r,o=i.getBuffer();return null===e?S(o):o.toString(e)}finally{r.closeSync()}},e.prototype._getHTTPPath=function(t){return"/"===t.charAt(0)&&(t=t.slice(1)),this.prefixUrl+t},e.prototype._requestFileAsync=function(t,e,n){this._requestFileAsyncInternal(this._getHTTPPath(t),e,n)},e.prototype._requestFileSync=function(t,e){return this._requestFileSyncInternal(this._getHTTPPath(t),e)},e.prototype._requestFileSizeAsync=function(t,e){this._requestFileSizeAsyncInternal(this._getHTTPPath(t),e)},e.prototype._requestFileSizeSync=function(t){return this._requestFileSizeSyncInternal(this._getHTTPPath(t))},e}(ze);si.Name="HTTPRequest",si.Options={index:{type:["string","object"],optional:!0,description:"URL to a file index as a JSON file or the file index object itself, generated with the make_http_index script. Defaults to `index.json`."},baseUrl:{type:"string",optional:!0,description:"Used as the URL prefix for fetched files. Default: Fetch files relative to the index."},preferXHR:{type:"boolean",optional:!0,description:"Whether to prefer XmlHttpRequest or fetch for async operations if both are available. Default: false"}};var ai=function(){};ai.str2byte=function(t,e){for(var n=t.length>e.length?e.length:t.length,r=0;r127){var o=ai.extendedChars.indexOf(t.charAt(r));o>-1&&(i=o+128)}e[i]=r}return n},ai.byte2str=function(t){for(var e=new Array(t.length),n=0;n127?ai.extendedChars[r-128]:String.fromCharCode(r)}return e.join("")},ai.byteLength=function(t){return t.length},ai.extendedChars=["Ç","ü","é","â","ä","à","å","ç","ê","ë","è","ï","î","ì","Ä","Å","É","æ","Æ","ô","ö","ò","û","ù","ÿ","Ö","Ü","ø","£","Ø","×","ƒ","á","í","ó","ú","ñ","Ñ","ª","º","¿","®","¬","½","¼","¡","«","»","_","_","_","¦","¦","Á","Â","À","©","¦","¦","+","+","¢","¥","+","+","-","-","+","-","+","ã","Ã","+","+","-","-","¦","-","+","¤","ð","Ð","Ê","Ë","È","i","Í","Î","Ï","+","+","_","_","¦","Ì","_","Ó","ß","Ô","Ò","õ","Õ","µ","þ","Þ","Ú","Û","Ù","ý","Ý","¯","´","","±","_","¾","¶","§","÷","¸","°","¨","·","¹","³","²","_"," "];var ci,ui=n(35).inflateRaw,fi={};!function(t){t[t.MSDOS=0]="MSDOS",t[t.AMIGA=1]="AMIGA",t[t.OPENVMS=2]="OPENVMS",t[t.UNIX=3]="UNIX",t[t.VM_CMS=4]="VM_CMS",t[t.ATARI_ST=5]="ATARI_ST",t[t.OS2_HPFS=6]="OS2_HPFS",t[t.MAC=7]="MAC",t[t.Z_SYSTEM=8]="Z_SYSTEM",t[t.CP_M=9]="CP_M",t[t.NTFS=10]="NTFS",t[t.MVS=11]="MVS",t[t.VSE=12]="VSE",t[t.ACORN_RISC=13]="ACORN_RISC",t[t.VFAT=14]="VFAT",t[t.ALT_MVS=15]="ALT_MVS",t[t.BEOS=16]="BEOS",t[t.TANDEM=17]="TANDEM",t[t.OS_400=18]="OS_400",t[t.OSX=19]="OSX"}(ci||(ci={}));var hi;!function(t){t[t.STORED=0]="STORED",t[t.SHRUNK=1]="SHRUNK",t[t.REDUCED_1=2]="REDUCED_1",t[t.REDUCED_2=3]="REDUCED_2",t[t.REDUCED_3=4]="REDUCED_3",t[t.REDUCED_4=5]="REDUCED_4",t[t.IMPLODE=6]="IMPLODE",t[t.DEFLATE=8]="DEFLATE",t[t.DEFLATE64=9]="DEFLATE64",t[t.TERSE_OLD=10]="TERSE_OLD",t[t.BZIP2=12]="BZIP2",t[t.LZMA=14]="LZMA",t[t.TERSE_NEW=18]="TERSE_NEW",t[t.LZ77=19]="LZ77",t[t.WAVPACK=97]="WAVPACK",t[t.PPMD=98]="PPMD"}(hi||(hi={}));var pi=function(t){if(this.data=t,67324752!==t.readUInt32LE(0))throw new ke(we.EINVAL,"Invalid Zip file: Local file header has invalid signature: "+this.data.readUInt32LE(0))};pi.prototype.versionNeeded=function(){return this.data.readUInt16LE(4)},pi.prototype.flags=function(){return this.data.readUInt16LE(6)},pi.prototype.compressionMethod=function(){return this.data.readUInt16LE(8)},pi.prototype.lastModFileTime=function(){return oe(this.data.readUInt16LE(10),this.data.readUInt16LE(12))},pi.prototype.rawLastModFileTime=function(){return this.data.readUInt32LE(10)},pi.prototype.crc32=function(){return this.data.readUInt32LE(14)},pi.prototype.fileNameLength=function(){return this.data.readUInt16LE(26)},pi.prototype.extraFieldLength=function(){return this.data.readUInt16LE(28)},pi.prototype.fileName=function(){return se(this.data,this.useUTF8(),30,this.fileNameLength())},pi.prototype.extraField=function(){var t=30+this.fileNameLength();return this.data.slice(t,t+this.extraFieldLength())},pi.prototype.totalSize=function(){return 30+this.fileNameLength()+this.extraFieldLength()},pi.prototype.useUTF8=function(){return 2048==(2048&this.flags())};var li=function(t,e,n){this.header=t,this.record=e,this.data=n};li.prototype.decompress=function(){var t=this.header.compressionMethod(),e=fi[t];if(e)return e(this.data,this.record.compressedSize(),this.record.uncompressedSize(),this.record.flag());var n=hi[t];throw n||(n="Unknown: "+t),new ke(we.EINVAL,"Invalid compression method on file '"+this.header.fileName()+"': "+n)},li.prototype.getHeader=function(){return this.header},li.prototype.getRecord=function(){return this.record},li.prototype.getRawData=function(){return this.data};var di=function(t){this.data=t};di.prototype.crc32=function(){return this.data.readUInt32LE(0)},di.prototype.compressedSize=function(){return this.data.readUInt32LE(4)},di.prototype.uncompressedSize=function(){return this.data.readUInt32LE(8)};var yi=function(t){if(this.data=t,134630224!==this.data.readUInt32LE(0))throw new ke(we.EINVAL,"Invalid archive extra data record signature: "+this.data.readUInt32LE(0))};yi.prototype.length=function(){return this.data.readUInt32LE(4)},yi.prototype.extraFieldData=function(){return this.data.slice(8,8+this.length())};var gi=function(t){if(this.data=t,84233040!==this.data.readUInt32LE(0))throw new ke(we.EINVAL,"Invalid digital signature signature: "+this.data.readUInt32LE(0))};gi.prototype.size=function(){return this.data.readUInt16LE(4)},gi.prototype.signatureData=function(){return this.data.slice(6,6+this.size())};var _i=function(t,e){if(this.zipData=t,this.data=e,33639248!==this.data.readUInt32LE(0))throw new ke(we.EINVAL,"Invalid Zip file: Central directory record has invalid signature: "+this.data.readUInt32LE(0));this._filename=this.produceFilename()};_i.prototype.versionMadeBy=function(){return this.data.readUInt16LE(4)},_i.prototype.versionNeeded=function(){return this.data.readUInt16LE(6)},_i.prototype.flag=function(){return this.data.readUInt16LE(8)},_i.prototype.compressionMethod=function(){return this.data.readUInt16LE(10)},_i.prototype.lastModFileTime=function(){return oe(this.data.readUInt16LE(12),this.data.readUInt16LE(14))},_i.prototype.rawLastModFileTime=function(){return this.data.readUInt32LE(12)},_i.prototype.crc32=function(){return this.data.readUInt32LE(16)},_i.prototype.compressedSize=function(){return this.data.readUInt32LE(20)},_i.prototype.uncompressedSize=function(){return this.data.readUInt32LE(24)},_i.prototype.fileNameLength=function(){return this.data.readUInt16LE(28)},_i.prototype.extraFieldLength=function(){return this.data.readUInt16LE(30)},_i.prototype.fileCommentLength=function(){return this.data.readUInt16LE(32)},_i.prototype.diskNumberStart=function(){return this.data.readUInt16LE(34)},_i.prototype.internalAttributes=function(){return this.data.readUInt16LE(36)},_i.prototype.externalAttributes=function(){return this.data.readUInt32LE(38)},_i.prototype.headerRelativeOffset=function(){return this.data.readUInt32LE(42)},_i.prototype.produceFilename=function(){return se(this.data,this.useUTF8(),46,this.fileNameLength()).replace(/\\/g,"/")},_i.prototype.fileName=function(){return this._filename},_i.prototype.rawFileName=function(){return this.data.slice(46,46+this.fileNameLength())},_i.prototype.extraField=function(){var t=44+this.fileNameLength();return this.data.slice(t,t+this.extraFieldLength())},_i.prototype.fileComment=function(){var t=46+this.fileNameLength()+this.extraFieldLength();return se(this.data,this.useUTF8(),t,this.fileCommentLength())},_i.prototype.rawFileComment=function(){var t=46+this.fileNameLength()+this.extraFieldLength();return this.data.slice(t,t+this.fileCommentLength())},_i.prototype.totalSize=function(){return 46+this.fileNameLength()+this.extraFieldLength()+this.fileCommentLength()},_i.prototype.isDirectory=function(){var t=this.fileName();return!!(16&this.externalAttributes())||"/"===t.charAt(t.length-1)},_i.prototype.isFile=function(){return!this.isDirectory()},_i.prototype.useUTF8=function(){return 2048==(2048&this.flag())},_i.prototype.isEncrypted=function(){return 1==(1&this.flag())},_i.prototype.getFileData=function(){var t=this.headerRelativeOffset(),e=new pi(this.zipData.slice(t));return new li(e,this,this.zipData.slice(t+e.totalSize()))},_i.prototype.getData=function(){return this.getFileData().decompress()},_i.prototype.getRawData=function(){return this.getFileData().getRawData()},_i.prototype.getStats=function(){return new Ne(Fe.FILE,this.uncompressedSize(),365,new Date,this.lastModFileTime())};var mi=function(t){if(this.data=t,101010256!==this.data.readUInt32LE(0))throw new ke(we.EINVAL,"Invalid Zip file: End of central directory record has invalid signature: "+this.data.readUInt32LE(0))};mi.prototype.diskNumber=function(){return this.data.readUInt16LE(4)},mi.prototype.cdDiskNumber=function(){return this.data.readUInt16LE(6)},mi.prototype.cdDiskEntryCount=function(){return this.data.readUInt16LE(8)},mi.prototype.cdTotalEntryCount=function(){return this.data.readUInt16LE(10)},mi.prototype.cdSize=function(){return this.data.readUInt32LE(12)},mi.prototype.cdOffset=function(){return this.data.readUInt32LE(16)},mi.prototype.cdZipCommentLength=function(){return this.data.readUInt16LE(20)},mi.prototype.cdZipComment=function(){return se(this.data,!0,22,this.cdZipCommentLength())},mi.prototype.rawCdZipComment=function(){return this.data.slice(22,22+this.cdZipCommentLength())};var wi=function(t,e,n,r){this.index=t,this.directoryEntries=e,this.eocd=n,this.data=r},vi=function(t){function e(e,n){void 0===n&&(n=""),t.call(this),this.name=n,this._index=new ri,this._directoryEntries=[],this._eocd=null,this._index=e.index,this._directoryEntries=e.directoryEntries,this._eocd=e.eocd,this.data=e.data}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.Create=function(t,n){try{e._computeIndex(t.zipData,function(r,i){if(i){var o=new e(i,t.name);n(null,o)}else n(r)})}catch(t){n(t)}},e.isAvailable=function(){return!0},e.RegisterDecompressionMethod=function(t,e){fi[t]=e},e._getEOCD=function(t){for(var e=Math.min(65557,t.length-1),n=22;n-1},Ii.prototype.getRockRidgeOffset=function(){return this._rockRidgeOffset},Ii.prototype.rootCheckForRockRidge=function(t){var e=this.getDirectory(t);this._rockRidgeOffset=e.getDotEntry(t)._getRockRidgeOffset(t),this._rockRidgeOffset>-1&&(this._fileOrDir=null)},Ii.prototype.length=function(){return this._data[0]},Ii.prototype.extendedAttributeRecordLength=function(){return this._data[1]},Ii.prototype.lba=function(){return 2048*this._data.readUInt32LE(2)},Ii.prototype.dataLength=function(){return this._data.readUInt32LE(10)},Ii.prototype.recordingDate=function(){return fe(this._data,18)},Ii.prototype.fileFlags=function(){return this._data[25]},Ii.prototype.fileUnitSize=function(){return this._data[26]},Ii.prototype.interleaveGapSize=function(){return this._data[27]},Ii.prototype.volumeSequenceNumber=function(){return this._data.readUInt16LE(28)},Ii.prototype.identifier=function(){return this._getString(33,this._data[32])},Ii.prototype.fileName=function(t){if(this.hasRockRidge()){var e=this._rockRidgeFilename(t);if(null!==e)return e}var n=this.identifier();if(this.isDirectory(t))return n;var r=n.indexOf(";");return-1===r?n:"."===n[r-1]?n.slice(0,r-1):n.slice(0,r)},Ii.prototype.isDirectory=function(t){var e=!!(2&this.fileFlags());return!e&&this.hasRockRidge()&&(e=this.getSUEntries(t).filter(function(t){return t instanceof zi}).length>0),e},Ii.prototype.isSymlink=function(t){return this.hasRockRidge()&&this.getSUEntries(t).filter(function(t){return t instanceof Mi}).length>0},Ii.prototype.getSymlinkPath=function(t){for(var e="",n=this.getSUEntries(t),r=this._getGetString(),i=0,o=n;i1&&"/"===e[e.length-1]?e.slice(0,e.length-1):e},Ii.prototype.getFile=function(t){if(this.isDirectory(t))throw new Error("Tried to get a File from a directory.");return null===this._fileOrDir&&(this._fileOrDir=t.slice(this.lba(),this.lba()+this.dataLength())),this._fileOrDir},Ii.prototype.getDirectory=function(t){if(!this.isDirectory(t))throw new Error("Tried to get a Directory from a file.");return null===this._fileOrDir&&(this._fileOrDir=this._constructDirectory(t)),this._fileOrDir},Ii.prototype.getSUEntries=function(t){return this._suEntries||this._constructSUEntries(t),this._suEntries},Ii.prototype._rockRidgeFilename=function(t){var e=this.getSUEntries(t).filter(function(t){return t instanceof Bi});if(0===e.length||6&e[0].flags())return null;for(var n="",r=this._getGetString(),i=0,o=e;i0){var n=e[0];if(n instanceof Li&&n.checkBytesPass())for(var r=1;r0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function i(t){return 3*t.length/4-r(t)}function o(t){var e,n,i,o,s,a=t.length;o=r(t),s=new h(3*a/4-o),n=o>0?a-4:a;var c=0;for(e=0;e>16&255,s[c++]=i>>8&255,s[c++]=255&i;return 2===o?(i=f[t.charCodeAt(e)]<<2|f[t.charCodeAt(e+1)]>>4,s[c++]=255&i):1===o&&(i=f[t.charCodeAt(e)]<<10|f[t.charCodeAt(e+1)]<<4|f[t.charCodeAt(e+2)]>>2,s[c++]=i>>8&255,s[c++]=255&i),s}function s(t){return u[t>>18&63]+u[t>>12&63]+u[t>>6&63]+u[63&t]}function a(t,e,n){for(var r,i=[],o=e;oc?c:s+16383));return 1===r?(e=t[n-1],i+=u[e>>2],i+=u[e<<4&63],i+="=="):2===r&&(e=(t[n-2]<<8)+t[n-1],i+=u[e>>10],i+=u[e>>4&63],i+=u[e<<2&63],i+="="),o.push(i),o.join("")}e.byteLength=i,e.toByteArray=o,e.fromByteArray=c;for(var u=[],f=[],h="undefined"!=typeof Uint8Array?Uint8Array:Array,p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",l=0,d=p.length;l>1,f=-7,h=n?i-1:0,p=n?-1:1,l=t[e+h];for(h+=p,o=l&(1<<-f)-1,l>>=-f,f+=a;f>0;o=256*o+t[e+h],h+=p,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=r;f>0;s=256*s+t[e+h],h+=p,f-=8);if(0===o)o=1-u;else{if(o===c)return s?NaN:1/0*(l?-1:1);s+=Math.pow(2,r),o-=u}return(l?-1:1)*s*Math.pow(2,o-r)},e.write=function(t,e,n,r,i,o){var s,a,c,u=8*o-i-1,f=(1<>1,p=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,l=r?0:o-1,d=r?1:-1,y=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=f):(s=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-s))<1&&(s--,c*=2),e+=s+h>=1?p/c:p*Math.pow(2,1-h),e*c>=2&&(s++,c/=2),s+h>=f?(a=0,s=f):s+h>=1?(a=(e*c-1)*Math.pow(2,i),s+=h):(a=e*Math.pow(2,h-1)*Math.pow(2,i),s=0));i>=8;t[n+l]=255&a,l+=d,a/=256,i-=8);for(s=s<0;t[n+l]=255&s,l+=d,s/=256,u-=8);t[n+l-d]|=128*y}},function(t,e,n){"use strict";(function(e){var r=this&&this.__extends||function(t,e){function n(){this.constructor=t}for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)},i=n(6),o=null,s=function(){function t(t,e){this.fun=t,this.array=e}return t.prototype.run=function(){this.fun.apply(null,this.array)},t}(),a=function(){function t(){this._queue=[],this._draining=!1,this._currentQueue=null,this._queueIndex=-1}return t.prototype.push=function(t){var e=this;1!==this._queue.push(t)||this._draining||setTimeout(function(){return e._drainQueue()},0)},t.prototype._cleanUpNextTick=function(){this._draining=!1,this._currentQueue&&this._currentQueue.length?this._queue=this._currentQueue.concat(this._queue):this._queueIndex=-1,this._queue.length&&this._drainQueue()},t.prototype._drainQueue=function(){var t=this;if(!this._draining){var e=setTimeout(function(){return t._cleanUpNextTick()});this._draining=!0;for(var n=this._queue.length;n;){for(this._currentQueue=this._queue,this._queue=[];++this._queueIndex0&&(this._waitingForWrites=this.push(this._bufferedWrites.shift()),this._waitingForWrites););},n}(i.Duplex);t.exports=o}).call(e,n(9))},function(t,e,n){function r(){i.call(this)}t.exports=r;var i=n(6).EventEmitter;n(1)(r,i),r.Readable=n(10),r.Writable=n(30),r.Duplex=n(31),r.Transform=n(32),r.PassThrough=n(33),r.Stream=r,r.prototype.pipe=function(t,e){function n(e){t.writable&&!1===t.write(e)&&u.pause&&u.pause()}function r(){u.readable&&u.resume&&u.resume()}function o(){f||(f=!0,t.end())}function s(){f||(f=!0,"function"==typeof t.destroy&&t.destroy())}function a(t){if(c(),0===i.listenerCount(this,"error"))throw t}function c(){u.removeListener("data",n),t.removeListener("drain",r),u.removeListener("end",o),u.removeListener("close",s),u.removeListener("error",a),t.removeListener("error",a),u.removeListener("end",c),u.removeListener("close",c),t.removeListener("close",c)}var u=this;u.on("data",n),t.on("drain",r),t._isStdio||e&&!1===e.end||(u.on("end",o),u.on("close",s));var f=!1;return u.on("error",a),t.on("error",a),u.on("end",c),u.on("close",c),t.on("close",c),t.emit("pipe",u),t}},function(t,e){var n={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},function(t,e){},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e,n){t.copy(e,n)}var o=n(11).Buffer;t.exports=function(){function t(){r(this,t),this.head=null,this.tail=null,this.length=0}return t.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},t.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},t.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},t.prototype.clear=function(){this.head=this.tail=null,this.length=0},t.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,n=""+e.data;e=e.next;)n+=t+e.data;return n},t.prototype.concat=function(t){if(0===this.length)return o.alloc(0);if(1===this.length)return this.head.data;for(var e=o.allocUnsafe(t>>>0),n=this.head,r=0;n;)i(n.data,e,r),r+=n.data.length,n=n.next;return e},t}()},function(t,e,n){(function(e){function n(t,e){function n(){if(!i){if(r("throwDeprecation"))throw new Error(e);r("traceDeprecation")?console.trace(e):console.warn(e),i=!0}return t.apply(this,arguments)}if(r("noDeprecation"))return t;var i=!1;return n}function r(t){try{if(!e.localStorage)return!1}catch(t){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}t.exports=n}).call(e,n(5))},function(t,e,n){"use strict";function r(t){if(!(this instanceof r))return new r(t);i.call(this,t)}t.exports=r;var i=n(18),o=n(3);o.inherits=n(1),o.inherits(r,i),r.prototype._transform=function(t,e,n){n(null,t)}},function(t,e,n){t.exports=n(12)},function(t,e,n){t.exports=n(0)},function(t,e,n){t.exports=n(10).Transform},function(t,e,n){t.exports=n(10).PassThrough},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t}},function(t,e,n){"use strict";function r(t){if(!(this instanceof r))return new r(t);this.options=a.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new h,this.strm.avail_out=0;var n=s.inflateInit2(this.strm,e.windowBits);if(n!==u.Z_OK)throw new Error(f[n]);this.header=new p,s.inflateGetHeader(this.strm,this.header)}function i(t,e){var n=new r(e);if(n.push(t,!0),n.err)throw n.msg||f[n.err];return n.result}function o(t,e){return e=e||{},e.raw=!0,i(t,e)}var s=n(36),a=n(8),c=n(41),u=n(42),f=n(43),h=n(44),p=n(45),l=Object.prototype.toString;r.prototype.push=function(t,e){var n,r,i,o,f,h,p=this.strm,d=this.options.chunkSize,y=this.options.dictionary,g=!1;if(this.ended)return!1;r=e===~~e?e:!0===e?u.Z_FINISH:u.Z_NO_FLUSH,"string"==typeof t?p.input=c.binstring2buf(t):"[object ArrayBuffer]"===l.call(t)?p.input=new Uint8Array(t):p.input=t,p.next_in=0,p.avail_in=p.input.length;do{if(0===p.avail_out&&(p.output=new a.Buf8(d),p.next_out=0,p.avail_out=d),n=s.inflate(p,u.Z_NO_FLUSH),n===u.Z_NEED_DICT&&y&&(h="string"==typeof y?c.string2buf(y):"[object ArrayBuffer]"===l.call(y)?new Uint8Array(y):y,n=s.inflateSetDictionary(this.strm,h)),n===u.Z_BUF_ERROR&&!0===g&&(n=u.Z_OK,g=!1),n!==u.Z_STREAM_END&&n!==u.Z_OK)return this.onEnd(n),this.ended=!0,!1;p.next_out&&(0!==p.avail_out&&n!==u.Z_STREAM_END&&(0!==p.avail_in||r!==u.Z_FINISH&&r!==u.Z_SYNC_FLUSH)||("string"===this.options.to?(i=c.utf8border(p.output,p.next_out),o=p.next_out-i,f=c.buf2string(p.output,i),p.next_out=o,p.avail_out=d-o,o&&a.arraySet(p.output,p.output,i,o,0),this.onData(f)):this.onData(a.shrinkBuf(p.output,p.next_out)))),0===p.avail_in&&0===p.avail_out&&(g=!0)}while((p.avail_in>0||0===p.avail_out)&&n!==u.Z_STREAM_END);return n===u.Z_STREAM_END&&(r=u.Z_FINISH),r===u.Z_FINISH?(n=s.inflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===u.Z_OK):r!==u.Z_SYNC_FLUSH||(this.onEnd(u.Z_OK),p.avail_out=0,!0)},r.prototype.onData=function(t){this.chunks.push(t)},r.prototype.onEnd=function(t){t===u.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=a.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},e.Inflate=r,e.inflate=i,e.inflateRaw=o,e.ungzip=i},function(t,e,n){"use strict";function r(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function i(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new m.Buf16(320),this.work=new m.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function o(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=U,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new m.Buf32(yt),e.distcode=e.distdyn=new m.Buf32(gt),e.sane=1,e.back=-1,R):x}function s(t){var e;return t&&t.state?(e=t.state,e.wsize=0,e.whave=0,e.wnext=0,o(t)):x}function a(t,e){var n,r;return t&&t.state?(r=t.state,e<0?(n=0,e=-e):(n=1+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?x:(null!==r.window&&r.wbits!==e&&(r.window=null),r.wrap=n,r.wbits=e,s(t))):x}function c(t,e){var n,r;return t?(r=new i,t.state=r,r.window=null,n=a(t,e),n!==R&&(t.state=null),n):x}function u(t){return c(t,_t)}function f(t){if(mt){var e;for(g=new m.Buf32(512),_=new m.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(S(k,t.lens,0,288,g,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;S(I,t.lens,0,32,_,0,t.work,{bits:5}),mt=!1}t.lencode=g,t.lenbits=9,t.distcode=_,t.distbits=5}function h(t,e,n,r){var i,o=t.state;return null===o.window&&(o.wsize=1<=o.wsize?(m.arraySet(o.window,e,n-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(i=o.wsize-o.wnext,i>r&&(i=r),m.arraySet(o.window,e,n-r,i,o.wnext),r-=i,r?(m.arraySet(o.window,e,n-r,r,0),o.wnext=r,o.whave=o.wsize):(o.wnext+=i,o.wnext===o.wsize&&(o.wnext=0),o.whave>>8&255,n.check=v(n.check,Ft,2,0),p=0,l=0,n.mode=M;break}if(n.flags=0,n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&p)<<8)+(p>>8))%31){t.msg="incorrect header check",n.mode=pt;break}if((15&p)!==C){t.msg="unknown compression method",n.mode=pt;break}if(p>>>=4,l-=4,St=8+(15&p),0===n.wbits)n.wbits=St;else if(St>n.wbits){t.msg="invalid window size",n.mode=pt;break}n.dmax=1<>8&1),512&n.flags&&(Ft[0]=255&p,Ft[1]=p>>>8&255,n.check=v(n.check,Ft,2,0)),p=0,l=0,n.mode=j;case j:for(;l<32;){if(0===c)break t;c--,p+=i[s++]<>>8&255,Ft[2]=p>>>16&255,Ft[3]=p>>>24&255,n.check=v(n.check,Ft,4,0)),p=0,l=0,n.mode=B;case B:for(;l<16;){if(0===c)break t;c--,p+=i[s++]<>8),512&n.flags&&(Ft[0]=255&p,Ft[1]=p>>>8&255,n.check=v(n.check,Ft,2,0)),p=0,l=0,n.mode=z;case z:if(1024&n.flags){for(;l<16;){if(0===c)break t;c--,p+=i[s++]<>>8&255,n.check=v(n.check,Ft,2,0)),p=0,l=0}else n.head&&(n.head.extra=null);n.mode=q;case q:if(1024&n.flags&&(g=n.length,g>c&&(g=c),g&&(n.head&&(St=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),m.arraySet(n.head.extra,i,s,g,St)),512&n.flags&&(n.check=v(n.check,i,g,s)),c-=g,s+=g,n.length-=g),n.length))break t;n.length=0,n.mode=V;case V:if(2048&n.flags){if(0===c)break t;g=0;do{St=i[s+g++],n.head&&St&&n.length<65536&&(n.head.name+=String.fromCharCode(St))}while(St&&g>9&1,n.head.done=!0),t.adler=n.check=0,n.mode=X;break;case Z:for(;l<32;){if(0===c)break t;c--,p+=i[s++]<>>=7&l,l-=7&l,n.mode=ut;break}for(;l<3;){if(0===c)break t;c--,p+=i[s++]<>>=1,l-=1,3&p){case 0:n.mode=K;break;case 1:if(f(n),n.mode=nt,e===N){p>>>=2,l-=2;break t}break;case 2:n.mode=$;break;case 3:t.msg="invalid block type",n.mode=pt}p>>>=2,l-=2;break;case K:for(p>>>=7&l,l-=7&l;l<32;){if(0===c)break t;c--,p+=i[s++]<>>16^65535)){t.msg="invalid stored block lengths",n.mode=pt;break}if(n.length=65535&p,p=0,l=0,n.mode=G,e===N)break t;case G:n.mode=Q;case Q:if(g=n.length){if(g>c&&(g=c),g>u&&(g=u),0===g)break t;m.arraySet(o,i,s,g,a),c-=g,s+=g,u-=g,a+=g,n.length-=g;break}n.mode=X;break;case $:for(;l<14;){if(0===c)break t;c--,p+=i[s++]<>>=5,l-=5,n.ndist=1+(31&p),p>>>=5,l-=5,n.ncode=4+(15&p),p>>>=4,l-=4,n.nlen>286||n.ndist>30){t.msg="too many length or distance symbols",n.mode=pt;break}n.have=0,n.mode=tt;case tt:for(;n.have>>=3,l-=3}for(;n.have<19;)n.lens[Nt[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,kt={bits:n.lenbits},Et=S(E,n.lens,0,19,n.lencode,0,n.work,kt),n.lenbits=kt.bits,Et){t.msg="invalid code lengths set",n.mode=pt;break}n.have=0,n.mode=et;case et:for(;n.have>>24,_t=Ot>>>16&255,mt=65535&Ot,!(gt<=l);){if(0===c)break t;c--,p+=i[s++]<>>=gt,l-=gt,n.lens[n.have++]=mt;else{if(16===mt){for(It=gt+2;l>>=gt,l-=gt,0===n.have){t.msg="invalid bit length repeat",n.mode=pt;break}St=n.lens[n.have-1],g=3+(3&p),p>>>=2,l-=2}else if(17===mt){for(It=gt+3;l>>=gt,l-=gt,St=0,g=3+(7&p),p>>>=3,l-=3}else{for(It=gt+7;l>>=gt,l-=gt,St=0,g=11+(127&p),p>>>=7,l-=7}if(n.have+g>n.nlen+n.ndist){t.msg="invalid bit length repeat",n.mode=pt;break}for(;g--;)n.lens[n.have++]=St}}if(n.mode===pt)break;if(0===n.lens[256]){t.msg="invalid code -- missing end-of-block",n.mode=pt;break}if(n.lenbits=9,kt={bits:n.lenbits},Et=S(k,n.lens,0,n.nlen,n.lencode,0,n.work,kt),n.lenbits=kt.bits,Et){t.msg="invalid literal/lengths set",n.mode=pt;break}if(n.distbits=6,n.distcode=n.distdyn,kt={bits:n.distbits},Et=S(I,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,kt),n.distbits=kt.bits,Et){t.msg="invalid distances set",n.mode=pt;break}if(n.mode=nt,e===N)break t;case nt:n.mode=rt;case rt:if(c>=6&&u>=258){t.next_out=a,t.avail_out=u,t.next_in=s,t.avail_in=c,n.hold=p,n.bits=l,b(t,y),a=t.next_out,o=t.output,u=t.avail_out,s=t.next_in,i=t.input,c=t.avail_in,p=n.hold,l=n.bits,n.mode===X&&(n.back=-1);break}for(n.back=0;Ot=n.lencode[p&(1<>>24,_t=Ot>>>16&255,mt=65535&Ot,!(gt<=l);){if(0===c)break t;c--,p+=i[s++]<>wt)],gt=Ot>>>24,_t=Ot>>>16&255,mt=65535&Ot,!(wt+gt<=l);){if(0===c)break t;c--,p+=i[s++]<>>=wt,l-=wt,n.back+=wt}if(p>>>=gt,l-=gt,n.back+=gt,n.length=mt,0===_t){n.mode=ct;break}if(32&_t){n.back=-1,n.mode=X;break}if(64&_t){t.msg="invalid literal/length code",n.mode=pt;break}n.extra=15&_t,n.mode=it;case it:if(n.extra){for(It=n.extra;l>>=n.extra,l-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=ot;case ot:for(;Ot=n.distcode[p&(1<>>24,_t=Ot>>>16&255,mt=65535&Ot,!(gt<=l);){if(0===c)break t;c--,p+=i[s++]<>wt)],gt=Ot>>>24,_t=Ot>>>16&255,mt=65535&Ot,!(wt+gt<=l);){if(0===c)break t;c--,p+=i[s++]<>>=wt,l-=wt,n.back+=wt}if(p>>>=gt,l-=gt,n.back+=gt,64&_t){t.msg="invalid distance code",n.mode=pt;break}n.offset=mt,n.extra=15&_t,n.mode=st;case st:if(n.extra){for(It=n.extra;l>>=n.extra,l-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){t.msg="invalid distance too far back",n.mode=pt;break}n.mode=at;case at:if(0===u)break t;if(g=y-u,n.offset>g){if((g=n.offset-g)>n.whave&&n.sane){t.msg="invalid distance too far back",n.mode=pt;break}g>n.wnext?(g-=n.wnext,_=n.wsize-g):_=n.wnext-g,g>n.length&&(g=n.length),yt=n.window}else yt=o,_=a-n.offset,g=n.length;g>u&&(g=u),u-=g,n.length-=g;do{o[a++]=yt[_++]}while(--g);0===n.length&&(n.mode=rt);break;case ct:if(0===u)break t;o[a++]=n.length,u--,n.mode=rt;break;case ut:if(n.wrap){for(;l<32;){if(0===c)break t;c--,p|=i[s++]<>>16&65535|0,s=0;0!==n;){s=n>2e3?2e3:n,n-=s;do{i=i+e[r++]|0,o=o+i|0}while(--s);i%=65521,o%=65521}return i|o<<16|0}t.exports=r},function(t,e,n){"use strict";function r(t,e,n,r){var o=i,s=r+n;t^=-1;for(var a=r;a>>8^o[255&(t^e[a])];return-1^t}var i=function(){for(var t,e=[],n=0;n<256;n++){t=n;for(var r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;e[n]=t}return e}();t.exports=r},function(t,e,n){"use strict";t.exports=function(t,e){var n,r,i,o,s,a,c,u,f,h,p,l,d,y,g,_,m,w,v,b,S,E,k,I,O;n=t.state,r=t.next_in,I=t.input,i=r+(t.avail_in-5),o=t.next_out,O=t.output,s=o-(e-t.avail_out),a=o+(t.avail_out-257),c=n.dmax,u=n.wsize,f=n.whave,h=n.wnext,p=n.window,l=n.hold,d=n.bits,y=n.lencode,g=n.distcode,_=(1<>>24,l>>>=v,d-=v,0===(v=w>>>16&255))O[o++]=65535&w;else{if(!(16&v)){if(0==(64&v)){w=y[(65535&w)+(l&(1<>>=v,d-=v),d<15&&(l+=I[r++]<>>24,l>>>=v,d-=v,!(16&(v=w>>>16&255))){if(0==(64&v)){w=g[(65535&w)+(l&(1<c){t.msg="invalid distance too far back",n.mode=30;break t}if(l>>>=v,d-=v,v=o-s,S>v){if((v=S-v)>f&&n.sane){t.msg="invalid distance too far back",n.mode=30;break t}if(E=0,k=p,0===h){if(E+=u-v,v2;)O[o++]=k[E++],O[o++]=k[E++],O[o++]=k[E++],b-=3;b&&(O[o++]=k[E++],b>1&&(O[o++]=k[E++]))}else{E=o-S;do{O[o++]=O[E++],O[o++]=O[E++],O[o++]=O[E++],b-=3}while(b>2);b&&(O[o++]=O[E++],b>1&&(O[o++]=O[E++]))}break}}break}}while(r>3,r-=b,d-=b<<3,l&=(1<=1&&0===P[O];O--);if(F>O&&(F=O),0===O)return u[f++]=20971520,u[f++]=20971520,p.bits=1,0;for(I=1;I0&&(0===t||1!==O))return-1;for(C[1]=0,E=1;E<15;E++)C[E+1]=C[E]+P[E];for(k=0;k852||2===t&&L>592)return 1;for(;;){w=E-R,h[k]m?(v=U[M+h[k]],b=D[A+h[k]]):(v=96,b=0),l=1<>R)+d]=w<<24|v<<16|b|0}while(0!==d);for(l=1<>=1;if(0!==l?(x&=l-1,x+=l):x=0,k++,0==--P[E]){if(E===O)break;E=e[n+h[k]]}if(E>F&&(x&g)!==y){for(0===R&&(R=F),_+=I,N=E-R,T=1<852||2===t&&L>592)return 1;y=x&g,u[y]=F<<24|N<<16|_-f|0}}return 0!==x&&(u[_+x]=E-R<<24|64<<16|0),p.bits=F,0}},function(t,e,n){"use strict";function r(t,e){if(e<65537&&(t.subarray&&s||!t.subarray&&o))return String.fromCharCode.apply(null,i.shrinkBuf(t,e));for(var n="",r=0;r=252?6:c>=248?5:c>=240?4:c>=224?3:c>=192?2:1;a[254]=a[254]=1,e.string2buf=function(t){var e,n,r,o,s,a=t.length,c=0;for(o=0;o>>6,e[s++]=128|63&n):n<65536?(e[s++]=224|n>>>12,e[s++]=128|n>>>6&63,e[s++]=128|63&n):(e[s++]=240|n>>>18,e[s++]=128|n>>>12&63,e[s++]=128|n>>>6&63,e[s++]=128|63&n);return e},e.buf2binstring=function(t){return r(t,t.length)},e.binstring2buf=function(t){for(var e=new i.Buf8(t.length),n=0,r=e.length;n4)u[i++]=65533,n+=s-1;else{for(o&=2===s?31:3===s?15:7;s>1&&n1?u[i++]=65533:o<65536?u[i++]=o:(o-=65536,u[i++]=55296|o>>10&1023,u[i++]=56320|1023&o)}return r(u,i)},e.utf8border=function(t,e){var n;for(e=e||t.length,e>t.length&&(e=t.length),n=e-1;n>=0&&128==(192&t[n]);)n--;return n<0?e:0===n?e:n+a[t[n]]>e?n:e}},function(t,e,n){"use strict";t.exports={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,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,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,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},function(t,e,n){"use strict";t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},function(t,e,n){"use strict";function r(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}t.exports=r},function(t,e,n){"use strict";function r(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}t.exports=r}])});
+//# sourceMappingURL=browserfs.min.js.map
\ No newline at end of file
diff --git a/public/wasm/pdfcpu-wrapper-browser.js b/public/wasm/pdfcpu-wrapper-browser.js
new file mode 100644
index 000000000..b0cbad7cf
--- /dev/null
+++ b/public/wasm/pdfcpu-wrapper-browser.js
@@ -0,0 +1,103 @@
+// TODO: Uses the BrowserFS import, needs to be changed for serverside
+
+let wasmLocation = "/wasm/";
+
+let fs;
+let Buffer;
+
+configureFs();
+loadWasm();
+
+function configureFs() {
+ BrowserFS.configure(
+ {
+ fs: "InMemory",
+ },
+ function (e) {
+ if (e) {
+ // An error happened!
+ throw e;
+ }
+ fs = BrowserFS.BFSRequire("fs");
+ Buffer = BrowserFS.BFSRequire("buffer").Buffer;
+
+ window.fs = fs;
+ window.Buffer = Buffer;
+ }
+ );
+}
+
+function loadWasm() {
+ const script = document.createElement("script");
+ script.src = wasmLocation + "/wasm_exec.js";
+ script.async = true;
+ document.body.appendChild(script);
+}
+
+const runWasm = async (param) => {
+ if (window.cachedWasmResponse === undefined) {
+ const response = await fetch(wasmLocation + "/pdfcpu.wasm");
+ const buffer = await response.arrayBuffer();
+ window.cachedWasmResponse = buffer;
+ window.go = new Go();
+ }
+ const { instance } = await WebAssembly.instantiate(
+ window.cachedWasmResponse,
+ window.go.importObject
+ );
+ window.go.argv = param;
+ await window.go.run(instance);
+ return window.go.exitCode;
+};
+
+async function loadFileAsync(data) {
+ console.log(`Writing file to MemoryFS`);
+ await fs.writeFile(`/input.pdf`, data);
+ console.log(`Write done. Validating...`);
+ let exitcode = await runWasm([
+ "pdfcpu.wasm",
+ "validate",
+ "-c",
+ "disable",
+ `/input.pdf`,
+ ]);
+
+ if (exitcode !== 0)
+ throw new Error("There was an error validating your PDFs");
+
+ console.log(`File is Valid`);
+}
+
+export async function impose(snapshot, nup, format) {
+
+};
+
+export async function oneToOne(wasmArray, snapshot) {
+ await loadFileAsync(Buffer.from(snapshot));
+
+ console.log("Nuping File");
+ let exitcode = await runWasm(wasmArray);
+
+ if (exitcode !== 0) {
+ console.error("There was an error nuping your PDFs");
+ return;
+ }
+
+ await fs.unlink("input.pdf");
+ const contents = fs.readFileSync("output.pdf");
+ fs.unlink("output.pdf");
+ console.log("Your File ist Ready!");
+ return new Uint8Array(contents);
+}
+
+export async function manyToOne() {
+ //TODO: Do this of neccesary for some operations
+}
+
+export async function oneToMany() {
+ //TODO: Do this of neccesary for some operations
+}
+
+export async function manyToMany() {
+ //TODO: Do this of neccesary for some operations
+}
\ No newline at end of file
diff --git a/public/wasm/pdfcpu-wrapper-node.js b/public/wasm/pdfcpu-wrapper-node.js
new file mode 100644
index 000000000..9e64c9e68
--- /dev/null
+++ b/public/wasm/pdfcpu-wrapper-node.js
@@ -0,0 +1,146 @@
+// TODO: Uses the BrowserFS import, needs to be changed for serverside
+
+import { WasmFs } from '@wasmer/wasmfs';
+import path from "path";
+
+let webWasmLocation = "/wasm/";
+let nodeWasmLocation = "./public/wasm/";
+
+let fs;
+const wasmfs = new WasmFs();
+
+(async () => {
+ await loadWasm();
+ await configureFs();
+})();
+
+async function configureFs() {
+ // Can't use BrowserFS: https://github.com/jvilk/BrowserFS/issues/271
+ fs = wasmfs.fs;
+ global.fs = fs;
+
+ console.log("InMemoryFs configured");
+}
+
+async function loadWasm() {
+ global.crypto = (await import("crypto")).webcrypto; // wasm dependecy
+ await import("./wasm_exec.js");
+}
+
+const runWasm = async (param) => {
+ if (global.cachedWasmResponse === undefined) {
+ const buffer = (await import("fs")).readFileSync(nodeWasmLocation + "/pdfcpu.wasm");
+ global.cachedWasmResponse = buffer;
+ global.go = new Go();
+ }
+ const { instance } = await WebAssembly.instantiate(
+ global.cachedWasmResponse,
+ global.go.importObject
+ );
+ global.go.argv = param;
+ await global.go.run(instance);
+ return global.go.exitCode;
+};
+
+async function loadFileAsync(data) {
+ console.log(`Writing file to Disk`);
+ fs.writeFileSync(`input.pdf`, data);
+ console.log(`Write done. Validating...`);
+ let exitcode = await runWasm([
+ "pdfcpu.wasm",
+ "validate",
+ "-c",
+ "disable",
+ `input.pdf`,
+ ]);
+ if (exitcode !== 0)
+ throw new Error("There was an error validating your PDFs");
+
+ // // Get logs of command
+ // wasmfs.getStdOut().then(response => {
+ // console.log(response);
+ // });
+
+ console.log(`File is Valid`);
+}
+
+export async function oneToOne(wasmArray, snapshot) {
+ await loadFileAsync(Buffer.from(snapshot));
+
+ console.log("Nuping File");
+
+ let exitcode = await runWasm(wasmArray);
+ if (exitcode !== 0) {
+ console.error("There was an error nuping your PDFs");
+ return;
+ }
+ console.log("Nuping Done");
+
+ await checkExistsWithTimeout("/output.pdf", 1000);
+ console.log("Write started...");
+
+
+ // TODO: Make this more elegant, this waits for the write to finish.
+ // Maybe replace wasmfs with https://github.com/streamich/memfs
+ let fileSize;
+ while (true) {
+ fileSize = fs.statSync("/output.pdf").size;
+ await new Promise((resolve, reject) => {
+ setTimeout(() => {
+ resolve();
+ }, 50);
+ });
+ if(fileSize > 0 && fileSize == fs.statSync("/output.pdf").size) // Wait for file Size not changing anymore.
+ break;
+ }
+
+ console.log("Could be done?");
+
+ fs.unlinkSync("input.pdf");
+
+ const data = fs.readFileSync("/output.pdf");
+ if(data.length == 0) {
+ throw Error("File Size 0 that should not happen. The write probably didn't finish in time.");
+ }
+ fs.unlinkSync("output.pdf");
+ console.log("Your File ist Ready!");
+ return new Uint8Array(data);
+}
+
+export async function manyToOne() {
+ //TODO: Do this if necessary for some pdfcpu operations
+}
+
+export async function oneToMany() {
+ //TODO: Do this if necessary for some pdfcpu operations
+}
+
+export async function manyToMany() {
+ //TODO: Do this if necessary for some pdfcpu operations
+}
+
+// THX: https://stackoverflow.com/questions/26165725/nodejs-check-file-exists-if-not-wait-till-it-exist
+function checkExistsWithTimeout(filePath, timeout) {
+ return new Promise(function (resolve, reject) {
+
+ var timer = setTimeout(function () {
+ watcher.close();
+ reject(new Error('File did not exists and was not created during the timeout.'));
+ }, timeout);
+
+ fs.access(filePath, fs.constants.R_OK, function (err) {
+ if (!err) {
+ clearTimeout(timer);
+ watcher.close();
+ resolve();
+ }
+ });
+
+ var dir = path.dirname(filePath);
+ var watcher = fs.watch(dir, function (eventType, filename) {
+ clearTimeout(timer);
+ watcher.close();
+ resolve();
+ });
+ });
+}
\ No newline at end of file
diff --git a/public/wasm/pdfcpu.wasm b/public/wasm/pdfcpu.wasm
new file mode 100644
index 000000000..fc7855d3f
Binary files /dev/null and b/public/wasm/pdfcpu.wasm differ
diff --git a/public/wasm/wasm_exec.js b/public/wasm/wasm_exec.js
new file mode 100644
index 000000000..0c8a1044c
--- /dev/null
+++ b/public/wasm/wasm_exec.js
@@ -0,0 +1,872 @@
+// Copyright 2018 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+(() => {
+ // Map multiple JavaScript environments to a single common API,
+ // preferring web standards over Node.js API.
+ //
+ // Environments considered:
+ // - Browsers
+ // - Node.js
+ // - Electron
+ // - Parcel
+ // - Webpack
+
+ console.log("imported")
+ if (typeof global !== "undefined") {
+ // global already exists
+ } else if (typeof window !== "undefined") {
+ window.global = window;
+ } else if (typeof self !== "undefined") {
+ self.global = self;
+ } else {
+ throw new Error("cannot export Go (neither global, window nor self is defined)");
+ }
+
+ let logFS = false
+ var handler = {
+ get: function (target, property) {
+ if (property in target && target[property] instanceof Function) {
+ return function () {
+ if (logFS) {
+ console.log(property, 'called', arguments);
+ }
+ // 将callback替换
+ if (arguments[arguments.length - 1] instanceof Function) {
+ var origCB = arguments[arguments.length - 1];
+ var newCB = function () {
+ if (logFS) {
+ console.log('callback for', property, 'get called with args:', arguments);
+ }
+ return Reflect.apply(origCB, arguments.callee, arguments);
+ }
+ arguments[arguments.length - 1] = newCB;
+ }
+ return Reflect.apply(target[property], target, arguments);
+ }
+ } else {
+ return target[property]
+ }
+ }
+ }
+
+ if (!global.require && typeof require !== "undefined") {
+ global.require = require;
+ }
+
+
+ if (!global.fs && global.require) {
+
+ //const fs = require("fs");
+ if (typeof fs === "object" && fs !== null && Object.keys(fs).length !== 0) {
+ global.fs = fs;
+ }
+
+ }
+
+ const enosys = () => {
+ const err = new Error("not implemented");
+ err.code = "ENOSYS";
+ return err;
+ };
+
+ if (!global.fs) {
+ let outputBuf = "";
+ global.fs = {
+ constants: {
+ O_WRONLY: -1,
+ O_RDWR: -1,
+ O_CREAT: -1,
+ O_TRUNC: -1,
+ O_APPEND: -1,
+ O_EXCL: -1
+ }, // unused
+ writeSync(fd, buf) {
+ outputBuf += decoder.decode(buf);
+ const nl = outputBuf.lastIndexOf("\n");
+ if (nl != -1) {
+ console.log(outputBuf.substr(0, nl));
+ outputBuf = outputBuf.substr(nl + 1);
+ }
+ return buf.length;
+ },
+ write(fd, buf, offset, length, position, callback) {
+ if (offset !== 0 || length !== buf.length || position !== null) {
+ callback(enosys());
+ return;
+ }
+ const n = this.writeSync(fd, buf);
+ callback(null, n);
+ },
+ chmod(path, mode, callback) {
+ callback(enosys());
+ },
+ chown(path, uid, gid, callback) {
+ callback(enosys());
+ },
+ close(fd, callback) {
+ callback(enosys());
+ },
+ fchmod(fd, mode, callback) {
+ callback(enosys());
+ },
+ fchown(fd, uid, gid, callback) {
+ callback(enosys());
+ },
+ fstat(fd, callback) {
+ callback(enosys());
+ },
+ fsync(fd, callback) {
+ callback(null);
+ },
+ ftruncate(fd, length, callback) {
+ callback(enosys());
+ },
+ lchown(path, uid, gid, callback) {
+ callback(enosys());
+ },
+ link(path, link, callback) {
+ callback(enosys());
+ },
+ lstat(path, callback) {
+ callback(enosys());
+ },
+ mkdir(path, perm, callback) {
+ callback(enosys());
+ },
+ open(path, flags, mode, callback) {
+ callback(enosys());
+ },
+ read(fd, buffer, offset, length, position, callback) {
+ callback(enosys());
+ },
+ readdir(path, callback) {
+ callback(enosys());
+ },
+ readlink(path, callback) {
+ callback(enosys());
+ },
+ rename(from, to, callback) {
+ callback(enosys());
+ },
+ rmdir(path, callback) {
+ callback(enosys());
+ },
+ stat(path, callback) {
+ callback(enosys());
+ },
+ symlink(path, link, callback) {
+ callback(enosys());
+ },
+ truncate(path, length, callback) {
+ callback(enosys());
+ },
+ unlink(path, callback) {
+ callback(enosys());
+ },
+ utimes(path, atime, mtime, callback) {
+ callback(enosys());
+ },
+ };
+ }
+
+ if (!global.process) {
+ global.process = {
+ getuid() {
+ return -1;
+ },
+ getgid() {
+ return -1;
+ },
+ geteuid() {
+ return -1;
+ },
+ getegid() {
+ return -1;
+ },
+ getgroups() {
+ throw enosys();
+ },
+ pid: -1,
+ ppid: -1,
+ umask() {
+ throw enosys();
+ },
+ cwd() {
+ throw enosys();
+ },
+ chdir() {
+ throw enosys();
+ },
+ }
+ }
+
+ if (!global.crypto && global.require) {
+ const nodeCrypto = require("crypto");
+ global.crypto = {
+ getRandomValues(b) {
+ nodeCrypto.randomFillSync(b);
+ },
+ };
+ }
+ if (!global.crypto) {
+ throw new Error("global.crypto is not available, polyfill required (getRandomValues only)");
+ }
+
+ if (!global.performance) {
+ global.performance = {
+ now() {
+ const [sec, nsec] = process.hrtime();
+ return sec * 1000 + nsec / 1000000;
+ },
+ };
+ }
+
+ if (!global.TextEncoder && global.require) {
+ global.TextEncoder = require("util").TextEncoder;
+ }
+ if (!global.TextEncoder) {
+ throw new Error("global.TextEncoder is not available, polyfill required");
+ }
+
+ if (!global.TextDecoder && global.require) {
+ global.TextDecoder = require("util").TextDecoder;
+ }
+ if (!global.TextDecoder) {
+ throw new Error("global.TextDecoder is not available, polyfill required");
+ }
+
+
+ const isNodeJS = global.process && global.process.title === "node";
+
+ if (!isNodeJS) {
+ // console.log("ini browser fs")
+ // var myfs = global.BrowserFS.BFSRequire('fs');
+ // global.Buffer = global.BrowserFS.BFSRequire('buffer').Buffer;
+ // global.fs = myfs;
+
+ global.fs.constants = {
+ O_RDONLY: 0,
+ O_WRONLY: 1,
+ O_RDWR: 2,
+ O_CREAT: 64,
+ O_CREATE: 64,
+ O_EXCL: 128,
+ O_NOCTTY: 256,
+ O_TRUNC: 512,
+ O_APPEND: 1024,
+ O_DIRECTORY: 65536,
+ O_NOATIME: 262144,
+ O_NOFOLLOW: 131072,
+ O_SYNC: 1052672,
+ O_DIRECT: 16384,
+ O_NONBLOCK: 2048,
+ };
+
+ let outputBuf = "";
+
+ global.fs.writeSyncOriginal = global.fs.writeSync
+ global.fs.writeSync = function (fd, buf) {
+ if (fd === 1 || fd === 2) {
+ outputBuf += decoder.decode(buf);
+ const nl = outputBuf.lastIndexOf("\n");
+ if (nl != -1) {
+ console.log(outputBuf.substr(0, nl));
+ outputBuf = outputBuf.substr(nl + 1);
+ }
+ return buf.length;
+ } else {
+ return global.fs.writeSyncOriginal(...arguments);
+ }
+ };
+
+ global.fs.writeOriginal = global.fs.write
+ global.fs.write = function (fd, buf, offset, length, position, callback) {
+ // (corresponding to STDOUT/STDERR)
+ if (fd === 1 || fd === 2) {
+ if (offset !== 0 || length !== buf.length || position !== null) {
+ throw new Error("not implemented");
+ }
+ const n = this.writeSync(fd, buf);
+ callback(null, n, buf);
+ } else {
+ // buf: read buf first
+ arguments[1] = global.Buffer.from(arguments[1]);
+ return global.fs.writeOriginal(...arguments);
+ }
+ };
+
+
+
+ global.fs.openOriginal = global.fs.open
+ global.fs.open = function (path, flags, mode, callback) {
+ var myflags = 'r';
+ var O = global.fs.constants;
+
+ // Convert numeric flags to string flags
+ // FIXME: maybe wrong...
+ console.log("open dir?", path, 'flag', flags, myflags)
+ if (flags & O.O_WRONLY) { // 'w'
+ myflags = 'w';
+ if (flags & O.O_EXCL) {
+ myflags = 'wx';
+ }
+ } else if (flags & O.O_RDWR) { // 'r+' or 'w+'
+ if (flags & O.O_CREAT && flags & O.O_TRUNC) { // w+
+ if (flags & O.O_EXCL) {
+ myflags = 'wx+';
+ } else {
+ myflags = 'w+';
+ }
+ } else { // r+
+ myflags = 'r+';
+ }
+ } else if (flags & O.O_APPEND) { // 'a'
+ console.log("append error")
+ throw new Error("Not implmented");
+ } else {
+ // 打开文件
+ myflags = 'r+';
+ console.log("open dir?", path, 'flag', flags, myflags)
+ }
+
+
+ return global.fs.openOriginal(path, myflags, mode, callback);
+ };
+
+ global.fs.fstatOriginal = global.fs.fstat;
+ global.fs.fstat = function (fd, callback) {
+ return global.fs.fstatOriginal(fd, function () {
+ var retStat = arguments[1];
+ delete retStat['fileData'];
+ retStat.atimeMs = retStat.atime.getTime();
+ retStat.mtimeMs = retStat.mtime.getTime();
+ retStat.ctimeMs = retStat.ctime.getTime();
+ retStat.birthtimeMs = retStat.birthtime.getTime();
+ return callback(arguments[0], retStat);
+
+ });
+ };
+
+
+
+ global.fs.closeOriginal = global.fs.close;
+ global.fs.close = function (fd, callback) {
+ return global.fs.closeOriginal(fd, function () {
+ if (typeof arguments[0] === 'undefined') arguments[0] = null;
+ return callback(...arguments);
+ });
+ }
+
+ // global.fs.renameOriginal = global.fs.rename
+ // global.fs.rename = function (from, to, callback) {
+ // console.log("rename a0", arguments[0])
+ // global.fs.renameOriginal(from, to);
+ // callback(arguments[0])
+ // }
+
+ // global.fs.renameSyncOriginal = global.fs.renameSync
+ // global.fs.renameSync = function(fd, options) {
+ // console.log("Sync")
+ // }
+
+
+ global.fs = new Proxy(global.fs, handler);
+ }
+
+ // End of polyfills for common API.
+
+ const encoder = new TextEncoder("utf-8");
+ const decoder = new TextDecoder("utf-8");
+
+ global.Go = class {
+ constructor() {
+ this.argv = ["js"];
+ this.env = {};
+ this.exit = (code) => {
+ this.exitCode = code;
+ if (code !== 0) {
+ console.warn("exit code:", code);
+ }
+ };
+ this._exitPromise = new Promise((resolve) => {
+ this._resolveExitPromise = resolve;
+ });
+ this._pendingEvent = null;
+ this._scheduledTimeouts = new Map();
+ this._nextCallbackTimeoutID = 1;
+
+ const setInt64 = (addr, v) => {
+ this.mem.setUint32(addr + 0, v, true);
+ this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
+ }
+
+ const getInt64 = (addr) => {
+ const low = this.mem.getUint32(addr + 0, true);
+ const high = this.mem.getInt32(addr + 4, true);
+ return low + high * 4294967296;
+ }
+
+ const loadValue = (addr) => {
+ const f = this.mem.getFloat64(addr, true);
+ if (f === 0) {
+ return undefined;
+ }
+ if (!isNaN(f)) {
+ return f;
+ }
+
+ const id = this.mem.getUint32(addr, true);
+ return this._values[id];
+ }
+
+ const storeValue = (addr, v) => {
+ const nanHead = 0x7FF80000;
+
+ if (typeof v === "number" && v !== 0) {
+ if (isNaN(v)) {
+ this.mem.setUint32(addr + 4, nanHead, true);
+ this.mem.setUint32(addr, 0, true);
+ return;
+ }
+ this.mem.setFloat64(addr, v, true);
+ return;
+ }
+
+ if (v === undefined) {
+ this.mem.setFloat64(addr, 0, true);
+ return;
+ }
+
+ let id = this._ids.get(v);
+ if (id === undefined) {
+ id = this._idPool.pop();
+ if (id === undefined) {
+ id = this._values.length;
+ }
+ this._values[id] = v;
+ this._goRefCounts[id] = 0;
+ this._ids.set(v, id);
+ }
+ this._goRefCounts[id]++;
+ let typeFlag = 0;
+ switch (typeof v) {
+ case "object":
+ if (v !== null) {
+ typeFlag = 1;
+ }
+ break;
+ case "string":
+ typeFlag = 2;
+ break;
+ case "symbol":
+ typeFlag = 3;
+ break;
+ case "function":
+ typeFlag = 4;
+ break;
+ }
+ this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
+ this.mem.setUint32(addr, id, true);
+ }
+
+ const loadSlice = (addr) => {
+ const array = getInt64(addr + 0);
+ const len = getInt64(addr + 8);
+ return new Uint8Array(this._inst.exports.mem.buffer, array, len);
+ }
+
+ const loadSliceOfValues = (addr) => {
+ const array = getInt64(addr + 0);
+ const len = getInt64(addr + 8);
+ const a = new Array(len);
+ for (let i = 0; i < len; i++) {
+ a[i] = loadValue(array + i * 8);
+ }
+ return a;
+ }
+
+ const loadString = (addr) => {
+ const saddr = getInt64(addr + 0);
+ const len = getInt64(addr + 8);
+ return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
+ }
+
+ const timeOrigin = Date.now() - performance.now();
+ this.importObject = {
+ go: {
+ // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
+ // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
+ // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
+ // This changes the SP, thus we have to update the SP used by the imported function.
+
+ // func wasmExit(code int32)
+ "runtime.wasmExit": (sp) => {
+ sp >>>= 0;
+ const code = this.mem.getInt32(sp + 8, true);
+ this.exited = true;
+ delete this._inst;
+ delete this._values;
+ delete this._goRefCounts;
+ delete this._ids;
+ delete this._idPool;
+ this.exit(code);
+ },
+
+ // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
+ "runtime.wasmWrite": (sp) => {
+ sp >>>= 0;
+ const fd = getInt64(sp + 8);
+ const p = getInt64(sp + 16);
+ const n = this.mem.getInt32(sp + 24, true);
+ fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
+ },
+
+ // func resetMemoryDataView()
+ "runtime.resetMemoryDataView": (sp) => {
+ sp >>>= 0;
+ this.mem = new DataView(this._inst.exports.mem.buffer);
+ },
+
+ // func nanotime1() int64
+ "runtime.nanotime1": (sp) => {
+ sp >>>= 0;
+ setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
+ },
+
+ // func walltime1() (sec int64, nsec int32)
+ "runtime.walltime1": (sp) => {
+ sp >>>= 0;
+ const msec = (new Date).getTime();
+ setInt64(sp + 8, msec / 1000);
+ this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
+ },
+
+ // func scheduleTimeoutEvent(delay int64) int32
+ "runtime.scheduleTimeoutEvent": (sp) => {
+ sp >>>= 0;
+ const id = this._nextCallbackTimeoutID;
+ this._nextCallbackTimeoutID++;
+ this._scheduledTimeouts.set(id, setTimeout(
+ () => {
+ this._resume();
+ while (this._scheduledTimeouts.has(id)) {
+ // for some reason Go failed to register the timeout event, log and try again
+ // (temporary workaround for https://github.com/golang/go/issues/28975)
+ console.warn("scheduleTimeoutEvent: missed timeout event");
+ this._resume();
+ }
+ },
+ getInt64(sp + 8) + 1, // setTimeout has been seen to fire up to 1 millisecond early
+ ));
+ this.mem.setInt32(sp + 16, id, true);
+ },
+
+ // func clearTimeoutEvent(id int32)
+ "runtime.clearTimeoutEvent": (sp) => {
+ sp >>>= 0;
+ const id = this.mem.getInt32(sp + 8, true);
+ clearTimeout(this._scheduledTimeouts.get(id));
+ this._scheduledTimeouts.delete(id);
+ },
+
+ // func getRandomData(r []byte)
+ "runtime.getRandomData": (sp) => {
+ sp >>>= 0;
+ crypto.getRandomValues(loadSlice(sp + 8));
+ },
+
+ // func finalizeRef(v ref)
+ "syscall/js.finalizeRef": (sp) => {
+ sp >>>= 0;
+ const id = this.mem.getUint32(sp + 8, true);
+ this._goRefCounts[id]--;
+ if (this._goRefCounts[id] === 0) {
+ const v = this._values[id];
+ this._values[id] = null;
+ this._ids.delete(v);
+ this._idPool.push(id);
+ }
+ },
+
+ // func stringVal(value string) ref
+ "syscall/js.stringVal": (sp) => {
+ sp >>>= 0;
+ storeValue(sp + 24, loadString(sp + 8));
+ },
+
+ // func valueGet(v ref, p string) ref
+ "syscall/js.valueGet": (sp) => {
+ sp >>>= 0;
+ const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
+ storeValue(sp + 32, result);
+ },
+
+ // func valueSet(v ref, p string, x ref)
+ "syscall/js.valueSet": (sp) => {
+ sp >>>= 0;
+ Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
+ },
+
+ // func valueDelete(v ref, p string)
+ "syscall/js.valueDelete": (sp) => {
+ sp >>>= 0;
+ Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
+ },
+
+ // func valueIndex(v ref, i int) ref
+ "syscall/js.valueIndex": (sp) => {
+ sp >>>= 0;
+ storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
+ },
+
+ // valueSetIndex(v ref, i int, x ref)
+ "syscall/js.valueSetIndex": (sp) => {
+ sp >>>= 0;
+ Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
+ },
+
+ // func valueCall(v ref, m string, args []ref) (ref, bool)
+ "syscall/js.valueCall": (sp) => {
+ sp >>>= 0;
+ try {
+ const v = loadValue(sp + 8);
+ const m = Reflect.get(v, loadString(sp + 16));
+ const args = loadSliceOfValues(sp + 32);
+ const result = Reflect.apply(m, v, args);
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
+ storeValue(sp + 56, result);
+ this.mem.setUint8(sp + 64, 1);
+ } catch (err) {
+ storeValue(sp + 56, err);
+ this.mem.setUint8(sp + 64, 0);
+ }
+ },
+
+ // func valueInvoke(v ref, args []ref) (ref, bool)
+ "syscall/js.valueInvoke": (sp) => {
+ sp >>>= 0;
+ try {
+ const v = loadValue(sp + 8);
+ const args = loadSliceOfValues(sp + 16);
+ const result = Reflect.apply(v, undefined, args);
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
+ storeValue(sp + 40, result);
+ this.mem.setUint8(sp + 48, 1);
+ } catch (err) {
+ storeValue(sp + 40, err);
+ this.mem.setUint8(sp + 48, 0);
+ }
+ },
+
+ // func valueNew(v ref, args []ref) (ref, bool)
+ "syscall/js.valueNew": (sp) => {
+ sp >>>= 0;
+ try {
+ const v = loadValue(sp + 8);
+ const args = loadSliceOfValues(sp + 16);
+ const result = Reflect.construct(v, args);
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
+ storeValue(sp + 40, result);
+ this.mem.setUint8(sp + 48, 1);
+ } catch (err) {
+ storeValue(sp + 40, err);
+ this.mem.setUint8(sp + 48, 0);
+ }
+ },
+
+ // func valueLength(v ref) int
+ "syscall/js.valueLength": (sp) => {
+ sp >>>= 0;
+ setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
+ },
+
+ // valuePrepareString(v ref) (ref, int)
+ "syscall/js.valuePrepareString": (sp) => {
+ sp >>>= 0;
+ const str = encoder.encode(String(loadValue(sp + 8)));
+ storeValue(sp + 16, str);
+ setInt64(sp + 24, str.length);
+ },
+
+ // valueLoadString(v ref, b []byte)
+ "syscall/js.valueLoadString": (sp) => {
+ sp >>>= 0;
+ const str = loadValue(sp + 8);
+ loadSlice(sp + 16).set(str);
+ },
+
+ // func valueInstanceOf(v ref, t ref) bool
+ "syscall/js.valueInstanceOf": (sp) => {
+ sp >>>= 0;
+ this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
+ },
+
+ // func copyBytesToGo(dst []byte, src ref) (int, bool)
+ "syscall/js.copyBytesToGo": (sp) => {
+ sp >>>= 0;
+ const dst = loadSlice(sp + 8);
+ const src = loadValue(sp + 32);
+ if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
+ this.mem.setUint8(sp + 48, 0);
+ return;
+ }
+ const toCopy = src.subarray(0, dst.length);
+ dst.set(toCopy);
+ setInt64(sp + 40, toCopy.length);
+ this.mem.setUint8(sp + 48, 1);
+ },
+
+ // func copyBytesToJS(dst ref, src []byte) (int, bool)
+ "syscall/js.copyBytesToJS": (sp) => {
+ sp >>>= 0;
+ const dst = loadValue(sp + 8);
+ const src = loadSlice(sp + 16);
+ if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
+ this.mem.setUint8(sp + 48, 0);
+ return;
+ }
+ const toCopy = src.subarray(0, dst.length);
+ dst.set(toCopy);
+ setInt64(sp + 40, toCopy.length);
+ this.mem.setUint8(sp + 48, 1);
+ },
+
+ "debug": (value) => {
+ console.log(value);
+ },
+ }
+ };
+ }
+
+ async run(instance) {
+ if (!(instance instanceof WebAssembly.Instance)) {
+ throw new Error("Go.run: WebAssembly.Instance expected");
+ }
+ this._inst = instance;
+ this.mem = new DataView(this._inst.exports.mem.buffer);
+ this._values = [ // JS values that Go currently has references to, indexed by reference id
+ NaN,
+ 0,
+ null,
+ true,
+ false,
+ global,
+ this,
+ ];
+ this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
+ this._ids = new Map([ // mapping from JS values to reference ids
+ [0, 1],
+ [null, 2],
+ [true, 3],
+ [false, 4],
+ [global, 5],
+ [this, 6],
+ ]);
+ this._idPool = []; // unused ids that have been garbage collected
+ this.exited = false; // whether the Go program has exited
+
+ // Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
+ let offset = 4096;
+
+ const strPtr = (str) => {
+ const ptr = offset;
+ const bytes = encoder.encode(str + "\0");
+ new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
+ offset += bytes.length;
+ if (offset % 8 !== 0) {
+ offset += 8 - (offset % 8);
+ }
+ return ptr;
+ };
+
+ const argc = this.argv.length;
+
+ const argvPtrs = [];
+ this.argv.forEach((arg) => {
+ argvPtrs.push(strPtr(arg));
+ });
+ argvPtrs.push(0);
+
+ const keys = Object.keys(this.env).sort();
+ keys.forEach((key) => {
+ argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
+ });
+ argvPtrs.push(0);
+
+ const argv = offset;
+ argvPtrs.forEach((ptr) => {
+ this.mem.setUint32(offset, ptr, true);
+ this.mem.setUint32(offset + 4, 0, true);
+ offset += 8;
+ });
+
+ this._inst.exports.run(argc, argv);
+ if (this.exited) {
+ this._resolveExitPromise();
+ }
+ await this._exitPromise;
+ }
+
+ _resume() {
+ if (this.exited) {
+ throw new Error("Go program has already exited");
+ }
+ this._inst.exports.resume();
+ if (this.exited) {
+ this._resolveExitPromise();
+ }
+ }
+
+ _makeFuncWrapper(id) {
+ const go = this;
+ return function () {
+ const event = {
+ id: id,
+ this: this,
+ args: arguments
+ };
+ go._pendingEvent = event;
+ go._resume();
+ return event.result;
+ };
+ }
+ }
+
+ if (
+ typeof module !== "undefined" &&
+ global.require &&
+ global.require.main === module &&
+ global.process &&
+ global.process.versions &&
+ !global.process.versions.electron
+ ) {
+ if (process.argv.length < 3) {
+ console.error("usage: go_js_wasm_exec [wasm binary] [arguments]");
+ process.exit(1);
+ }
+
+ const go = new Go();
+ go.argv = process.argv.slice(2);
+ go.env = Object.assign({
+ TMPDIR: require("os").tmpdir()
+ }, process.env);
+ go.exit = process.exit;
+ WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject).then((result) => {
+ process.on("exit", (code) => { // Node.js exits if no event handler is pending
+ if (code === 0 && !go.exited) {
+ // deadlock, make Go print error and stack traces
+ go._pendingEvent = {
+ id: 0
+ };
+ go._resume();
+ }
+ });
+ return go.run(result.instance);
+ }).catch((err) => {
+ console.error(err);
+ process.exit(1);
+ });
+ }
+})();
\ No newline at end of file
diff --git a/routes/api/index.js b/routes/api/index.js
new file mode 100644
index 000000000..be18148c6
--- /dev/null
+++ b/routes/api/index.js
@@ -0,0 +1,15 @@
+import express from 'express';
+import workflow from './workflow.js';
+import fileUpload from 'express-fileupload';
+
+const router = express.Router();
+router.use(fileUpload());
+
+router.get("/", function (req, res, next) {
+ // TODO: Implement root api endpoint
+ res.status(501).json({"Error": "Unfinished Endpoint. This sould probably send some api docs?"});
+});
+
+router.use("/workflow", workflow);
+
+export default router;
\ No newline at end of file
diff --git a/routes/api/workflow.js b/routes/api/workflow.js
new file mode 100644
index 000000000..499484d48
--- /dev/null
+++ b/routes/api/workflow.js
@@ -0,0 +1,233 @@
+import express from 'express';
+import crypto from 'crypto';
+import stream from "stream";
+import Archiver from 'archiver';
+
+import * as Functions from "../../functions.js";
+import { traverseOperations } from "../../public/traverseOperations.js";
+
+const activeWorkflows = {};
+
+const router = express.Router();
+
+router.post("/:workflowUuid?", [
+ async (req, res) => {
+ if(req.files == null) {
+ res.status(400).json({"error": "No files were uploaded."});
+ return;
+ }
+
+ if(Array.isArray(req.files.files)) {
+ req.files = req.files.files;
+ }
+ else {
+ req.files = [req.files.files];
+ }
+
+ const workflow = JSON.parse(req.body.workflow);
+ // TODO: Validate input further (json may fail or not be a valid workflow)
+
+ const inputs = await Promise.all(req.files.map(async file => {
+ return {
+ originalFileName: file.name.replace(/\.[^/.]+$/, ""),
+ fileName: file.name.replace(/\.[^/.]+$/, ""),
+ buffer: new Uint8Array(await file.data)
+ }
+ }));
+
+ // Allow option to do it synchronously and just make a long request
+ if(req.body.async === "false") {
+ console.log("Don't do async");
+
+ const traverse = traverseOperations(workflow.operations, inputs, Functions);
+
+ let pdfResults;
+ let iteration;
+ while (true) {
+ iteration = await traverse.next();
+ if (iteration.done) {
+ pdfResults = iteration.value;
+ console.log("Done");
+ break;
+ }
+ console.log(iteration.value);
+ }
+
+ console.log("Download");
+ downloadHandler(res, pdfResults);
+ }
+ else {
+ console.log("Start Aync Workflow");
+ // TODO: UUID collision checks
+ let workflowID = req.params.workflowUuid
+ if(!workflowID)
+ workflowID = generateWorkflowID();
+
+ activeWorkflows[workflowID] = {
+ createdAt: Date.now(),
+ finished: false,
+ eventStream: null,
+ result: null,
+ // TODO: When auth is implemented: owner
+ }
+ const activeWorkflow = activeWorkflows[workflowID];
+
+ res.status(200).json({
+ "workflowID": workflowID,
+ "data-recieved": {
+ "fileCount": req.files.length,
+ "workflow": workflow
+ }
+ });
+
+ const traverse = traverseOperations(workflow.operations, inputs);
+
+ let pdfResults;
+ let iteration;
+ while (true) {
+ iteration = await traverse.next();
+ if (iteration.done) {
+ pdfResults = iteration.value;
+ if(activeWorkflow.eventStream) {
+ activeWorkflow.eventStream.write(`data: processing done\n\n`);
+ activeWorkflow.eventStream.end();
+ }
+ break;
+ }
+ if(activeWorkflow.eventStream)
+ activeWorkflow.eventStream.write(`data: ${iteration.value}\n\n`);
+ }
+
+ activeWorkflow.result = pdfResults;
+ activeWorkflow.finished = true;
+ }
+ }
+]);
+
+router.get("/progress/:workflowUuid", (req, res, nex) => {
+ if(!req.params.workflowUuid) {
+ res.status(400).json({"error": "No workflowUuid weres provided."});
+ return;
+ }
+ if(!activeWorkflows.hasOwnProperty(req.params.workflowUuid)) {
+ res.status(400).json({"error": `No workflow with workflowUuid "${req.params.workflowUuid}" was found.`});
+ return;
+ }
+
+ // Return current progress
+ const workflow = activeWorkflows[req.params.workflowUuid];
+ res.status(200).json({ createdAt: workflow.createdAt, finished: workflow.finished });
+});
+
+router.get("/progress-stream/:workflowUuid", (req, res, nex) => {
+ if(!req.params.workflowUuid) {
+ res.status(400).json({"error": "No workflowUuid weres provided."});
+ return;
+ }
+ if(!activeWorkflows.hasOwnProperty(req.params.workflowUuid)) {
+ res.status(400).json({"error": `No workflow with workflowUuid "${req.params.workflowUuid}" was found.`});
+ return;
+ }
+
+ // TODO: Check if already done
+
+ // Send realtime updates
+ res.setHeader('Cache-Control', 'no-cache');
+ res.setHeader('Content-Type', 'text/event-stream');
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Connection', 'keep-alive');
+ res.flushHeaders(); // flush the headers to establish SSE with client
+
+ const workflow = activeWorkflows[req.params.workflowUuid];
+ workflow.eventStream = res;
+
+ res.on('close', () => {
+ res.end();
+ // TODO: Abort if not already done?
+ });
+});
+
+router.get("/result/:workflowUuid", (req, res, nex) => {
+ if(!req.params.workflowUuid) {
+ res.status(400).json({"error": "No workflowUuid weres provided."});
+ return;
+ }
+ if(!activeWorkflows.hasOwnProperty(req.params.workflowUuid)) {
+ res.status(400).json({"error": `No workflow with workflowUuid "${req.params.workflowUuid}" was found.`});
+ return;
+ }
+
+ /*
+ * If workflow isn't done return error
+ * Send file, TODO: if there are multiple outputs return as zip
+ * If download is done, delete results / allow deletion within the next 5-60 mins
+ */
+ const workflow = activeWorkflows[req.params.workflowUuid];
+ if(!workflow.finished) {
+ res.status(202).json({ message: "Workflow hasn't finished yet. Check progress or connect to progress-steam to get notified when its done." });
+ return
+ }
+
+ downloadHandler(res, workflow.result);
+ // Delete workflow / results when done.
+ delete activeWorkflows[req.params.workflowUuid];
+});
+
+router.post("/abort/:workflowUuid", (req, res, nex) => {
+ if(!req.params.workflowUuid) {
+ res.status(400).json({"error": "No workflowUuid weres provided."});
+ return;
+ }
+ if(!activeWorkflows.hasOwnProperty(req.params.workflowUuid)) {
+ res.status(400).json({"error": `No workflow with workflowUuid "${req.params.workflowUuid}" was found.`});
+ return;
+ }
+
+ // TODO: Abort workflow
+ res.status(501).json({"warning": "Abortion has not been implemented yet."});
+});
+
+function generateWorkflowID() {
+ return crypto.randomUUID();
+}
+
+function downloadHandler(res, pdfResults) {
+ if(pdfResults.length == 0) {
+ res.status(500).json({"warning": "The workflow had no outputs."});
+ }
+ else if(pdfResults.length > 1) {
+ // TODO: Also allow the user to download multiple files without zip compressen, because this is kind of slow...
+ res.writeHead(200, {
+ 'Content-Type': 'application/zip',
+ 'Content-disposition': 'attachment; filename=workflow-results.zip'
+ });
+
+ var zip = Archiver('zip');
+
+ // Stream the file to the user.
+ zip.pipe(res);
+
+ console.log("Adding Files to ZIP...");
+
+ for (let i = 0; i < pdfResults.length; i++) {
+ // TODO: Implement other file types (mostly fro image & text extraction)
+ // TODO: Check for name collisions
+ zip.append(Buffer.from(pdfResults[i].buffer), { name: pdfResults[i].fileName + ".pdf" });
+ }
+
+ zip.finalize();
+ console.log("Sent");
+ }
+ else {
+ const readStream = new stream.PassThrough();
+ readStream.end(pdfResults[0].buffer);
+
+ // TODO: Implement other file types (mostly fro image & text extraction)
+ res.set("Content-disposition", 'attachment; filename=' + pdfResults[0].fileName + ".pdf");
+ res.set("Content-Type", "application/pdf");
+
+ readStream.pipe(res);
+ }
+}
+
+export default router;
\ No newline at end of file