From 972e9307c8ba327f0702eb52e2e7e2c54705089c Mon Sep 17 00:00:00 2001 From: yumoqing Date: Wed, 19 Aug 2026 12:59:52 +0800 Subject: [PATCH] =?UTF-8?q?feat(skills):=20=E6=96=B0=E5=A2=9E=20office-tex?= =?UTF-8?q?t-extract=20+=20markdown-to-docx=20=E6=8A=80=E8=83=BD(=E4=BB=8E?= =?UTF-8?q?=20Hermes=20=E8=BF=81=E7=A7=BB=EF=BC=8C=E5=90=AB=E8=84=9A?= =?UTF-8?q?=E6=9C=AC=EF=BC=8C=E8=B7=AF=E5=BE=84=E6=94=B9=E7=9B=B8=E5=AF=B9?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- skills_library/all/markdown-to-docx/SKILL.md | 95 + .../scripts/convert_md_to_docx.js | 244 + .../all/office-text-extract/SKILL.md | 87 + .../all/office-text-extract/scripts/build.sh | 146 + .../scripts/extract_pdf.py | 67 + .../scripts/genoffice-extract.mjs | 29239 ++++++++++++++++ .../scripts/office-extract | 39 + 7 files changed, 29917 insertions(+) create mode 100644 skills_library/all/markdown-to-docx/SKILL.md create mode 100644 skills_library/all/markdown-to-docx/scripts/convert_md_to_docx.js create mode 100644 skills_library/all/office-text-extract/SKILL.md create mode 100644 skills_library/all/office-text-extract/scripts/build.sh create mode 100755 skills_library/all/office-text-extract/scripts/extract_pdf.py create mode 100755 skills_library/all/office-text-extract/scripts/genoffice-extract.mjs create mode 100755 skills_library/all/office-text-extract/scripts/office-extract diff --git a/skills_library/all/markdown-to-docx/SKILL.md b/skills_library/all/markdown-to-docx/SKILL.md new file mode 100644 index 0000000..78eb1b8 --- /dev/null +++ b/skills_library/all/markdown-to-docx/SKILL.md @@ -0,0 +1,95 @@ +--- +name: markdown-to-docx +description: "Convert Markdown to .docx with CJK fonts, no pandoc." +version: 1.0.0 +metadata: + hermes: + tags: [docx, word, markdown, cjk, chinese, conversion, docx-js, node] + category: productivity + related_skills: [docx, pdf, officecli] +--- + +# Markdown → DOCX (no pandoc / LibreOffice) + +## When to use + +Trigger on: "转成 Word / 导出 docx / Word 版本 / 白皮书 Word 版" — any request to turn a Markdown document (whitepaper, report, spec, README) into a `.docx`, especially on hosts where `pandoc`, `LibreOffice`/`soffice`, or `python-docx` are NOT installed. + +The bundled `docx` skill covers creating `.docx` by hand and editing existing files, but assumes pandoc/soffice for reading/verification. When those binaries are missing, this skill is the fallback: parse Markdown with `marked` and emit `.docx` with `docx-js`, fully controlling CJK fonts. + +## Prerequisites (no sudo) + +```bash +# node + npm are usually already present; registry reachable via `npm ping` +mkdir -p /tmp/md2docx && cd /tmp/md2docx && npm init -y >/dev/null +npm install docx marked adm-zip +``` + +`docx` (docx-js) and `marked` generate/parse; `adm-zip` is for verification only. + +## The approach + +`marked.lexer(md)` returns a flat token stream. Walk it once and map each `type` to a docx-js element: + +| marked token | docx-js output | +|--------------|----------------| +| `heading` | `Paragraph({ heading: HeadingLevel.HEADING_ })` | +| `paragraph` | `Paragraph` from inline runs | +| `code` | single `Paragraph` — one `TextRun` per line joined with `new TextRun({ break: 1 })`, gray `shading` + box `border` | +| `table` | `Table` — `columnWidths` + per-cell `width` (both DXA), header row shaded + bold | +| `list` | bullet (`•`) / numbered (`N.`) paragraphs with `indent` + `hanging` | +| `blockquote` | indented paragraph with left border, italic gray | +| `hr` | empty paragraph with bottom border (NOT a table) | + +A complete, tested converter is shipped at `scripts/convert_md_to_docx.js`. Run: + +```bash +node scripts/convert_md_to_docx.js input.md output.docx [title] +``` + +Optional 4th arg sets the Word `title` property (defaults to "Converted from Markdown" — pass the real doc title so the `.docx` metadata isn't a stale leftover). The converter auto-inserts a `PageBreak` before every H1 (after the first) so each `#` chapter starts on a fresh page — right for multi-chapter whitepapers and 投标文件 (bid documents); for continuous-flow docs, delete the `firstH1Seen` block in the main loop. + +Inline runs are built recursively from `tok.tokens`, mapping `strong`/`em`/`codespan`/`link` to run formatting. `codespan` (`` `...` ``) renders as red Consolas — critical for documents full of `${param}$`, `sqlExe`, `load_xxx()`. + +## CJK font handling (the main gotcha) + +Word does NOT reliably auto-fallback Chinese glyphs. Set the **`eastAsia`** attribute on every run's `font`, alongside `ascii`/`hAnsi`: + +```js +const FONT_BODY = { ascii: "Times New Roman", hAnsi: "Times New Roman", eastAsia: "宋体" }; +const FONT_HEAD = { ascii: "Arial", hAnsi: "Arial", eastAsia: "微软雅黑" }; +const FONT_CODE = { ascii: "Consolas", hAnsi: "Consolas", eastAsia: "宋体" }; +// ...new TextRun({ text, font: FONT_BODY }) +``` + +Convention for Chinese technical docs: 标题 `微软雅黑` navy, 正文 `宋体`, 代码 `Consolas`. Omit `eastAsia` and the whole document renders in a Latin fallback font. + +## docx-js footguns (reinforced from the bundled `docx` skill) + +- **Tables need dual widths**: `columnWidths` on the `Table` AND `width` on every `TableCell`, both `WidthType.DXA` (PERCENTAGE breaks in Google Docs). Sum to the usable page width (A4 11906 DXA − 1440×2 margins = **9026 DXA**). +- **Shading type is `ShadingType.CLEAR`, never `SOLID`** (SOLID renders black). +- **No `\n` in a `TextRun`** — multi-line code blocks use `new TextRun({ break: 1 })` between line runs. +- **`PageBreak` must live inside a `Paragraph`.** +- Lists: either use a `numbering` config or prefix the marker manually (`• ` / `N. `); never assume a literal bullet is styled as a list marker. + +## Verification without soffice + +No LibreOffice available to render → verify by reading the OOXML directly with `adm-zip`: + +```js +const AdmZip = require("adm-zip"); +const z = new AdmZip("out.docx"); +const xml = z.readAsText("word/document.xml"); +(xml.match(//g) || []).length // table count +(xml.match(/w:fill="F5F5F5"/g) || []).length // code blocks +(xml.match(/w:fill="D9E2F3"/g) || []).length // header cells +xml.includes("eastAsia") // CJK fonts present +``` + +Spot-check key strings (proper nouns, code identifiers) with `xml.includes(...)` to catch content loss. The docx-js `Packer.toBuffer` output is well-formed OOXML — adm-zip reading `word/document.xml` is sufficient structural proof of validity in the absence of a renderer. + +## Pitfalls + +- **`require('docx/package.json')` throws** `ERR_PACKAGE_PATH_NOT_EXPORTED` — the `exports` map blocks it. Verify install with `typeof require('docx').Document === 'function'` instead. +- **Don't reach for pandoc/soffice installs** on sudo-less hosts as a first move — npm + docx-js is self-contained and faster to stand up. +- Keep the `.md` source alongside the `.docx`; regenerate by rerunning the script after any content edit (single source of truth). diff --git a/skills_library/all/markdown-to-docx/scripts/convert_md_to_docx.js b/skills_library/all/markdown-to-docx/scripts/convert_md_to_docx.js new file mode 100644 index 0000000..16a52d2 --- /dev/null +++ b/skills_library/all/markdown-to-docx/scripts/convert_md_to_docx.js @@ -0,0 +1,244 @@ +// convert_md_to_docx.js — Markdown → .docx with CJK font support. +// No pandoc / LibreOffice / python-docx required. +// +// Usage: node convert_md_to_docx.js input.md output.docx +// Deps: npm install docx marked +// +// Verified 2026-08-17 on a sudo-less host (A4, 42 headings, 6 tables, +// 15 code blocks, CJK fonts via eastAsia). Uses marked.lexer() token walk. + +const fs = require('fs'); +const { + Document, Packer, Paragraph, TextRun, HeadingLevel, Table, TableRow, TableCell, + WidthType, AlignmentType, BorderStyle, ShadingType, PageBreak, +} = require('docx'); +const { marked } = require('marked'); + +const SRC = process.argv[2]; +const OUT = process.argv[3]; +const TITLE = process.argv[4] || 'Converted from Markdown'; +if (!SRC || !OUT) { + console.error('Usage: node convert_md_to_docx.js input.md output.docx [title]'); + process.exit(1); +} + +// ---- fonts (CJK via eastAsia) ---- +const FONT_BODY = { ascii: "Times New Roman", hAnsi: "Times New Roman", eastAsia: "宋体" }; +const FONT_HEAD = { ascii: "Arial", hAnsi: "Arial", eastAsia: "微软雅黑" }; +const FONT_CODE = { ascii: "Consolas", hAnsi: "Consolas", eastAsia: "宋体" }; +const NAVY = "1F3864"; +const GRAY = "595959"; +const CODE_BG = "F5F5F5"; +const CODE_BORDER = "CCCCCC"; + +const md = fs.readFileSync(SRC, 'utf8'); +const tokens = marked.lexer(md); + +// A4 usable width in DXA (page 11906 - margins 1440*2 = 9026) +const PAGE_W = 9026; + +function cellWidths(n) { + const w = Math.floor(PAGE_W / n); + const arr = new Array(n).fill(w); + arr[n - 1] = PAGE_W - w * (n - 1); // last cell absorbs remainder + return arr; +} + +// ---- inline run builder ---- +function inlineRuns(toks, opts = {}) { + const out = []; + const font = opts.font || FONT_BODY; + const size = opts.size || 21; // half-points (10.5pt body) + const color = opts.color; + (toks || []).forEach(t => { + switch (t.type) { + case 'text': + if (t.text) out.push(new TextRun({ text: t.text, font, size, color })); + break; + case 'strong': + out.push(...inlineRuns(t.tokens, { ...opts, bold: true })); + break; + case 'em': + out.push(...inlineRuns(t.tokens, { ...opts, italics: true })); + break; + case 'codespan': + out.push(new TextRun({ text: t.text, font: FONT_CODE, size: size - 1, color: "C7254E" })); + break; + case 'del': + out.push(...inlineRuns(t.tokens, { ...opts, strike: true })); + break; + case 'link': + out.push(...inlineRuns(t.tokens, { ...opts, color: "0563C1", underline: {} })); + break; + case 'html': + case 'br': + break; + default: + if (t.tokens) out.push(...inlineRuns(t.tokens, opts)); + else if (t.text) out.push(new TextRun({ text: t.text, font, size, color })); + } + }); + if (opts.bold || opts.italics || opts.strike) { + out.forEach(r => { + if (opts.bold) r.bold = () => true; + if (opts.italics) r.italics = () => true; + if (opts.strike) r.strike = () => true; + }); + } + return out; +} + +function plainText(toks) { + let s = ''; + (toks || []).forEach(t => { + if (t.type === 'text' || t.type === 'codespan') s += t.text || ''; + else if (t.tokens) s += plainText(t.tokens); + }); + return s; +} + +// ---- block handlers ---- +function headingPara(tok) { + const lvl = tok.depth; + const isTitle = lvl === 1; + const size = isTitle ? 36 : lvl === 2 ? 28 : 24; + const map = { 1: HeadingLevel.HEADING_1, 2: HeadingLevel.HEADING_2, 3: HeadingLevel.HEADING_3, + 4: HeadingLevel.HEADING_4, 5: HeadingLevel.HEADING_5, 6: HeadingLevel.HEADING_6 }; + return new Paragraph({ + heading: map[lvl], + alignment: isTitle ? AlignmentType.CENTER : AlignmentType.LEFT, + spacing: { before: isTitle ? 0 : 240, after: isTitle ? 240 : 120 }, + children: inlineRuns(tok.tokens, { font: FONT_HEAD, size, color: NAVY, bold: true }), + }); +} + +function paragraphPara(tok) { + const children = inlineRuns(tok.tokens || []); + if (!children.length) return new Paragraph({ children: [] }); + return new Paragraph({ spacing: { after: 120, line: 360 }, children }); +} + +function codePara(tok) { + const lines = (tok.text || '').replace(/\n$/, '').split('\n'); + const children = []; + lines.forEach((line, i) => { + if (i > 0) children.push(new TextRun({ break: 1 })); + children.push(new TextRun({ text: line, font: FONT_CODE, size: 18 })); + }); + const border = { style: BorderStyle.SINGLE, size: 4, color: CODE_BORDER }; + return new Paragraph({ + spacing: { before: 80, after: 120 }, + shading: { type: ShadingType.CLEAR, fill: CODE_BG }, + border: { top: border, bottom: border, left: border, right: border }, + children, + }); +} + +function tableBlock(tok) { + const headerCells = tok.header || []; + const ncols = headerCells.length || 1; + const widths = cellWidths(ncols); + const rows = []; + + const buildRow = (cells, isHeader) => new TableRow({ + tableHeader: isHeader, + children: cells.map((c, i) => new TableCell({ + width: { size: widths[i], type: WidthType.DXA }, + shading: isHeader ? { type: ShadingType.CLEAR, fill: "D9E2F3" } : undefined, + children: [new Paragraph({ + spacing: { after: 0 }, + children: [new TextRun({ + text: plainText(c.tokens || []), font: FONT_BODY, size: 20, + bold: isHeader, color: isHeader ? NAVY : undefined, + })], + })], + })), + }); + + rows.push(buildRow(headerCells, true)); + (tok.rows || []).forEach(r => rows.push(buildRow(r, false))); + + const b = { style: BorderStyle.SINGLE, size: 4, color: "BFBFBF" }; + return new Table({ + width: { size: PAGE_W, type: WidthType.DXA }, + columnWidths: widths, + borders: { top: b, bottom: b, left: b, right: b, + insideHorizontal: b, insideVertical: b }, + rows, + }); +} + +function listBlock(tok, ordered) { + const paras = []; + const walk = (items, depth) => { + items.forEach((item, idx) => { + const marker = ordered ? `${idx + 1}. ` : '• '; + const indentLeft = 360 + depth * 360; + item.tokens.forEach(bt => { + if (bt.type === 'list') { walk(bt.items, depth + 1); return; } + if (bt.type === 'text' || bt.type === 'paragraph' || bt.type === 'space') { + const children = inlineRuns(bt.tokens || []); + children.unshift(new TextRun({ text: marker, font: FONT_BODY, size: 21, bold: ordered })); + paras.push(new Paragraph({ + spacing: { after: 40, line: 340 }, + indent: { left: indentLeft, hanging: 240 }, + children, + })); + } + }); + }); + }; + walk(tok.items, 0); + return paras; +} + +function blockquotePara(tok) { + return new Paragraph({ + spacing: { after: 120 }, + indent: { left: 360 }, + border: { left: { style: BorderStyle.SINGLE, size: 12, color: NAVY } }, + children: [new TextRun({ text: plainText(tok.tokens || []), font: FONT_BODY, size: 21, italics: true, color: GRAY })], + }); +} + +function hrPara() { + return new Paragraph({ + spacing: { before: 120, after: 120 }, + border: { bottom: { style: BorderStyle.SINGLE, size: 6, color: "BFBFBF" } }, + children: [], + }); +} + +// ---- main loop ---- +const children = []; +let firstH1Seen = false; +for (const tok of tokens) { + switch (tok.type) { + case 'heading': + if (tok.depth === 1 && firstH1Seen) { + children.push(new Paragraph({ children: [new PageBreak()] })); + } + if (tok.depth === 1) firstH1Seen = true; + children.push(headingPara(tok)); + break; + case 'paragraph': children.push(paragraphPara(tok)); break; + case 'code': children.push(codePara(tok)); break; + case 'table': children.push(tableBlock(tok)); break; + case 'list': children.push(...listBlock(tok, !!tok.ordered)); break; + case 'blockquote':children.push(blockquotePara(tok)); break; + case 'hr': children.push(hrPara()); break; + case 'space': break; + default: break; + } +} + +const doc = new Document({ + creator: 'Hermes Agent', + title: TITLE, + sections: [{ properties: {}, children }], +}); + +Packer.toBuffer(doc).then(buf => { + fs.writeFileSync(OUT, buf); + console.log('WROTE', OUT, buf.length, 'bytes'); +}); diff --git a/skills_library/all/office-text-extract/SKILL.md b/skills_library/all/office-text-extract/SKILL.md new file mode 100644 index 0000000..280cd20 --- /dev/null +++ b/skills_library/all/office-text-extract/SKILL.md @@ -0,0 +1,87 @@ +--- +name: office-text-extract +description: "Extract text from .docx/.pptx/.xlsx/.pdf without pandoc." +version: 2.0.0 +author: Hermes Agent +license: Apache-2.0 (docx/pptx/xlsx engine from genspark-ai/genoffice) +metadata: + hermes: + tags: [office, docx, pptx, xlsx, pdf, text-extraction, headless, genoffice, pymupdf] + related_skills: [docx, xlsx, powerpoint, pdf, markdown-to-docx, ocr-and-documents] +--- + +# Office Text Extraction (headless) + +从 `.docx` / `.pptx` / `.xlsx` / `.pdf` 提取纯文本,**无需 pandoc / LibreOffice**。统一入口一个命令覆盖四种格式: + +- `.docx` / `.pptx` / `.xlsx` → GenOffice 引擎(github.com/genspark-ai/genoffice,Apache-2.0)的 `file-parse` + `docx-engine`,esbuild 打成单文件 Node CLI +- `.pdf`(文本型)→ pymupdf(Python) +- `.pdf`(扫描件/图片型,需 OCR)→ marker-pdf,见 `ocr-and-documents` 技能 + +## 何时用 + +- 需要**读取**已有 Office/PDF 文档内容(本机无 pandoc/LibreOffice 时尤其适用) +- 给 AI 附加 Office/PDF 附件前先转文本 +- 快速抽取正文做检索、摘要、diff + +## 工具位置 + +``` +scripts/office-extract # 统一入口(bash,按扩展名分发)★ 主入口 +scripts/genoffice-extract.mjs # docx/pptx/xlsx 引擎(Node,单文件,~1MB) +scripts/extract_pdf.py # pdf 文本提取(pymupdf) +scripts/build.sh # 可复现重建 Node 引擎(从 genoffice 源重新打包) +``` + +要求:Node 18+(docx/pptx/xlsx)+ `pymupdf`(pdf)。 + +## 用法 + +```bash +BIN=scripts/office-extract + +# 统一入口,四种格式都行(纯文本到 stdout) +"$BIN" /path/to/file.docx +"$BIN" /path/to/file.pdf + +# JSON 模式({ok,kind,ext,text|error}),便于程序化处理 +"$BIN" --json /path/to/file.xlsx +``` + +也可以直接调底层:`node scripts/genoffice-extract.mjs `、`python3 scripts/extract_pdf.py `。 + +## 输出格式 + +- **docx**:标题转 `#`/`##`(按级别),列表项转 `-`,有序列表转 `1. 2. 3.`,表格行转 `cell1 | cell2 | ...`,正文段落原样。接近 Markdown。 +- **pptx**:每页一段 `## Slide N`,每段文字一行,按 slide 编号升序。 +- **xlsx**:每个工作表一段 `# SheetName`,行内单元格用 ` | ` 连接(空单元格占位对齐),inlineStr/sharedStrings/布尔/数字均正确处理。 +- **pdf**:每页文本用 `\n\n` 分隔,中文/多页正常。 +- 中文、ASCII 图、多列表格均无损(docx/pdf 实测通过)。 + +## 坑 + +1. **PDF 分两类**: + - 文本型 PDF(有嵌入文本层)→ `extract_pdf.py`(pymupdf),即时返回。 + - 扫描件/图片型 PDF(无文本层)→ pymupdf 提取为空,脚本会提示改用 marker-pdf OCR(`ocr-and-documents` 技能的 `extract_marker.py`)。marker-pdf 需 ~5GB(PyTorch+模型)且首次运行下载模型。 +2. **只有提取,没有生成/编辑**:本工具只读文本。生成 docx 用 `docx` 技能(docx-js)、md→docx 用 `markdown-to-docx` 技能;编辑已有 docx 的批注/修订/图表需 `docx-engine` 的 patch 能力(未封装)。 +3. **Node 版本**:bundle target 是 node18,老环境可能不兼容。 +4. **大文件**:docx 解析会展开整个 OOXML;超大文件(>50MB)内存占用高。 + +## 重建 Node 引擎(genoffice 上游更新时) + +```bash +bash scripts/build.sh +``` + +`build.sh` 从 genoffice main 分支重新下载 `file-parse` + `docx-engine` 源码、装依赖、esbuild 打包,覆盖 `scripts/genoffice-extract.mjs`。需网络可达 raw.githubusercontent.com(若被墙,先建 SOCKS5 隧道并设 `PROXY=socks5h://127.0.0.1:1080`)。 + +## 迁移到其他机器 / pipeline-app + +- **docx/pptx/xlsx**:`genoffice-extract.mjs` 是纯 Node 单文件工具,**只需 Node 18+**,零依赖。拷过去 `node ` 即用。 +- **pdf**:需要目标机 `pip install pymupdf`(~25MB,一条命令)。 +- **pdf OCR**:需要 `pip install marker-pdf` + ~5GB 磁盘(首次运行下载模型)。 + +三者迁移成本递增:docx/pptx/xlsx(零依赖)< pdf 文本(pip 装 pymupdf)< pdf OCR(5GB)。 + +- 若 pipeline-app 服务器有 Node:拷 `genoffice-extract.mjs` 即可在服务器 shell 用。 +- 若要 pipeline-app 的 DSPY/前端调用:另写一个薄 Sage 模块,用 `subprocess`/`child_process` 调对应 CLI 取 stdout(后续集成决策,本 skill 不涉及)。 diff --git a/skills_library/all/office-text-extract/scripts/build.sh b/skills_library/all/office-text-extract/scripts/build.sh new file mode 100644 index 0000000..873b522 --- /dev/null +++ b/skills_library/all/office-text-extract/scripts/build.sh @@ -0,0 +1,146 @@ +#!/usr/bin/env bash +# 从 genspark-ai/genoffice 重建 genoffice-extract.mjs +# 用法: [PROXY=socks5h://127.0.0.1:1080] bash build.sh +# 产物覆盖本目录下的 genoffice-extract.mjs +set -euo pipefail + +BASE="https://raw.githubusercontent.com/genspark-ai/genoffice/main" +PROXY="${PROXY:-}" +CURL=(curl -s --fail --connect-timeout 30) +[ -n "$PROXY" ] && CURL+=(-x "$PROXY") + +SKILL_DIR="$(cd "$(dirname "$0")" && pwd)" +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT + +# 仅需 file-parse + docx-engine 两个包的源码(PDF 未打包,pdf.ts 不会被 cli.ts 引入) +FILES=( + packages/docx-engine/package.json + packages/docx-engine/src/blank.ts + packages/docx-engine/src/chart.ts + packages/docx-engine/src/generate.ts + packages/docx-engine/src/index.ts + packages/docx-engine/src/ink.ts + packages/docx-engine/src/list-markers.ts + packages/docx-engine/src/math.ts + packages/docx-engine/src/metafile.ts + packages/docx-engine/src/notes.ts + packages/docx-engine/src/parse.ts + packages/docx-engine/src/patch.ts + packages/docx-engine/src/protection.ts + packages/docx-engine/src/scan.ts + packages/docx-engine/src/section.ts + packages/docx-engine/src/sources.ts + packages/docx-engine/src/symbol-fonts.ts + packages/docx-engine/src/text-patch.ts + packages/docx-engine/src/theme.ts + packages/docx-engine/src/tiff.ts + packages/docx-engine/src/types.ts + packages/docx-engine/src/watermark.ts + packages/docx-engine/src/xml-utils.ts + packages/docx-engine/src/zip-load.ts + packages/docx-engine/src/vendor/emf-converter/index.mjs + packages/file-parse/package.json + packages/file-parse/src/docx.ts + packages/file-parse/src/index.ts + packages/file-parse/src/parse.ts + packages/file-parse/src/pdf.ts + packages/file-parse/src/pptx.ts + packages/file-parse/src/xlsx.ts +) + +echo "[1/4] 下载源码 ($((${#FILES[@]})) 个文件)..." +for f in "${FILES[@]}"; do + mkdir -p "$WORK/$(dirname "$f")" + "${CURL[@]}" "$BASE/$f" -o "$WORK/$f" +done + +echo "[2/4] 写入口 cli.ts..." +cat > "$WORK/cli.ts" <<'CLIEOF' +#!/usr/bin/env node +import { readFile } from 'node:fs/promises' +import { extname } from 'node:path' +import { docxToText } from './packages/file-parse/src/docx.ts' +import { pptxToText } from './packages/file-parse/src/pptx.ts' +import { xlsxToText } from './packages/file-parse/src/xlsx.ts' + +const SUPPORTED = new Set(['docx', 'pptx', 'xlsx', 'pdf']) + +function usage() { + console.error( + [ + 'genoffice-extract — 提取 Office 文档纯文本(无 pandoc/LibreOffice 依赖)', + '', + '用法:', + ' genoffice-extract 输出纯文本到 stdout', + ' genoffice-extract --json 输出 {ok,kind,ext,text|error} JSON', + '', + '支持: .docx .pptx .xlsx (.pdf 未打包,请用 pdf/pymupdf 技能)', + ].join('\n'), + ) +} + +async function main() { + const args = process.argv.slice(2) + const json = args.includes('--json') + const files = args.filter((a) => !a.startsWith('--')) + if (files.length === 0) { + usage() + process.exit(2) + } + const file = files[0] + const ext = extname(file).slice(1).toLowerCase() + + if (!SUPPORTED.has(ext)) { + const err = `Unsupported file type: .${ext || 'unknown'} (支持 docx/pptx/xlsx)` + if (json) console.log(JSON.stringify({ ok: false, kind: 'unsupported', ext, error: err })) + else console.error(err) + process.exit(1) + } + if (ext === 'pdf') { + const err = 'PDF 提取未打包(pdfjs-dist 体积/worker 复杂);请用 pdf 或 ocr-and-documents 技能' + if (json) console.log(JSON.stringify({ ok: false, kind: 'unsupported', ext, error: err })) + else console.error(err) + process.exit(1) + } + + let bytes + try { + bytes = await readFile(file) + } catch (e) { + const err = `无法读取文件: ${e instanceof Error ? e.message : String(e)}` + if (json) console.log(JSON.stringify({ ok: false, kind: 'unsupported', ext, error: err })) + else console.error(err) + process.exit(1) + } + + try { + let text = '' + if (ext === 'docx') text = await docxToText(bytes) + else if (ext === 'pptx') text = await pptxToText(bytes) + else if (ext === 'xlsx') text = await xlsxToText(bytes) + if (json) console.log(JSON.stringify({ ok: true, kind: 'text', ext, text })) + else console.log(text) + } catch (e) { + const err = e instanceof Error ? e.message : String(e) + if (json) console.log(JSON.stringify({ ok: false, kind: 'text', ext, error: err })) + else { + console.error('提取失败: ' + err) + process.exit(1) + } + } +} + +main() +CLIEOF + +echo "[3/4] 安装依赖并 esbuild 打包..." +cd "$WORK" +npm init -y >/dev/null 2>&1 +npm install jszip fast-xml-parser utif2 esbuild >/dev/null 2>&1 +npx esbuild cli.ts --bundle --platform=node --format=esm --target=node18 \ + --outfile="$SKILL_DIR/genoffice-extract.mjs" \ + --alias:@genoffice/docx-engine="$WORK/packages/docx-engine/src/index.ts" 2>&1 | grep -v 'tsconfig.base.json' || true + +chmod +x "$SKILL_DIR/genoffice-extract.mjs" +echo "[4/4] 完成: $SKILL_DIR/genoffice-extract.mjs ($(du -h "$SKILL_DIR/genoffice-extract.mjs" | cut -f1))" diff --git a/skills_library/all/office-text-extract/scripts/extract_pdf.py b/skills_library/all/office-text-extract/scripts/extract_pdf.py new file mode 100755 index 0000000..b33ca18 --- /dev/null +++ b/skills_library/all/office-text-extract/scripts/extract_pdf.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""从 PDF 提取纯文本(pymupdf)。输出格式与 genoffice-extract.mjs 对齐。 + +用法: + extract_pdf.py 纯文本到 stdout + extract_pdf.py --json {ok,kind,ext,text|error} JSON + +注意: pymupdf 只提取文本型 PDF(有嵌入文本层)。扫描件/图片型 PDF 无文本层, +提取为空 —— 此时提示改用 marker-pdf OCR。 +""" +import sys +import json +import pymupdf + + +def main() -> int: + args = sys.argv[1:] + as_json = '--json' in args + files = [a for a in args if not a.startswith('--')] + if not files: + print('usage: extract_pdf.py [--json] ', file=sys.stderr) + return 2 + + path = files[0] + ext = 'pdf' + + def emit(ok: bool, kind: str, text: str = '', error: str = '') -> int: + if as_json: + payload = {'ok': ok, 'kind': kind, 'ext': ext} + if ok: + payload['text'] = text + else: + payload['error'] = error + print(json.dumps(payload, ensure_ascii=False)) + else: + if ok: + sys.stdout.write(text) + else: + print(error, file=sys.stderr) + return 0 if ok else 1 + + try: + doc = pymupdf.open(path) + except Exception as e: # noqa: BLE001 + return emit(False, 'unsupported', error='无法打开 PDF: %s' % (e,)) + + try: + pages = [page.get_text() for page in doc] + text = '\n\n'.join(pages).strip() + doc.close() + if not text: + return emit( + False, 'text', + error=('该 PDF 无文本层(可能是扫描件/图片型)。' + 'pymupdf 无法 OCR,请改用 marker-pdf OCR(见 ocr-and-documents 技能)。'), + ) + return emit(True, 'text', text=text) + except Exception as e: # noqa: BLE001 + try: + doc.close() + except Exception: # noqa: BLE001 + pass + return emit(False, 'text', error='提取失败: %s' % (e,)) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/skills_library/all/office-text-extract/scripts/genoffice-extract.mjs b/skills_library/all/office-text-extract/scripts/genoffice-extract.mjs new file mode 100755 index 0000000..426b865 --- /dev/null +++ b/skills_library/all/office-text-extract/scripts/genoffice-extract.mjs @@ -0,0 +1,29239 @@ +#!/usr/bin/env node +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { + get: (a, b) => (typeof require !== "undefined" ? require : a)[b] +}) : x)(function(x) { + if (typeof require !== "undefined") return require.apply(this, arguments); + throw Error('Dynamic require of "' + x + '" is not supported'); +}); +var __commonJS = (cb, mod) => function __require2() { + try { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; + } catch (e) { + throw mod = 0, e; + } +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// node_modules/process-nextick-args/index.js +var require_process_nextick_args = __commonJS({ + "node_modules/process-nextick-args/index.js"(exports2, module) { + "use strict"; + if (typeof process === "undefined" || !process.version || process.version.indexOf("v0.") === 0 || process.version.indexOf("v1.") === 0 && process.version.indexOf("v1.8.") !== 0) { + module.exports = { nextTick }; + } else { + module.exports = process; + } + function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== "function") { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } + } + } +}); + +// node_modules/isarray/index.js +var require_isarray = __commonJS({ + "node_modules/isarray/index.js"(exports2, module) { + var toString = {}.toString; + module.exports = Array.isArray || function(arr) { + return toString.call(arr) == "[object Array]"; + }; + } +}); + +// node_modules/readable-stream/lib/internal/streams/stream.js +var require_stream = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/stream.js"(exports2, module) { + module.exports = __require("stream"); + } +}); + +// node_modules/safe-buffer/index.js +var require_safe_buffer = __commonJS({ + "node_modules/safe-buffer/index.js"(exports2, module) { + var buffer = __require("buffer"); + var Buffer2 = buffer.Buffer; + function copyProps(src, dst) { + for (var key in src) { + dst[key] = src[key]; + } + } + if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) { + module.exports = buffer; + } else { + copyProps(buffer, exports2); + exports2.Buffer = SafeBuffer; + } + function SafeBuffer(arg, encodingOrOffset, length) { + return Buffer2(arg, encodingOrOffset, length); + } + copyProps(Buffer2, SafeBuffer); + SafeBuffer.from = function(arg, encodingOrOffset, length) { + if (typeof arg === "number") { + throw new TypeError("Argument must not be a number"); + } + return Buffer2(arg, encodingOrOffset, length); + }; + SafeBuffer.alloc = function(size, fill, encoding) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + var buf = Buffer2(size); + if (fill !== void 0) { + if (typeof encoding === "string") { + buf.fill(fill, encoding); + } else { + buf.fill(fill); + } + } else { + buf.fill(0); + } + return buf; + }; + SafeBuffer.allocUnsafe = function(size) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + return Buffer2(size); + }; + SafeBuffer.allocUnsafeSlow = function(size) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + return buffer.SlowBuffer(size); + }; + } +}); + +// node_modules/core-util-is/lib/util.js +var require_util = __commonJS({ + "node_modules/core-util-is/lib/util.js"(exports2) { + function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === "[object Array]"; + } + exports2.isArray = isArray; + function isBoolean(arg) { + return typeof arg === "boolean"; + } + exports2.isBoolean = isBoolean; + function isNull(arg) { + return arg === null; + } + exports2.isNull = isNull; + function isNullOrUndefined(arg) { + return arg == null; + } + exports2.isNullOrUndefined = isNullOrUndefined; + function isNumber(arg) { + return typeof arg === "number"; + } + exports2.isNumber = isNumber; + function isString(arg) { + return typeof arg === "string"; + } + exports2.isString = isString; + function isSymbol(arg) { + return typeof arg === "symbol"; + } + exports2.isSymbol = isSymbol; + function isUndefined(arg) { + return arg === void 0; + } + exports2.isUndefined = isUndefined; + function isRegExp(re) { + return objectToString(re) === "[object RegExp]"; + } + exports2.isRegExp = isRegExp; + function isObject(arg) { + return typeof arg === "object" && arg !== null; + } + exports2.isObject = isObject; + function isDate(d) { + return objectToString(d) === "[object Date]"; + } + exports2.isDate = isDate; + function isError(e) { + return objectToString(e) === "[object Error]" || e instanceof Error; + } + exports2.isError = isError; + function isFunction(arg) { + return typeof arg === "function"; + } + exports2.isFunction = isFunction; + function isPrimitive(arg) { + return arg === null || typeof arg === "boolean" || typeof arg === "number" || typeof arg === "string" || typeof arg === "symbol" || // ES6 symbol + typeof arg === "undefined"; + } + exports2.isPrimitive = isPrimitive; + exports2.isBuffer = __require("buffer").Buffer.isBuffer; + function objectToString(o) { + return Object.prototype.toString.call(o); + } + } +}); + +// node_modules/inherits/inherits_browser.js +var require_inherits_browser = __commonJS({ + "node_modules/inherits/inherits_browser.js"(exports2, module) { + if (typeof Object.create === "function") { + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + } + }; + } else { + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() { + }; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + }; + } + } +}); + +// node_modules/inherits/inherits.js +var require_inherits = __commonJS({ + "node_modules/inherits/inherits.js"(exports2, module) { + try { + util = __require("util"); + if (typeof util.inherits !== "function") throw ""; + module.exports = util.inherits; + } catch (e) { + module.exports = require_inherits_browser(); + } + var util; + } +}); + +// node_modules/readable-stream/lib/internal/streams/BufferList.js +var require_BufferList = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/BufferList.js"(exports2, module) { + "use strict"; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + var Buffer2 = require_safe_buffer().Buffer; + var util = __require("util"); + function copyBuffer(src, target, offset) { + src.copy(target, offset); + } + module.exports = (function() { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry; + else this.head = entry; + this.tail = entry; + ++this.length; + }; + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null; + else this.head = this.head.next; + --this.length; + return ret; + }; + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ""; + var p = this.head; + var ret = "" + p.data; + while (p = p.next) { + ret += s + p.data; + } + return ret; + }; + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer2.alloc(0); + var ret = Buffer2.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + return BufferList; + })(); + if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function() { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + " " + obj; + }; + } + } +}); + +// node_modules/readable-stream/lib/internal/streams/destroy.js +var require_destroy = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/destroy.js"(exports2, module) { + "use strict"; + var pna = require_process_nextick_args(); + function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + pna.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + pna.nextTick(emitErrorNT, this, err); + } + } + return this; + } + if (this._readableState) { + this._readableState.destroyed = true; + } + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function(err2) { + if (!cb && err2) { + if (!_this._writableState) { + pna.nextTick(emitErrorNT, _this, err2); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + pna.nextTick(emitErrorNT, _this, err2); + } + } else if (cb) { + cb(err2); + } + }); + return this; + } + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } + } + function emitErrorNT(self2, err) { + self2.emit("error", err); + } + module.exports = { + destroy, + undestroy + }; + } +}); + +// node_modules/util-deprecate/node.js +var require_node = __commonJS({ + "node_modules/util-deprecate/node.js"(exports2, module) { + module.exports = __require("util").deprecate; + } +}); + +// node_modules/readable-stream/lib/_stream_writable.js +var require_stream_writable = __commonJS({ + "node_modules/readable-stream/lib/_stream_writable.js"(exports2, module) { + "use strict"; + var pna = require_process_nextick_args(); + module.exports = Writable; + function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function() { + onCorkedFinish(_this, state); + }; + } + var asyncWrite = !process.browser && ["v0.10", "v0.9."].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; + var Duplex; + Writable.WritableState = WritableState; + var util = Object.create(require_util()); + util.inherits = require_inherits(); + var internalUtil = { + deprecate: require_node() + }; + var Stream = require_stream(); + var Buffer2 = require_safe_buffer().Buffer; + var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var destroyImpl = require_destroy(); + util.inherits(Writable, Stream); + function nop() { + } + function WritableState(options, stream) { + Duplex = Duplex || require_stream_duplex(); + options = options || {}; + var isDuplex = stream instanceof Duplex; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + if (hwm || hwm === 0) this.highWaterMark = hwm; + else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm; + else this.highWaterMark = defaultHwm; + this.highWaterMark = Math.floor(this.highWaterMark); + this.finalCalled = false; + this.needDrain = false; + this.ending = false; + this.ended = false; + this.finished = false; + this.destroyed = false; + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + this.defaultEncoding = options.defaultEncoding || "utf8"; + this.length = 0; + this.writing = false; + this.corked = 0; + this.sync = true; + this.bufferProcessing = false; + this.onwrite = function(er) { + onwrite(stream, er); + }; + this.writecb = null; + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + this.pendingcb = 0; + this.prefinished = false; + this.errorEmitted = false; + this.bufferedRequestCount = 0; + this.corkedRequestsFree = new CorkedRequest(this); + } + WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + (function() { + try { + Object.defineProperty(WritableState.prototype, "buffer", { + get: internalUtil.deprecate(function() { + return this.getBuffer(); + }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003") + }); + } catch (_) { + } + })(); + var realHasInstance; + if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); + } else { + realHasInstance = function(object) { + return object instanceof this; + }; + } + function Writable(options) { + Duplex = Duplex || require_stream_duplex(); + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } + this._writableState = new WritableState(options, this); + this.writable = true; + if (options) { + if (typeof options.write === "function") this._write = options.write; + if (typeof options.writev === "function") this._writev = options.writev; + if (typeof options.destroy === "function") this._destroy = options.destroy; + if (typeof options.final === "function") this._final = options.final; + } + Stream.call(this); + } + Writable.prototype.pipe = function() { + this.emit("error", new Error("Cannot pipe, not readable")); + }; + function writeAfterEnd(stream, cb) { + var er = new Error("write after end"); + stream.emit("error", er); + pna.nextTick(cb, er); + } + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + if (chunk === null) { + er = new TypeError("May not write null values to stream"); + } else if (typeof chunk !== "string" && chunk !== void 0 && !state.objectMode) { + er = new TypeError("Invalid non-string/buffer chunk"); + } + if (er) { + stream.emit("error", er); + pna.nextTick(cb, er); + valid = false; + } + return valid; + } + Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer2.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding === "function") { + cb = encoding; + encoding = null; + } + if (isBuf) encoding = "buffer"; + else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== "function") cb = nop; + if (state.ended) writeAfterEnd(this, cb); + else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; + }; + Writable.prototype.cork = function() { + var state = this._writableState; + state.corked++; + }; + Writable.prototype.uncork = function() { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + if (typeof encoding === "string") encoding = encoding.toLowerCase(); + if (!(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((encoding + "").toLowerCase()) > -1)) throw new TypeError("Unknown encoding: " + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === "string") { + chunk = Buffer2.from(chunk, encoding); + } + return chunk; + } + Object.defineProperty(Writable.prototype, "writableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function() { + return this._writableState.highWaterMark; + } + }); + function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = "buffer"; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk, + encoding, + isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + return ret; + } + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite); + else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) { + pna.nextTick(cb, er); + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit("error", er); + } else { + cb(er); + stream._writableState.errorEmitted = true; + stream.emit("error", er); + finishMaybe(stream, state); + } + } + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb); + else { + var finished = needFinish(state); + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + if (sync) { + asyncWrite(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } + } + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit("drain"); + } + } + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream._writev && entry && entry.next) { + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, "", holder.finish); + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + if (state.writing) { + break; + } + } + if (entry === null) state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error("_write() is not implemented")); + }; + Writable.prototype._writev = null; + Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === "function") { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === "function") { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== void 0) this.write(chunk, encoding); + if (state.corked) { + state.corked = 1; + this.uncork(); + } + if (!state.ending) endWritable(this, state, cb); + }; + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + function callFinal(stream, state) { + stream._final(function(err) { + state.pendingcb--; + if (err) { + stream.emit("error", err); + } + state.prefinished = true; + stream.emit("prefinish"); + finishMaybe(stream, state); + }); + } + function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === "function") { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit("prefinish"); + } + } + } + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit("finish"); + } + } + return need; + } + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.nextTick(cb); + else stream.once("finish", cb); + } + state.ended = true; + stream.writable = false; + } + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + state.corkedRequestsFree.next = corkReq; + } + Object.defineProperty(Writable.prototype, "destroyed", { + get: function() { + if (this._writableState === void 0) { + return false; + } + return this._writableState.destroyed; + }, + set: function(value) { + if (!this._writableState) { + return; + } + this._writableState.destroyed = value; + } + }); + Writable.prototype.destroy = destroyImpl.destroy; + Writable.prototype._undestroy = destroyImpl.undestroy; + Writable.prototype._destroy = function(err, cb) { + this.end(); + cb(err); + }; + } +}); + +// node_modules/readable-stream/lib/_stream_duplex.js +var require_stream_duplex = __commonJS({ + "node_modules/readable-stream/lib/_stream_duplex.js"(exports2, module) { + "use strict"; + var pna = require_process_nextick_args(); + var objectKeys = Object.keys || function(obj) { + var keys2 = []; + for (var key in obj) { + keys2.push(key); + } + return keys2; + }; + module.exports = Duplex; + var util = Object.create(require_util()); + util.inherits = require_inherits(); + var Readable = require_stream_readable(); + var Writable = require_stream_writable(); + util.inherits(Duplex, Readable); + { + keys = objectKeys(Writable.prototype); + for (v = 0; v < keys.length; v++) { + method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + } + var keys; + var method; + var v; + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + if (options && options.readable === false) this.readable = false; + if (options && options.writable === false) this.writable = false; + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + this.once("end", onend); + } + Object.defineProperty(Duplex.prototype, "writableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function() { + return this._writableState.highWaterMark; + } + }); + function onend() { + if (this.allowHalfOpen || this._writableState.ended) return; + pna.nextTick(onEndNT, this); + } + function onEndNT(self2) { + self2.end(); + } + Object.defineProperty(Duplex.prototype, "destroyed", { + get: function() { + if (this._readableState === void 0 || this._writableState === void 0) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function(value) { + if (this._readableState === void 0 || this._writableState === void 0) { + return; + } + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); + Duplex.prototype._destroy = function(err, cb) { + this.push(null); + this.end(); + pna.nextTick(cb, err); + }; + } +}); + +// node_modules/string_decoder/lib/string_decoder.js +var require_string_decoder = __commonJS({ + "node_modules/string_decoder/lib/string_decoder.js"(exports2) { + "use strict"; + var Buffer2 = require_safe_buffer().Buffer; + var isEncoding = Buffer2.isEncoding || function(encoding) { + encoding = "" + encoding; + switch (encoding && encoding.toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + case "raw": + return true; + default: + return false; + } + }; + function _normalizeEncoding(enc) { + if (!enc) return "utf8"; + var retried; + while (true) { + switch (enc) { + case "utf8": + case "utf-8": + return "utf8"; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return "utf16le"; + case "latin1": + case "binary": + return "latin1"; + case "base64": + case "ascii": + case "hex": + return enc; + default: + if (retried) return; + enc = ("" + enc).toLowerCase(); + retried = true; + } + } + } + function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== "string" && (Buffer2.isEncoding === isEncoding || !isEncoding(enc))) throw new Error("Unknown encoding: " + enc); + return nenc || enc; + } + exports2.StringDecoder = StringDecoder; + function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case "utf16le": + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case "utf8": + this.fillLast = utf8FillLast; + nb = 4; + break; + case "base64": + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer2.allocUnsafe(nb); + } + StringDecoder.prototype.write = function(buf) { + if (buf.length === 0) return ""; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === void 0) return ""; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ""; + }; + StringDecoder.prototype.end = utf8End; + StringDecoder.prototype.text = utf8Text; + StringDecoder.prototype.fillLast = function(buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; + }; + function utf8CheckByte(byte) { + if (byte <= 127) return 0; + else if (byte >> 5 === 6) return 2; + else if (byte >> 4 === 14) return 3; + else if (byte >> 3 === 30) return 4; + return byte >> 6 === 2 ? -1 : -2; + } + function utf8CheckIncomplete(self2, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self2.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self2.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0; + else self2.lastNeed = nb - 3; + } + return nb; + } + return 0; + } + function utf8CheckExtraBytes(self2, buf, p) { + if ((buf[0] & 192) !== 128) { + self2.lastNeed = 0; + return "\uFFFD"; + } + if (self2.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 192) !== 128) { + self2.lastNeed = 1; + return "\uFFFD"; + } + if (self2.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 192) !== 128) { + self2.lastNeed = 2; + return "\uFFFD"; + } + } + } + } + function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== void 0) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; + } + function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString("utf8", i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString("utf8", i, end); + } + function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) return r + "\uFFFD"; + return r; + } + function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString("utf16le", i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 55296 && c <= 56319) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString("utf16le", i, buf.length - 1); + } + function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString("utf16le", 0, end); + } + return r; + } + function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString("base64", i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString("base64", i, buf.length - n); + } + function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) return r + this.lastChar.toString("base64", 0, 3 - this.lastNeed); + return r; + } + function simpleWrite(buf) { + return buf.toString(this.encoding); + } + function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ""; + } + } +}); + +// node_modules/readable-stream/lib/_stream_readable.js +var require_stream_readable = __commonJS({ + "node_modules/readable-stream/lib/_stream_readable.js"(exports2, module) { + "use strict"; + var pna = require_process_nextick_args(); + module.exports = Readable; + var isArray = require_isarray(); + var Duplex; + Readable.ReadableState = ReadableState; + var EE = __require("events").EventEmitter; + var EElistenerCount = function(emitter, type) { + return emitter.listeners(type).length; + }; + var Stream = require_stream(); + var Buffer2 = require_safe_buffer().Buffer; + var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var util = Object.create(require_util()); + util.inherits = require_inherits(); + var debugUtil = __require("util"); + var debug = void 0; + if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog("stream"); + } else { + debug = function() { + }; + } + var BufferList = require_BufferList(); + var destroyImpl = require_destroy(); + var StringDecoder; + util.inherits(Readable, Stream); + var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; + function prependListener(emitter, event, fn) { + if (typeof emitter.prependListener === "function") return emitter.prependListener(event, fn); + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn); + else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn); + else emitter._events[event] = [fn, emitter._events[event]]; + } + function ReadableState(options, stream) { + Duplex = Duplex || require_stream_duplex(); + options = options || {}; + var isDuplex = stream instanceof Duplex; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + if (hwm || hwm === 0) this.highWaterMark = hwm; + else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm; + else this.highWaterMark = defaultHwm; + this.highWaterMark = Math.floor(this.highWaterMark); + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + this.sync = true; + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.destroyed = false; + this.defaultEncoding = options.defaultEncoding || "utf8"; + this.awaitDrain = 0; + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require_string_decoder().StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + Duplex = Duplex || require_stream_duplex(); + if (!(this instanceof Readable)) return new Readable(options); + this._readableState = new ReadableState(options, this); + this.readable = true; + if (options) { + if (typeof options.read === "function") this._read = options.read; + if (typeof options.destroy === "function") this._destroy = options.destroy; + } + Stream.call(this); + } + Object.defineProperty(Readable.prototype, "destroyed", { + get: function() { + if (this._readableState === void 0) { + return false; + } + return this._readableState.destroyed; + }, + set: function(value) { + if (!this._readableState) { + return; + } + this._readableState.destroyed = value; + } + }); + Readable.prototype.destroy = destroyImpl.destroy; + Readable.prototype._undestroy = destroyImpl.undestroy; + Readable.prototype._destroy = function(err, cb) { + this.push(null); + cb(err); + }; + Readable.prototype.push = function(chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === "string") { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer2.from(chunk, encoding); + encoding = ""; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); + }; + Readable.prototype.unshift = function(chunk) { + return readableAddChunk(this, chunk, null, true, false); + }; + function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit("error", er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== "string" && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer2.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state.endEmitted) stream.emit("error", new Error("stream.unshift() after end event")); + else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit("error", new Error("stream.push() after EOF")); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false); + else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } + } + return needMoreData(state); + } + function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit("data", chunk); + stream.read(0); + } else { + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk); + else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); + } + function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state.objectMode) { + er = new TypeError("Invalid non-string/buffer chunk"); + } + return er; + } + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + Readable.prototype.isPaused = function() { + return this._readableState.flowing === false; + }; + Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) StringDecoder = require_string_decoder().StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + var MAX_HWM = 8388608; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + if (state.flowing && state.length) return state.buffer.head.data.length; + else return state.length; + } + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + Readable.prototype.read = function(n) { + debug("read", n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug("read: emitReadable", state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this); + else emitReadable(this); + return null; + } + n = howMuchToRead(n, state); + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + var doRead = state.needReadable; + debug("need readable", doRead); + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug("length less than watermark", doRead); + } + if (state.ended || state.reading) { + doRead = false; + debug("reading or ended", doRead); + } else if (doRead) { + debug("do read"); + state.reading = true; + state.sync = true; + if (state.length === 0) state.needReadable = true; + this._read(state.highWaterMark); + state.sync = false; + if (!state.reading) n = howMuchToRead(nOrig, state); + } + var ret; + if (n > 0) ret = fromList(n, state); + else ret = null; + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + if (state.length === 0) { + if (!state.ended) state.needReadable = true; + if (nOrig !== n && state.ended) endReadable(this); + } + if (ret !== null) this.emit("data", ret); + return ret; + }; + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + emitReadable(stream); + } + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug("emitReadable", state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream); + else emitReadable_(stream); + } + } + function emitReadable_(stream) { + debug("emit readable"); + stream.emit("readable"); + flow(stream); + } + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); + } + } + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug("maybeReadMore read 0"); + stream.read(0); + if (len === state.length) + break; + else len = state.length; + } + state.readingMore = false; + } + Readable.prototype._read = function(n) { + this.emit("error", new Error("_read() is not implemented")); + }; + Readable.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug("pipe count=%d opts=%j", state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn); + else src.once("end", endFn); + dest.on("unpipe", onunpipe); + function onunpipe(readable, unpipeInfo) { + debug("onunpipe"); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug("onend"); + dest.end(); + } + var ondrain = pipeOnDrain(src); + dest.on("drain", ondrain); + var cleanedUp = false; + function cleanup() { + debug("cleanup"); + dest.removeListener("close", onclose); + dest.removeListener("finish", onfinish); + dest.removeListener("drain", ondrain); + dest.removeListener("error", onerror); + dest.removeListener("unpipe", onunpipe); + src.removeListener("end", onend); + src.removeListener("end", unpipe); + src.removeListener("data", ondata); + cleanedUp = true; + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + var increasedAwaitDrain = false; + src.on("data", ondata); + function ondata(chunk) { + debug("ondata"); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug("false write response, pause", state.awaitDrain); + state.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + function onerror(er) { + debug("onerror", er); + unpipe(); + dest.removeListener("error", onerror); + if (EElistenerCount(dest, "error") === 0) dest.emit("error", er); + } + prependListener(dest, "error", onerror); + function onclose() { + dest.removeListener("finish", onfinish); + unpipe(); + } + dest.once("close", onclose); + function onfinish() { + debug("onfinish"); + dest.removeListener("close", onclose); + unpipe(); + } + dest.once("finish", onfinish); + function unpipe() { + debug("unpipe"); + src.unpipe(dest); + } + dest.emit("pipe", src); + if (!state.flowing) { + debug("pipe resume"); + src.resume(); + } + return dest; + }; + function pipeOnDrain(src) { + return function() { + var state = src._readableState; + debug("pipeOnDrain", state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, "data")) { + state.flowing = true; + flow(src); + } + }; + } + Readable.prototype.unpipe = function(dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; + if (state.pipesCount === 0) return this; + if (state.pipesCount === 1) { + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit("unpipe", this, unpipeInfo); + return this; + } + if (!dest) { + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) { + dests[i].emit("unpipe", this, { hasUnpiped: false }); + } + return this; + } + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit("unpipe", this, unpipeInfo); + return this; + }; + Readable.prototype.on = function(ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + if (ev === "data") { + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === "readable") { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + function nReadingNextTick(self2) { + debug("readable nexttick read 0"); + self2.read(0); + } + Readable.prototype.resume = function() { + var state = this._readableState; + if (!state.flowing) { + debug("resume"); + state.flowing = true; + resume(this, state); + } + return this; + }; + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } + } + function resume_(stream, state) { + if (!state.reading) { + debug("resume read 0"); + stream.read(0); + } + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit("resume"); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + Readable.prototype.pause = function() { + debug("call pause flowing=%j", this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug("pause"); + this._readableState.flowing = false; + this.emit("pause"); + } + return this; + }; + function flow(stream) { + var state = stream._readableState; + debug("flow", state.flowing); + while (state.flowing && stream.read() !== null) { + } + } + Readable.prototype.wrap = function(stream) { + var _this = this; + var state = this._readableState; + var paused = false; + stream.on("end", function() { + debug("wrapped end"); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream.on("data", function(chunk) { + debug("wrapped data"); + if (state.decoder) chunk = state.decoder.write(chunk); + if (state.objectMode && (chunk === null || chunk === void 0)) return; + else if (!state.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + for (var i in stream) { + if (this[i] === void 0 && typeof stream[i] === "function") { + this[i] = /* @__PURE__ */ (function(method) { + return function() { + return stream[method].apply(stream, arguments); + }; + })(i); + } + } + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + this._read = function(n2) { + debug("wrapped _read", n2); + if (paused) { + paused = false; + stream.resume(); + } + }; + return this; + }; + Object.defineProperty(Readable.prototype, "readableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function() { + return this._readableState.highWaterMark; + } + }); + Readable._fromList = fromList; + function fromList(n, state) { + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift(); + else if (!n || n >= state.length) { + if (state.decoder) ret = state.buffer.join(""); + else if (state.buffer.length === 1) ret = state.buffer.head.data; + else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + ret = fromListPartial(n, state.buffer, state.decoder); + } + return ret; + } + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + ret = list.shift(); + } else { + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str; + else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next; + else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + function copyFromBuffer(n, list) { + var ret = Buffer2.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next; + else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + function endReadable(stream) { + var state = stream._readableState; + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } + } + function endReadableNT(state, stream) { + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit("end"); + } + } + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + } +}); + +// node_modules/readable-stream/lib/_stream_transform.js +var require_stream_transform = __commonJS({ + "node_modules/readable-stream/lib/_stream_transform.js"(exports2, module) { + "use strict"; + module.exports = Transform; + var Duplex = require_stream_duplex(); + var util = Object.create(require_util()); + util.inherits = require_inherits(); + util.inherits(Transform, Duplex); + function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (!cb) { + return this.emit("error", new Error("write callback called multiple times")); + } + ts.writechunk = null; + ts.writecb = null; + if (data != null) + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + this._readableState.needReadable = true; + this._readableState.sync = false; + if (options) { + if (typeof options.transform === "function") this._transform = options.transform; + if (typeof options.flush === "function") this._flush = options.flush; + } + this.on("prefinish", prefinish); + } + function prefinish() { + var _this = this; + if (typeof this._flush === "function") { + this._flush(function(er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } + } + Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + Transform.prototype._transform = function(chunk, encoding, cb) { + throw new Error("_transform() is not implemented"); + }; + Transform.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + Transform.prototype._read = function(n) { + var ts = this._transformState; + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + ts.needTransform = true; + } + }; + Transform.prototype._destroy = function(err, cb) { + var _this2 = this; + Duplex.prototype._destroy.call(this, err, function(err2) { + cb(err2); + _this2.emit("close"); + }); + }; + function done(stream, er, data) { + if (er) return stream.emit("error", er); + if (data != null) + stream.push(data); + if (stream._writableState.length) throw new Error("Calling transform done when ws.length != 0"); + if (stream._transformState.transforming) throw new Error("Calling transform done when still transforming"); + return stream.push(null); + } + } +}); + +// node_modules/readable-stream/lib/_stream_passthrough.js +var require_stream_passthrough = __commonJS({ + "node_modules/readable-stream/lib/_stream_passthrough.js"(exports2, module) { + "use strict"; + module.exports = PassThrough; + var Transform = require_stream_transform(); + var util = Object.create(require_util()); + util.inherits = require_inherits(); + util.inherits(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); + } + PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); + }; + } +}); + +// node_modules/readable-stream/readable.js +var require_readable = __commonJS({ + "node_modules/readable-stream/readable.js"(exports2, module) { + var Stream = __require("stream"); + if (process.env.READABLE_STREAM === "disable" && Stream) { + module.exports = Stream; + exports2 = module.exports = Stream.Readable; + exports2.Readable = Stream.Readable; + exports2.Writable = Stream.Writable; + exports2.Duplex = Stream.Duplex; + exports2.Transform = Stream.Transform; + exports2.PassThrough = Stream.PassThrough; + exports2.Stream = Stream; + } else { + exports2 = module.exports = require_stream_readable(); + exports2.Stream = Stream || exports2; + exports2.Readable = exports2; + exports2.Writable = require_stream_writable(); + exports2.Duplex = require_stream_duplex(); + exports2.Transform = require_stream_transform(); + exports2.PassThrough = require_stream_passthrough(); + } + } +}); + +// node_modules/jszip/lib/support.js +var require_support = __commonJS({ + "node_modules/jszip/lib/support.js"(exports2) { + "use strict"; + exports2.base64 = true; + exports2.array = true; + exports2.string = true; + exports2.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined"; + exports2.nodebuffer = typeof Buffer !== "undefined"; + exports2.uint8array = typeof Uint8Array !== "undefined"; + if (typeof ArrayBuffer === "undefined") { + exports2.blob = false; + } else { + buffer = new ArrayBuffer(0); + try { + exports2.blob = new Blob([buffer], { + type: "application/zip" + }).size === 0; + } catch (e) { + try { + Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder; + builder = new Builder(); + builder.append(buffer); + exports2.blob = builder.getBlob("application/zip").size === 0; + } catch (e2) { + exports2.blob = false; + } + } + } + var buffer; + var Builder; + var builder; + try { + exports2.nodestream = !!require_readable().Readable; + } catch (e) { + exports2.nodestream = false; + } + } +}); + +// node_modules/jszip/lib/base64.js +var require_base64 = __commonJS({ + "node_modules/jszip/lib/base64.js"(exports2) { + "use strict"; + var utils = require_utils(); + var support = require_support(); + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + exports2.encode = function(input) { + var output = []; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0, len = input.length, remainingBytes = len; + var isArray = utils.getTypeOf(input) !== "string"; + while (i < input.length) { + remainingBytes = len - i; + if (!isArray) { + chr1 = input.charCodeAt(i++); + chr2 = i < len ? input.charCodeAt(i++) : 0; + chr3 = i < len ? input.charCodeAt(i++) : 0; + } else { + chr1 = input[i++]; + chr2 = i < len ? input[i++] : 0; + chr3 = i < len ? input[i++] : 0; + } + enc1 = chr1 >> 2; + enc2 = (chr1 & 3) << 4 | chr2 >> 4; + enc3 = remainingBytes > 1 ? (chr2 & 15) << 2 | chr3 >> 6 : 64; + enc4 = remainingBytes > 2 ? chr3 & 63 : 64; + output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4)); + } + return output.join(""); + }; + exports2.decode = function(input) { + var chr1, chr2, chr3; + var enc1, enc2, enc3, enc4; + var i = 0, resultIndex = 0; + var dataUrlPrefix = "data:"; + if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) { + throw new Error("Invalid base64 input, it looks like a data url."); + } + input = input.replace(/[^A-Za-z0-9+/=]/g, ""); + var totalLength = input.length * 3 / 4; + if (input.charAt(input.length - 1) === _keyStr.charAt(64)) { + totalLength--; + } + if (input.charAt(input.length - 2) === _keyStr.charAt(64)) { + totalLength--; + } + if (totalLength % 1 !== 0) { + throw new Error("Invalid base64 input, bad content length."); + } + var output; + if (support.uint8array) { + output = new Uint8Array(totalLength | 0); + } else { + output = new Array(totalLength | 0); + } + while (i < input.length) { + enc1 = _keyStr.indexOf(input.charAt(i++)); + enc2 = _keyStr.indexOf(input.charAt(i++)); + enc3 = _keyStr.indexOf(input.charAt(i++)); + enc4 = _keyStr.indexOf(input.charAt(i++)); + chr1 = enc1 << 2 | enc2 >> 4; + chr2 = (enc2 & 15) << 4 | enc3 >> 2; + chr3 = (enc3 & 3) << 6 | enc4; + output[resultIndex++] = chr1; + if (enc3 !== 64) { + output[resultIndex++] = chr2; + } + if (enc4 !== 64) { + output[resultIndex++] = chr3; + } + } + return output; + }; + } +}); + +// node_modules/jszip/lib/nodejsUtils.js +var require_nodejsUtils = __commonJS({ + "node_modules/jszip/lib/nodejsUtils.js"(exports2, module) { + "use strict"; + module.exports = { + /** + * True if this is running in Nodejs, will be undefined in a browser. + * In a browser, browserify won't include this file and the whole module + * will be resolved an empty object. + */ + isNode: typeof Buffer !== "undefined", + /** + * Create a new nodejs Buffer from an existing content. + * @param {Object} data the data to pass to the constructor. + * @param {String} encoding the encoding to use. + * @return {Buffer} a new Buffer. + */ + newBufferFrom: function(data, encoding) { + if (Buffer.from && Buffer.from !== Uint8Array.from) { + return Buffer.from(data, encoding); + } else { + if (typeof data === "number") { + throw new Error('The "data" argument must not be a number'); + } + return new Buffer(data, encoding); + } + }, + /** + * Create a new nodejs Buffer with the specified size. + * @param {Integer} size the size of the buffer. + * @return {Buffer} a new Buffer. + */ + allocBuffer: function(size) { + if (Buffer.alloc) { + return Buffer.alloc(size); + } else { + var buf = new Buffer(size); + buf.fill(0); + return buf; + } + }, + /** + * Find out if an object is a Buffer. + * @param {Object} b the object to test. + * @return {Boolean} true if the object is a Buffer, false otherwise. + */ + isBuffer: function(b) { + return Buffer.isBuffer(b); + }, + isStream: function(obj) { + return obj && typeof obj.on === "function" && typeof obj.pause === "function" && typeof obj.resume === "function"; + } + }; + } +}); + +// node_modules/immediate/lib/index.js +var require_lib = __commonJS({ + "node_modules/immediate/lib/index.js"(exports2, module) { + "use strict"; + var Mutation = global.MutationObserver || global.WebKitMutationObserver; + var scheduleDrain; + if (process.browser) { + if (Mutation) { + called = 0; + observer = new Mutation(nextTick); + element = global.document.createTextNode(""); + observer.observe(element, { + characterData: true + }); + scheduleDrain = function() { + element.data = called = ++called % 2; + }; + } else if (!global.setImmediate && typeof global.MessageChannel !== "undefined") { + channel = new global.MessageChannel(); + channel.port1.onmessage = nextTick; + scheduleDrain = function() { + channel.port2.postMessage(0); + }; + } else if ("document" in global && "onreadystatechange" in global.document.createElement("script")) { + scheduleDrain = function() { + var scriptEl = global.document.createElement("script"); + scriptEl.onreadystatechange = function() { + nextTick(); + scriptEl.onreadystatechange = null; + scriptEl.parentNode.removeChild(scriptEl); + scriptEl = null; + }; + global.document.documentElement.appendChild(scriptEl); + }; + } else { + scheduleDrain = function() { + setTimeout(nextTick, 0); + }; + } + } else { + scheduleDrain = function() { + process.nextTick(nextTick); + }; + } + var called; + var observer; + var element; + var channel; + var draining; + var queue = []; + function nextTick() { + draining = true; + var i, oldQueue; + var len = queue.length; + while (len) { + oldQueue = queue; + queue = []; + i = -1; + while (++i < len) { + oldQueue[i](); + } + len = queue.length; + } + draining = false; + } + module.exports = immediate; + function immediate(task) { + if (queue.push(task) === 1 && !draining) { + scheduleDrain(); + } + } + } +}); + +// node_modules/lie/lib/index.js +var require_lib2 = __commonJS({ + "node_modules/lie/lib/index.js"(exports2, module) { + "use strict"; + var immediate = require_lib(); + function INTERNAL() { + } + var handlers = {}; + var REJECTED = ["REJECTED"]; + var FULFILLED = ["FULFILLED"]; + var PENDING = ["PENDING"]; + if (!process.browser) { + UNHANDLED = ["UNHANDLED"]; + } + var UNHANDLED; + module.exports = Promise2; + function Promise2(resolver) { + if (typeof resolver !== "function") { + throw new TypeError("resolver must be a function"); + } + this.state = PENDING; + this.queue = []; + this.outcome = void 0; + if (!process.browser) { + this.handled = UNHANDLED; + } + if (resolver !== INTERNAL) { + safelyResolveThenable(this, resolver); + } + } + Promise2.prototype.finally = function(callback) { + if (typeof callback !== "function") { + return this; + } + var p = this.constructor; + return this.then(resolve2, reject2); + function resolve2(value) { + function yes() { + return value; + } + return p.resolve(callback()).then(yes); + } + function reject2(reason) { + function no() { + throw reason; + } + return p.resolve(callback()).then(no); + } + }; + Promise2.prototype.catch = function(onRejected) { + return this.then(null, onRejected); + }; + Promise2.prototype.then = function(onFulfilled, onRejected) { + if (typeof onFulfilled !== "function" && this.state === FULFILLED || typeof onRejected !== "function" && this.state === REJECTED) { + return this; + } + var promise = new this.constructor(INTERNAL); + if (!process.browser) { + if (this.handled === UNHANDLED) { + this.handled = null; + } + } + if (this.state !== PENDING) { + var resolver = this.state === FULFILLED ? onFulfilled : onRejected; + unwrap(promise, resolver, this.outcome); + } else { + this.queue.push(new QueueItem(promise, onFulfilled, onRejected)); + } + return promise; + }; + function QueueItem(promise, onFulfilled, onRejected) { + this.promise = promise; + if (typeof onFulfilled === "function") { + this.onFulfilled = onFulfilled; + this.callFulfilled = this.otherCallFulfilled; + } + if (typeof onRejected === "function") { + this.onRejected = onRejected; + this.callRejected = this.otherCallRejected; + } + } + QueueItem.prototype.callFulfilled = function(value) { + handlers.resolve(this.promise, value); + }; + QueueItem.prototype.otherCallFulfilled = function(value) { + unwrap(this.promise, this.onFulfilled, value); + }; + QueueItem.prototype.callRejected = function(value) { + handlers.reject(this.promise, value); + }; + QueueItem.prototype.otherCallRejected = function(value) { + unwrap(this.promise, this.onRejected, value); + }; + function unwrap(promise, func, value) { + immediate(function() { + var returnValue; + try { + returnValue = func(value); + } catch (e) { + return handlers.reject(promise, e); + } + if (returnValue === promise) { + handlers.reject(promise, new TypeError("Cannot resolve promise with itself")); + } else { + handlers.resolve(promise, returnValue); + } + }); + } + handlers.resolve = function(self2, value) { + var result = tryCatch(getThen, value); + if (result.status === "error") { + return handlers.reject(self2, result.value); + } + var thenable = result.value; + if (thenable) { + safelyResolveThenable(self2, thenable); + } else { + self2.state = FULFILLED; + self2.outcome = value; + var i = -1; + var len = self2.queue.length; + while (++i < len) { + self2.queue[i].callFulfilled(value); + } + } + return self2; + }; + handlers.reject = function(self2, error) { + self2.state = REJECTED; + self2.outcome = error; + if (!process.browser) { + if (self2.handled === UNHANDLED) { + immediate(function() { + if (self2.handled === UNHANDLED) { + process.emit("unhandledRejection", error, self2); + } + }); + } + } + var i = -1; + var len = self2.queue.length; + while (++i < len) { + self2.queue[i].callRejected(error); + } + return self2; + }; + function getThen(obj) { + var then = obj && obj.then; + if (obj && (typeof obj === "object" || typeof obj === "function") && typeof then === "function") { + return function appyThen() { + then.apply(obj, arguments); + }; + } + } + function safelyResolveThenable(self2, thenable) { + var called = false; + function onError(value) { + if (called) { + return; + } + called = true; + handlers.reject(self2, value); + } + function onSuccess(value) { + if (called) { + return; + } + called = true; + handlers.resolve(self2, value); + } + function tryToUnwrap() { + thenable(onSuccess, onError); + } + var result = tryCatch(tryToUnwrap); + if (result.status === "error") { + onError(result.value); + } + } + function tryCatch(func, value) { + var out = {}; + try { + out.value = func(value); + out.status = "success"; + } catch (e) { + out.status = "error"; + out.value = e; + } + return out; + } + Promise2.resolve = resolve; + function resolve(value) { + if (value instanceof this) { + return value; + } + return handlers.resolve(new this(INTERNAL), value); + } + Promise2.reject = reject; + function reject(reason) { + var promise = new this(INTERNAL); + return handlers.reject(promise, reason); + } + Promise2.all = all; + function all(iterable) { + var self2 = this; + if (Object.prototype.toString.call(iterable) !== "[object Array]") { + return this.reject(new TypeError("must be an array")); + } + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + var values = new Array(len); + var resolved = 0; + var i = -1; + var promise = new this(INTERNAL); + while (++i < len) { + allResolver(iterable[i], i); + } + return promise; + function allResolver(value, i2) { + self2.resolve(value).then(resolveFromAll, function(error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + function resolveFromAll(outValue) { + values[i2] = outValue; + if (++resolved === len && !called) { + called = true; + handlers.resolve(promise, values); + } + } + } + } + Promise2.race = race; + function race(iterable) { + var self2 = this; + if (Object.prototype.toString.call(iterable) !== "[object Array]") { + return this.reject(new TypeError("must be an array")); + } + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + var i = -1; + var promise = new this(INTERNAL); + while (++i < len) { + resolver(iterable[i]); + } + return promise; + function resolver(value) { + self2.resolve(value).then(function(response) { + if (!called) { + called = true; + handlers.resolve(promise, response); + } + }, function(error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + } + } + } +}); + +// node_modules/jszip/lib/external.js +var require_external = __commonJS({ + "node_modules/jszip/lib/external.js"(exports2, module) { + "use strict"; + var ES6Promise = null; + if (typeof Promise !== "undefined") { + ES6Promise = Promise; + } else { + ES6Promise = require_lib2(); + } + module.exports = { + Promise: ES6Promise + }; + } +}); + +// node_modules/setimmediate/setImmediate.js +var require_setImmediate = __commonJS({ + "node_modules/setimmediate/setImmediate.js"(exports2) { + (function(global2, undefined2) { + "use strict"; + if (global2.setImmediate) { + return; + } + var nextHandle = 1; + var tasksByHandle = {}; + var currentlyRunningATask = false; + var doc = global2.document; + var registerImmediate; + function setImmediate2(callback) { + if (typeof callback !== "function") { + callback = new Function("" + callback); + } + var args = new Array(arguments.length - 1); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i + 1]; + } + var task = { callback, args }; + tasksByHandle[nextHandle] = task; + registerImmediate(nextHandle); + return nextHandle++; + } + function clearImmediate(handle) { + delete tasksByHandle[handle]; + } + function run(task) { + var callback = task.callback; + var args = task.args; + switch (args.length) { + case 0: + callback(); + break; + case 1: + callback(args[0]); + break; + case 2: + callback(args[0], args[1]); + break; + case 3: + callback(args[0], args[1], args[2]); + break; + default: + callback.apply(undefined2, args); + break; + } + } + function runIfPresent(handle) { + if (currentlyRunningATask) { + setTimeout(runIfPresent, 0, handle); + } else { + var task = tasksByHandle[handle]; + if (task) { + currentlyRunningATask = true; + try { + run(task); + } finally { + clearImmediate(handle); + currentlyRunningATask = false; + } + } + } + } + function installNextTickImplementation() { + registerImmediate = function(handle) { + process.nextTick(function() { + runIfPresent(handle); + }); + }; + } + function canUsePostMessage() { + if (global2.postMessage && !global2.importScripts) { + var postMessageIsAsynchronous = true; + var oldOnMessage = global2.onmessage; + global2.onmessage = function() { + postMessageIsAsynchronous = false; + }; + global2.postMessage("", "*"); + global2.onmessage = oldOnMessage; + return postMessageIsAsynchronous; + } + } + function installPostMessageImplementation() { + var messagePrefix = "setImmediate$" + Math.random() + "$"; + var onGlobalMessage = function(event) { + if (event.source === global2 && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { + runIfPresent(+event.data.slice(messagePrefix.length)); + } + }; + if (global2.addEventListener) { + global2.addEventListener("message", onGlobalMessage, false); + } else { + global2.attachEvent("onmessage", onGlobalMessage); + } + registerImmediate = function(handle) { + global2.postMessage(messagePrefix + handle, "*"); + }; + } + function installMessageChannelImplementation() { + var channel = new MessageChannel(); + channel.port1.onmessage = function(event) { + var handle = event.data; + runIfPresent(handle); + }; + registerImmediate = function(handle) { + channel.port2.postMessage(handle); + }; + } + function installReadyStateChangeImplementation() { + var html = doc.documentElement; + registerImmediate = function(handle) { + var script = doc.createElement("script"); + script.onreadystatechange = function() { + runIfPresent(handle); + script.onreadystatechange = null; + html.removeChild(script); + script = null; + }; + html.appendChild(script); + }; + } + function installSetTimeoutImplementation() { + registerImmediate = function(handle) { + setTimeout(runIfPresent, 0, handle); + }; + } + var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global2); + attachTo = attachTo && attachTo.setTimeout ? attachTo : global2; + if ({}.toString.call(global2.process) === "[object process]") { + installNextTickImplementation(); + } else if (canUsePostMessage()) { + installPostMessageImplementation(); + } else if (global2.MessageChannel) { + installMessageChannelImplementation(); + } else if (doc && "onreadystatechange" in doc.createElement("script")) { + installReadyStateChangeImplementation(); + } else { + installSetTimeoutImplementation(); + } + attachTo.setImmediate = setImmediate2; + attachTo.clearImmediate = clearImmediate; + })(typeof self === "undefined" ? typeof global === "undefined" ? exports2 : global : self); + } +}); + +// node_modules/jszip/lib/utils.js +var require_utils = __commonJS({ + "node_modules/jszip/lib/utils.js"(exports2) { + "use strict"; + var support = require_support(); + var base64 = require_base64(); + var nodejsUtils = require_nodejsUtils(); + var external = require_external(); + require_setImmediate(); + function string2binary(str) { + var result = null; + if (support.uint8array) { + result = new Uint8Array(str.length); + } else { + result = new Array(str.length); + } + return stringToArrayLike(str, result); + } + exports2.newBlob = function(part, type) { + exports2.checkSupport("blob"); + try { + return new Blob([part], { + type + }); + } catch (e) { + try { + var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder; + var builder = new Builder(); + builder.append(part); + return builder.getBlob(type); + } catch (e2) { + throw new Error("Bug : can't construct the Blob."); + } + } + }; + function identity(input) { + return input; + } + function stringToArrayLike(str, array) { + for (var i = 0; i < str.length; ++i) { + array[i] = str.charCodeAt(i) & 255; + } + return array; + } + var arrayToStringHelper = { + /** + * Transform an array of int into a string, chunk by chunk. + * See the performances notes on arrayLikeToString. + * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. + * @param {String} type the type of the array. + * @param {Integer} chunk the chunk size. + * @return {String} the resulting string. + * @throws Error if the chunk is too big for the stack. + */ + stringifyByChunk: function(array, type, chunk) { + var result = [], k = 0, len = array.length; + if (len <= chunk) { + return String.fromCharCode.apply(null, array); + } + while (k < len) { + if (type === "array" || type === "nodebuffer") { + result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len)))); + } else { + result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len)))); + } + k += chunk; + } + return result.join(""); + }, + /** + * Call String.fromCharCode on every item in the array. + * This is the naive implementation, which generate A LOT of intermediate string. + * This should be used when everything else fail. + * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. + * @return {String} the result. + */ + stringifyByChar: function(array) { + var resultStr = ""; + for (var i = 0; i < array.length; i++) { + resultStr += String.fromCharCode(array[i]); + } + return resultStr; + }, + applyCanBeUsed: { + /** + * true if the browser accepts to use String.fromCharCode on Uint8Array + */ + uint8array: (function() { + try { + return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1; + } catch (e) { + return false; + } + })(), + /** + * true if the browser accepts to use String.fromCharCode on nodejs Buffer. + */ + nodebuffer: (function() { + try { + return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1; + } catch (e) { + return false; + } + })() + } + }; + function arrayLikeToString(array) { + var chunk = 65536, type = exports2.getTypeOf(array), canUseApply = true; + if (type === "uint8array") { + canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array; + } else if (type === "nodebuffer") { + canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer; + } + if (canUseApply) { + while (chunk > 1) { + try { + return arrayToStringHelper.stringifyByChunk(array, type, chunk); + } catch (e) { + chunk = Math.floor(chunk / 2); + } + } + } + return arrayToStringHelper.stringifyByChar(array); + } + exports2.applyFromCharCode = arrayLikeToString; + function arrayLikeToArrayLike(arrayFrom, arrayTo) { + for (var i = 0; i < arrayFrom.length; i++) { + arrayTo[i] = arrayFrom[i]; + } + return arrayTo; + } + var transform = {}; + transform["string"] = { + "string": identity, + "array": function(input) { + return stringToArrayLike(input, new Array(input.length)); + }, + "arraybuffer": function(input) { + return transform["string"]["uint8array"](input).buffer; + }, + "uint8array": function(input) { + return stringToArrayLike(input, new Uint8Array(input.length)); + }, + "nodebuffer": function(input) { + return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length)); + } + }; + transform["array"] = { + "string": arrayLikeToString, + "array": identity, + "arraybuffer": function(input) { + return new Uint8Array(input).buffer; + }, + "uint8array": function(input) { + return new Uint8Array(input); + }, + "nodebuffer": function(input) { + return nodejsUtils.newBufferFrom(input); + } + }; + transform["arraybuffer"] = { + "string": function(input) { + return arrayLikeToString(new Uint8Array(input)); + }, + "array": function(input) { + return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength)); + }, + "arraybuffer": identity, + "uint8array": function(input) { + return new Uint8Array(input); + }, + "nodebuffer": function(input) { + return nodejsUtils.newBufferFrom(new Uint8Array(input)); + } + }; + transform["uint8array"] = { + "string": arrayLikeToString, + "array": function(input) { + return arrayLikeToArrayLike(input, new Array(input.length)); + }, + "arraybuffer": function(input) { + return input.buffer; + }, + "uint8array": identity, + "nodebuffer": function(input) { + return nodejsUtils.newBufferFrom(input); + } + }; + transform["nodebuffer"] = { + "string": arrayLikeToString, + "array": function(input) { + return arrayLikeToArrayLike(input, new Array(input.length)); + }, + "arraybuffer": function(input) { + return transform["nodebuffer"]["uint8array"](input).buffer; + }, + "uint8array": function(input) { + return arrayLikeToArrayLike(input, new Uint8Array(input.length)); + }, + "nodebuffer": identity + }; + exports2.transformTo = function(outputType, input) { + if (!input) { + input = ""; + } + if (!outputType) { + return input; + } + exports2.checkSupport(outputType); + var inputType = exports2.getTypeOf(input); + var result = transform[inputType][outputType](input); + return result; + }; + exports2.resolve = function(path) { + var parts = path.split("/"); + var result = []; + for (var index = 0; index < parts.length; index++) { + var part = parts[index]; + if (part === "." || part === "" && index !== 0 && index !== parts.length - 1) { + continue; + } else if (part === "..") { + result.pop(); + } else { + result.push(part); + } + } + return result.join("/"); + }; + exports2.getTypeOf = function(input) { + if (typeof input === "string") { + return "string"; + } + if (Object.prototype.toString.call(input) === "[object Array]") { + return "array"; + } + if (support.nodebuffer && nodejsUtils.isBuffer(input)) { + return "nodebuffer"; + } + if (support.uint8array && input instanceof Uint8Array) { + return "uint8array"; + } + if (support.arraybuffer && input instanceof ArrayBuffer) { + return "arraybuffer"; + } + }; + exports2.checkSupport = function(type) { + var supported = support[type.toLowerCase()]; + if (!supported) { + throw new Error(type + " is not supported by this platform"); + } + }; + exports2.MAX_VALUE_16BITS = 65535; + exports2.MAX_VALUE_32BITS = -1; + exports2.pretty = function(str) { + var res = "", code, i; + for (i = 0; i < (str || "").length; i++) { + code = str.charCodeAt(i); + res += "\\x" + (code < 16 ? "0" : "") + code.toString(16).toUpperCase(); + } + return res; + }; + exports2.delay = function(callback, args, self2) { + setImmediate(function() { + callback.apply(self2 || null, args || []); + }); + }; + exports2.inherits = function(ctor, superCtor) { + var Obj = function() { + }; + Obj.prototype = superCtor.prototype; + ctor.prototype = new Obj(); + }; + exports2.extend = function() { + var result = {}, i, attr; + for (i = 0; i < arguments.length; i++) { + for (attr in arguments[i]) { + if (Object.prototype.hasOwnProperty.call(arguments[i], attr) && typeof result[attr] === "undefined") { + result[attr] = arguments[i][attr]; + } + } + } + return result; + }; + exports2.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) { + var promise = external.Promise.resolve(inputData).then(function(data) { + var isBlob = support.blob && (data instanceof Blob || ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(data)) !== -1); + if (isBlob && typeof FileReader !== "undefined") { + return new external.Promise(function(resolve, reject) { + var reader = new FileReader(); + reader.onload = function(e) { + resolve(e.target.result); + }; + reader.onerror = function(e) { + reject(e.target.error); + }; + reader.readAsArrayBuffer(data); + }); + } else { + return data; + } + }); + return promise.then(function(data) { + var dataType = exports2.getTypeOf(data); + if (!dataType) { + return external.Promise.reject( + new Error("Can't read the data of '" + name + "'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?") + ); + } + if (dataType === "arraybuffer") { + data = exports2.transformTo("uint8array", data); + } else if (dataType === "string") { + if (isBase64) { + data = base64.decode(data); + } else if (isBinary) { + if (isOptimizedBinaryString !== true) { + data = string2binary(data); + } + } + } + return data; + }); + }; + } +}); + +// node_modules/jszip/lib/stream/GenericWorker.js +var require_GenericWorker = __commonJS({ + "node_modules/jszip/lib/stream/GenericWorker.js"(exports2, module) { + "use strict"; + function GenericWorker(name) { + this.name = name || "default"; + this.streamInfo = {}; + this.generatedError = null; + this.extraStreamInfo = {}; + this.isPaused = true; + this.isFinished = false; + this.isLocked = false; + this._listeners = { + "data": [], + "end": [], + "error": [] + }; + this.previous = null; + } + GenericWorker.prototype = { + /** + * Push a chunk to the next workers. + * @param {Object} chunk the chunk to push + */ + push: function(chunk) { + this.emit("data", chunk); + }, + /** + * End the stream. + * @return {Boolean} true if this call ended the worker, false otherwise. + */ + end: function() { + if (this.isFinished) { + return false; + } + this.flush(); + try { + this.emit("end"); + this.cleanUp(); + this.isFinished = true; + } catch (e) { + this.emit("error", e); + } + return true; + }, + /** + * End the stream with an error. + * @param {Error} e the error which caused the premature end. + * @return {Boolean} true if this call ended the worker with an error, false otherwise. + */ + error: function(e) { + if (this.isFinished) { + return false; + } + if (this.isPaused) { + this.generatedError = e; + } else { + this.isFinished = true; + this.emit("error", e); + if (this.previous) { + this.previous.error(e); + } + this.cleanUp(); + } + return true; + }, + /** + * Add a callback on an event. + * @param {String} name the name of the event (data, end, error) + * @param {Function} listener the function to call when the event is triggered + * @return {GenericWorker} the current object for chainability + */ + on: function(name, listener) { + this._listeners[name].push(listener); + return this; + }, + /** + * Clean any references when a worker is ending. + */ + cleanUp: function() { + this.streamInfo = this.generatedError = this.extraStreamInfo = null; + this._listeners = []; + }, + /** + * Trigger an event. This will call registered callback with the provided arg. + * @param {String} name the name of the event (data, end, error) + * @param {Object} arg the argument to call the callback with. + */ + emit: function(name, arg) { + if (this._listeners[name]) { + for (var i = 0; i < this._listeners[name].length; i++) { + this._listeners[name][i].call(this, arg); + } + } + }, + /** + * Chain a worker with an other. + * @param {Worker} next the worker receiving events from the current one. + * @return {worker} the next worker for chainability + */ + pipe: function(next) { + return next.registerPrevious(this); + }, + /** + * Same as `pipe` in the other direction. + * Using an API with `pipe(next)` is very easy. + * Implementing the API with the point of view of the next one registering + * a source is easier, see the ZipFileWorker. + * @param {Worker} previous the previous worker, sending events to this one + * @return {Worker} the current worker for chainability + */ + registerPrevious: function(previous) { + if (this.isLocked) { + throw new Error("The stream '" + this + "' has already been used."); + } + this.streamInfo = previous.streamInfo; + this.mergeStreamInfo(); + this.previous = previous; + var self2 = this; + previous.on("data", function(chunk) { + self2.processChunk(chunk); + }); + previous.on("end", function() { + self2.end(); + }); + previous.on("error", function(e) { + self2.error(e); + }); + return this; + }, + /** + * Pause the stream so it doesn't send events anymore. + * @return {Boolean} true if this call paused the worker, false otherwise. + */ + pause: function() { + if (this.isPaused || this.isFinished) { + return false; + } + this.isPaused = true; + if (this.previous) { + this.previous.pause(); + } + return true; + }, + /** + * Resume a paused stream. + * @return {Boolean} true if this call resumed the worker, false otherwise. + */ + resume: function() { + if (!this.isPaused || this.isFinished) { + return false; + } + this.isPaused = false; + var withError = false; + if (this.generatedError) { + this.error(this.generatedError); + withError = true; + } + if (this.previous) { + this.previous.resume(); + } + return !withError; + }, + /** + * Flush any remaining bytes as the stream is ending. + */ + flush: function() { + }, + /** + * Process a chunk. This is usually the method overridden. + * @param {Object} chunk the chunk to process. + */ + processChunk: function(chunk) { + this.push(chunk); + }, + /** + * Add a key/value to be added in the workers chain streamInfo once activated. + * @param {String} key the key to use + * @param {Object} value the associated value + * @return {Worker} the current worker for chainability + */ + withStreamInfo: function(key, value) { + this.extraStreamInfo[key] = value; + this.mergeStreamInfo(); + return this; + }, + /** + * Merge this worker's streamInfo into the chain's streamInfo. + */ + mergeStreamInfo: function() { + for (var key in this.extraStreamInfo) { + if (!Object.prototype.hasOwnProperty.call(this.extraStreamInfo, key)) { + continue; + } + this.streamInfo[key] = this.extraStreamInfo[key]; + } + }, + /** + * Lock the stream to prevent further updates on the workers chain. + * After calling this method, all calls to pipe will fail. + */ + lock: function() { + if (this.isLocked) { + throw new Error("The stream '" + this + "' has already been used."); + } + this.isLocked = true; + if (this.previous) { + this.previous.lock(); + } + }, + /** + * + * Pretty print the workers chain. + */ + toString: function() { + var me = "Worker " + this.name; + if (this.previous) { + return this.previous + " -> " + me; + } else { + return me; + } + } + }; + module.exports = GenericWorker; + } +}); + +// node_modules/jszip/lib/utf8.js +var require_utf8 = __commonJS({ + "node_modules/jszip/lib/utf8.js"(exports2) { + "use strict"; + var utils = require_utils(); + var support = require_support(); + var nodejsUtils = require_nodejsUtils(); + var GenericWorker = require_GenericWorker(); + var _utf8len = new Array(256); + for (i = 0; i < 256; i++) { + _utf8len[i] = i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1; + } + var i; + _utf8len[254] = _utf8len[254] = 1; + var string2buf = function(str) { + var buf, c, c2, m_pos, i2, str_len = str.length, buf_len = 0; + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + buf_len += c < 128 ? 1 : c < 2048 ? 2 : c < 65536 ? 3 : 4; + } + if (support.uint8array) { + buf = new Uint8Array(buf_len); + } else { + buf = new Array(buf_len); + } + for (i2 = 0, m_pos = 0; i2 < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + if (c < 128) { + buf[i2++] = c; + } else if (c < 2048) { + buf[i2++] = 192 | c >>> 6; + buf[i2++] = 128 | c & 63; + } else if (c < 65536) { + buf[i2++] = 224 | c >>> 12; + buf[i2++] = 128 | c >>> 6 & 63; + buf[i2++] = 128 | c & 63; + } else { + buf[i2++] = 240 | c >>> 18; + buf[i2++] = 128 | c >>> 12 & 63; + buf[i2++] = 128 | c >>> 6 & 63; + buf[i2++] = 128 | c & 63; + } + } + return buf; + }; + var utf8border = function(buf, max) { + var pos; + max = max || buf.length; + if (max > buf.length) { + max = buf.length; + } + pos = max - 1; + while (pos >= 0 && (buf[pos] & 192) === 128) { + pos--; + } + if (pos < 0) { + return max; + } + if (pos === 0) { + return max; + } + return pos + _utf8len[buf[pos]] > max ? pos : max; + }; + var buf2string = function(buf) { + var i2, out, c, c_len; + var len = buf.length; + var utf16buf = new Array(len * 2); + for (out = 0, i2 = 0; i2 < len; ) { + c = buf[i2++]; + if (c < 128) { + utf16buf[out++] = c; + continue; + } + c_len = _utf8len[c]; + if (c_len > 4) { + utf16buf[out++] = 65533; + i2 += c_len - 1; + continue; + } + c &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7; + while (c_len > 1 && i2 < len) { + c = c << 6 | buf[i2++] & 63; + c_len--; + } + if (c_len > 1) { + utf16buf[out++] = 65533; + continue; + } + if (c < 65536) { + utf16buf[out++] = c; + } else { + c -= 65536; + utf16buf[out++] = 55296 | c >> 10 & 1023; + utf16buf[out++] = 56320 | c & 1023; + } + } + if (utf16buf.length !== out) { + if (utf16buf.subarray) { + utf16buf = utf16buf.subarray(0, out); + } else { + utf16buf.length = out; + } + } + return utils.applyFromCharCode(utf16buf); + }; + exports2.utf8encode = function utf8encode(str) { + if (support.nodebuffer) { + return nodejsUtils.newBufferFrom(str, "utf-8"); + } + return string2buf(str); + }; + exports2.utf8decode = function utf8decode(buf) { + if (support.nodebuffer) { + return utils.transformTo("nodebuffer", buf).toString("utf-8"); + } + buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf); + return buf2string(buf); + }; + function Utf8DecodeWorker() { + GenericWorker.call(this, "utf-8 decode"); + this.leftOver = null; + } + utils.inherits(Utf8DecodeWorker, GenericWorker); + Utf8DecodeWorker.prototype.processChunk = function(chunk) { + var data = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data); + if (this.leftOver && this.leftOver.length) { + if (support.uint8array) { + var previousData = data; + data = new Uint8Array(previousData.length + this.leftOver.length); + data.set(this.leftOver, 0); + data.set(previousData, this.leftOver.length); + } else { + data = this.leftOver.concat(data); + } + this.leftOver = null; + } + var nextBoundary = utf8border(data); + var usableData = data; + if (nextBoundary !== data.length) { + if (support.uint8array) { + usableData = data.subarray(0, nextBoundary); + this.leftOver = data.subarray(nextBoundary, data.length); + } else { + usableData = data.slice(0, nextBoundary); + this.leftOver = data.slice(nextBoundary, data.length); + } + } + this.push({ + data: exports2.utf8decode(usableData), + meta: chunk.meta + }); + }; + Utf8DecodeWorker.prototype.flush = function() { + if (this.leftOver && this.leftOver.length) { + this.push({ + data: exports2.utf8decode(this.leftOver), + meta: {} + }); + this.leftOver = null; + } + }; + exports2.Utf8DecodeWorker = Utf8DecodeWorker; + function Utf8EncodeWorker() { + GenericWorker.call(this, "utf-8 encode"); + } + utils.inherits(Utf8EncodeWorker, GenericWorker); + Utf8EncodeWorker.prototype.processChunk = function(chunk) { + this.push({ + data: exports2.utf8encode(chunk.data), + meta: chunk.meta + }); + }; + exports2.Utf8EncodeWorker = Utf8EncodeWorker; + } +}); + +// node_modules/jszip/lib/stream/ConvertWorker.js +var require_ConvertWorker = __commonJS({ + "node_modules/jszip/lib/stream/ConvertWorker.js"(exports2, module) { + "use strict"; + var GenericWorker = require_GenericWorker(); + var utils = require_utils(); + function ConvertWorker(destType) { + GenericWorker.call(this, "ConvertWorker to " + destType); + this.destType = destType; + } + utils.inherits(ConvertWorker, GenericWorker); + ConvertWorker.prototype.processChunk = function(chunk) { + this.push({ + data: utils.transformTo(this.destType, chunk.data), + meta: chunk.meta + }); + }; + module.exports = ConvertWorker; + } +}); + +// node_modules/jszip/lib/nodejs/NodejsStreamOutputAdapter.js +var require_NodejsStreamOutputAdapter = __commonJS({ + "node_modules/jszip/lib/nodejs/NodejsStreamOutputAdapter.js"(exports2, module) { + "use strict"; + var Readable = require_readable().Readable; + var utils = require_utils(); + utils.inherits(NodejsStreamOutputAdapter, Readable); + function NodejsStreamOutputAdapter(helper, options, updateCb) { + Readable.call(this, options); + this._helper = helper; + var self2 = this; + helper.on("data", function(data, meta) { + if (!self2.push(data)) { + self2._helper.pause(); + } + if (updateCb) { + updateCb(meta); + } + }).on("error", function(e) { + self2.emit("error", e); + }).on("end", function() { + self2.push(null); + }); + } + NodejsStreamOutputAdapter.prototype._read = function() { + this._helper.resume(); + }; + module.exports = NodejsStreamOutputAdapter; + } +}); + +// node_modules/jszip/lib/stream/StreamHelper.js +var require_StreamHelper = __commonJS({ + "node_modules/jszip/lib/stream/StreamHelper.js"(exports2, module) { + "use strict"; + var utils = require_utils(); + var ConvertWorker = require_ConvertWorker(); + var GenericWorker = require_GenericWorker(); + var base64 = require_base64(); + var support = require_support(); + var external = require_external(); + var NodejsStreamOutputAdapter = null; + if (support.nodestream) { + try { + NodejsStreamOutputAdapter = require_NodejsStreamOutputAdapter(); + } catch (e) { + } + } + function transformZipOutput(type, content, mimeType) { + switch (type) { + case "blob": + return utils.newBlob(utils.transformTo("arraybuffer", content), mimeType); + case "base64": + return base64.encode(content); + default: + return utils.transformTo(type, content); + } + } + function concat(type, dataArray) { + var i, index = 0, res = null, totalLength = 0; + for (i = 0; i < dataArray.length; i++) { + totalLength += dataArray[i].length; + } + switch (type) { + case "string": + return dataArray.join(""); + case "array": + return Array.prototype.concat.apply([], dataArray); + case "uint8array": + res = new Uint8Array(totalLength); + for (i = 0; i < dataArray.length; i++) { + res.set(dataArray[i], index); + index += dataArray[i].length; + } + return res; + case "nodebuffer": + return Buffer.concat(dataArray); + default: + throw new Error("concat : unsupported type '" + type + "'"); + } + } + function accumulate(helper, updateCallback) { + return new external.Promise(function(resolve, reject) { + var dataArray = []; + var chunkType = helper._internalType, resultType = helper._outputType, mimeType = helper._mimeType; + helper.on("data", function(data, meta) { + dataArray.push(data); + if (updateCallback) { + updateCallback(meta); + } + }).on("error", function(err) { + dataArray = []; + reject(err); + }).on("end", function() { + try { + var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType); + resolve(result); + } catch (e) { + reject(e); + } + dataArray = []; + }).resume(); + }); + } + function StreamHelper(worker, outputType, mimeType) { + var internalType = outputType; + switch (outputType) { + case "blob": + case "arraybuffer": + internalType = "uint8array"; + break; + case "base64": + internalType = "string"; + break; + } + try { + this._internalType = internalType; + this._outputType = outputType; + this._mimeType = mimeType; + utils.checkSupport(internalType); + this._worker = worker.pipe(new ConvertWorker(internalType)); + worker.lock(); + } catch (e) { + this._worker = new GenericWorker("error"); + this._worker.error(e); + } + } + StreamHelper.prototype = { + /** + * Listen a StreamHelper, accumulate its content and concatenate it into a + * complete block. + * @param {Function} updateCb the update callback. + * @return Promise the promise for the accumulation. + */ + accumulate: function(updateCb) { + return accumulate(this, updateCb); + }, + /** + * Add a listener on an event triggered on a stream. + * @param {String} evt the name of the event + * @param {Function} fn the listener + * @return {StreamHelper} the current helper. + */ + on: function(evt, fn) { + var self2 = this; + if (evt === "data") { + this._worker.on(evt, function(chunk) { + fn.call(self2, chunk.data, chunk.meta); + }); + } else { + this._worker.on(evt, function() { + utils.delay(fn, arguments, self2); + }); + } + return this; + }, + /** + * Resume the flow of chunks. + * @return {StreamHelper} the current helper. + */ + resume: function() { + utils.delay(this._worker.resume, [], this._worker); + return this; + }, + /** + * Pause the flow of chunks. + * @return {StreamHelper} the current helper. + */ + pause: function() { + this._worker.pause(); + return this; + }, + /** + * Return a nodejs stream for this helper. + * @param {Function} updateCb the update callback. + * @return {NodejsStreamOutputAdapter} the nodejs stream. + */ + toNodejsStream: function(updateCb) { + utils.checkSupport("nodestream"); + if (this._outputType !== "nodebuffer") { + throw new Error(this._outputType + " is not supported by this method"); + } + return new NodejsStreamOutputAdapter(this, { + objectMode: this._outputType !== "nodebuffer" + }, updateCb); + } + }; + module.exports = StreamHelper; + } +}); + +// node_modules/jszip/lib/defaults.js +var require_defaults = __commonJS({ + "node_modules/jszip/lib/defaults.js"(exports2) { + "use strict"; + exports2.base64 = false; + exports2.binary = false; + exports2.dir = false; + exports2.createFolders = true; + exports2.date = null; + exports2.compression = null; + exports2.compressionOptions = null; + exports2.comment = null; + exports2.unixPermissions = null; + exports2.dosPermissions = null; + } +}); + +// node_modules/jszip/lib/stream/DataWorker.js +var require_DataWorker = __commonJS({ + "node_modules/jszip/lib/stream/DataWorker.js"(exports2, module) { + "use strict"; + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var DEFAULT_BLOCK_SIZE = 16 * 1024; + function DataWorker(dataP) { + GenericWorker.call(this, "DataWorker"); + var self2 = this; + this.dataIsReady = false; + this.index = 0; + this.max = 0; + this.data = null; + this.type = ""; + this._tickScheduled = false; + dataP.then(function(data) { + self2.dataIsReady = true; + self2.data = data; + self2.max = data && data.length || 0; + self2.type = utils.getTypeOf(data); + if (!self2.isPaused) { + self2._tickAndRepeat(); + } + }, function(e) { + self2.error(e); + }); + } + utils.inherits(DataWorker, GenericWorker); + DataWorker.prototype.cleanUp = function() { + GenericWorker.prototype.cleanUp.call(this); + this.data = null; + }; + DataWorker.prototype.resume = function() { + if (!GenericWorker.prototype.resume.call(this)) { + return false; + } + if (!this._tickScheduled && this.dataIsReady) { + this._tickScheduled = true; + utils.delay(this._tickAndRepeat, [], this); + } + return true; + }; + DataWorker.prototype._tickAndRepeat = function() { + this._tickScheduled = false; + if (this.isPaused || this.isFinished) { + return; + } + this._tick(); + if (!this.isFinished) { + utils.delay(this._tickAndRepeat, [], this); + this._tickScheduled = true; + } + }; + DataWorker.prototype._tick = function() { + if (this.isPaused || this.isFinished) { + return false; + } + var size = DEFAULT_BLOCK_SIZE; + var data = null, nextIndex = Math.min(this.max, this.index + size); + if (this.index >= this.max) { + return this.end(); + } else { + switch (this.type) { + case "string": + data = this.data.substring(this.index, nextIndex); + break; + case "uint8array": + data = this.data.subarray(this.index, nextIndex); + break; + case "array": + case "nodebuffer": + data = this.data.slice(this.index, nextIndex); + break; + } + this.index = nextIndex; + return this.push({ + data, + meta: { + percent: this.max ? this.index / this.max * 100 : 0 + } + }); + } + }; + module.exports = DataWorker; + } +}); + +// node_modules/jszip/lib/crc32.js +var require_crc32 = __commonJS({ + "node_modules/jszip/lib/crc32.js"(exports2, module) { + "use strict"; + var utils = require_utils(); + function makeTable() { + var c, table = []; + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1; + } + table[n] = c; + } + return table; + } + var crcTable = makeTable(); + function crc32(crc, buf, len, pos) { + var t = crcTable, end = pos + len; + crc = crc ^ -1; + for (var i = pos; i < end; i++) { + crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 255]; + } + return crc ^ -1; + } + function crc32str(crc, str, len, pos) { + var t = crcTable, end = pos + len; + crc = crc ^ -1; + for (var i = pos; i < end; i++) { + crc = crc >>> 8 ^ t[(crc ^ str.charCodeAt(i)) & 255]; + } + return crc ^ -1; + } + module.exports = function crc32wrapper(input, crc) { + if (typeof input === "undefined" || !input.length) { + return 0; + } + var isArray = utils.getTypeOf(input) !== "string"; + if (isArray) { + return crc32(crc | 0, input, input.length, 0); + } else { + return crc32str(crc | 0, input, input.length, 0); + } + }; + } +}); + +// node_modules/jszip/lib/stream/Crc32Probe.js +var require_Crc32Probe = __commonJS({ + "node_modules/jszip/lib/stream/Crc32Probe.js"(exports2, module) { + "use strict"; + var GenericWorker = require_GenericWorker(); + var crc32 = require_crc32(); + var utils = require_utils(); + function Crc32Probe() { + GenericWorker.call(this, "Crc32Probe"); + this.withStreamInfo("crc32", 0); + } + utils.inherits(Crc32Probe, GenericWorker); + Crc32Probe.prototype.processChunk = function(chunk) { + this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0); + this.push(chunk); + }; + module.exports = Crc32Probe; + } +}); + +// node_modules/jszip/lib/stream/DataLengthProbe.js +var require_DataLengthProbe = __commonJS({ + "node_modules/jszip/lib/stream/DataLengthProbe.js"(exports2, module) { + "use strict"; + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + function DataLengthProbe(propName2) { + GenericWorker.call(this, "DataLengthProbe for " + propName2); + this.propName = propName2; + this.withStreamInfo(propName2, 0); + } + utils.inherits(DataLengthProbe, GenericWorker); + DataLengthProbe.prototype.processChunk = function(chunk) { + if (chunk) { + var length = this.streamInfo[this.propName] || 0; + this.streamInfo[this.propName] = length + chunk.data.length; + } + GenericWorker.prototype.processChunk.call(this, chunk); + }; + module.exports = DataLengthProbe; + } +}); + +// node_modules/jszip/lib/compressedObject.js +var require_compressedObject = __commonJS({ + "node_modules/jszip/lib/compressedObject.js"(exports2, module) { + "use strict"; + var external = require_external(); + var DataWorker = require_DataWorker(); + var Crc32Probe = require_Crc32Probe(); + var DataLengthProbe = require_DataLengthProbe(); + function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) { + this.compressedSize = compressedSize; + this.uncompressedSize = uncompressedSize; + this.crc32 = crc32; + this.compression = compression; + this.compressedContent = data; + } + CompressedObject.prototype = { + /** + * Create a worker to get the uncompressed content. + * @return {GenericWorker} the worker. + */ + getContentWorker: function() { + var worker = new DataWorker(external.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new DataLengthProbe("data_length")); + var that = this; + worker.on("end", function() { + if (this.streamInfo["data_length"] !== that.uncompressedSize) { + throw new Error("Bug : uncompressed data size mismatch"); + } + }); + return worker; + }, + /** + * Create a worker to get the compressed content. + * @return {GenericWorker} the worker. + */ + getCompressedWorker: function() { + return new DataWorker(external.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize", this.compressedSize).withStreamInfo("uncompressedSize", this.uncompressedSize).withStreamInfo("crc32", this.crc32).withStreamInfo("compression", this.compression); + } + }; + CompressedObject.createWorkerFrom = function(uncompressedWorker, compression, compressionOptions) { + return uncompressedWorker.pipe(new Crc32Probe()).pipe(new DataLengthProbe("uncompressedSize")).pipe(compression.compressWorker(compressionOptions)).pipe(new DataLengthProbe("compressedSize")).withStreamInfo("compression", compression); + }; + module.exports = CompressedObject; + } +}); + +// node_modules/jszip/lib/zipObject.js +var require_zipObject = __commonJS({ + "node_modules/jszip/lib/zipObject.js"(exports2, module) { + "use strict"; + var StreamHelper = require_StreamHelper(); + var DataWorker = require_DataWorker(); + var utf8 = require_utf8(); + var CompressedObject = require_compressedObject(); + var GenericWorker = require_GenericWorker(); + var ZipObject = function(name, data, options) { + this.name = name; + this.dir = options.dir; + this.date = options.date; + this.comment = options.comment; + this.unixPermissions = options.unixPermissions; + this.dosPermissions = options.dosPermissions; + this._data = data; + this._dataBinary = options.binary; + this.options = { + compression: options.compression, + compressionOptions: options.compressionOptions + }; + }; + ZipObject.prototype = { + /** + * Create an internal stream for the content of this object. + * @param {String} type the type of each chunk. + * @return StreamHelper the stream. + */ + internalStream: function(type) { + var result = null, outputType = "string"; + try { + if (!type) { + throw new Error("No output type specified."); + } + outputType = type.toLowerCase(); + var askUnicodeString = outputType === "string" || outputType === "text"; + if (outputType === "binarystring" || outputType === "text") { + outputType = "string"; + } + result = this._decompressWorker(); + var isUnicodeString = !this._dataBinary; + if (isUnicodeString && !askUnicodeString) { + result = result.pipe(new utf8.Utf8EncodeWorker()); + } + if (!isUnicodeString && askUnicodeString) { + result = result.pipe(new utf8.Utf8DecodeWorker()); + } + } catch (e) { + result = new GenericWorker("error"); + result.error(e); + } + return new StreamHelper(result, outputType, ""); + }, + /** + * Prepare the content in the asked type. + * @param {String} type the type of the result. + * @param {Function} onUpdate a function to call on each internal update. + * @return Promise the promise of the result. + */ + async: function(type, onUpdate) { + return this.internalStream(type).accumulate(onUpdate); + }, + /** + * Prepare the content as a nodejs stream. + * @param {String} type the type of each chunk. + * @param {Function} onUpdate a function to call on each internal update. + * @return Stream the stream. + */ + nodeStream: function(type, onUpdate) { + return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate); + }, + /** + * Return a worker for the compressed content. + * @private + * @param {Object} compression the compression object to use. + * @param {Object} compressionOptions the options to use when compressing. + * @return Worker the worker. + */ + _compressWorker: function(compression, compressionOptions) { + if (this._data instanceof CompressedObject && this._data.compression.magic === compression.magic) { + return this._data.getCompressedWorker(); + } else { + var result = this._decompressWorker(); + if (!this._dataBinary) { + result = result.pipe(new utf8.Utf8EncodeWorker()); + } + return CompressedObject.createWorkerFrom(result, compression, compressionOptions); + } + }, + /** + * Return a worker for the decompressed content. + * @private + * @return Worker the worker. + */ + _decompressWorker: function() { + if (this._data instanceof CompressedObject) { + return this._data.getContentWorker(); + } else if (this._data instanceof GenericWorker) { + return this._data; + } else { + return new DataWorker(this._data); + } + } + }; + var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"]; + var removedFn = function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }; + for (i = 0; i < removedMethods.length; i++) { + ZipObject.prototype[removedMethods[i]] = removedFn; + } + var i; + module.exports = ZipObject; + } +}); + +// node_modules/pako/lib/utils/common.js +var require_common = __commonJS({ + "node_modules/pako/lib/utils/common.js"(exports2) { + "use strict"; + var TYPED_OK = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Int32Array !== "undefined"; + function _has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); + } + exports2.assign = function(obj) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { + continue; + } + if (typeof source !== "object") { + throw new TypeError(source + "must be non-object"); + } + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + return obj; + }; + exports2.shrinkBuf = function(buf, size) { + if (buf.length === size) { + return buf; + } + if (buf.subarray) { + return buf.subarray(0, size); + } + buf.length = size; + return buf; + }; + var fnTyped = { + arraySet: function(dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function(chunks) { + var i, l, len, pos, chunk, result; + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + return result; + } + }; + var fnUntyped = { + arraySet: function(dest, src, src_offs, len, dest_offs) { + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function(chunks) { + return [].concat.apply([], chunks); + } + }; + exports2.setTyped = function(on) { + if (on) { + exports2.Buf8 = Uint8Array; + exports2.Buf16 = Uint16Array; + exports2.Buf32 = Int32Array; + exports2.assign(exports2, fnTyped); + } else { + exports2.Buf8 = Array; + exports2.Buf16 = Array; + exports2.Buf32 = Array; + exports2.assign(exports2, fnUntyped); + } + }; + exports2.setTyped(TYPED_OK); + } +}); + +// node_modules/pako/lib/zlib/trees.js +var require_trees = __commonJS({ + "node_modules/pako/lib/zlib/trees.js"(exports2) { + "use strict"; + var utils = require_common(); + var Z_FIXED = 4; + var Z_BINARY = 0; + var Z_TEXT = 1; + var Z_UNKNOWN = 2; + function zero(buf) { + var len = buf.length; + while (--len >= 0) { + buf[len] = 0; + } + } + var STORED_BLOCK = 0; + var STATIC_TREES = 1; + var DYN_TREES = 2; + var MIN_MATCH = 3; + var MAX_MATCH = 258; + var LENGTH_CODES = 29; + var LITERALS = 256; + var L_CODES = LITERALS + 1 + LENGTH_CODES; + var D_CODES = 30; + var BL_CODES = 19; + var HEAP_SIZE = 2 * L_CODES + 1; + var MAX_BITS = 15; + var Buf_size = 16; + var MAX_BL_BITS = 7; + var END_BLOCK = 256; + var REP_3_6 = 16; + var REPZ_3_10 = 17; + var REPZ_11_138 = 18; + var extra_lbits = ( + /* extra bits for each length code */ + [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0] + ); + var extra_dbits = ( + /* extra bits for each distance code */ + [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13] + ); + var extra_blbits = ( + /* extra bits for each bit length code */ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7] + ); + var bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + var DIST_CODE_LEN = 512; + var static_ltree = new Array((L_CODES + 2) * 2); + zero(static_ltree); + var static_dtree = new Array(D_CODES * 2); + zero(static_dtree); + var _dist_code = new Array(DIST_CODE_LEN); + zero(_dist_code); + var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); + zero(_length_code); + var base_length = new Array(LENGTH_CODES); + zero(base_length); + var base_dist = new Array(D_CODES); + zero(base_dist); + function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + this.static_tree = static_tree; + this.extra_bits = extra_bits; + this.extra_base = extra_base; + this.elems = elems; + this.max_length = max_length; + this.has_stree = static_tree && static_tree.length; + } + var static_l_desc; + var static_d_desc; + var static_bl_desc; + function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; + this.max_code = 0; + this.stat_desc = stat_desc; + } + function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; + } + function put_short(s, w) { + s.pending_buf[s.pending++] = w & 255; + s.pending_buf[s.pending++] = w >>> 8 & 255; + } + function send_bits(s, value, length) { + if (s.bi_valid > Buf_size - length) { + s.bi_buf |= value << s.bi_valid & 65535; + put_short(s, s.bi_buf); + s.bi_buf = value >> Buf_size - s.bi_valid; + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= value << s.bi_valid & 65535; + s.bi_valid += length; + } + } + function send_code(s, c, tree) { + send_bits( + s, + tree[c * 2], + tree[c * 2 + 1] + /*.Len*/ + ); + } + function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; + } + function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 255; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } + } + function gen_bitlen(s, desc) { + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; + var n, m; + var bits; + var xbits; + var f; + var overflow = 0; + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + tree[s.heap[s.heap_max] * 2 + 1] = 0; + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1] * 2 + 1] + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1] = bits; + if (n > max_code) { + continue; + } + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1] + xbits); + } + } + if (overflow === 0) { + return; + } + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { + bits--; + } + s.bl_count[bits]--; + s.bl_count[bits + 1] += 2; + s.bl_count[max_length]--; + overflow -= 2; + } while (overflow > 0); + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { + continue; + } + if (tree[m * 2 + 1] !== bits) { + s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2]; + tree[m * 2 + 1] = bits; + } + n--; + } + } + } + function gen_codes(tree, max_code, bl_count) { + var next_code = new Array(MAX_BITS + 1); + var code = 0; + var bits; + var n; + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = code + bl_count[bits - 1] << 1; + } + for (n = 0; n <= max_code; n++) { + var len = tree[n * 2 + 1]; + if (len === 0) { + continue; + } + tree[n * 2] = bi_reverse(next_code[len]++, len); + } + } + function tr_static_init() { + var n; + var bits; + var length; + var code; + var dist; + var bl_count = new Array(MAX_BITS + 1); + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < 1 << extra_lbits[code]; n++) { + _length_code[length++] = code; + } + } + _length_code[length - 1] = code; + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < 1 << extra_dbits[code]; n++) { + _dist_code[dist++] = code; + } + } + dist >>= 7; + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < 1 << extra_dbits[code] - 7; n++) { + _dist_code[256 + dist++] = code; + } + } + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1] = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1] = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1] = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1] = 8; + n++; + bl_count[8]++; + } + gen_codes(static_ltree, L_CODES + 1, bl_count); + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1] = 5; + static_dtree[n * 2] = bi_reverse(n, 5); + } + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + } + function init_block(s) { + var n; + for (n = 0; n < L_CODES; n++) { + s.dyn_ltree[n * 2] = 0; + } + for (n = 0; n < D_CODES; n++) { + s.dyn_dtree[n * 2] = 0; + } + for (n = 0; n < BL_CODES; n++) { + s.bl_tree[n * 2] = 0; + } + s.dyn_ltree[END_BLOCK * 2] = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; + } + function bi_windup(s) { + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; + } + function copy_block(s, buf, len, header) { + bi_windup(s); + if (header) { + put_short(s, len); + put_short(s, ~len); + } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; + } + function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return tree[_n2] < tree[_m2] || tree[_n2] === tree[_m2] && depth[n] <= depth[m]; + } + function pqdownheap(s, tree, k) { + var v = s.heap[k]; + var j = k << 1; + while (j <= s.heap_len) { + if (j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + if (smaller(tree, v, s.heap[j], s.depth)) { + break; + } + s.heap[k] = s.heap[j]; + k = j; + j <<= 1; + } + s.heap[k] = v; + } + function compress_block(s, ltree, dtree) { + var dist; + var lc; + var lx = 0; + var code; + var extra; + if (s.last_lit !== 0) { + do { + dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1]; + lc = s.pending_buf[s.l_buf + lx]; + lx++; + if (dist === 0) { + send_code(s, lc, ltree); + } else { + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); + } + dist--; + code = d_code(dist); + send_code(s, code, dtree); + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); + } + } + } while (lx < s.last_lit); + } + send_code(s, END_BLOCK, ltree); + } + function build_tree(s, desc) { + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; + var max_code = -1; + var node; + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + for (n = 0; n < elems; n++) { + if (tree[n * 2] !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + } else { + tree[n * 2 + 1] = 0; + } + } + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0; + tree[node * 2] = 1; + s.depth[node] = 0; + s.opt_len--; + if (has_stree) { + s.static_len -= stree[node * 2 + 1]; + } + } + desc.max_code = max_code; + for (n = s.heap_len >> 1; n >= 1; n--) { + pqdownheap(s, tree, n); + } + node = elems; + do { + n = s.heap[ + 1 + /*SMALLEST*/ + ]; + s.heap[ + 1 + /*SMALLEST*/ + ] = s.heap[s.heap_len--]; + pqdownheap( + s, + tree, + 1 + /*SMALLEST*/ + ); + m = s.heap[ + 1 + /*SMALLEST*/ + ]; + s.heap[--s.heap_max] = n; + s.heap[--s.heap_max] = m; + tree[node * 2] = tree[n * 2] + tree[m * 2]; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1] = tree[m * 2 + 1] = node; + s.heap[ + 1 + /*SMALLEST*/ + ] = node++; + pqdownheap( + s, + tree, + 1 + /*SMALLEST*/ + ); + } while (s.heap_len >= 2); + s.heap[--s.heap_max] = s.heap[ + 1 + /*SMALLEST*/ + ]; + gen_bitlen(s, desc); + gen_codes(tree, max_code, s.bl_count); + } + function scan_tree(s, tree, max_code) { + var n; + var prevlen = -1; + var curlen; + var nextlen = tree[0 * 2 + 1]; + var count = 0; + var max_count = 7; + var min_count = 4; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1] = 65535; + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]; + if (++count < max_count && curlen === nextlen) { + continue; + } else if (count < min_count) { + s.bl_tree[curlen * 2] += count; + } else if (curlen !== 0) { + if (curlen !== prevlen) { + s.bl_tree[curlen * 2]++; + } + s.bl_tree[REP_3_6 * 2]++; + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]++; + } else { + s.bl_tree[REPZ_11_138 * 2]++; + } + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + } else { + max_count = 7; + min_count = 4; + } + } + } + function send_tree(s, tree, max_code) { + var n; + var prevlen = -1; + var curlen; + var nextlen = tree[0 * 2 + 1]; + var count = 0; + var max_count = 7; + var min_count = 4; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]; + if (++count < max_count && curlen === nextlen) { + continue; + } else if (count < min_count) { + do { + send_code(s, curlen, s.bl_tree); + } while (--count !== 0); + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + } else { + max_count = 7; + min_count = 4; + } + } + } + function build_bl_tree(s) { + var max_blindex; + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + build_tree(s, s.bl_desc); + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1] !== 0) { + break; + } + } + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + return max_blindex; + } + function send_all_trees(s, lcodes, dcodes, blcodes) { + var rank; + send_bits(s, lcodes - 257, 5); + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); + for (rank = 0; rank < blcodes; rank++) { + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1], 3); + } + send_tree(s, s.dyn_ltree, lcodes - 1); + send_tree(s, s.dyn_dtree, dcodes - 1); + } + function detect_data_type(s) { + var black_mask = 4093624447; + var n; + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if (black_mask & 1 && s.dyn_ltree[n * 2] !== 0) { + return Z_BINARY; + } + } + if (s.dyn_ltree[9 * 2] !== 0 || s.dyn_ltree[10 * 2] !== 0 || s.dyn_ltree[13 * 2] !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2] !== 0) { + return Z_TEXT; + } + } + return Z_BINARY; + } + var static_init_done = false; + function _tr_init(s) { + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + s.bi_buf = 0; + s.bi_valid = 0; + init_block(s); + } + function _tr_stored_block(s, buf, stored_len, last) { + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); + copy_block(s, buf, stored_len, true); + } + function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); + } + function _tr_flush_block(s, buf, stored_len, last) { + var opt_lenb, static_lenb; + var max_blindex = 0; + if (s.level > 0) { + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + build_tree(s, s.l_desc); + build_tree(s, s.d_desc); + max_blindex = build_bl_tree(s); + opt_lenb = s.opt_len + 3 + 7 >>> 3; + static_lenb = s.static_len + 3 + 7 >>> 3; + if (static_lenb <= opt_lenb) { + opt_lenb = static_lenb; + } + } else { + opt_lenb = static_lenb = stored_len + 5; + } + if (stored_len + 4 <= opt_lenb && buf !== -1) { + _tr_stored_block(s, buf, stored_len, last); + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + init_block(s); + if (last) { + bi_windup(s); + } + } + function _tr_tally(s, dist, lc) { + s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 255; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 255; + s.pending_buf[s.l_buf + s.last_lit] = lc & 255; + s.last_lit++; + if (dist === 0) { + s.dyn_ltree[lc * 2]++; + } else { + s.matches++; + dist--; + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]++; + s.dyn_dtree[d_code(dist) * 2]++; + } + return s.last_lit === s.lit_bufsize - 1; + } + exports2._tr_init = _tr_init; + exports2._tr_stored_block = _tr_stored_block; + exports2._tr_flush_block = _tr_flush_block; + exports2._tr_tally = _tr_tally; + exports2._tr_align = _tr_align; + } +}); + +// node_modules/pako/lib/zlib/adler32.js +var require_adler32 = __commonJS({ + "node_modules/pako/lib/zlib/adler32.js"(exports2, module) { + "use strict"; + function adler32(adler, buf, len, pos) { + var s1 = adler & 65535 | 0, s2 = adler >>> 16 & 65535 | 0, n = 0; + while (len !== 0) { + n = len > 2e3 ? 2e3 : len; + len -= n; + do { + s1 = s1 + buf[pos++] | 0; + s2 = s2 + s1 | 0; + } while (--n); + s1 %= 65521; + s2 %= 65521; + } + return s1 | s2 << 16 | 0; + } + module.exports = adler32; + } +}); + +// node_modules/pako/lib/zlib/crc32.js +var require_crc322 = __commonJS({ + "node_modules/pako/lib/zlib/crc32.js"(exports2, module) { + "use strict"; + function makeTable() { + var c, table = []; + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1; + } + table[n] = c; + } + return table; + } + var crcTable = makeTable(); + function crc32(crc, buf, len, pos) { + var t = crcTable, end = pos + len; + crc ^= -1; + for (var i = pos; i < end; i++) { + crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 255]; + } + return crc ^ -1; + } + module.exports = crc32; + } +}); + +// node_modules/pako/lib/zlib/messages.js +var require_messages = __commonJS({ + "node_modules/pako/lib/zlib/messages.js"(exports2, module) { + "use strict"; + module.exports = { + 2: "need dictionary", + /* Z_NEED_DICT 2 */ + 1: "stream end", + /* Z_STREAM_END 1 */ + 0: "", + /* Z_OK 0 */ + "-1": "file error", + /* Z_ERRNO (-1) */ + "-2": "stream error", + /* Z_STREAM_ERROR (-2) */ + "-3": "data error", + /* Z_DATA_ERROR (-3) */ + "-4": "insufficient memory", + /* Z_MEM_ERROR (-4) */ + "-5": "buffer error", + /* Z_BUF_ERROR (-5) */ + "-6": "incompatible version" + /* Z_VERSION_ERROR (-6) */ + }; + } +}); + +// node_modules/pako/lib/zlib/deflate.js +var require_deflate = __commonJS({ + "node_modules/pako/lib/zlib/deflate.js"(exports2) { + "use strict"; + var utils = require_common(); + var trees = require_trees(); + var adler32 = require_adler32(); + var crc32 = require_crc322(); + var msg = require_messages(); + var Z_NO_FLUSH = 0; + var Z_PARTIAL_FLUSH = 1; + var Z_FULL_FLUSH = 3; + var Z_FINISH = 4; + var Z_BLOCK = 5; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_STREAM_ERROR = -2; + var Z_DATA_ERROR = -3; + var Z_BUF_ERROR = -5; + var Z_DEFAULT_COMPRESSION = -1; + var Z_FILTERED = 1; + var Z_HUFFMAN_ONLY = 2; + var Z_RLE = 3; + var Z_FIXED = 4; + var Z_DEFAULT_STRATEGY = 0; + var Z_UNKNOWN = 2; + var Z_DEFLATED = 8; + var MAX_MEM_LEVEL = 9; + var MAX_WBITS = 15; + var DEF_MEM_LEVEL = 8; + var LENGTH_CODES = 29; + var LITERALS = 256; + var L_CODES = LITERALS + 1 + LENGTH_CODES; + var D_CODES = 30; + var BL_CODES = 19; + var HEAP_SIZE = 2 * L_CODES + 1; + var MAX_BITS = 15; + var MIN_MATCH = 3; + var MAX_MATCH = 258; + var MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1; + var PRESET_DICT = 32; + var INIT_STATE = 42; + var EXTRA_STATE = 69; + var NAME_STATE = 73; + var COMMENT_STATE = 91; + var HCRC_STATE = 103; + var BUSY_STATE = 113; + var FINISH_STATE = 666; + var BS_NEED_MORE = 1; + var BS_BLOCK_DONE = 2; + var BS_FINISH_STARTED = 3; + var BS_FINISH_DONE = 4; + var OS_CODE = 3; + function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; + } + function rank(f) { + return (f << 1) - (f > 4 ? 9 : 0); + } + function zero(buf) { + var len = buf.length; + while (--len >= 0) { + buf[len] = 0; + } + } + function flush_pending(strm) { + var s = strm.state; + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { + return; + } + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } + } + function flush_block_only(s, last) { + trees._tr_flush_block(s, s.block_start >= 0 ? s.block_start : -1, s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); + } + function put_byte(s, b) { + s.pending_buf[s.pending++] = b; + } + function putShortMSB(s, b) { + s.pending_buf[s.pending++] = b >>> 8 & 255; + s.pending_buf[s.pending++] = b & 255; + } + function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + if (len > size) { + len = size; + } + if (len === 0) { + return 0; + } + strm.avail_in -= len; + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + strm.next_in += len; + strm.total_in += len; + return len; + } + function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; + var scan = s.strstart; + var match; + var len; + var best_len = s.prev_length; + var nice_match = s.nice_match; + var limit = s.strstart > s.w_size - MIN_LOOKAHEAD ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0; + var _win = s.window; + var wmask = s.w_mask; + var prev = s.prev; + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + if (nice_match > s.lookahead) { + nice_match = s.lookahead; + } + do { + match = cur_match; + if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { + continue; + } + scan += 2; + match++; + do { + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; + } + function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + do { + more = s.window_size - s.lookahead - s.strstart; + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + s.block_start -= _w_size; + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = m >= _w_size ? m - _w_size : 0; + } while (--n); + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = m >= _w_size ? m - _w_size : 0; + } while (--n); + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + 1]) & s.hash_mask; + while (s.insert) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + } + function deflate_stored(s, flush) { + var max_block_size = 65535; + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + for (; ; ) { + if (s.lookahead <= 1) { + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + s.strstart += s.lookahead; + s.lookahead = 0; + var max_start = s.block_start + max_block_size; + if (s.strstart === 0 || s.strstart >= max_start) { + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + if (s.strstart - s.block_start >= s.w_size - MIN_LOOKAHEAD) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = 0; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.strstart > s.block_start) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_NEED_MORE; + } + function deflate_fast(s, flush) { + var hash_head; + var bflush; + for (; ; ) { + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + hash_head = 0; + if (s.lookahead >= MIN_MATCH) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + if (hash_head !== 0 && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) { + s.match_length = longest_match(s, hash_head); + } + if (s.match_length >= MIN_MATCH) { + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + s.lookahead -= s.match_length; + if (s.match_length <= s.max_lazy_match && s.lookahead >= MIN_MATCH) { + s.match_length--; + do { + s.strstart++; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } while (--s.match_length !== 0); + s.strstart++; + } else { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + 1]) & s.hash_mask; + } + } else { + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + } + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function deflate_slow(s, flush) { + var hash_head; + var bflush; + var max_insert; + for (; ; ) { + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + hash_head = 0; + if (s.lookahead >= MIN_MATCH) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + if (hash_head !== 0 && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) { + s.match_length = longest_match(s, hash_head); + if (s.match_length <= 5 && (s.strategy === Z_FILTERED || s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096)) { + s.match_length = MIN_MATCH - 1; + } + } + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } else if (s.match_available) { + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + if (bflush) { + flush_block_only(s, false); + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + if (s.match_available) { + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function deflate_rle(s, flush) { + var bflush; + var prev; + var scan, strend; + var _win = s.window; + for (; ; ) { + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + } + if (s.match_length >= MIN_MATCH) { + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + } + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = 0; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function deflate_huff(s, flush) { + var bflush; + for (; ; ) { + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; + } + } + s.match_length = 0; + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = 0; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; + } + var configuration_table; + configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), + /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), + /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), + /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), + /* 3 */ + new Config(4, 4, 16, 16, deflate_slow), + /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), + /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), + /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), + /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), + /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) + /* 9 max compression */ + ]; + function lm_init(s) { + s.window_size = 2 * s.w_size; + zero(s.head); + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; + } + function DeflateState() { + this.strm = null; + this.status = 0; + this.pending_buf = null; + this.pending_buf_size = 0; + this.pending_out = 0; + this.pending = 0; + this.wrap = 0; + this.gzhead = null; + this.gzindex = 0; + this.method = Z_DEFLATED; + this.last_flush = -1; + this.w_size = 0; + this.w_bits = 0; + this.w_mask = 0; + this.window = null; + this.window_size = 0; + this.prev = null; + this.head = null; + this.ins_h = 0; + this.hash_size = 0; + this.hash_bits = 0; + this.hash_mask = 0; + this.hash_shift = 0; + this.block_start = 0; + this.match_length = 0; + this.prev_match = 0; + this.match_available = 0; + this.strstart = 0; + this.match_start = 0; + this.lookahead = 0; + this.prev_length = 0; + this.max_chain_length = 0; + this.max_lazy_match = 0; + this.level = 0; + this.strategy = 0; + this.good_match = 0; + this.nice_match = 0; + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + this.l_desc = null; + this.d_desc = null; + this.bl_desc = null; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + this.heap = new utils.Buf16(2 * L_CODES + 1); + zero(this.heap); + this.heap_len = 0; + this.heap_max = 0; + this.depth = new utils.Buf16(2 * L_CODES + 1); + zero(this.depth); + this.l_buf = 0; + this.lit_bufsize = 0; + this.last_lit = 0; + this.d_buf = 0; + this.opt_len = 0; + this.static_len = 0; + this.matches = 0; + this.insert = 0; + this.bi_buf = 0; + this.bi_valid = 0; + } + function deflateResetKeep(strm) { + var s; + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + s = strm.state; + s.pending = 0; + s.pending_out = 0; + if (s.wrap < 0) { + s.wrap = -s.wrap; + } + s.status = s.wrap ? INIT_STATE : BUSY_STATE; + strm.adler = s.wrap === 2 ? 0 : 1; + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; + } + function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; + } + function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + if (strm.state.wrap !== 2) { + return Z_STREAM_ERROR; + } + strm.state.gzhead = head; + return Z_OK; + } + function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { + return Z_STREAM_ERROR; + } + var wrap = 1; + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } else if (windowBits > 15) { + wrap = 2; + windowBits -= 16; + } + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + if (windowBits === 8) { + windowBits = 9; + } + var s = new DeflateState(); + strm.state = s; + s.strm = strm; + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + s.lit_bufsize = 1 << memLevel + 6; + s.pending_buf_size = s.lit_bufsize * 4; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + s.d_buf = 1 * s.lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + s.level = level; + s.strategy = strategy; + s.method = method; + return deflateReset(strm); + } + function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); + } + function deflate(strm, flush) { + var old_flush, s; + var beg, val; + if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + s = strm.state; + if (!strm.output || !strm.input && strm.avail_in !== 0 || s.status === FINISH_STATE && flush !== Z_FINISH) { + return err(strm, strm.avail_out === 0 ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + s.strm = strm; + old_flush = s.last_flush; + s.last_flush = flush; + if (s.status === INIT_STATE) { + if (s.wrap === 2) { + strm.adler = 0; + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } else { + put_byte( + s, + (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 255); + put_byte(s, s.gzhead.time >> 8 & 255); + put_byte(s, s.gzhead.time >> 16 & 255); + put_byte(s, s.gzhead.time >> 24 & 255); + put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0); + put_byte(s, s.gzhead.os & 255); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 255); + put_byte(s, s.gzhead.extra.length >> 8 & 255); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } else { + var header = Z_DEFLATED + (s.w_bits - 8 << 4) << 8; + var level_flags = -1; + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= level_flags << 6; + if (s.strstart !== 0) { + header |= PRESET_DICT; + } + header += 31 - header % 31; + s.status = BUSY_STATE; + putShortMSB(s, header); + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 65535); + } + strm.adler = 1; + } + } + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra) { + beg = s.pending; + while (s.gzindex < (s.gzhead.extra.length & 65535)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 255); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name) { + beg = s.pending; + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 255; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment) { + beg = s.pending; + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 255; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 255); + put_byte(s, strm.adler >> 8 & 255); + strm.adler = 0; + s.status = BUSY_STATE; + } + } else { + s.status = BUSY_STATE; + } + } + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; + return Z_OK; + } + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + if (strm.avail_in !== 0 || s.lookahead !== 0 || flush !== Z_NO_FLUSH && s.status !== FINISH_STATE) { + var bstate = s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush); + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + } + return Z_OK; + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } else if (flush !== Z_BLOCK) { + trees._tr_stored_block(s, 0, 0, false); + if (flush === Z_FULL_FLUSH) { + zero(s.head); + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; + return Z_OK; + } + } + } + if (flush !== Z_FINISH) { + return Z_OK; + } + if (s.wrap <= 0) { + return Z_STREAM_END; + } + if (s.wrap === 2) { + put_byte(s, strm.adler & 255); + put_byte(s, strm.adler >> 8 & 255); + put_byte(s, strm.adler >> 16 & 255); + put_byte(s, strm.adler >> 24 & 255); + put_byte(s, strm.total_in & 255); + put_byte(s, strm.total_in >> 8 & 255); + put_byte(s, strm.total_in >> 16 & 255); + put_byte(s, strm.total_in >> 24 & 255); + } else { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 65535); + } + flush_pending(strm); + if (s.wrap > 0) { + s.wrap = -s.wrap; + } + return s.pending !== 0 ? Z_OK : Z_STREAM_END; + } + function deflateEnd(strm) { + var status; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + status = strm.state.status; + if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE) { + return err(strm, Z_STREAM_ERROR); + } + strm.state = null; + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; + } + function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + s = strm.state; + wrap = s.wrap; + if (wrap === 2 || wrap === 1 && s.status !== INIT_STATE || s.lookahead) { + return Z_STREAM_ERROR; + } + if (wrap === 1) { + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + s.wrap = 0; + if (dictLength >= s.w_size) { + if (wrap === 0) { + zero(s.head); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; + } + exports2.deflateInit = deflateInit; + exports2.deflateInit2 = deflateInit2; + exports2.deflateReset = deflateReset; + exports2.deflateResetKeep = deflateResetKeep; + exports2.deflateSetHeader = deflateSetHeader; + exports2.deflate = deflate; + exports2.deflateEnd = deflateEnd; + exports2.deflateSetDictionary = deflateSetDictionary; + exports2.deflateInfo = "pako deflate (from Nodeca project)"; + } +}); + +// node_modules/pako/lib/utils/strings.js +var require_strings = __commonJS({ + "node_modules/pako/lib/utils/strings.js"(exports2) { + "use strict"; + var utils = require_common(); + var STR_APPLY_OK = true; + var STR_APPLY_UIA_OK = true; + try { + String.fromCharCode.apply(null, [0]); + } catch (__) { + STR_APPLY_OK = false; + } + try { + String.fromCharCode.apply(null, new Uint8Array(1)); + } catch (__) { + STR_APPLY_UIA_OK = false; + } + var _utf8len = new utils.Buf8(256); + for (q = 0; q < 256; q++) { + _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1; + } + var q; + _utf8len[254] = _utf8len[254] = 1; + exports2.string2buf = function(str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + buf_len += c < 128 ? 1 : c < 2048 ? 2 : c < 65536 ? 3 : 4; + } + buf = new utils.Buf8(buf_len); + for (i = 0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + if (c < 128) { + buf[i++] = c; + } else if (c < 2048) { + buf[i++] = 192 | c >>> 6; + buf[i++] = 128 | c & 63; + } else if (c < 65536) { + buf[i++] = 224 | c >>> 12; + buf[i++] = 128 | c >>> 6 & 63; + buf[i++] = 128 | c & 63; + } else { + buf[i++] = 240 | c >>> 18; + buf[i++] = 128 | c >>> 12 & 63; + buf[i++] = 128 | c >>> 6 & 63; + buf[i++] = 128 | c & 63; + } + } + return buf; + }; + function buf2binstring(buf, len) { + if (len < 65534) { + if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) { + return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); + } + } + var result = ""; + for (var i = 0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; + } + exports2.buf2binstring = function(buf) { + return buf2binstring(buf, buf.length); + }; + exports2.binstring2buf = function(str) { + var buf = new utils.Buf8(str.length); + for (var i = 0, len = buf.length; i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; + }; + exports2.buf2string = function(buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + var utf16buf = new Array(len * 2); + for (out = 0, i = 0; i < len; ) { + c = buf[i++]; + if (c < 128) { + utf16buf[out++] = c; + continue; + } + c_len = _utf8len[c]; + if (c_len > 4) { + utf16buf[out++] = 65533; + i += c_len - 1; + continue; + } + c &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7; + while (c_len > 1 && i < len) { + c = c << 6 | buf[i++] & 63; + c_len--; + } + if (c_len > 1) { + utf16buf[out++] = 65533; + continue; + } + if (c < 65536) { + utf16buf[out++] = c; + } else { + c -= 65536; + utf16buf[out++] = 55296 | c >> 10 & 1023; + utf16buf[out++] = 56320 | c & 1023; + } + } + return buf2binstring(utf16buf, out); + }; + exports2.utf8border = function(buf, max) { + var pos; + max = max || buf.length; + if (max > buf.length) { + max = buf.length; + } + pos = max - 1; + while (pos >= 0 && (buf[pos] & 192) === 128) { + pos--; + } + if (pos < 0) { + return max; + } + if (pos === 0) { + return max; + } + return pos + _utf8len[buf[pos]] > max ? pos : max; + }; + } +}); + +// node_modules/pako/lib/zlib/zstream.js +var require_zstream = __commonJS({ + "node_modules/pako/lib/zlib/zstream.js"(exports2, module) { + "use strict"; + function ZStream() { + 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; + } + module.exports = ZStream; + } +}); + +// node_modules/pako/lib/deflate.js +var require_deflate2 = __commonJS({ + "node_modules/pako/lib/deflate.js"(exports2) { + "use strict"; + var zlib_deflate = require_deflate(); + var utils = require_common(); + var strings = require_strings(); + var msg = require_messages(); + var ZStream = require_zstream(); + var toString = Object.prototype.toString; + var Z_NO_FLUSH = 0; + var Z_FINISH = 4; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_SYNC_FLUSH = 2; + var Z_DEFAULT_COMPRESSION = -1; + var Z_DEFAULT_STRATEGY = 0; + var Z_DEFLATED = 8; + function Deflate(options) { + if (!(this instanceof Deflate)) return new Deflate(options); + this.options = utils.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY, + to: "" + }, options || {}); + var opt = this.options; + if (opt.raw && opt.windowBits > 0) { + opt.windowBits = -opt.windowBits; + } else if (opt.gzip && opt.windowBits > 0 && opt.windowBits < 16) { + opt.windowBits += 16; + } + this.err = 0; + this.msg = ""; + this.ended = false; + this.chunks = []; + this.strm = new ZStream(); + this.strm.avail_out = 0; + var status = zlib_deflate.deflateInit2( + this.strm, + opt.level, + opt.method, + opt.windowBits, + opt.memLevel, + opt.strategy + ); + if (status !== Z_OK) { + throw new Error(msg[status]); + } + if (opt.header) { + zlib_deflate.deflateSetHeader(this.strm, opt.header); + } + if (opt.dictionary) { + var dict; + if (typeof opt.dictionary === "string") { + dict = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === "[object ArrayBuffer]") { + dict = new Uint8Array(opt.dictionary); + } else { + dict = opt.dictionary; + } + status = zlib_deflate.deflateSetDictionary(this.strm, dict); + if (status !== Z_OK) { + throw new Error(msg[status]); + } + this._dict_set = true; + } + } + Deflate.prototype.push = function(data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; + if (this.ended) { + return false; + } + _mode = mode === ~~mode ? mode : mode === true ? Z_FINISH : Z_NO_FLUSH; + if (typeof data === "string") { + strm.input = strings.string2buf(data); + } else if (toString.call(data) === "[object ArrayBuffer]") { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + strm.next_in = 0; + strm.avail_in = strm.input.length; + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_deflate.deflate(strm, _mode); + if (status !== Z_STREAM_END && status !== Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH)) { + if (this.options.to === "string") { + this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); + if (_mode === Z_FINISH) { + status = zlib_deflate.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK; + } + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK); + strm.avail_out = 0; + return true; + } + return true; + }; + Deflate.prototype.onData = function(chunk) { + this.chunks.push(chunk); + }; + Deflate.prototype.onEnd = function(status) { + if (status === Z_OK) { + if (this.options.to === "string") { + this.result = this.chunks.join(""); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; + }; + function deflate(input, options) { + var deflator = new Deflate(options); + deflator.push(input, true); + if (deflator.err) { + throw deflator.msg || msg[deflator.err]; + } + return deflator.result; + } + function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate(input, options); + } + function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate(input, options); + } + exports2.Deflate = Deflate; + exports2.deflate = deflate; + exports2.deflateRaw = deflateRaw; + exports2.gzip = gzip; + } +}); + +// node_modules/pako/lib/zlib/inffast.js +var require_inffast = __commonJS({ + "node_modules/pako/lib/zlib/inffast.js"(exports2, module) { + "use strict"; + var BAD = 30; + var TYPE = 12; + module.exports = function inflate_fast(strm, start) { + var state; + var _in; + var last; + var _out; + var beg; + var end; + var dmax; + var wsize; + var whave; + var wnext; + var s_window; + var hold; + var bits; + var lcode; + var dcode; + var lmask; + var dmask; + var here; + var op; + var len; + var dist; + var from; + var from_source; + var input, output; + state = strm.state; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); + dmax = state.dmax; + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = lcode[hold & lmask]; + dolen: + for (; ; ) { + op = here >>> 24; + hold >>>= op; + bits -= op; + op = here >>> 16 & 255; + if (op === 0) { + output[_out++] = here & 65535; + } else if (op & 16) { + len = here & 65535; + op &= 15; + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & (1 << op) - 1; + hold >>>= op; + bits -= op; + } + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + dodist: + for (; ; ) { + op = here >>> 24; + hold >>>= op; + bits -= op; + op = here >>> 16 & 255; + if (op & 16) { + dist = here & 65535; + op &= 15; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & (1 << op) - 1; + if (dist > dmax) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break top; + } + hold >>>= op; + bits -= op; + op = _out - beg; + if (dist > op) { + op = dist - op; + if (op > whave) { + if (state.sane) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break top; + } + } + from = 0; + from_source = s_window; + if (wnext === 0) { + from += wsize - op; + if (op < len) { + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; + from_source = output; + } + } else if (wnext < op) { + from += wsize + wnext - op; + op -= wnext; + if (op < len) { + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; + from_source = output; + } + } + } else { + from += wnext - op; + if (op < len) { + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } else { + from = _out - dist; + do { + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } else if ((op & 64) === 0) { + here = dcode[(here & 65535) + (hold & (1 << op) - 1)]; + continue dodist; + } else { + strm.msg = "invalid distance code"; + state.mode = BAD; + break top; + } + break; + } + } else if ((op & 64) === 0) { + here = lcode[(here & 65535) + (hold & (1 << op) - 1)]; + continue dolen; + } else if (op & 32) { + state.mode = TYPE; + break top; + } else { + strm.msg = "invalid literal/length code"; + state.mode = BAD; + break top; + } + break; + } + } while (_in < last && _out < end); + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last); + strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end); + state.hold = hold; + state.bits = bits; + return; + }; + } +}); + +// node_modules/pako/lib/zlib/inftrees.js +var require_inftrees = __commonJS({ + "node_modules/pako/lib/zlib/inftrees.js"(exports2, module) { + "use strict"; + var utils = require_common(); + var MAXBITS = 15; + var ENOUGH_LENS = 852; + var ENOUGH_DISTS = 592; + var CODES = 0; + var LENS = 1; + var DISTS = 2; + var lbase = [ + /* Length codes 257..285 base */ + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 13, + 15, + 17, + 19, + 23, + 27, + 31, + 35, + 43, + 51, + 59, + 67, + 83, + 99, + 115, + 131, + 163, + 195, + 227, + 258, + 0, + 0 + ]; + var lext = [ + /* Length codes 257..285 extra */ + 16, + 16, + 16, + 16, + 16, + 16, + 16, + 16, + 17, + 17, + 17, + 17, + 18, + 18, + 18, + 18, + 19, + 19, + 19, + 19, + 20, + 20, + 20, + 20, + 21, + 21, + 21, + 21, + 16, + 72, + 78 + ]; + var dbase = [ + /* Distance codes 0..29 base */ + 1, + 2, + 3, + 4, + 5, + 7, + 9, + 13, + 17, + 25, + 33, + 49, + 65, + 97, + 129, + 193, + 257, + 385, + 513, + 769, + 1025, + 1537, + 2049, + 3073, + 4097, + 6145, + 8193, + 12289, + 16385, + 24577, + 0, + 0 + ]; + var dext = [ + /* Distance codes 0..29 extra */ + 16, + 16, + 16, + 16, + 17, + 17, + 18, + 18, + 19, + 19, + 20, + 20, + 21, + 21, + 22, + 22, + 23, + 23, + 24, + 24, + 25, + 25, + 26, + 26, + 27, + 27, + 28, + 28, + 29, + 29, + 64, + 64 + ]; + module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { + var bits = opts.bits; + var len = 0; + var sym = 0; + var min = 0, max = 0; + var root = 0; + var curr = 0; + var drop = 0; + var left = 0; + var used = 0; + var huff = 0; + var incr; + var fill; + var low; + var mask; + var next; + var base = null; + var base_index = 0; + var end; + var count = new utils.Buf16(MAXBITS + 1); + var offs = new utils.Buf16(MAXBITS + 1); + var extra = null; + var extra_index = 0; + var here_bits, here_op, here_val; + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { + break; + } + } + if (root > max) { + root = max; + } + if (max === 0) { + table[table_index++] = 1 << 24 | 64 << 16 | 0; + table[table_index++] = 1 << 24 | 64 << 16 | 0; + opts.bits = 1; + return 0; + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { + break; + } + } + if (root < min) { + root = min; + } + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; + } + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + if (type === CODES) { + base = extra = work; + end = 19; + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + } else { + base = dbase; + extra = dext; + end = -1; + } + huff = 0; + sym = 0; + len = min; + next = table_index; + curr = root; + drop = 0; + low = -1; + used = 1 << root; + mask = used - 1; + if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) { + return 1; + } + for (; ; ) { + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } else { + here_op = 32 + 64; + here_val = 0; + } + incr = 1 << len - drop; + fill = 1 << curr; + min = fill; + do { + fill -= incr; + table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val | 0; + } while (fill !== 0); + incr = 1 << len - 1; + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + sym++; + if (--count[len] === 0) { + if (len === max) { + break; + } + len = lens[lens_index + work[sym]]; + } + if (len > root && (huff & mask) !== low) { + if (drop === 0) { + drop = root; + } + next += min; + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { + break; + } + curr++; + left <<= 1; + } + used += 1 << curr; + if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) { + return 1; + } + low = huff & mask; + table[low] = root << 24 | curr << 16 | next - table_index | 0; + } + } + if (huff !== 0) { + table[next + huff] = len - drop << 24 | 64 << 16 | 0; + } + opts.bits = root; + return 0; + }; + } +}); + +// node_modules/pako/lib/zlib/inflate.js +var require_inflate = __commonJS({ + "node_modules/pako/lib/zlib/inflate.js"(exports2) { + "use strict"; + var utils = require_common(); + var adler32 = require_adler32(); + var crc32 = require_crc322(); + var inflate_fast = require_inffast(); + var inflate_table = require_inftrees(); + var CODES = 0; + var LENS = 1; + var DISTS = 2; + var Z_FINISH = 4; + var Z_BLOCK = 5; + var Z_TREES = 6; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_NEED_DICT = 2; + var Z_STREAM_ERROR = -2; + var Z_DATA_ERROR = -3; + var Z_MEM_ERROR = -4; + var Z_BUF_ERROR = -5; + var Z_DEFLATED = 8; + var HEAD = 1; + var FLAGS = 2; + var TIME = 3; + var OS = 4; + var EXLEN = 5; + var EXTRA = 6; + var NAME = 7; + var COMMENT = 8; + var HCRC = 9; + var DICTID = 10; + var DICT = 11; + var TYPE = 12; + var TYPEDO = 13; + var STORED = 14; + var COPY_ = 15; + var COPY = 16; + var TABLE2 = 17; + var LENLENS = 18; + var CODELENS = 19; + var LEN_ = 20; + var LEN = 21; + var LENEXT = 22; + var DIST = 23; + var DISTEXT = 24; + var MATCH = 25; + var LIT = 26; + var CHECK = 27; + var LENGTH = 28; + var DONE = 29; + var BAD = 30; + var MEM = 31; + var SYNC = 32; + var ENOUGH_LENS = 852; + var ENOUGH_DISTS = 592; + var MAX_WBITS = 15; + var DEF_WBITS = MAX_WBITS; + function zswap32(q) { + return (q >>> 24 & 255) + (q >>> 8 & 65280) + ((q & 65280) << 8) + ((q & 255) << 24); + } + function InflateState() { + this.mode = 0; + this.last = false; + this.wrap = 0; + this.havedict = false; + 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 utils.Buf16(320); + this.work = new utils.Buf16(288); + this.lendyn = null; + this.distdyn = null; + this.sane = 0; + this.back = 0; + this.was = 0; + } + function inflateResetKeep(strm) { + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ""; + if (state.wrap) { + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null; + state.hold = 0; + state.bits = 0; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + state.sane = 1; + state.back = -1; + return Z_OK; + } + function inflateReset(strm) { + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + } + function inflateReset2(strm, windowBits) { + var wrap; + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); + } + function inflateInit2(strm, windowBits) { + var ret; + var state; + if (!strm) { + return Z_STREAM_ERROR; + } + state = new InflateState(); + strm.state = state; + state.window = null; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null; + } + return ret; + } + function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); + } + var virgin = true; + var lenfix; + var distfix; + function fixedtables(state) { + if (virgin) { + var sym; + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + sym = 0; + while (sym < 144) { + state.lens[sym++] = 8; + } + while (sym < 256) { + state.lens[sym++] = 9; + } + while (sym < 280) { + state.lens[sym++] = 7; + } + while (sym < 288) { + state.lens[sym++] = 8; + } + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + sym = 0; + while (sym < 32) { + state.lens[sym++] = 5; + } + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + virgin = false; + } + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; + } + function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + state.window = new utils.Buf8(state.wsize); + } + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } else { + state.wnext += dist; + if (state.wnext === state.wsize) { + state.wnext = 0; + } + if (state.whave < state.wsize) { + state.whave += dist; + } + } + } + return 0; + } + function inflate(strm, flush) { + var state; + var input, output; + var next; + var put; + var have, left; + var hold; + var bits; + var _in, _out; + var copy; + var from; + var from_source; + var here = 0; + var here_bits, here_op, here_val; + var last_bits, last_op, last_val; + var len; + var ret; + var hbuf = new utils.Buf8(4); + var opts; + var n; + var order = ( + /* permutation of code lengths */ + [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15] + ); + if (!strm || !strm.state || !strm.output || !strm.input && strm.avail_in !== 0) { + return Z_STREAM_ERROR; + } + state = strm.state; + if (state.mode === TYPE) { + state.mode = TYPEDO; + } + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + _in = have; + _out = left; + ret = Z_OK; + inf_leave: + for (; ; ) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state.wrap & 2 && hold === 35615) { + state.check = 0; + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + hold = 0; + bits = 0; + state.mode = FLAGS; + break; + } + state.flags = 0; + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 255) << 8) + (hold >> 8)) % 31) { + strm.msg = "incorrect header check"; + state.mode = BAD; + break; + } + if ((hold & 15) !== Z_DEFLATED) { + strm.msg = "unknown compression method"; + state.mode = BAD; + break; + } + hold >>>= 4; + bits -= 4; + len = (hold & 15) + 8; + if (state.wbits === 0) { + state.wbits = len; + } else if (len > state.wbits) { + strm.msg = "invalid window size"; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + strm.adler = state.check = 1; + state.mode = hold & 512 ? DICTID : TYPE; + hold = 0; + bits = 0; + break; + case FLAGS: + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.flags = hold; + if ((state.flags & 255) !== Z_DEFLATED) { + strm.msg = "unknown compression method"; + state.mode = BAD; + break; + } + if (state.flags & 57344) { + strm.msg = "unknown header flags set"; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = hold >> 8 & 1; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + state.mode = TIME; + /* falls through */ + case TIME: + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state.head) { + state.head.time = hold; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + hbuf[2] = hold >>> 16 & 255; + hbuf[3] = hold >>> 24 & 255; + state.check = crc32(state.check, hbuf, 4, 0); + } + hold = 0; + bits = 0; + state.mode = OS; + /* falls through */ + case OS: + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state.head) { + state.head.xflags = hold & 255; + state.head.os = hold >> 8; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 1024) { + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + } else if (state.head) { + state.head.extra = null; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 1024) { + copy = state.length; + if (copy > have) { + copy = have; + } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + } + if (state.flags & 512) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { + break inf_leave; + } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 2048) { + if (have === 0) { + break inf_leave; + } + copy = 0; + do { + len = input[next + copy++]; + if (state.head && len && state.length < 65536) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 512) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { + break inf_leave; + } + } else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 4096) { + if (have === 0) { + break inf_leave; + } + copy = 0; + do { + len = input[next + copy++]; + if (state.head && len && state.length < 65536) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 512) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { + break inf_leave; + } + } else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 512) { + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (hold !== (state.check & 65535)) { + strm.msg = "header crc mismatch"; + state.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + if (state.head) { + state.head.hcrc = state.flags >> 9 & 1; + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + strm.adler = state.check = zswap32(hold); + hold = 0; + bits = 0; + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + return Z_NEED_DICT; + } + strm.adler = state.check = 1; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { + break inf_leave; + } + /* falls through */ + case TYPEDO: + if (state.last) { + hold >>>= bits & 7; + bits -= bits & 7; + state.mode = CHECK; + break; + } + while (bits < 3) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.last = hold & 1; + hold >>>= 1; + bits -= 1; + switch (hold & 3) { + case 0: + state.mode = STORED; + break; + case 1: + fixedtables(state); + state.mode = LEN_; + if (flush === Z_TREES) { + hold >>>= 2; + bits -= 2; + break inf_leave; + } + break; + case 2: + state.mode = TABLE2; + break; + case 3: + strm.msg = "invalid block type"; + state.mode = BAD; + } + hold >>>= 2; + bits -= 2; + break; + case STORED: + hold >>>= bits & 7; + bits -= bits & 7; + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if ((hold & 65535) !== (hold >>> 16 ^ 65535)) { + strm.msg = "invalid stored block lengths"; + state.mode = BAD; + break; + } + state.length = hold & 65535; + hold = 0; + bits = 0; + state.mode = COPY_; + if (flush === Z_TREES) { + break inf_leave; + } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { + copy = have; + } + if (copy > left) { + copy = left; + } + if (copy === 0) { + break inf_leave; + } + utils.arraySet(output, input, next, copy, put); + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + state.mode = TYPE; + break; + case TABLE2: + while (bits < 14) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.nlen = (hold & 31) + 257; + hold >>>= 5; + bits -= 5; + state.ndist = (hold & 31) + 1; + hold >>>= 5; + bits -= 5; + state.ncode = (hold & 15) + 4; + hold >>>= 4; + bits -= 4; + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = "too many length or distance symbols"; + state.mode = BAD; + break; + } + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + while (bits < 3) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.lens[order[state.have++]] = hold & 7; + hold >>>= 3; + bits -= 3; + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + state.lencode = state.lendyn; + state.lenbits = 7; + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + if (ret) { + strm.msg = "invalid code lengths set"; + state.mode = BAD; + break; + } + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (; ; ) { + here = state.lencode[hold & (1 << state.lenbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (here_val < 16) { + hold >>>= here_bits; + bits -= here_bits; + state.lens[state.have++] = here_val; + } else { + if (here_val === 16) { + n = here_bits + 2; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + if (state.have === 0) { + strm.msg = "invalid bit length repeat"; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 3); + hold >>>= 2; + bits -= 2; + } else if (here_val === 17) { + n = here_bits + 3; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + len = 0; + copy = 3 + (hold & 7); + hold >>>= 3; + bits -= 3; + } else { + n = here_bits + 7; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + len = 0; + copy = 11 + (hold & 127); + hold >>>= 7; + bits -= 7; + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = "invalid bit length repeat"; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + if (state.mode === BAD) { + break; + } + if (state.lens[256] === 0) { + strm.msg = "invalid code -- missing end-of-block"; + state.mode = BAD; + break; + } + state.lenbits = 9; + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + if (ret) { + strm.msg = "invalid literal/lengths set"; + state.mode = BAD; + break; + } + state.distbits = 6; + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + state.distbits = opts.bits; + if (ret) { + strm.msg = "invalid distances set"; + state.mode = BAD; + break; + } + state.mode = LEN_; + if (flush === Z_TREES) { + break inf_leave; + } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + inflate_fast(strm, _out); + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (; ; ) { + here = state.lencode[hold & (1 << state.lenbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (here_op && (here_op & 240) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (; ; ) { + here = state.lencode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (last_bits + here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= last_bits; + bits -= last_bits; + state.back += last_bits; + } + hold >>>= here_bits; + bits -= here_bits; + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + state.mode = LIT; + break; + } + if (here_op & 32) { + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = "invalid literal/length code"; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + n = state.extra; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.length += hold & (1 << state.extra) - 1; + hold >>>= state.extra; + bits -= state.extra; + state.back += state.extra; + } + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (; ; ) { + here = state.distcode[hold & (1 << state.distbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if ((here_op & 240) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (; ; ) { + here = state.distcode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (last_bits + here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= last_bits; + bits -= last_bits; + state.back += last_bits; + } + hold >>>= here_bits; + bits -= here_bits; + state.back += here_bits; + if (here_op & 64) { + strm.msg = "invalid distance code"; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = here_op & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + n = state.extra; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.offset += hold & (1 << state.extra) - 1; + hold >>>= state.extra; + bits -= state.extra; + state.back += state.extra; + } + if (state.offset > state.dmax) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break; + } + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { + break inf_leave; + } + copy = _out - left; + if (state.offset > copy) { + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break; + } + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } else { + from = state.wnext - copy; + } + if (copy > state.length) { + copy = state.length; + } + from_source = state.window; + } else { + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { + copy = left; + } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { + state.mode = LEN; + } + break; + case LIT: + if (left === 0) { + break inf_leave; + } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold |= input[next++] << bits; + bits += 8; + } + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ + state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out); + } + _out = left; + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = "incorrect data check"; + state.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (hold !== (state.total & 4294967295)) { + strm.msg = "incorrect length check"; + state.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } + } + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + if (state.wsize || _out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH)) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if ((_in === 0 && _out === 0 || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; + } + function inflateEnd(strm) { + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; + } + function inflateGetHeader(strm, head) { + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + if ((state.wrap & 2) === 0) { + return Z_STREAM_ERROR; + } + state.head = head; + head.done = false; + return Z_OK; + } + function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + var state; + var dictid; + var ret; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } + if (state.mode === DICT) { + dictid = 1; + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } + } + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + return Z_OK; + } + exports2.inflateReset = inflateReset; + exports2.inflateReset2 = inflateReset2; + exports2.inflateResetKeep = inflateResetKeep; + exports2.inflateInit = inflateInit; + exports2.inflateInit2 = inflateInit2; + exports2.inflate = inflate; + exports2.inflateEnd = inflateEnd; + exports2.inflateGetHeader = inflateGetHeader; + exports2.inflateSetDictionary = inflateSetDictionary; + exports2.inflateInfo = "pako inflate (from Nodeca project)"; + } +}); + +// node_modules/pako/lib/zlib/constants.js +var require_constants = __commonJS({ + "node_modules/pako/lib/zlib/constants.js"(exports2, module) { + "use strict"; + module.exports = { + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type + }; + } +}); + +// node_modules/pako/lib/zlib/gzheader.js +var require_gzheader = __commonJS({ + "node_modules/pako/lib/zlib/gzheader.js"(exports2, module) { + "use strict"; + function GZheader() { + 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 = false; + } + module.exports = GZheader; + } +}); + +// node_modules/pako/lib/inflate.js +var require_inflate2 = __commonJS({ + "node_modules/pako/lib/inflate.js"(exports2) { + "use strict"; + var zlib_inflate = require_inflate(); + var utils = require_common(); + var strings = require_strings(); + var c = require_constants(); + var msg = require_messages(); + var ZStream = require_zstream(); + var GZheader = require_gzheader(); + var toString = Object.prototype.toString; + function Inflate(options) { + if (!(this instanceof Inflate)) return new Inflate(options); + this.options = utils.assign({ + chunkSize: 16384, + windowBits: 0, + to: "" + }, options || {}); + var opt = this.options; + if (opt.raw && opt.windowBits >= 0 && opt.windowBits < 16) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { + opt.windowBits = -15; + } + } + if (opt.windowBits >= 0 && opt.windowBits < 16 && !(options && options.windowBits)) { + opt.windowBits += 32; + } + if (opt.windowBits > 15 && opt.windowBits < 48) { + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + this.err = 0; + this.msg = ""; + this.ended = false; + this.chunks = []; + this.strm = new ZStream(); + this.strm.avail_out = 0; + var status = zlib_inflate.inflateInit2( + this.strm, + opt.windowBits + ); + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + this.header = new GZheader(); + zlib_inflate.inflateGetHeader(this.strm, this.header); + if (opt.dictionary) { + if (typeof opt.dictionary === "string") { + opt.dictionary = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === "[object ArrayBuffer]") { + opt.dictionary = new Uint8Array(opt.dictionary); + } + if (opt.raw) { + status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary); + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + } + } + } + Inflate.prototype.push = function(data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var dictionary = this.options.dictionary; + var status, _mode; + var next_out_utf8, tail, utf8str; + var allowBufError = false; + if (this.ended) { + return false; + } + _mode = mode === ~~mode ? mode : mode === true ? c.Z_FINISH : c.Z_NO_FLUSH; + if (typeof data === "string") { + strm.input = strings.binstring2buf(data); + } else if (toString.call(data) === "[object ArrayBuffer]") { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + strm.next_in = 0; + strm.avail_in = strm.input.length; + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); + if (status === c.Z_NEED_DICT && dictionary) { + status = zlib_inflate.inflateSetDictionary(this.strm, dictionary); + } + if (status === c.Z_BUF_ERROR && allowBufError === true) { + status = c.Z_OK; + allowBufError = false; + } + if (status !== c.Z_STREAM_END && status !== c.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.next_out) { + if (strm.avail_out === 0 || status === c.Z_STREAM_END || strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH)) { + if (this.options.to === "string") { + next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + tail = strm.next_out - next_out_utf8; + utf8str = strings.buf2string(strm.output, next_out_utf8); + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { + utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); + } + this.onData(utf8str); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); + if (status === c.Z_STREAM_END) { + _mode = c.Z_FINISH; + } + if (_mode === c.Z_FINISH) { + status = zlib_inflate.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === c.Z_OK; + } + if (_mode === c.Z_SYNC_FLUSH) { + this.onEnd(c.Z_OK); + strm.avail_out = 0; + return true; + } + return true; + }; + Inflate.prototype.onData = function(chunk) { + this.chunks.push(chunk); + }; + Inflate.prototype.onEnd = function(status) { + if (status === c.Z_OK) { + if (this.options.to === "string") { + this.result = this.chunks.join(""); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; + }; + function inflate(input, options) { + var inflator = new Inflate(options); + inflator.push(input, true); + if (inflator.err) { + throw inflator.msg || msg[inflator.err]; + } + return inflator.result; + } + function inflateRaw(input, options) { + options = options || {}; + options.raw = true; + return inflate(input, options); + } + exports2.Inflate = Inflate; + exports2.inflate = inflate; + exports2.inflateRaw = inflateRaw; + exports2.ungzip = inflate; + } +}); + +// node_modules/pako/index.js +var require_pako = __commonJS({ + "node_modules/pako/index.js"(exports2, module) { + "use strict"; + var assign = require_common().assign; + var deflate = require_deflate2(); + var inflate = require_inflate2(); + var constants = require_constants(); + var pako = {}; + assign(pako, deflate, inflate, constants); + module.exports = pako; + } +}); + +// node_modules/jszip/lib/flate.js +var require_flate = __commonJS({ + "node_modules/jszip/lib/flate.js"(exports2) { + "use strict"; + var USE_TYPEDARRAY = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Uint32Array !== "undefined"; + var pako = require_pako(); + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array"; + exports2.magic = "\b\0"; + function FlateWorker(action, options) { + GenericWorker.call(this, "FlateWorker/" + action); + this._pako = null; + this._pakoAction = action; + this._pakoOptions = options; + this.meta = {}; + } + utils.inherits(FlateWorker, GenericWorker); + FlateWorker.prototype.processChunk = function(chunk) { + this.meta = chunk.meta; + if (this._pako === null) { + this._createPako(); + } + this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false); + }; + FlateWorker.prototype.flush = function() { + GenericWorker.prototype.flush.call(this); + if (this._pako === null) { + this._createPako(); + } + this._pako.push([], true); + }; + FlateWorker.prototype.cleanUp = function() { + GenericWorker.prototype.cleanUp.call(this); + this._pako = null; + }; + FlateWorker.prototype._createPako = function() { + this._pako = new pako[this._pakoAction]({ + raw: true, + level: this._pakoOptions.level || -1 + // default compression + }); + var self2 = this; + this._pako.onData = function(data) { + self2.push({ + data, + meta: self2.meta + }); + }; + }; + exports2.compressWorker = function(compressionOptions) { + return new FlateWorker("Deflate", compressionOptions); + }; + exports2.uncompressWorker = function() { + return new FlateWorker("Inflate", {}); + }; + } +}); + +// node_modules/jszip/lib/compressions.js +var require_compressions = __commonJS({ + "node_modules/jszip/lib/compressions.js"(exports2) { + "use strict"; + var GenericWorker = require_GenericWorker(); + exports2.STORE = { + magic: "\0\0", + compressWorker: function() { + return new GenericWorker("STORE compression"); + }, + uncompressWorker: function() { + return new GenericWorker("STORE decompression"); + } + }; + exports2.DEFLATE = require_flate(); + } +}); + +// node_modules/jszip/lib/signature.js +var require_signature = __commonJS({ + "node_modules/jszip/lib/signature.js"(exports2) { + "use strict"; + exports2.LOCAL_FILE_HEADER = "PK"; + exports2.CENTRAL_FILE_HEADER = "PK"; + exports2.CENTRAL_DIRECTORY_END = "PK"; + exports2.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x07"; + exports2.ZIP64_CENTRAL_DIRECTORY_END = "PK"; + exports2.DATA_DESCRIPTOR = "PK\x07\b"; + } +}); + +// node_modules/jszip/lib/generate/ZipFileWorker.js +var require_ZipFileWorker = __commonJS({ + "node_modules/jszip/lib/generate/ZipFileWorker.js"(exports2, module) { + "use strict"; + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var utf8 = require_utf8(); + var crc32 = require_crc32(); + var signature = require_signature(); + var decToHex = function(dec, bytes) { + var hex = "", i; + for (i = 0; i < bytes; i++) { + hex += String.fromCharCode(dec & 255); + dec = dec >>> 8; + } + return hex; + }; + var generateUnixExternalFileAttr = function(unixPermissions, isDir) { + var result = unixPermissions; + if (!unixPermissions) { + result = isDir ? 16893 : 33204; + } + return (result & 65535) << 16; + }; + var generateDosExternalFileAttr = function(dosPermissions) { + return (dosPermissions || 0) & 63; + }; + var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) { + var file = streamInfo["file"], compression = streamInfo["compression"], useCustomEncoding = encodeFileName !== utf8.utf8encode, encodedFileName = utils.transformTo("string", encodeFileName(file.name)), utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)), comment = file.comment, encodedComment = utils.transformTo("string", encodeFileName(comment)), utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)), useUTF8ForFileName = utfEncodedFileName.length !== file.name.length, useUTF8ForComment = utfEncodedComment.length !== comment.length, dosTime, dosDate, extraFields = "", unicodePathExtraField = "", unicodeCommentExtraField = "", dir = file.dir, date = file.date; + var dataInfo = { + crc32: 0, + compressedSize: 0, + uncompressedSize: 0 + }; + if (!streamedContent || streamingEnded) { + dataInfo.crc32 = streamInfo["crc32"]; + dataInfo.compressedSize = streamInfo["compressedSize"]; + dataInfo.uncompressedSize = streamInfo["uncompressedSize"]; + } + var bitflag = 0; + if (streamedContent) { + bitflag |= 8; + } + if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) { + bitflag |= 2048; + } + var extFileAttr = 0; + var versionMadeBy = 0; + if (dir) { + extFileAttr |= 16; + } + if (platform === "UNIX") { + versionMadeBy = 798; + extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir); + } else { + versionMadeBy = 20; + extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir); + } + dosTime = date.getUTCHours(); + dosTime = dosTime << 6; + dosTime = dosTime | date.getUTCMinutes(); + dosTime = dosTime << 5; + dosTime = dosTime | date.getUTCSeconds() / 2; + dosDate = date.getUTCFullYear() - 1980; + dosDate = dosDate << 4; + dosDate = dosDate | date.getUTCMonth() + 1; + dosDate = dosDate << 5; + dosDate = dosDate | date.getUTCDate(); + if (useUTF8ForFileName) { + unicodePathExtraField = // Version + decToHex(1, 1) + // NameCRC32 + decToHex(crc32(encodedFileName), 4) + // UnicodeName + utfEncodedFileName; + extraFields += // Info-ZIP Unicode Path Extra Field + "up" + // size + decToHex(unicodePathExtraField.length, 2) + // content + unicodePathExtraField; + } + if (useUTF8ForComment) { + unicodeCommentExtraField = // Version + decToHex(1, 1) + // CommentCRC32 + decToHex(crc32(encodedComment), 4) + // UnicodeName + utfEncodedComment; + extraFields += // Info-ZIP Unicode Path Extra Field + "uc" + // size + decToHex(unicodeCommentExtraField.length, 2) + // content + unicodeCommentExtraField; + } + var header = ""; + header += "\n\0"; + header += decToHex(bitflag, 2); + header += compression.magic; + header += decToHex(dosTime, 2); + header += decToHex(dosDate, 2); + header += decToHex(dataInfo.crc32, 4); + header += decToHex(dataInfo.compressedSize, 4); + header += decToHex(dataInfo.uncompressedSize, 4); + header += decToHex(encodedFileName.length, 2); + header += decToHex(extraFields.length, 2); + var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields; + var dirRecord = signature.CENTRAL_FILE_HEADER + // version made by (00: DOS) + decToHex(versionMadeBy, 2) + // file header (common to file and central directory) + header + // file comment length + decToHex(encodedComment.length, 2) + // disk number start + "\0\0\0\0" + // external file attributes + decToHex(extFileAttr, 4) + // relative offset of local header + decToHex(offset, 4) + // file name + encodedFileName + // extra field + extraFields + // file comment + encodedComment; + return { + fileRecord, + dirRecord + }; + }; + var generateCentralDirectoryEnd = function(entriesCount, centralDirLength, localDirLength, comment, encodeFileName) { + var dirEnd = ""; + var encodedComment = utils.transformTo("string", encodeFileName(comment)); + dirEnd = signature.CENTRAL_DIRECTORY_END + // number of this disk + "\0\0\0\0" + // total number of entries in the central directory on this disk + decToHex(entriesCount, 2) + // total number of entries in the central directory + decToHex(entriesCount, 2) + // size of the central directory 4 bytes + decToHex(centralDirLength, 4) + // offset of start of central directory with respect to the starting disk number + decToHex(localDirLength, 4) + // .ZIP file comment length + decToHex(encodedComment.length, 2) + // .ZIP file comment + encodedComment; + return dirEnd; + }; + var generateDataDescriptors = function(streamInfo) { + var descriptor = ""; + descriptor = signature.DATA_DESCRIPTOR + // crc-32 4 bytes + decToHex(streamInfo["crc32"], 4) + // compressed size 4 bytes + decToHex(streamInfo["compressedSize"], 4) + // uncompressed size 4 bytes + decToHex(streamInfo["uncompressedSize"], 4); + return descriptor; + }; + function ZipFileWorker(streamFiles, comment, platform, encodeFileName) { + GenericWorker.call(this, "ZipFileWorker"); + this.bytesWritten = 0; + this.zipComment = comment; + this.zipPlatform = platform; + this.encodeFileName = encodeFileName; + this.streamFiles = streamFiles; + this.accumulate = false; + this.contentBuffer = []; + this.dirRecords = []; + this.currentSourceOffset = 0; + this.entriesCount = 0; + this.currentFile = null; + this._sources = []; + } + utils.inherits(ZipFileWorker, GenericWorker); + ZipFileWorker.prototype.push = function(chunk) { + var currentFilePercent = chunk.meta.percent || 0; + var entriesCount = this.entriesCount; + var remainingFiles = this._sources.length; + if (this.accumulate) { + this.contentBuffer.push(chunk); + } else { + this.bytesWritten += chunk.data.length; + GenericWorker.prototype.push.call(this, { + data: chunk.data, + meta: { + currentFile: this.currentFile, + percent: entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100 + } + }); + } + }; + ZipFileWorker.prototype.openedSource = function(streamInfo) { + this.currentSourceOffset = this.bytesWritten; + this.currentFile = streamInfo["file"].name; + var streamedContent = this.streamFiles && !streamInfo["file"].dir; + if (streamedContent) { + var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); + this.push({ + data: record.fileRecord, + meta: { percent: 0 } + }); + } else { + this.accumulate = true; + } + }; + ZipFileWorker.prototype.closedSource = function(streamInfo) { + this.accumulate = false; + var streamedContent = this.streamFiles && !streamInfo["file"].dir; + var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); + this.dirRecords.push(record.dirRecord); + if (streamedContent) { + this.push({ + data: generateDataDescriptors(streamInfo), + meta: { percent: 100 } + }); + } else { + this.push({ + data: record.fileRecord, + meta: { percent: 0 } + }); + while (this.contentBuffer.length) { + this.push(this.contentBuffer.shift()); + } + } + this.currentFile = null; + }; + ZipFileWorker.prototype.flush = function() { + var localDirLength = this.bytesWritten; + for (var i = 0; i < this.dirRecords.length; i++) { + this.push({ + data: this.dirRecords[i], + meta: { percent: 100 } + }); + } + var centralDirLength = this.bytesWritten - localDirLength; + var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName); + this.push({ + data: dirEnd, + meta: { percent: 100 } + }); + }; + ZipFileWorker.prototype.prepareNextSource = function() { + this.previous = this._sources.shift(); + this.openedSource(this.previous.streamInfo); + if (this.isPaused) { + this.previous.pause(); + } else { + this.previous.resume(); + } + }; + ZipFileWorker.prototype.registerPrevious = function(previous) { + this._sources.push(previous); + var self2 = this; + previous.on("data", function(chunk) { + self2.processChunk(chunk); + }); + previous.on("end", function() { + self2.closedSource(self2.previous.streamInfo); + if (self2._sources.length) { + self2.prepareNextSource(); + } else { + self2.end(); + } + }); + previous.on("error", function(e) { + self2.error(e); + }); + return this; + }; + ZipFileWorker.prototype.resume = function() { + if (!GenericWorker.prototype.resume.call(this)) { + return false; + } + if (!this.previous && this._sources.length) { + this.prepareNextSource(); + return true; + } + if (!this.previous && !this._sources.length && !this.generatedError) { + this.end(); + return true; + } + }; + ZipFileWorker.prototype.error = function(e) { + var sources = this._sources; + if (!GenericWorker.prototype.error.call(this, e)) { + return false; + } + for (var i = 0; i < sources.length; i++) { + try { + sources[i].error(e); + } catch (e2) { + } + } + return true; + }; + ZipFileWorker.prototype.lock = function() { + GenericWorker.prototype.lock.call(this); + var sources = this._sources; + for (var i = 0; i < sources.length; i++) { + sources[i].lock(); + } + }; + module.exports = ZipFileWorker; + } +}); + +// node_modules/jszip/lib/generate/index.js +var require_generate = __commonJS({ + "node_modules/jszip/lib/generate/index.js"(exports2) { + "use strict"; + var compressions = require_compressions(); + var ZipFileWorker = require_ZipFileWorker(); + var getCompression = function(fileCompression, zipCompression) { + var compressionName = fileCompression || zipCompression; + var compression = compressions[compressionName]; + if (!compression) { + throw new Error(compressionName + " is not a valid compression method !"); + } + return compression; + }; + exports2.generateWorker = function(zip, options, comment) { + var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName); + var entriesCount = 0; + try { + zip.forEach(function(relativePath, file) { + entriesCount++; + var compression = getCompression(file.options.compression, options.compression); + var compressionOptions = file.options.compressionOptions || options.compressionOptions || {}; + var dir = file.dir, date = file.date; + file._compressWorker(compression, compressionOptions).withStreamInfo("file", { + name: relativePath, + dir, + date, + comment: file.comment || "", + unixPermissions: file.unixPermissions, + dosPermissions: file.dosPermissions + }).pipe(zipFileWorker); + }); + zipFileWorker.entriesCount = entriesCount; + } catch (e) { + zipFileWorker.error(e); + } + return zipFileWorker; + }; + } +}); + +// node_modules/jszip/lib/nodejs/NodejsStreamInputAdapter.js +var require_NodejsStreamInputAdapter = __commonJS({ + "node_modules/jszip/lib/nodejs/NodejsStreamInputAdapter.js"(exports2, module) { + "use strict"; + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + function NodejsStreamInputAdapter(filename, stream) { + GenericWorker.call(this, "Nodejs stream input adapter for " + filename); + this._upstreamEnded = false; + this._bindStream(stream); + } + utils.inherits(NodejsStreamInputAdapter, GenericWorker); + NodejsStreamInputAdapter.prototype._bindStream = function(stream) { + var self2 = this; + this._stream = stream; + stream.pause(); + stream.on("data", function(chunk) { + self2.push({ + data: chunk, + meta: { + percent: 0 + } + }); + }).on("error", function(e) { + if (self2.isPaused) { + this.generatedError = e; + } else { + self2.error(e); + } + }).on("end", function() { + if (self2.isPaused) { + self2._upstreamEnded = true; + } else { + self2.end(); + } + }); + }; + NodejsStreamInputAdapter.prototype.pause = function() { + if (!GenericWorker.prototype.pause.call(this)) { + return false; + } + this._stream.pause(); + return true; + }; + NodejsStreamInputAdapter.prototype.resume = function() { + if (!GenericWorker.prototype.resume.call(this)) { + return false; + } + if (this._upstreamEnded) { + this.end(); + } else { + this._stream.resume(); + } + return true; + }; + module.exports = NodejsStreamInputAdapter; + } +}); + +// node_modules/jszip/lib/object.js +var require_object = __commonJS({ + "node_modules/jszip/lib/object.js"(exports2, module) { + "use strict"; + var utf8 = require_utf8(); + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var StreamHelper = require_StreamHelper(); + var defaults = require_defaults(); + var CompressedObject = require_compressedObject(); + var ZipObject = require_zipObject(); + var generate = require_generate(); + var nodejsUtils = require_nodejsUtils(); + var NodejsStreamInputAdapter = require_NodejsStreamInputAdapter(); + var fileAdd = function(name, data, originalOptions) { + var dataType = utils.getTypeOf(data), parent; + var o = utils.extend(originalOptions || {}, defaults); + o.date = o.date || /* @__PURE__ */ new Date(); + if (o.compression !== null) { + o.compression = o.compression.toUpperCase(); + } + if (typeof o.unixPermissions === "string") { + o.unixPermissions = parseInt(o.unixPermissions, 8); + } + if (o.unixPermissions && o.unixPermissions & 16384) { + o.dir = true; + } + if (o.dosPermissions && o.dosPermissions & 16) { + o.dir = true; + } + if (o.dir) { + name = forceTrailingSlash(name); + } + if (o.createFolders && (parent = parentFolder(name))) { + folderAdd.call(this, parent, true); + } + var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false; + if (!originalOptions || typeof originalOptions.binary === "undefined") { + o.binary = !isUnicodeString; + } + var isCompressedEmpty = data instanceof CompressedObject && data.uncompressedSize === 0; + if (isCompressedEmpty || o.dir || !data || data.length === 0) { + o.base64 = false; + o.binary = true; + data = ""; + o.compression = "STORE"; + dataType = "string"; + } + var zipObjectContent = null; + if (data instanceof CompressedObject || data instanceof GenericWorker) { + zipObjectContent = data; + } else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) { + zipObjectContent = new NodejsStreamInputAdapter(name, data); + } else { + zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64); + } + var object = new ZipObject(name, zipObjectContent, o); + this.files[name] = object; + }; + var parentFolder = function(path) { + if (path.slice(-1) === "/") { + path = path.substring(0, path.length - 1); + } + var lastSlash = path.lastIndexOf("/"); + return lastSlash > 0 ? path.substring(0, lastSlash) : ""; + }; + var forceTrailingSlash = function(path) { + if (path.slice(-1) !== "/") { + path += "/"; + } + return path; + }; + var folderAdd = function(name, createFolders) { + createFolders = typeof createFolders !== "undefined" ? createFolders : defaults.createFolders; + name = forceTrailingSlash(name); + if (!this.files[name]) { + fileAdd.call(this, name, null, { + dir: true, + createFolders + }); + } + return this.files[name]; + }; + function isRegExp(object) { + return Object.prototype.toString.call(object) === "[object RegExp]"; + } + var out = { + /** + * @see loadAsync + */ + load: function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }, + /** + * Call a callback function for each entry at this folder level. + * @param {Function} cb the callback function: + * function (relativePath, file) {...} + * It takes 2 arguments : the relative path and the file. + */ + forEach: function(cb) { + var filename, relativePath, file; + for (filename in this.files) { + file = this.files[filename]; + relativePath = filename.slice(this.root.length, filename.length); + if (relativePath && filename.slice(0, this.root.length) === this.root) { + cb(relativePath, file); + } + } + }, + /** + * Filter nested files/folders with the specified function. + * @param {Function} search the predicate to use : + * function (relativePath, file) {...} + * It takes 2 arguments : the relative path and the file. + * @return {Array} An array of matching elements. + */ + filter: function(search) { + var result = []; + this.forEach(function(relativePath, entry) { + if (search(relativePath, entry)) { + result.push(entry); + } + }); + return result; + }, + /** + * Add a file to the zip file, or search a file. + * @param {string|RegExp} name The name of the file to add (if data is defined), + * the name of the file to find (if no data) or a regex to match files. + * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded + * @param {Object} o File options + * @return {JSZip|Object|Array} this JSZip object (when adding a file), + * a file (when searching by string) or an array of files (when searching by regex). + */ + file: function(name, data, o) { + if (arguments.length === 1) { + if (isRegExp(name)) { + var regexp = name; + return this.filter(function(relativePath, file) { + return !file.dir && regexp.test(relativePath); + }); + } else { + var obj = this.files[this.root + name]; + if (obj && !obj.dir) { + return obj; + } else { + return null; + } + } + } else { + name = this.root + name; + fileAdd.call(this, name, data, o); + } + return this; + }, + /** + * Add a directory to the zip file, or search. + * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders. + * @return {JSZip} an object with the new directory as the root, or an array containing matching folders. + */ + folder: function(arg) { + if (!arg) { + return this; + } + if (isRegExp(arg)) { + return this.filter(function(relativePath, file) { + return file.dir && arg.test(relativePath); + }); + } + var name = this.root + arg; + var newFolder = folderAdd.call(this, name); + var ret = this.clone(); + ret.root = newFolder.name; + return ret; + }, + /** + * Delete a file, or a directory and all sub-files, from the zip + * @param {string} name the name of the file to delete + * @return {JSZip} this JSZip object + */ + remove: function(name) { + name = this.root + name; + var file = this.files[name]; + if (!file) { + if (name.slice(-1) !== "/") { + name += "/"; + } + file = this.files[name]; + } + if (file && !file.dir) { + delete this.files[name]; + } else { + var kids = this.filter(function(relativePath, file2) { + return file2.name.slice(0, name.length) === name; + }); + for (var i = 0; i < kids.length; i++) { + delete this.files[kids[i].name]; + } + } + return this; + }, + /** + * @deprecated This method has been removed in JSZip 3.0, please check the upgrade guide. + */ + generate: function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }, + /** + * Generate the complete zip file as an internal stream. + * @param {Object} options the options to generate the zip file : + * - compression, "STORE" by default. + * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob. + * @return {StreamHelper} the streamed zip file. + */ + generateInternalStream: function(options) { + var worker, opts = {}; + try { + opts = utils.extend(options || {}, { + streamFiles: false, + compression: "STORE", + compressionOptions: null, + type: "", + platform: "DOS", + comment: null, + mimeType: "application/zip", + encodeFileName: utf8.utf8encode + }); + opts.type = opts.type.toLowerCase(); + opts.compression = opts.compression.toUpperCase(); + if (opts.type === "binarystring") { + opts.type = "string"; + } + if (!opts.type) { + throw new Error("No output type specified."); + } + utils.checkSupport(opts.type); + if (opts.platform === "darwin" || opts.platform === "freebsd" || opts.platform === "linux" || opts.platform === "sunos") { + opts.platform = "UNIX"; + } + if (opts.platform === "win32") { + opts.platform = "DOS"; + } + var comment = opts.comment || this.comment || ""; + worker = generate.generateWorker(this, opts, comment); + } catch (e) { + worker = new GenericWorker("error"); + worker.error(e); + } + return new StreamHelper(worker, opts.type || "string", opts.mimeType); + }, + /** + * Generate the complete zip file asynchronously. + * @see generateInternalStream + */ + generateAsync: function(options, onUpdate) { + return this.generateInternalStream(options).accumulate(onUpdate); + }, + /** + * Generate the complete zip file asynchronously. + * @see generateInternalStream + */ + generateNodeStream: function(options, onUpdate) { + options = options || {}; + if (!options.type) { + options.type = "nodebuffer"; + } + return this.generateInternalStream(options).toNodejsStream(onUpdate); + } + }; + module.exports = out; + } +}); + +// node_modules/jszip/lib/reader/DataReader.js +var require_DataReader = __commonJS({ + "node_modules/jszip/lib/reader/DataReader.js"(exports2, module) { + "use strict"; + var utils = require_utils(); + function DataReader(data) { + this.data = data; + this.length = data.length; + this.index = 0; + this.zero = 0; + } + DataReader.prototype = { + /** + * Check that the offset will not go too far. + * @param {string} offset the additional offset to check. + * @throws {Error} an Error if the offset is out of bounds. + */ + checkOffset: function(offset) { + this.checkIndex(this.index + offset); + }, + /** + * Check that the specified index will not be too far. + * @param {string} newIndex the index to check. + * @throws {Error} an Error if the index is out of bounds. + */ + checkIndex: function(newIndex) { + if (this.length < this.zero + newIndex || newIndex < 0) { + throw new Error("End of data reached (data length = " + this.length + ", asked index = " + newIndex + "). Corrupted zip ?"); + } + }, + /** + * Change the index. + * @param {number} newIndex The new index. + * @throws {Error} if the new index is out of the data. + */ + setIndex: function(newIndex) { + this.checkIndex(newIndex); + this.index = newIndex; + }, + /** + * Skip the next n bytes. + * @param {number} n the number of bytes to skip. + * @throws {Error} if the new index is out of the data. + */ + skip: function(n) { + this.setIndex(this.index + n); + }, + /** + * Get the byte at the specified index. + * @param {number} i the index to use. + * @return {number} a byte. + */ + byteAt: function() { + }, + /** + * Get the next number with a given byte size. + * @param {number} size the number of bytes to read. + * @return {number} the corresponding number. + */ + readInt: function(size) { + var result = 0, i; + this.checkOffset(size); + for (i = this.index + size - 1; i >= this.index; i--) { + result = (result << 8) + this.byteAt(i); + } + this.index += size; + return result; + }, + /** + * Get the next string with a given byte size. + * @param {number} size the number of bytes to read. + * @return {string} the corresponding string. + */ + readString: function(size) { + return utils.transformTo("string", this.readData(size)); + }, + /** + * Get raw data without conversion, bytes. + * @param {number} size the number of bytes to read. + * @return {Object} the raw data, implementation specific. + */ + readData: function() { + }, + /** + * Find the last occurrence of a zip signature (4 bytes). + * @param {string} sig the signature to find. + * @return {number} the index of the last occurrence, -1 if not found. + */ + lastIndexOfSignature: function() { + }, + /** + * Read the signature (4 bytes) at the current position and compare it with sig. + * @param {string} sig the expected signature + * @return {boolean} true if the signature matches, false otherwise. + */ + readAndCheckSignature: function() { + }, + /** + * Get the next date. + * @return {Date} the date. + */ + readDate: function() { + var dostime = this.readInt(4); + return new Date(Date.UTC( + (dostime >> 25 & 127) + 1980, + // year + (dostime >> 21 & 15) - 1, + // month + dostime >> 16 & 31, + // day + dostime >> 11 & 31, + // hour + dostime >> 5 & 63, + // minute + (dostime & 31) << 1 + )); + } + }; + module.exports = DataReader; + } +}); + +// node_modules/jszip/lib/reader/ArrayReader.js +var require_ArrayReader = __commonJS({ + "node_modules/jszip/lib/reader/ArrayReader.js"(exports2, module) { + "use strict"; + var DataReader = require_DataReader(); + var utils = require_utils(); + function ArrayReader(data) { + DataReader.call(this, data); + for (var i = 0; i < this.data.length; i++) { + data[i] = data[i] & 255; + } + } + utils.inherits(ArrayReader, DataReader); + ArrayReader.prototype.byteAt = function(i) { + return this.data[this.zero + i]; + }; + ArrayReader.prototype.lastIndexOfSignature = function(sig) { + var sig0 = sig.charCodeAt(0), sig1 = sig.charCodeAt(1), sig2 = sig.charCodeAt(2), sig3 = sig.charCodeAt(3); + for (var i = this.length - 4; i >= 0; --i) { + if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) { + return i - this.zero; + } + } + return -1; + }; + ArrayReader.prototype.readAndCheckSignature = function(sig) { + var sig0 = sig.charCodeAt(0), sig1 = sig.charCodeAt(1), sig2 = sig.charCodeAt(2), sig3 = sig.charCodeAt(3), data = this.readData(4); + return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3]; + }; + ArrayReader.prototype.readData = function(size) { + this.checkOffset(size); + if (size === 0) { + return []; + } + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module.exports = ArrayReader; + } +}); + +// node_modules/jszip/lib/reader/StringReader.js +var require_StringReader = __commonJS({ + "node_modules/jszip/lib/reader/StringReader.js"(exports2, module) { + "use strict"; + var DataReader = require_DataReader(); + var utils = require_utils(); + function StringReader(data) { + DataReader.call(this, data); + } + utils.inherits(StringReader, DataReader); + StringReader.prototype.byteAt = function(i) { + return this.data.charCodeAt(this.zero + i); + }; + StringReader.prototype.lastIndexOfSignature = function(sig) { + return this.data.lastIndexOf(sig) - this.zero; + }; + StringReader.prototype.readAndCheckSignature = function(sig) { + var data = this.readData(4); + return sig === data; + }; + StringReader.prototype.readData = function(size) { + this.checkOffset(size); + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module.exports = StringReader; + } +}); + +// node_modules/jszip/lib/reader/Uint8ArrayReader.js +var require_Uint8ArrayReader = __commonJS({ + "node_modules/jszip/lib/reader/Uint8ArrayReader.js"(exports2, module) { + "use strict"; + var ArrayReader = require_ArrayReader(); + var utils = require_utils(); + function Uint8ArrayReader(data) { + ArrayReader.call(this, data); + } + utils.inherits(Uint8ArrayReader, ArrayReader); + Uint8ArrayReader.prototype.readData = function(size) { + this.checkOffset(size); + if (size === 0) { + return new Uint8Array(0); + } + var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module.exports = Uint8ArrayReader; + } +}); + +// node_modules/jszip/lib/reader/NodeBufferReader.js +var require_NodeBufferReader = __commonJS({ + "node_modules/jszip/lib/reader/NodeBufferReader.js"(exports2, module) { + "use strict"; + var Uint8ArrayReader = require_Uint8ArrayReader(); + var utils = require_utils(); + function NodeBufferReader(data) { + Uint8ArrayReader.call(this, data); + } + utils.inherits(NodeBufferReader, Uint8ArrayReader); + NodeBufferReader.prototype.readData = function(size) { + this.checkOffset(size); + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module.exports = NodeBufferReader; + } +}); + +// node_modules/jszip/lib/reader/readerFor.js +var require_readerFor = __commonJS({ + "node_modules/jszip/lib/reader/readerFor.js"(exports2, module) { + "use strict"; + var utils = require_utils(); + var support = require_support(); + var ArrayReader = require_ArrayReader(); + var StringReader = require_StringReader(); + var NodeBufferReader = require_NodeBufferReader(); + var Uint8ArrayReader = require_Uint8ArrayReader(); + module.exports = function(data) { + var type = utils.getTypeOf(data); + utils.checkSupport(type); + if (type === "string" && !support.uint8array) { + return new StringReader(data); + } + if (type === "nodebuffer") { + return new NodeBufferReader(data); + } + if (support.uint8array) { + return new Uint8ArrayReader(utils.transformTo("uint8array", data)); + } + return new ArrayReader(utils.transformTo("array", data)); + }; + } +}); + +// node_modules/jszip/lib/zipEntry.js +var require_zipEntry = __commonJS({ + "node_modules/jszip/lib/zipEntry.js"(exports2, module) { + "use strict"; + var readerFor = require_readerFor(); + var utils = require_utils(); + var CompressedObject = require_compressedObject(); + var crc32fn = require_crc32(); + var utf8 = require_utf8(); + var compressions = require_compressions(); + var support = require_support(); + var MADE_BY_DOS = 0; + var MADE_BY_UNIX = 3; + var findCompression = function(compressionMethod) { + for (var method in compressions) { + if (!Object.prototype.hasOwnProperty.call(compressions, method)) { + continue; + } + if (compressions[method].magic === compressionMethod) { + return compressions[method]; + } + } + return null; + }; + function ZipEntry(options, loadOptions) { + this.options = options; + this.loadOptions = loadOptions; + } + ZipEntry.prototype = { + /** + * say if the file is encrypted. + * @return {boolean} true if the file is encrypted, false otherwise. + */ + isEncrypted: function() { + return (this.bitFlag & 1) === 1; + }, + /** + * say if the file has utf-8 filename/comment. + * @return {boolean} true if the filename/comment is in utf-8, false otherwise. + */ + useUTF8: function() { + return (this.bitFlag & 2048) === 2048; + }, + /** + * Read the local part of a zip file and add the info in this object. + * @param {DataReader} reader the reader to use. + */ + readLocalPart: function(reader) { + var compression, localExtraFieldsLength; + reader.skip(22); + this.fileNameLength = reader.readInt(2); + localExtraFieldsLength = reader.readInt(2); + this.fileName = reader.readData(this.fileNameLength); + reader.skip(localExtraFieldsLength); + if (this.compressedSize === -1 || this.uncompressedSize === -1) { + throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)"); + } + compression = findCompression(this.compressionMethod); + if (compression === null) { + throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")"); + } + this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize)); + }, + /** + * Read the central part of a zip file and add the info in this object. + * @param {DataReader} reader the reader to use. + */ + readCentralPart: function(reader) { + this.versionMadeBy = reader.readInt(2); + reader.skip(2); + this.bitFlag = reader.readInt(2); + this.compressionMethod = reader.readString(2); + this.date = reader.readDate(); + this.crc32 = reader.readInt(4); + this.compressedSize = reader.readInt(4); + this.uncompressedSize = reader.readInt(4); + var fileNameLength = reader.readInt(2); + this.extraFieldsLength = reader.readInt(2); + this.fileCommentLength = reader.readInt(2); + this.diskNumberStart = reader.readInt(2); + this.internalFileAttributes = reader.readInt(2); + this.externalFileAttributes = reader.readInt(4); + this.localHeaderOffset = reader.readInt(4); + if (this.isEncrypted()) { + throw new Error("Encrypted zip are not supported"); + } + reader.skip(fileNameLength); + this.readExtraFields(reader); + this.parseZIP64ExtraField(reader); + this.fileComment = reader.readData(this.fileCommentLength); + }, + /** + * Parse the external file attributes and get the unix/dos permissions. + */ + processAttributes: function() { + this.unixPermissions = null; + this.dosPermissions = null; + var madeBy = this.versionMadeBy >> 8; + this.dir = this.externalFileAttributes & 16 ? true : false; + if (madeBy === MADE_BY_DOS) { + this.dosPermissions = this.externalFileAttributes & 63; + } + if (madeBy === MADE_BY_UNIX) { + this.unixPermissions = this.externalFileAttributes >> 16 & 65535; + } + if (!this.dir && this.fileNameStr.slice(-1) === "/") { + this.dir = true; + } + }, + /** + * Parse the ZIP64 extra field and merge the info in the current ZipEntry. + * @param {DataReader} reader the reader to use. + */ + parseZIP64ExtraField: function() { + if (!this.extraFields[1]) { + return; + } + var extraReader = readerFor(this.extraFields[1].value); + if (this.uncompressedSize === utils.MAX_VALUE_32BITS) { + this.uncompressedSize = extraReader.readInt(8); + } + if (this.compressedSize === utils.MAX_VALUE_32BITS) { + this.compressedSize = extraReader.readInt(8); + } + if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) { + this.localHeaderOffset = extraReader.readInt(8); + } + if (this.diskNumberStart === utils.MAX_VALUE_32BITS) { + this.diskNumberStart = extraReader.readInt(4); + } + }, + /** + * Read the central part of a zip file and add the info in this object. + * @param {DataReader} reader the reader to use. + */ + readExtraFields: function(reader) { + var end = reader.index + this.extraFieldsLength, extraFieldId, extraFieldLength, extraFieldValue; + if (!this.extraFields) { + this.extraFields = {}; + } + while (reader.index + 4 < end) { + extraFieldId = reader.readInt(2); + extraFieldLength = reader.readInt(2); + extraFieldValue = reader.readData(extraFieldLength); + this.extraFields[extraFieldId] = { + id: extraFieldId, + length: extraFieldLength, + value: extraFieldValue + }; + } + reader.setIndex(end); + }, + /** + * Apply an UTF8 transformation if needed. + */ + handleUTF8: function() { + var decodeParamType = support.uint8array ? "uint8array" : "array"; + if (this.useUTF8()) { + this.fileNameStr = utf8.utf8decode(this.fileName); + this.fileCommentStr = utf8.utf8decode(this.fileComment); + } else { + var upath = this.findExtraFieldUnicodePath(); + if (upath !== null) { + this.fileNameStr = upath; + } else { + var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName); + this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray); + } + var ucomment = this.findExtraFieldUnicodeComment(); + if (ucomment !== null) { + this.fileCommentStr = ucomment; + } else { + var commentByteArray = utils.transformTo(decodeParamType, this.fileComment); + this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray); + } + } + }, + /** + * Find the unicode path declared in the extra field, if any. + * @return {String} the unicode path, null otherwise. + */ + findExtraFieldUnicodePath: function() { + var upathField = this.extraFields[28789]; + if (upathField) { + var extraReader = readerFor(upathField.value); + if (extraReader.readInt(1) !== 1) { + return null; + } + if (crc32fn(this.fileName) !== extraReader.readInt(4)) { + return null; + } + return utf8.utf8decode(extraReader.readData(upathField.length - 5)); + } + return null; + }, + /** + * Find the unicode comment declared in the extra field, if any. + * @return {String} the unicode comment, null otherwise. + */ + findExtraFieldUnicodeComment: function() { + var ucommentField = this.extraFields[25461]; + if (ucommentField) { + var extraReader = readerFor(ucommentField.value); + if (extraReader.readInt(1) !== 1) { + return null; + } + if (crc32fn(this.fileComment) !== extraReader.readInt(4)) { + return null; + } + return utf8.utf8decode(extraReader.readData(ucommentField.length - 5)); + } + return null; + } + }; + module.exports = ZipEntry; + } +}); + +// node_modules/jszip/lib/zipEntries.js +var require_zipEntries = __commonJS({ + "node_modules/jszip/lib/zipEntries.js"(exports2, module) { + "use strict"; + var readerFor = require_readerFor(); + var utils = require_utils(); + var sig = require_signature(); + var ZipEntry = require_zipEntry(); + var support = require_support(); + function ZipEntries(loadOptions) { + this.files = []; + this.loadOptions = loadOptions; + } + ZipEntries.prototype = { + /** + * Check that the reader is on the specified signature. + * @param {string} expectedSignature the expected signature. + * @throws {Error} if it is an other signature. + */ + checkSignature: function(expectedSignature) { + if (!this.reader.readAndCheckSignature(expectedSignature)) { + this.reader.index -= 4; + var signature = this.reader.readString(4); + throw new Error("Corrupted zip or bug: unexpected signature (" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")"); + } + }, + /** + * Check if the given signature is at the given index. + * @param {number} askedIndex the index to check. + * @param {string} expectedSignature the signature to expect. + * @return {boolean} true if the signature is here, false otherwise. + */ + isSignature: function(askedIndex, expectedSignature) { + var currentIndex = this.reader.index; + this.reader.setIndex(askedIndex); + var signature = this.reader.readString(4); + var result = signature === expectedSignature; + this.reader.setIndex(currentIndex); + return result; + }, + /** + * Read the end of the central directory. + */ + readBlockEndOfCentral: function() { + this.diskNumber = this.reader.readInt(2); + this.diskWithCentralDirStart = this.reader.readInt(2); + this.centralDirRecordsOnThisDisk = this.reader.readInt(2); + this.centralDirRecords = this.reader.readInt(2); + this.centralDirSize = this.reader.readInt(4); + this.centralDirOffset = this.reader.readInt(4); + this.zipCommentLength = this.reader.readInt(2); + var zipComment = this.reader.readData(this.zipCommentLength); + var decodeParamType = support.uint8array ? "uint8array" : "array"; + var decodeContent = utils.transformTo(decodeParamType, zipComment); + this.zipComment = this.loadOptions.decodeFileName(decodeContent); + }, + /** + * Read the end of the Zip 64 central directory. + * Not merged with the method readEndOfCentral : + * The end of central can coexist with its Zip64 brother, + * I don't want to read the wrong number of bytes ! + */ + readBlockZip64EndOfCentral: function() { + this.zip64EndOfCentralSize = this.reader.readInt(8); + this.reader.skip(4); + this.diskNumber = this.reader.readInt(4); + this.diskWithCentralDirStart = this.reader.readInt(4); + this.centralDirRecordsOnThisDisk = this.reader.readInt(8); + this.centralDirRecords = this.reader.readInt(8); + this.centralDirSize = this.reader.readInt(8); + this.centralDirOffset = this.reader.readInt(8); + this.zip64ExtensibleData = {}; + var extraDataSize = this.zip64EndOfCentralSize - 44, index = 0, extraFieldId, extraFieldLength, extraFieldValue; + while (index < extraDataSize) { + extraFieldId = this.reader.readInt(2); + extraFieldLength = this.reader.readInt(4); + extraFieldValue = this.reader.readData(extraFieldLength); + this.zip64ExtensibleData[extraFieldId] = { + id: extraFieldId, + length: extraFieldLength, + value: extraFieldValue + }; + } + }, + /** + * Read the end of the Zip 64 central directory locator. + */ + readBlockZip64EndOfCentralLocator: function() { + this.diskWithZip64CentralDirStart = this.reader.readInt(4); + this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8); + this.disksCount = this.reader.readInt(4); + if (this.disksCount > 1) { + throw new Error("Multi-volumes zip are not supported"); + } + }, + /** + * Read the local files, based on the offset read in the central part. + */ + readLocalFiles: function() { + var i, file; + for (i = 0; i < this.files.length; i++) { + file = this.files[i]; + this.reader.setIndex(file.localHeaderOffset); + this.checkSignature(sig.LOCAL_FILE_HEADER); + file.readLocalPart(this.reader); + file.handleUTF8(); + file.processAttributes(); + } + }, + /** + * Read the central directory. + */ + readCentralDir: function() { + var file; + this.reader.setIndex(this.centralDirOffset); + while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) { + file = new ZipEntry({ + zip64: this.zip64 + }, this.loadOptions); + file.readCentralPart(this.reader); + this.files.push(file); + } + if (this.centralDirRecords !== this.files.length) { + if (this.centralDirRecords !== 0 && this.files.length === 0) { + throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length); + } else { + } + } + }, + /** + * Read the end of central directory. + */ + readEndOfCentral: function() { + var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END); + if (offset < 0) { + var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER); + if (isGarbage) { + throw new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html"); + } else { + throw new Error("Corrupted zip: can't find end of central directory"); + } + } + this.reader.setIndex(offset); + var endOfCentralDirOffset = offset; + this.checkSignature(sig.CENTRAL_DIRECTORY_END); + this.readBlockEndOfCentral(); + if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) { + this.zip64 = true; + offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); + if (offset < 0) { + throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator"); + } + this.reader.setIndex(offset); + this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); + this.readBlockZip64EndOfCentralLocator(); + if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) { + this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); + if (this.relativeOffsetEndOfZip64CentralDir < 0) { + throw new Error("Corrupted zip: can't find the ZIP64 end of central directory"); + } + } + this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir); + this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); + this.readBlockZip64EndOfCentral(); + } + var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize; + if (this.zip64) { + expectedEndOfCentralDirOffset += 20; + expectedEndOfCentralDirOffset += 12 + this.zip64EndOfCentralSize; + } + var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset; + if (extraBytes > 0) { + if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) { + } else { + this.reader.zero = extraBytes; + } + } else if (extraBytes < 0) { + throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes."); + } + }, + prepareReader: function(data) { + this.reader = readerFor(data); + }, + /** + * Read a zip file and create ZipEntries. + * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file. + */ + load: function(data) { + this.prepareReader(data); + this.readEndOfCentral(); + this.readCentralDir(); + this.readLocalFiles(); + } + }; + module.exports = ZipEntries; + } +}); + +// node_modules/jszip/lib/load.js +var require_load = __commonJS({ + "node_modules/jszip/lib/load.js"(exports2, module) { + "use strict"; + var utils = require_utils(); + var external = require_external(); + var utf8 = require_utf8(); + var ZipEntries = require_zipEntries(); + var Crc32Probe = require_Crc32Probe(); + var nodejsUtils = require_nodejsUtils(); + function checkEntryCRC32(zipEntry) { + return new external.Promise(function(resolve, reject) { + var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe()); + worker.on("error", function(e) { + reject(e); + }).on("end", function() { + if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) { + reject(new Error("Corrupted zip : CRC32 mismatch")); + } else { + resolve(); + } + }).resume(); + }); + } + module.exports = function(data, options) { + var zip = this; + options = utils.extend(options || {}, { + base64: false, + checkCRC32: false, + optimizedBinaryString: false, + createFolders: false, + decodeFileName: utf8.utf8decode + }); + if (nodejsUtils.isNode && nodejsUtils.isStream(data)) { + return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")); + } + return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64).then(function(data2) { + var zipEntries = new ZipEntries(options); + zipEntries.load(data2); + return zipEntries; + }).then(function checkCRC32(zipEntries) { + var promises = [external.Promise.resolve(zipEntries)]; + var files = zipEntries.files; + if (options.checkCRC32) { + for (var i = 0; i < files.length; i++) { + promises.push(checkEntryCRC32(files[i])); + } + } + return external.Promise.all(promises); + }).then(function addFiles(results) { + var zipEntries = results.shift(); + var files = zipEntries.files; + for (var i = 0; i < files.length; i++) { + var input = files[i]; + var unsafeName = input.fileNameStr; + var safeName = utils.resolve(input.fileNameStr); + zip.file(safeName, input.decompressed, { + binary: true, + optimizedBinaryString: true, + date: input.date, + dir: input.dir, + comment: input.fileCommentStr.length ? input.fileCommentStr : null, + unixPermissions: input.unixPermissions, + dosPermissions: input.dosPermissions, + createFolders: options.createFolders + }); + if (!input.dir) { + zip.file(safeName).unsafeOriginalName = unsafeName; + } + } + if (zipEntries.zipComment.length) { + zip.comment = zipEntries.zipComment; + } + return zip; + }); + }; + } +}); + +// node_modules/jszip/lib/index.js +var require_lib3 = __commonJS({ + "node_modules/jszip/lib/index.js"(exports2, module) { + "use strict"; + function JSZip7() { + if (!(this instanceof JSZip7)) { + return new JSZip7(); + } + if (arguments.length) { + throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide."); + } + this.files = /* @__PURE__ */ Object.create(null); + this.comment = null; + this.root = ""; + this.clone = function() { + var newObj = new JSZip7(); + for (var i in this) { + if (typeof this[i] !== "function") { + newObj[i] = this[i]; + } + } + return newObj; + }; + } + JSZip7.prototype = require_object(); + JSZip7.prototype.loadAsync = require_load(); + JSZip7.support = require_support(); + JSZip7.defaults = require_defaults(); + JSZip7.version = "3.10.1"; + JSZip7.loadAsync = function(content, options) { + return new JSZip7().loadAsync(content, options); + }; + JSZip7.external = require_external(); + module.exports = JSZip7; + } +}); + +// node_modules/utif2/UTIF.js +var require_UTIF = __commonJS({ + "node_modules/utif2/UTIF.js"(exports2, module) { + (function() { + var UTIF2 = {}; + if (typeof module == "object") { + module.exports = UTIF2; + } else { + self.UTIF = UTIF2; + } + var pako = typeof __require === "function" ? require_pako() : self.pako; + function log() { + if (typeof process == "undefined" || process.env.NODE_ENV == "development") console.log.apply(console, arguments); + } + (function(UTIF3, pako2) { + (function() { + "use strict"; + var W = (function a1() { + function W2(p) { + this.message = "JPEG error: " + p; + } + W2.prototype = new Error(); + W2.prototype.name = "JpegError"; + W2.constructor = W2; + return W2; + })(), ak = (function ag() { + var p = new Uint8Array([0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63]), t = 4017, ac = 799, ah = 3406, ao = 2276, ar = 1567, ai = 3784, s = 5793, ad = 2896; + function ak2(Q) { + if (Q == null) Q = {}; + if (Q.w == null) Q.w = -1; + this.V = Q.n; + this.N = Q.w; + } + function a5(Q, h) { + var f = 0, G = [], n, E, a = 16, F; + while (a > 0 && !Q[a - 1]) { + a--; + } + G.push({ children: [], index: 0 }); + var C = G[0]; + for (n = 0; n < a; n++) { + for (E = 0; E < Q[n]; E++) { + C = G.pop(); + C.children[C.index] = h[f]; + while (C.index > 0) { + C = G.pop(); + } + C.index++; + G.push(C); + while (G.length <= n) { + G.push(F = { children: [], index: 0 }); + C.children[C.index] = F.children; + C = F; + } + f++; + } + if (n + 1 < a) { + G.push(F = { children: [], index: 0 }); + C.children[C.index] = F.children; + C = F; + } + } + return G[0].children; + } + function a2(Q, h, f) { + return 64 * ((Q.P + 1) * h + f); + } + function a7(Q, h, f, G, n, E, a, C, F, d) { + if (d == null) d = false; + var T = f.m, U = f.Z, z = h, J = 0, V = 0, r = 0, D = 0, a8, q = 0, X, O, _, N, e, K, x = 0, k, g, R, c; + function Y() { + if (V > 0) { + V--; + return J >> V & 1; + } + J = Q[h++]; + if (J === 255) { + var I = Q[h++]; + if (I) { + if (I === 220 && d) { + h += 2; + var l = Z(Q, h); + h += 2; + if (l > 0 && l !== f.s) { + throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data", l); + } + } else if (I === 217) { + if (d) { + var M = q * 8; + if (M > 0 && M < f.s / 10) { + throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter", M); + } + } + throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data"); + } + throw new W("unexpected marker"); + } + } + V = 7; + return J >>> 7; + } + function u(I) { + var l = I; + while (true) { + l = l[Y()]; + switch (typeof l) { + case "number": + return l; + case "object": + continue; + } + throw new W("invalid huffman sequence"); + } + } + function m(I) { + var e2 = 0; + while (I > 0) { + e2 = e2 << 1 | Y(); + I--; + } + return e2; + } + function j(I) { + if (I === 1) { + return Y() === 1 ? 1 : -1; + } + var e2 = m(I); + if (e2 >= 1 << I - 1) { + return e2; + } + return e2 + (-1 << I) + 1; + } + function v(X2, I) { + var l = u(X2.J), M = l === 0 ? 0 : j(l), N2 = 1; + X2.D[I] = X2.Q += M; + while (N2 < 64) { + var S = u(X2.i), i = S & 15, A = S >> 4; + if (i === 0) { + if (A < 15) { + break; + } + N2 += 16; + continue; + } + N2 += A; + var o = p[N2]; + X2.D[I + o] = j(i); + N2++; + } + } + function $(X2, I) { + var l = u(X2.J), M = l === 0 ? 0 : j(l) << F; + X2.D[I] = X2.Q += M; + } + function b(X2, I) { + X2.D[I] |= Y() << F; + } + function P(X2, I) { + if (r > 0) { + r--; + return; + } + var N2 = E, l = a; + while (N2 <= l) { + var M = u(X2.i), S = M & 15, i = M >> 4; + if (S === 0) { + if (i < 15) { + r = m(i) + (1 << i) - 1; + break; + } + N2 += 16; + continue; + } + N2 += i; + var A = p[N2]; + X2.D[I + A] = j(S) * (1 << F); + N2++; + } + } + function a4(X2, I) { + var N2 = E, l = a, M = 0, S, i; + while (N2 <= l) { + var A = I + p[N2], o = X2.D[A] < 0 ? -1 : 1; + switch (D) { + case 0: + i = u(X2.i); + S = i & 15; + M = i >> 4; + if (S === 0) { + if (M < 15) { + r = m(M) + (1 << M); + D = 4; + } else { + M = 16; + D = 1; + } + } else { + if (S !== 1) { + throw new W("invalid ACn encoding"); + } + a8 = j(S); + D = M ? 2 : 3; + } + continue; + case 1: + case 2: + if (X2.D[A]) { + X2.D[A] += o * (Y() << F); + } else { + M--; + if (M === 0) { + D = D === 2 ? 3 : 0; + } + } + break; + case 3: + if (X2.D[A]) { + X2.D[A] += o * (Y() << F); + } else { + X2.D[A] = a8 << F; + D = 0; + } + break; + case 4: + if (X2.D[A]) { + X2.D[A] += o * (Y() << F); + } + break; + } + N2++; + } + if (D === 4) { + r--; + if (r === 0) { + D = 0; + } + } + } + function H(X2, I, x2, l, M) { + var S = x2 / T | 0, i = x2 % T; + q = S * X2.A + l; + var A = i * X2.h + M, o = a2(X2, q, A); + I(X2, o); + } + function w(X2, I, x2) { + q = x2 / X2.P | 0; + var l = x2 % X2.P, M = a2(X2, q, l); + I(X2, M); + } + var y = G.length; + if (U) { + if (E === 0) { + K = C === 0 ? $ : b; + } else { + K = C === 0 ? P : a4; + } + } else { + K = v; + } + if (y === 1) { + g = G[0].P * G[0].c; + } else { + g = T * f.R; + } + while (x <= g) { + var L = n ? Math.min(g - x, n) : g; + if (L > 0) { + for (O = 0; O < y; O++) { + G[O].Q = 0; + } + r = 0; + if (y === 1) { + X = G[0]; + for (e = 0; e < L; e++) { + w(X, K, x); + x++; + } + } else { + for (e = 0; e < L; e++) { + for (O = 0; O < y; O++) { + X = G[O]; + R = X.h; + c = X.A; + for (_ = 0; _ < c; _++) { + for (N = 0; N < R; N++) { + H(X, K, x, _, N); + } + } + } + x++; + } + } + } + V = 0; + k = an(Q, h); + if (!k) { + break; + } + if (k.u) { + var a6 = L > 0 ? "unexpected" : "excessive"; + h = k.offset; + } + if (k.M >= 65488 && k.M <= 65495) { + h += 2; + } else { + break; + } + } + return h - z; + } + function al(Q, h, f) { + var G = Q.$, n = Q.D, E, a, C, F, d, T, U, z, J, V, Y, u, m, j, v, $, b; + if (!G) { + throw new W("missing required Quantization Table."); + } + for (var r = 0; r < 64; r += 8) { + J = n[h + r]; + V = n[h + r + 1]; + Y = n[h + r + 2]; + u = n[h + r + 3]; + m = n[h + r + 4]; + j = n[h + r + 5]; + v = n[h + r + 6]; + $ = n[h + r + 7]; + J *= G[r]; + if ((V | Y | u | m | j | v | $) === 0) { + b = s * J + 512 >> 10; + f[r] = b; + f[r + 1] = b; + f[r + 2] = b; + f[r + 3] = b; + f[r + 4] = b; + f[r + 5] = b; + f[r + 6] = b; + f[r + 7] = b; + continue; + } + V *= G[r + 1]; + Y *= G[r + 2]; + u *= G[r + 3]; + m *= G[r + 4]; + j *= G[r + 5]; + v *= G[r + 6]; + $ *= G[r + 7]; + E = s * J + 128 >> 8; + a = s * m + 128 >> 8; + C = Y; + F = v; + d = ad * (V - $) + 128 >> 8; + z = ad * (V + $) + 128 >> 8; + T = u << 4; + U = j << 4; + E = E + a + 1 >> 1; + a = E - a; + b = C * ai + F * ar + 128 >> 8; + C = C * ar - F * ai + 128 >> 8; + F = b; + d = d + U + 1 >> 1; + U = d - U; + z = z + T + 1 >> 1; + T = z - T; + E = E + F + 1 >> 1; + F = E - F; + a = a + C + 1 >> 1; + C = a - C; + b = d * ao + z * ah + 2048 >> 12; + d = d * ah - z * ao + 2048 >> 12; + z = b; + b = T * ac + U * t + 2048 >> 12; + T = T * t - U * ac + 2048 >> 12; + U = b; + f[r] = E + z; + f[r + 7] = E - z; + f[r + 1] = a + U; + f[r + 6] = a - U; + f[r + 2] = C + T; + f[r + 5] = C - T; + f[r + 3] = F + d; + f[r + 4] = F - d; + } + for (var P = 0; P < 8; ++P) { + J = f[P]; + V = f[P + 8]; + Y = f[P + 16]; + u = f[P + 24]; + m = f[P + 32]; + j = f[P + 40]; + v = f[P + 48]; + $ = f[P + 56]; + if ((V | Y | u | m | j | v | $) === 0) { + b = s * J + 8192 >> 14; + if (b < -2040) { + b = 0; + } else if (b >= 2024) { + b = 255; + } else { + b = b + 2056 >> 4; + } + n[h + P] = b; + n[h + P + 8] = b; + n[h + P + 16] = b; + n[h + P + 24] = b; + n[h + P + 32] = b; + n[h + P + 40] = b; + n[h + P + 48] = b; + n[h + P + 56] = b; + continue; + } + E = s * J + 2048 >> 12; + a = s * m + 2048 >> 12; + C = Y; + F = v; + d = ad * (V - $) + 2048 >> 12; + z = ad * (V + $) + 2048 >> 12; + T = u; + U = j; + E = (E + a + 1 >> 1) + 4112; + a = E - a; + b = C * ai + F * ar + 2048 >> 12; + C = C * ar - F * ai + 2048 >> 12; + F = b; + d = d + U + 1 >> 1; + U = d - U; + z = z + T + 1 >> 1; + T = z - T; + E = E + F + 1 >> 1; + F = E - F; + a = a + C + 1 >> 1; + C = a - C; + b = d * ao + z * ah + 2048 >> 12; + d = d * ah - z * ao + 2048 >> 12; + z = b; + b = T * ac + U * t + 2048 >> 12; + T = T * t - U * ac + 2048 >> 12; + U = b; + J = E + z; + $ = E - z; + V = a + U; + v = a - U; + Y = C + T; + j = C - T; + u = F + d; + m = F - d; + if (J < 16) { + J = 0; + } else if (J >= 4080) { + J = 255; + } else { + J >>= 4; + } + if (V < 16) { + V = 0; + } else if (V >= 4080) { + V = 255; + } else { + V >>= 4; + } + if (Y < 16) { + Y = 0; + } else if (Y >= 4080) { + Y = 255; + } else { + Y >>= 4; + } + if (u < 16) { + u = 0; + } else if (u >= 4080) { + u = 255; + } else { + u >>= 4; + } + if (m < 16) { + m = 0; + } else if (m >= 4080) { + m = 255; + } else { + m >>= 4; + } + if (j < 16) { + j = 0; + } else if (j >= 4080) { + j = 255; + } else { + j >>= 4; + } + if (v < 16) { + v = 0; + } else if (v >= 4080) { + v = 255; + } else { + v >>= 4; + } + if ($ < 16) { + $ = 0; + } else if ($ >= 4080) { + $ = 255; + } else { + $ >>= 4; + } + n[h + P] = J; + n[h + P + 8] = V; + n[h + P + 16] = Y; + n[h + P + 24] = u; + n[h + P + 32] = m; + n[h + P + 40] = j; + n[h + P + 48] = v; + n[h + P + 56] = $; + } + } + function a0(Q, h) { + var f = h.P, G = h.c, n = new Int16Array(64); + for (var E = 0; E < G; E++) { + for (var a = 0; a < f; a++) { + var C = a2(h, E, a); + al(h, C, n); + } + } + return h.D; + } + function an(Q, h, f) { + if (f == null) f = h; + var G = Q.length - 1, n = f < h ? f : h; + if (h >= G) { + return null; + } + var E = Z(Q, h); + if (E >= 65472 && E <= 65534) { + return { u: null, M: E, offset: h }; + } + var a = Z(Q, n); + while (!(a >= 65472 && a <= 65534)) { + if (++n >= G) { + return null; + } + a = Z(Q, n); + } + return { u: E.toString(16), M: a, offset: n }; + } + ak2.prototype = { parse(Q, h) { + if (h == null) h = {}; + var f = h.F, E = 0, a = null, C = null, F, d, T = 0; + function G() { + var o = Z(Q, E); + E += 2; + var B = E + o - 2, V2 = an(Q, B, E); + if (V2 && V2.u) { + B = V2.offset; + } + var ab = Q.subarray(E, B); + E += ab.length; + return ab; + } + function n(F2) { + var o = Math.ceil(F2.o / 8 / F2.X), B = Math.ceil(F2.s / 8 / F2.B); + for (var Y2 = 0; Y2 < F2.W.length; Y2++) { + R = F2.W[Y2]; + var ab = Math.ceil(Math.ceil(F2.o / 8) * R.h / F2.X), af = Math.ceil(Math.ceil(F2.s / 8) * R.A / F2.B), ap = o * R.h, aq = B * R.A, ae = 64 * aq * (ap + 1); + R.D = new Int16Array(ae); + R.P = ab; + R.c = af; + } + F2.m = o; + F2.R = B; + } + var U = [], z = [], J = [], V = Z(Q, E); + E += 2; + if (V !== 65496) { + throw new W("SOI not found"); + } + V = Z(Q, E); + E += 2; + markerLoop: while (V !== 65497) { + var Y, u, m; + switch (V) { + case 65504: + case 65505: + case 65506: + case 65507: + case 65508: + case 65509: + case 65510: + case 65511: + case 65512: + case 65513: + case 65514: + case 65515: + case 65516: + case 65517: + case 65518: + case 65519: + case 65534: + var j = G(); + if (V === 65504) { + if (j[0] === 74 && j[1] === 70 && j[2] === 73 && j[3] === 70 && j[4] === 0) { + a = { version: { d: j[5], T: j[6] }, K: j[7], j: j[8] << 8 | j[9], H: j[10] << 8 | j[11], S: j[12], I: j[13], C: j.subarray(14, 14 + 3 * j[12] * j[13]) }; + } + } + if (V === 65518) { + if (j[0] === 65 && j[1] === 100 && j[2] === 111 && j[3] === 98 && j[4] === 101) { + C = { version: j[5] << 8 | j[6], k: j[7] << 8 | j[8], q: j[9] << 8 | j[10], a: j[11] }; + } + } + break; + case 65499: + var v = Z(Q, E), b; + E += 2; + var $ = v + E - 2; + while (E < $) { + var r = Q[E++], P = new Uint16Array(64); + if (r >> 4 === 0) { + for (u = 0; u < 64; u++) { + b = p[u]; + P[b] = Q[E++]; + } + } else if (r >> 4 === 1) { + for (u = 0; u < 64; u++) { + b = p[u]; + P[b] = Z(Q, E); + E += 2; + } + } else { + throw new W("DQT - invalid table spec"); + } + U[r & 15] = P; + } + break; + case 65472: + case 65473: + case 65474: + if (F) { + throw new W("Only single frame JPEGs supported"); + } + E += 2; + F = {}; + F.G = V === 65473; + F.Z = V === 65474; + F.precision = Q[E++]; + var D = Z(Q, E), a4, q = 0, H = 0; + E += 2; + F.s = f || D; + F.o = Z(Q, E); + E += 2; + F.W = []; + F._ = {}; + var a8 = Q[E++]; + for (Y = 0; Y < a8; Y++) { + a4 = Q[E]; + var w = Q[E + 1] >> 4, y = Q[E + 1] & 15; + if (q < w) { + q = w; + } + if (H < y) { + H = y; + } + var X = Q[E + 2]; + m = F.W.push({ h: w, A: y, L: X, $: null }); + F._[a4] = m - 1; + E += 3; + } + F.X = q; + F.B = H; + n(F); + break; + case 65476: + var O = Z(Q, E); + E += 2; + for (Y = 2; Y < O; ) { + var _ = Q[E++], N = new Uint8Array(16), e = 0; + for (u = 0; u < 16; u++, E++) { + e += N[u] = Q[E]; + } + var K = new Uint8Array(e); + for (u = 0; u < e; u++, E++) { + K[u] = Q[E]; + } + Y += 17 + e; + (_ >> 4 === 0 ? J : z)[_ & 15] = a5(N, K); + } + break; + case 65501: + E += 2; + d = Z(Q, E); + E += 2; + break; + case 65498: + var x = ++T === 1 && !f, R; + E += 2; + var k = Q[E++], g = []; + for (Y = 0; Y < k; Y++) { + var c = Q[E++], L = F._[c]; + R = F.W[L]; + R.index = c; + var a6 = Q[E++]; + R.J = J[a6 >> 4]; + R.i = z[a6 & 15]; + g.push(R); + } + var I = Q[E++], l = Q[E++], M = Q[E++]; + try { + var S = a7(Q, E, F, g, d, I, l, M >> 4, M & 15, x); + E += S; + } catch (ex) { + if (ex instanceof DNLMarkerError) { + return this.parse(Q, { F: ex.s }); + } else if (ex instanceof EOIMarkerError) { + break markerLoop; + } + throw ex; + } + break; + case 65500: + E += 4; + break; + case 65535: + if (Q[E] !== 255) { + E--; + } + break; + default: + var i = an(Q, E - 2, E - 3); + if (i && i.u) { + E = i.offset; + break; + } + if (E >= Q.length - 1) { + break markerLoop; + } + throw new W("JpegImage.parse - unknown marker: " + V.toString(16)); + } + V = Z(Q, E); + E += 2; + } + this.width = F.o; + this.height = F.s; + this.g = a; + this.b = C; + this.W = []; + for (Y = 0; Y < F.W.length; Y++) { + R = F.W[Y]; + var A = U[R.L]; + if (A) { + R.$ = A; + } + this.W.push({ index: R.index, e: a0(F, R), l: R.h / F.X, t: R.A / F.B, P: R.P, c: R.c }); + } + this.p = this.W.length; + return void 0; + }, Y(Q, h, f) { + if (f == null) f = false; + var G = this.width / Q, n = this.height / h, E, a, C, F, d, T, U, z, J, V, Y = 0, u, m = this.W.length, j = Q * h * m, v = new Uint8ClampedArray(j), $ = new Uint32Array(Q), b = 4294967288, r; + for (U = 0; U < m; U++) { + E = this.W[U]; + a = E.l * G; + C = E.t * n; + Y = U; + u = E.e; + F = E.P + 1 << 3; + if (a !== r) { + for (d = 0; d < Q; d++) { + z = 0 | d * a; + $[d] = (z & b) << 3 | z & 7; + } + r = a; + } + for (T = 0; T < h; T++) { + z = 0 | T * C; + V = F * (z & b) | (z & 7) << 3; + for (d = 0; d < Q; d++) { + v[Y] = u[V + $[d]]; + Y += m; + } + } + } + var P = this.V; + if (!f && m === 4 && !P) { + P = new Int32Array([-256, 255, -256, 255, -256, 255, -256, 255]); + } + if (P) { + for (U = 0; U < j; ) { + for (z = 0, J = 0; z < m; z++, U++, J += 2) { + v[U] = (v[U] * P[J] >> 8) + P[J + 1]; + } + } + } + return v; + }, get f() { + if (this.b) { + return !!this.b.a; + } + if (this.p === 3) { + if (this.N === 0) { + return false; + } else if (this.W[0].index === 82 && this.W[1].index === 71 && this.W[2].index === 66) { + return false; + } + return true; + } + if (this.N === 1) { + return true; + } + return false; + }, z: function aj(Q) { + var h, f, G; + for (var n = 0, E = Q.length; n < E; n += 3) { + h = Q[n]; + f = Q[n + 1]; + G = Q[n + 2]; + Q[n] = h - 179.456 + 1.402 * G; + Q[n + 1] = h + 135.459 - 0.344 * f - 0.714 * G; + Q[n + 2] = h - 226.816 + 1.772 * f; + } + return Q; + }, O: function aa(Q) { + var h, f, G, n, E = 0; + for (var a = 0, C = Q.length; a < C; a += 4) { + h = Q[a]; + f = Q[a + 1]; + G = Q[a + 2]; + n = Q[a + 3]; + Q[E++] = -122.67195406894 + f * (-660635669420364e-19 * f + 437130475926232e-18 * G - 54080610064599e-18 * h + 48449797120281e-17 * n - 0.154362151871126) + G * (-957964378445773e-18 * G + 817076911346625e-18 * h - 0.00477271405408747 * n + 1.53380253221734) + h * (961250184130688e-18 * h - 0.00266257332283933 * n + 0.48357088451265) + n * (-336197177618394e-18 * n + 0.484791561490776); + Q[E++] = 107.268039397724 + f * (219927104525741e-19 * f - 640992018297945e-18 * G + 659397001245577e-18 * h + 426105652938837e-18 * n - 0.176491792462875) + G * (-778269941513683e-18 * G + 0.00130872261408275 * h + 770482631801132e-18 * n - 0.151051492775562) + h * (0.00126935368114843 * h - 0.00265090189010898 * n + 0.25802910206845) + n * (-318913117588328e-18 * n - 0.213742400323665); + Q[E++] = -20.810012546947 + f * (-570115196973677e-18 * f - 263409051004589e-19 * G + 0.0020741088115012 * h - 0.00288260236853442 * n + 0.814272968359295) + G * (-153496057440975e-19 * G - 132689043961446e-18 * h + 560833691242812e-18 * n - 0.195152027534049) + h * (0.00174418132927582 * h - 0.00255243321439347 * n + 0.116935020465145) + n * (-343531996510555e-18 * n + 0.24165260232407); + } + return Q.subarray(0, E); + }, r: function a3(Q) { + var h, f, G; + for (var n = 0, E = Q.length; n < E; n += 4) { + h = Q[n]; + f = Q[n + 1]; + G = Q[n + 2]; + Q[n] = 434.456 - h - 1.402 * G; + Q[n + 1] = 119.541 - h + 0.344 * f + 0.714 * G; + Q[n + 2] = 481.816 - h - 1.772 * f; + } + return Q; + }, U: function as(Q) { + var h, f, G, n, E = 0; + for (var a = 0, C = Q.length; a < C; a += 4) { + h = Q[a]; + f = Q[a + 1]; + G = Q[a + 2]; + n = Q[a + 3]; + Q[E++] = 255 + h * (-6747147073602441e-20 * h + 8379262121013727e-19 * f + 2894718188643294e-19 * G + 0.003264231057537806 * n - 1.1185611867203937) + f * (26374107616089405e-21 * f - 8626949158638572e-20 * G - 2748769067499491e-19 * n - 0.02155688794978967) + G * (-3878099212869363e-20 * G - 3267808279485286e-19 * n + 0.0686742238595345) - n * (3361971776183937e-19 * n + 0.7430659151342254); + Q[E++] = 255 + h * (13596372813588848e-20 * h + 924537132573585e-18 * f + 10567359618683593e-20 * G + 4791864687436512e-19 * n - 0.3109689587515875) + f * (-23545346108370344e-20 * f + 2702845253534714e-19 * G + 0.0020200308977307156 * n - 0.7488052167015494) + G * (6834815998235662e-20 * G + 15168452363460973e-20 * n - 0.09751927774728933) - n * (3189131175883281e-19 * n + 0.7364883807733168); + Q[E++] = 255 + h * (13598650411385307e-21 * h + 12423956175490851e-20 * f + 4751985097583589e-19 * G - 36729317476630422e-22 * n - 0.05562186980264034) + f * (16141380598724676e-20 * f + 9692239130725186e-19 * G + 7782692450036253e-19 * n - 0.44015232367526463) + G * (5068882914068769e-22 * G + 0.0017778369011375071 * n - 0.7591454649749609) - n * (3435319965105553e-19 * n + 0.7063770186160144); + } + return Q.subarray(0, E); + }, getData: function(Q) { + var h = Q.width, f = Q.height, G = Q.forceRGB, n = Q.isSourcePDF; + if (this.p > 4) { + throw new W("Unsupported color mode"); + } + var E = this.Y(h, f, n); + if (this.p === 1 && G) { + var a = E.length, C = new Uint8ClampedArray(a * 3), F = 0; + for (var d = 0; d < a; d++) { + var T = E[d]; + C[F++] = T; + C[F++] = T; + C[F++] = T; + } + return C; + } else if (this.p === 3 && this.f) { + return this.z(E); + } else if (this.p === 4) { + if (this.f) { + if (G) { + return this.O(E); + } + return this.r(E); + } else if (G) { + return this.U(E); + } + } + return E; + } }; + return ak2; + })(); + function a9(p, t) { + return p[t] << 24 >> 24; + } + function Z(p, t) { + return p[t] << 8 | p[t + 1]; + } + function am(p, t) { + return (p[t] << 24 | p[t + 1] << 16 | p[t + 2] << 8 | p[t + 3]) >>> 0; + } + UTIF3.JpegDecoder = ak; + })(); + UTIF3.encodeImage = function(rgba, w, h, metadata) { + var idf = { + "t256": [w], + "t257": [h], + "t258": [8, 8, 8, 8], + "t259": [1], + "t262": [2], + "t273": [1e3], + // strips offset + "t277": [4], + "t278": [h], + /* rows per strip */ + "t279": [w * h * 4], + // strip byte counts + "t282": [[72, 1]], + "t283": [[72, 1]], + "t284": [1], + "t286": [[0, 1]], + "t287": [[0, 1]], + "t296": [1], + "t305": ["Photopea (UTIF.js)"], + "t338": [1] + }; + if (metadata) for (var i in metadata) idf[i] = metadata[i]; + var prfx = new Uint8Array(UTIF3.encode([idf])); + var img = new Uint8Array(rgba); + var data = new Uint8Array(1e3 + w * h * 4); + for (var i = 0; i < prfx.length; i++) data[i] = prfx[i]; + for (var i = 0; i < img.length; i++) data[1e3 + i] = img[i]; + return data.buffer; + }; + UTIF3.encode = function(ifds) { + var LE = false; + var data = new Uint8Array(2e4), offset = 4, bin = LE ? UTIF3._binLE : UTIF3._binBE; + data[0] = data[1] = LE ? 73 : 77; + bin.writeUshort(data, 2, 42); + var ifdo = 8; + bin.writeUint(data, offset, ifdo); + offset += 4; + for (var i = 0; i < ifds.length; i++) { + var noffs = UTIF3._writeIFD(bin, UTIF3._types.basic, data, ifdo, ifds[i]); + ifdo = noffs[1]; + if (i < ifds.length - 1) { + if ((ifdo & 3) != 0) ifdo += 4 - (ifdo & 3); + bin.writeUint(data, noffs[0], ifdo); + } + } + return data.slice(0, ifdo).buffer; + }; + UTIF3.decode = function(buff, prm) { + if (prm == null) prm = { parseMN: true, debug: false }; + var data = new Uint8Array(buff), offset = 0; + var id = UTIF3._binBE.readASCII(data, offset, 2); + offset += 2; + var bin = id == "II" ? UTIF3._binLE : UTIF3._binBE; + var num = bin.readUshort(data, offset); + offset += 2; + var ifdo = bin.readUint(data, offset); + offset += 4; + var ifds = []; + while (true) { + var cnt = bin.readUshort(data, ifdo), typ = bin.readUshort(data, ifdo + 4); + if (cnt != 0) { + if (typ < 1 || 13 < typ) { + log("error in TIFF"); + break; + } + } + ; + UTIF3._readIFD(bin, data, ifdo, ifds, 0, prm); + ifdo = bin.readUint(data, ifdo + 2 + cnt * 12); + if (ifdo == 0) break; + } + return ifds; + }; + UTIF3.decodeImage = function(buff, img, ifds) { + if (img.data) return; + var data = new Uint8Array(buff); + var id = UTIF3._binBE.readASCII(data, 0, 2); + if (img["t256"] == null) return; + img.isLE = id == "II"; + img.width = img["t256"][0]; + img.height = img["t257"][0]; + var cmpr = img["t259"] ? img["t259"][0] : 1; + var fo = img["t266"] ? img["t266"][0] : 1; + if (img["t284"] && img["t284"][0] == 2) log("PlanarConfiguration 2 should not be used!"); + if (cmpr == 7 && img["t258"] && img["t258"].length > 3) img["t258"] = img["t258"].slice(0, 3); + var spp = img["t277"] ? img["t277"][0] : 1; + var bps = img["t258"] ? img["t258"][0] : 1; + var bipp = bps * spp; + if (cmpr == 1 && img["t279"] != null && img["t278"] && img["t262"][0] == 32803) { + bipp = Math.round(img["t279"][0] * 8 / (img.width * img["t278"][0])); + } + if (img["t50885"] && img["t50885"][0] == 4) bipp = img["t258"][0] * 3; + var bipl = Math.ceil(img.width * bipp / 8) * 8; + var soff = img["t273"]; + if (soff == null || img["t322"]) soff = img["t324"]; + var bcnt = img["t279"]; + if (cmpr == 1 && soff.length == 1) bcnt = [img.height * (bipl >>> 3)]; + if (bcnt == null || img["t322"]) bcnt = img["t325"]; + var bytes = new Uint8Array(img.height * (bipl >>> 3)), bilen = 0; + if (img["t322"] != null) { + var tw = img["t322"][0], th = img["t323"][0]; + var tx = Math.floor((img.width + tw - 1) / tw); + var ty = Math.floor((img.height + th - 1) / th); + var tbuff = new Uint8Array(Math.ceil(tw * th * bipp / 8) | 0); + console.log("====", tx, ty); + for (var y = 0; y < ty; y++) + for (var x = 0; x < tx; x++) { + var i = y * tx + x; + tbuff.fill(0); + UTIF3.decode._decompress(img, ifds, data, soff[i], bcnt[i], cmpr, tbuff, 0, fo, tw, th); + if (cmpr == 6) bytes = tbuff; + else UTIF3._copyTile(tbuff, Math.ceil(tw * bipp / 8) | 0, th, bytes, Math.ceil(img.width * bipp / 8) | 0, img.height, Math.ceil(x * tw * bipp / 8) | 0, y * th); + } + bilen = bytes.length * 8; + } else { + if (soff == null) return; + var rps = img["t278"] ? img["t278"][0] : img.height; + rps = Math.min(rps, img.height); + for (var i = 0; i < soff.length; i++) { + UTIF3.decode._decompress(img, ifds, data, soff[i], bcnt[i], cmpr, bytes, Math.ceil(bilen / 8) | 0, fo, img.width, rps); + bilen += bipl * rps; + } + bilen = Math.min(bilen, bytes.length * 8); + } + img.data = new Uint8Array(bytes.buffer, 0, Math.ceil(bilen / 8) | 0); + }; + UTIF3.decode._decompress = function(img, ifds, data, off, len, cmpr, tgt, toff, fo, w, h) { + if (img["t271"] && img["t271"][0] == "Panasonic" && img["t45"] && img["t45"][0] == 6) cmpr = 34316; + if (false) { + } else if (cmpr == 1) for (var j = 0; j < len; j++) tgt[toff + j] = data[off + j]; + else if (cmpr == 2) UTIF3.decode._decodeG2(data, off, len, tgt, toff, w, fo); + else if (cmpr == 3) UTIF3.decode._decodeG3(data, off, len, tgt, toff, w, fo, img["t292"] ? (img["t292"][0] & 1) == 1 : false); + else if (cmpr == 4) UTIF3.decode._decodeG4(data, off, len, tgt, toff, w, fo); + else if (cmpr == 5) UTIF3.decode._decodeLZW(data, off, len, tgt, toff, 8); + else if (cmpr == 6) UTIF3.decode._decodeOldJPEG(img, data, off, len, tgt, toff); + else if (cmpr == 7 || cmpr == 34892) UTIF3.decode._decodeNewJPEG(img, data, off, len, tgt, toff); + else if (cmpr == 8 || cmpr == 32946) { + var src = new Uint8Array(data.buffer, off + 2, len - 6); + var bin = pako2["inflateRaw"](src); + if (toff + bin.length <= tgt.length) tgt.set(bin, toff); + } else if (cmpr == 9) UTIF3.decode._decodeVC5(data, off, len, tgt, toff, img["t33422"]); + else if (cmpr == 32767) UTIF3.decode._decodeARW(img, data, off, len, tgt, toff); + else if (cmpr == 32773) UTIF3.decode._decodePackBits(data, off, len, tgt, toff); + else if (cmpr == 32809) UTIF3.decode._decodeThunder(data, off, len, tgt, toff); + else if (cmpr == 34316) UTIF3.decode._decodePanasonic(img, data, off, len, tgt, toff); + else if (cmpr == 34713) + UTIF3.decode._decodeNikon(img, ifds, data, off, len, tgt, toff); + else if (cmpr == 34676) UTIF3.decode._decodeLogLuv32(img, data, off, len, tgt, toff); + else log("Unknown compression", cmpr); + var bps = img["t258"] ? Math.min(32, img["t258"][0]) : 1; + var noc = img["t277"] ? img["t277"][0] : 1, bpp = bps * noc >>> 3, bpl = Math.ceil(bps * noc * w / 8); + if (bps == 16 && !img.isLE && img["t33422"] == null) + for (var y = 0; y < h; y++) { + var roff = toff + y * bpl; + for (var x = 1; x < bpl; x += 2) { + var t = tgt[roff + x]; + tgt[roff + x] = tgt[roff + x - 1]; + tgt[roff + x - 1] = t; + } + } + if (img["t317"] && img["t317"][0] == 2) { + for (var y = 0; y < h; y++) { + var ntoff = toff + y * bpl; + if (bps == 16) for (var j = bpp; j < bpl; j += 2) { + var nv = (tgt[ntoff + j + 1] << 8 | tgt[ntoff + j]) + (tgt[ntoff + j - bpp + 1] << 8 | tgt[ntoff + j - bpp]); + tgt[ntoff + j] = nv & 255; + tgt[ntoff + j + 1] = nv >>> 8 & 255; + } + else if (noc == 3) for (var j = 3; j < bpl; j += 3) { + tgt[ntoff + j] = tgt[ntoff + j] + tgt[ntoff + j - 3] & 255; + tgt[ntoff + j + 1] = tgt[ntoff + j + 1] + tgt[ntoff + j - 2] & 255; + tgt[ntoff + j + 2] = tgt[ntoff + j + 2] + tgt[ntoff + j - 1] & 255; + } + else for (var j = bpp; j < bpl; j++) tgt[ntoff + j] = tgt[ntoff + j] + tgt[ntoff + j - bpp] & 255; + } + } + }; + UTIF3.decode._decodePanasonic = function(img, data, off, len, tgt, toff) { + var img_buffer = data.buffer; + var rawWidth = img["t2"][0]; + var rawHeight = img["t3"][0]; + var bitsPerSample = img["t10"][0]; + var RW2_Format = img["t45"][0]; + var bidx = 0; + var imageIndex = 0; + var vpos = 0; + var byte = 0; + var arr_a, arr_b; + var bytes = RW2_Format == 6 ? new Uint32Array(18) : new Uint8Array(16); + var i, j, sh, pred = [0, 0], nonz = [0, 0], isOdd, idx = 0, pixel_base; + var row, col, crow; + var buffer = new Uint8Array(16384); + var result = new Uint16Array(tgt.buffer); + function getDataRaw(bits) { + if (vpos == 0) { + var arr_a2 = new Uint8Array(img_buffer, off + imageIndex + 8184, 16384 - 8184); + var arr_b2 = new Uint8Array(img_buffer, off + imageIndex, 8184); + buffer.set(arr_a2); + buffer.set(arr_b2, arr_a2.length); + imageIndex += 16384; + } + if (RW2_Format == 5) { + for (i = 0; i < 16; i++) { + bytes[i] = buffer[vpos++]; + vpos &= 16383; + } + } else { + vpos = vpos - bits & 131071; + byte = vpos >> 3 ^ 16368; + return (buffer[byte] | buffer[byte + 1] << 8) >> (vpos & 7) & ~(-1 << bits); + } + } + function getBufferDataRW6(i2) { + return buffer[vpos + 15 - i2]; + } + function readPageRW6() { + bytes[0] = getBufferDataRW6(0) << 6 | getBufferDataRW6(1) >> 2; + bytes[1] = ((getBufferDataRW6(1) & 3) << 12 | getBufferDataRW6(2) << 4 | getBufferDataRW6(3) >> 4) & 16383; + bytes[2] = getBufferDataRW6(3) >> 2 & 3; + bytes[3] = (getBufferDataRW6(3) & 3) << 8 | getBufferDataRW6(4); + bytes[4] = getBufferDataRW6(5) << 2 | getBufferDataRW6(6) >> 6; + bytes[5] = (getBufferDataRW6(6) & 63) << 4 | getBufferDataRW6(7) >> 4; + bytes[6] = getBufferDataRW6(7) >> 2 & 3; + bytes[7] = (getBufferDataRW6(7) & 3) << 8 | getBufferDataRW6(8); + bytes[8] = getBufferDataRW6(9) << 2 & 1020 | getBufferDataRW6(10) >> 6; + bytes[9] = (getBufferDataRW6(10) << 4 | getBufferDataRW6(11) >> 4) & 1023; + bytes[10] = getBufferDataRW6(11) >> 2 & 3; + bytes[11] = (getBufferDataRW6(11) & 3) << 8 | getBufferDataRW6(12); + bytes[12] = (getBufferDataRW6(13) << 2 & 1020 | getBufferDataRW6(14) >> 6) & 1023; + bytes[13] = (getBufferDataRW6(14) << 4 | getBufferDataRW6(15) >> 4) & 1023; + vpos += 16; + byte = 0; + } + function readPageRw6_bps12() { + bytes[0] = getBufferDataRW6(0) << 4 | getBufferDataRW6(1) >> 4; + bytes[1] = ((getBufferDataRW6(1) & 15) << 8 | getBufferDataRW6(2)) & 4095; + bytes[2] = getBufferDataRW6(3) >> 6 & 3; + bytes[3] = (getBufferDataRW6(3) & 63) << 2 | getBufferDataRW6(4) >> 6; + bytes[4] = (getBufferDataRW6(4) & 63) << 2 | getBufferDataRW6(5) >> 6; + bytes[5] = (getBufferDataRW6(5) & 63) << 2 | getBufferDataRW6(6) >> 6; + bytes[6] = getBufferDataRW6(6) >> 4 & 3; + bytes[7] = (getBufferDataRW6(6) & 15) << 4 | getBufferDataRW6(7) >> 4; + bytes[8] = (getBufferDataRW6(7) & 15) << 4 | getBufferDataRW6(8) >> 4; + bytes[9] = (getBufferDataRW6(8) & 15) << 4 | getBufferDataRW6(9) >> 4; + bytes[10] = getBufferDataRW6(9) >> 2 & 3; + bytes[11] = (getBufferDataRW6(9) & 3) << 6 | getBufferDataRW6(10) >> 2; + bytes[12] = (getBufferDataRW6(10) & 3) << 6 | getBufferDataRW6(11) >> 2; + bytes[13] = (getBufferDataRW6(11) & 3) << 6 | getBufferDataRW6(12) >> 2; + bytes[14] = getBufferDataRW6(12) & 3; + bytes[15] = getBufferDataRW6(13); + bytes[16] = getBufferDataRW6(14); + bytes[17] = getBufferDataRW6(15); + vpos += 16; + byte = 0; + } + function resetPredNonzeros() { + pred[0] = 0; + pred[1] = 0; + nonz[0] = 0; + nonz[1] = 0; + } + if (RW2_Format == 7) { + throw RW2_Format; + } else if (RW2_Format == 6) { + var is12bit = bitsPerSample == 12, readPageRw6Fn = is12bit ? readPageRw6_bps12 : readPageRW6, pixelsPerBlock = is12bit ? 14 : 11, pixelbase0 = is12bit ? 128 : 512, pixelbase_compare = is12bit ? 2048 : 8192, spix_compare = is12bit ? 16383 : 65535, pixel_mask = is12bit ? 4095 : 16383, blocksperrow = rawWidth / pixelsPerBlock, rowbytes = blocksperrow * 16, bufferSize = is12bit ? 18 : 14; + for (row = 0; row < rawHeight - 15; row += 16) { + var rowstoread = Math.min(16, rawHeight - row); + var readlen = rowbytes * rowstoread; + buffer = new Uint8Array(img_buffer, off + bidx, readlen); + vpos = 0; + bidx += readlen; + for (crow = 0, col = 0; crow < rowstoread; crow++, col = 0) { + idx = (row + crow) * rawWidth; + for (var rblock = 0; rblock < blocksperrow; rblock++) { + readPageRw6Fn(); + resetPredNonzeros(); + sh = 0; + pixel_base = 0; + for (i = 0; i < pixelsPerBlock; i++) { + isOdd = i & 1; + if (i % 3 == 2) { + var base = byte < bufferSize ? bytes[byte++] : 0; + if (base == 3) base = 4; + pixel_base = pixelbase0 << base; + sh = 1 << base; + } + var epixel = byte < bufferSize ? bytes[byte++] : 0; + if (pred[isOdd]) { + epixel *= sh; + if (pixel_base < pixelbase_compare && nonz[isOdd] > pixel_base) + epixel += nonz[isOdd] - pixel_base; + nonz[isOdd] = epixel; + } else { + pred[isOdd] = epixel; + if (epixel) + nonz[isOdd] = epixel; + else + epixel = nonz[isOdd]; + } + result[idx + col++] = epixel - 15 <= spix_compare ? epixel - 15 & spix_compare : epixel + 2147483633 >> 31 & pixel_mask; + } + } + } + } + } else if (RW2_Format == 5) { + var blockSize = bitsPerSample == 12 ? 10 : 9; + for (row = 0; row < rawHeight; row++) { + for (col = 0; col < rawWidth; col += blockSize) { + getDataRaw(0); + if (bitsPerSample == 12) { + result[idx++] = ((bytes[1] & 15) << 8) + bytes[0]; + result[idx++] = 16 * bytes[2] + (bytes[1] >> 4); + result[idx++] = ((bytes[4] & 15) << 8) + bytes[3]; + result[idx++] = 16 * bytes[5] + (bytes[4] >> 4); + result[idx++] = ((bytes[7] & 15) << 8) + bytes[6]; + result[idx++] = 16 * bytes[8] + (bytes[7] >> 4); + result[idx++] = ((bytes[10] & 15) << 8) + bytes[9]; + result[idx++] = 16 * bytes[11] + (bytes[10] >> 4); + result[idx++] = ((bytes[13] & 15) << 8) + bytes[12]; + result[idx++] = 16 * bytes[14] + (bytes[13] >> 4); + } else if (bitsPerSample == 14) { + result[idx++] = bytes[0] + ((bytes[1] & 63) << 8); + result[idx++] = (bytes[1] >> 6) + 4 * bytes[2] + ((bytes[3] & 15) << 10); + result[idx++] = (bytes[3] >> 4) + 16 * bytes[4] + ((bytes[5] & 3) << 12); + result[idx++] = ((bytes[5] & 252) >> 2) + (bytes[6] << 6); + result[idx++] = bytes[7] + ((bytes[8] & 63) << 8); + result[idx++] = (bytes[8] >> 6) + 4 * bytes[9] + ((bytes[10] & 15) << 10); + result[idx++] = (bytes[10] >> 4) + 16 * bytes[11] + ((bytes[12] & 3) << 12); + result[idx++] = ((bytes[12] & 252) >> 2) + (bytes[13] << 6); + result[idx++] = bytes[14] + ((bytes[15] & 63) << 8); + } + } + } + } else if (RW2_Format == 4) { + for (row = 0; row < rawHeight; row++) { + for (col = 0; col < rawWidth; col++) { + i = col % 14; + isOdd = i & 1; + if (i == 0) resetPredNonzeros(); + if (i % 3 == 2) + sh = 4 >> 3 - getDataRaw(2); + if (nonz[isOdd]) { + j = getDataRaw(8); + if (j != 0) { + pred[isOdd] -= 128 << sh; + if (pred[isOdd] < 0 || sh == 4) + pred[isOdd] &= ~(-1 << sh); + pred[isOdd] += j << sh; + } + } else { + nonz[isOdd] = getDataRaw(8); + if (nonz[isOdd] || i > 11) + pred[isOdd] = nonz[isOdd] << 4 | getDataRaw(4); + } + result[idx++] = pred[col & 1]; + } + } + } else throw RW2_Format; + }; + UTIF3.decode._decodeVC5 = (function() { + var x = [1, 0, 1, 0, 2, 2, 1, 1, 3, 7, 1, 2, 5, 25, 1, 3, 6, 48, 1, 4, 6, 54, 1, 5, 7, 111, 1, 8, 7, 99, 1, 6, 7, 105, 12, 0, 7, 107, 1, 7, 8, 209, 20, 0, 8, 212, 1, 9, 8, 220, 1, 10, 9, 393, 1, 11, 9, 394, 32, 0, 9, 416, 1, 12, 9, 427, 1, 13, 10, 887, 1, 18, 10, 784, 1, 14, 10, 790, 1, 15, 10, 835, 60, 0, 10, 852, 1, 16, 10, 885, 1, 17, 11, 1571, 1, 19, 11, 1668, 1, 20, 11, 1669, 100, 0, 11, 1707, 1, 21, 11, 1772, 1, 22, 12, 3547, 1, 29, 12, 3164, 1, 24, 12, 3166, 1, 25, 12, 3140, 1, 23, 12, 3413, 1, 26, 12, 3537, 1, 27, 12, 3539, 1, 28, 13, 7093, 1, 35, 13, 6283, 1, 30, 13, 6331, 1, 31, 13, 6335, 180, 0, 13, 6824, 1, 32, 13, 7072, 1, 33, 13, 7077, 320, 0, 13, 7076, 1, 34, 14, 12565, 1, 36, 14, 12661, 1, 37, 14, 12669, 1, 38, 14, 13651, 1, 39, 14, 14184, 1, 40, 15, 28295, 1, 46, 15, 28371, 1, 47, 15, 25320, 1, 42, 15, 25336, 1, 43, 15, 25128, 1, 41, 15, 27300, 1, 44, 15, 28293, 1, 45, 16, 50259, 1, 48, 16, 50643, 1, 49, 16, 50675, 1, 50, 16, 56740, 1, 53, 16, 56584, 1, 51, 16, 56588, 1, 52, 17, 113483, 1, 61, 17, 113482, 1, 60, 17, 101285, 1, 55, 17, 101349, 1, 56, 17, 109205, 1, 57, 17, 109207, 1, 58, 17, 100516, 1, 54, 17, 113171, 1, 59, 18, 202568, 1, 62, 18, 202696, 1, 63, 18, 218408, 1, 64, 18, 218412, 1, 65, 18, 226340, 1, 66, 18, 226356, 1, 67, 18, 226358, 1, 68, 19, 402068, 1, 69, 19, 405138, 1, 70, 19, 405394, 1, 71, 19, 436818, 1, 72, 19, 436826, 1, 73, 19, 452714, 1, 75, 19, 452718, 1, 76, 19, 452682, 1, 74, 20, 804138, 1, 77, 20, 810279, 1, 78, 20, 810790, 1, 79, 20, 873638, 1, 80, 20, 873654, 1, 81, 20, 905366, 1, 82, 20, 905430, 1, 83, 20, 905438, 1, 84, 21, 1608278, 1, 85, 21, 1620557, 1, 86, 21, 1621582, 1, 87, 21, 1621583, 1, 88, 21, 1747310, 1, 89, 21, 1810734, 1, 90, 21, 1810735, 1, 91, 21, 1810863, 1, 92, 21, 1810879, 1, 93, 22, 3621725, 1, 99, 22, 3621757, 1, 100, 22, 3241112, 1, 94, 22, 3494556, 1, 95, 22, 3494557, 1, 96, 22, 3494622, 1, 97, 22, 3494623, 1, 98, 23, 6482227, 1, 102, 23, 6433117, 1, 101, 23, 6989117, 1, 103, 23, 6989119, 1, 105, 23, 6989118, 1, 104, 23, 7243449, 1, 106, 23, 7243512, 1, 107, 24, 13978233, 1, 111, 24, 12964453, 1, 109, 24, 12866232, 1, 108, 24, 14486897, 1, 113, 24, 13978232, 1, 110, 24, 14486896, 1, 112, 24, 14487026, 1, 114, 24, 14487027, 1, 115, 25, 25732598, 1, 225, 25, 25732597, 1, 189, 25, 25732596, 1, 188, 25, 25732595, 1, 203, 25, 25732594, 1, 202, 25, 25732593, 1, 197, 25, 25732592, 1, 207, 25, 25732591, 1, 169, 25, 25732590, 1, 223, 25, 25732589, 1, 159, 25, 25732522, 1, 235, 25, 25732579, 1, 152, 25, 25732575, 1, 192, 25, 25732489, 1, 179, 25, 25732573, 1, 201, 25, 25732472, 1, 172, 25, 25732576, 1, 149, 25, 25732488, 1, 178, 25, 25732566, 1, 120, 25, 25732571, 1, 219, 25, 25732577, 1, 150, 25, 25732487, 1, 127, 25, 25732506, 1, 211, 25, 25732548, 1, 125, 25, 25732588, 1, 158, 25, 25732486, 1, 247, 25, 25732467, 1, 238, 25, 25732508, 1, 163, 25, 25732552, 1, 228, 25, 25732603, 1, 183, 25, 25732513, 1, 217, 25, 25732587, 1, 168, 25, 25732520, 1, 122, 25, 25732484, 1, 128, 25, 25732562, 1, 249, 25, 25732505, 1, 187, 25, 25732504, 1, 186, 25, 25732483, 1, 136, 25, 25928905, 1, 181, 25, 25732560, 1, 255, 25, 25732500, 1, 230, 25, 25732482, 1, 135, 25, 25732555, 1, 233, 25, 25732568, 1, 222, 25, 25732583, 1, 145, 25, 25732481, 1, 134, 25, 25732586, 1, 167, 25, 25732521, 1, 248, 25, 25732518, 1, 209, 25, 25732480, 1, 243, 25, 25732512, 1, 216, 25, 25732509, 1, 164, 25, 25732547, 1, 140, 25, 25732479, 1, 157, 25, 25732544, 1, 239, 25, 25732574, 1, 191, 25, 25732564, 1, 251, 25, 25732478, 1, 156, 25, 25732546, 1, 139, 25, 25732498, 1, 242, 25, 25732557, 1, 133, 25, 25732477, 1, 162, 25, 25732515, 1, 213, 25, 25732584, 1, 165, 25, 25732514, 1, 212, 25, 25732476, 1, 227, 25, 25732494, 1, 198, 25, 25732531, 1, 236, 25, 25732530, 1, 234, 25, 25732529, 1, 117, 25, 25732528, 1, 215, 25, 25732527, 1, 124, 25, 25732526, 1, 123, 25, 25732525, 1, 254, 25, 25732524, 1, 253, 25, 25732523, 1, 148, 25, 25732570, 1, 218, 25, 25732580, 1, 146, 25, 25732581, 1, 147, 25, 25732569, 1, 224, 25, 25732533, 1, 143, 25, 25732540, 1, 184, 25, 25732541, 1, 185, 25, 25732585, 1, 166, 25, 25732556, 1, 132, 25, 25732485, 1, 129, 25, 25732563, 1, 250, 25, 25732578, 1, 151, 25, 25732501, 1, 119, 25, 25732502, 1, 193, 25, 25732536, 1, 176, 25, 25732496, 1, 245, 25, 25732553, 1, 229, 25, 25732516, 1, 206, 25, 25732582, 1, 144, 25, 25732517, 1, 208, 25, 25732558, 1, 137, 25, 25732543, 1, 241, 25, 25732466, 1, 237, 25, 25732507, 1, 190, 25, 25732542, 1, 240, 25, 25732551, 1, 131, 25, 25732554, 1, 232, 25, 25732565, 1, 252, 25, 25732475, 1, 171, 25, 25732493, 1, 205, 25, 25732492, 1, 204, 25, 25732491, 1, 118, 25, 25732490, 1, 214, 25, 25928904, 1, 180, 25, 25732549, 1, 126, 25, 25732602, 1, 182, 25, 25732539, 1, 175, 25, 25732545, 1, 141, 25, 25732559, 1, 138, 25, 25732537, 1, 177, 25, 25732534, 1, 153, 25, 25732503, 1, 194, 25, 25732606, 1, 160, 25, 25732567, 1, 121, 25, 25732538, 1, 174, 25, 25732497, 1, 246, 25, 25732550, 1, 130, 25, 25732572, 1, 200, 25, 25732474, 1, 170, 25, 25732511, 1, 221, 25, 25732601, 1, 196, 25, 25732532, 1, 142, 25, 25732519, 1, 210, 25, 25732495, 1, 199, 25, 25732605, 1, 155, 25, 25732535, 1, 154, 25, 25732499, 1, 244, 25, 25732510, 1, 220, 25, 25732600, 1, 195, 25, 25732607, 1, 161, 25, 25732604, 1, 231, 25, 25732473, 1, 173, 25, 25732599, 1, 226, 26, 51465122, 1, 116, 26, 51465123, 0, 1], o, C, k, P = [3, 3, 3, 3, 2, 2, 2, 1, 1, 1], V = 24576, ar = 16384, H = 8192, az = ar | H; + function d(t) { + var E = t[1], h = t[0][E >>> 3] >>> 7 - (E & 7) & 1; + t[1]++; + return h; + } + function ag(t, E) { + if (o == null) { + o = {}; + for (var h = 0; h < x.length; h += 4) o[x[h + 1]] = x.slice(h, h + 4); + } + var L = d(t), g = o[L]; + while (g == null) { + L = L << 1 | d(t); + g = o[L]; + } + var n = g[3]; + if (n != 0) n = d(t) == 0 ? n : -n; + E[0] = g[2]; + E[1] = n; + } + function m(t, E) { + for (var h = 0; h < E; h++) { + if ((t & 1) == 1) t++; + t = t >>> 1; + } + return t; + } + function A(t, E) { + return t >> E; + } + function O(t, E, h, L, g, n) { + E[h] = A(A(11 * t[g] - 4 * t[g + n] + t[g + n + n] + 4, 3) + t[L], 1); + E[h + n] = A(A(5 * t[g] + 4 * t[g + n] - t[g + n + n] + 4, 3) - t[L], 1); + } + function J(t, E, h, L, g, n) { + var W = t[g - n] - t[g + n], j = t[g], $ = t[L]; + E[h] = A(A(W + 4, 3) + j + $, 1); + E[h + n] = A(A(-W + 4, 3) + j - $, 1); + } + function y(t, E, h, L, g, n) { + E[h] = A(A(5 * t[g] + 4 * t[g - n] - t[g - n - n] + 4, 3) + t[L], 1); + E[h + n] = A(A(11 * t[g] - 4 * t[g - n] + t[g - n - n] + 4, 3) - t[L], 1); + } + function q(t) { + t = t < 0 ? 0 : t > 4095 ? 4095 : t; + t = k[t] >>> 2; + return t; + } + function av(t, E, h, L, g, n) { + L = new Uint16Array(L.buffer); + var W = Date.now(), j = UTIF3._binBE, $ = E + h, r, u, X, I, ax, a3, R, ai, aa, ap, ah, ae, aD, al, i, aE, T, B; + E += 4; + var a5 = n[0] == 1; + while (E < $) { + var S = j.readShort(t, E), s = j.readUshort(t, E + 2); + E += 4; + if (S == 12) r = s; + else if (S == 20) u = s; + else if (S == 21) X = s; + else if (S == 48) I = s; + else if (S == 53) ax = s; + else if (S == 35) a3 = s; + else if (S == 62) R = s; + else if (S == 101) ai = s; + else if (S == 109) aa = s; + else if (S == 84) ap = s; + else if (S == 106) ah = s; + else if (S == 107) ae = s; + else if (S == 108) aD = s; + else if (S == 102) al = s; + else if (S == 104) i = s; + else if (S == 105) aE = s; + else { + var F = S < 0 ? -S : S, D = F & 65280, _ = 0; + if (F & az) { + if (F & H) { + _ = s & 65535; + _ += (F & 255) << 16; + } else { + _ = s & 65535; + } + } + if ((F & V) == V) { + if (T == null) { + T = []; + for (var M = 0; M < 4; M++) T[M] = new Int16Array((u >>> 1) * (X >>> 1)); + B = new Int16Array((u >>> 1) * (X >>> 1)); + C = new Int16Array(1024); + for (var M = 0; M < 1024; M++) { + var aG = M - 512, p = Math.abs(aG), r = Math.floor(768 * p * p * p / (255 * 255 * 255)) + p; + C[M] = Math.sign(aG) * r; + } + k = new Uint16Array(4096); + var aA = (1 << 16) - 1; + for (var M = 0; M < 4096; M++) { + var at = M, a1 = aA * (Math.pow(113, at / 4095) - 1) / 112; + k[M] = Math.min(a1, aA); + } + } + var w = T[R], v = m(u, 1 + P[I]), N = m(X, 1 + P[I]); + if (I == 0) { + for (var b = 0; b < N; b++) for (var G = 0; G < v; G++) { + var c = E + (b * v + G) * 2; + w[b * (u >>> 1) + G] = t[c] << 8 | t[c + 1]; + } + } else { + var a7 = [t, E * 8], a4 = [], ay = 0, aw = v * N, f = [0, 0], Q = 0, s = 0; + while (ay < aw) { + ag(a7, f); + Q = f[0]; + s = f[1]; + while (Q > 0) { + a4[ay++] = s; + Q--; + } + } + var l = (I - 1) % 3, aF = l != 1 ? v : 0, a2 = l != 0 ? N : 0; + for (var b = 0; b < N; b++) { + var af = (b + a2) * (u >>> 1) + aF, au = b * v; + for (var G = 0; G < v; G++) w[af + G] = C[a4[au + G] + 512] * ax; + } + if (l == 2) { + var i = u >>> 1, an = v * 2, a9 = N * 2; + for (var b = 0; b < N; b++) { + for (var G = 0; G < an; G++) { + var M = b * 2 * i + G, a = b * i + G, e = N * i + a; + if (b == 0) O(w, B, M, e, a, i); + else if (b == N - 1) y(w, B, M, e, a, i); + else J(w, B, M, e, a, i); + } + } + var Z = w; + w = B; + B = Z; + for (var b = 0; b < a9; b++) { + for (var G = 0; G < v; G++) { + var M = b * i + 2 * G, a = b * i + G, e = v + a; + if (G == 0) O(w, B, M, e, a, 1); + else if (G == v - 1) y(w, B, M, e, a, 1); + else J(w, B, M, e, a, 1); + } + } + var Z = w; + w = B; + B = Z; + var aC = [], aB = 2 - ~~((I - 1) / 3); + for (var K = 0; K < 3; K++) aC[K] = aa >> 14 - K * 2 & 3; + var a6 = aC[aB]; + if (a6 != 0) for (var b = 0; b < a9; b++) for (var G = 0; G < an; G++) { + var M = b * i + G; + w[M] = w[M] << a6; + } + } + } + if (I == 9 && R == 3) { + var a8 = T[0], ab = T[1], aq = T[2], as = T[3]; + for (var b = 0; b < X; b += 2) for (var G = 0; G < u; G += 2) { + var U = b * u + G, c = (b >>> 1) * (u >>> 1) + (G >>> 1), z = a8[c], ao = ab[c] - 2048, ak = aq[c] - 2048, ad = as[c] - 2048, aj = (ao << 1) + z, a0 = (ak << 1) + z, aH = z + ad, am = z - ad; + if (a5) { + L[U] = q(aH); + L[U + 1] = q(a0); + L[U + u] = q(aj); + L[U + u + 1] = q(am); + } else { + L[U] = q(aj); + L[U + 1] = q(aH); + L[U + u] = q(am); + L[U + u + 1] = q(a0); + } + } + } + E += _ * 4; + } else if (F == 16388) { + E += _ * 4; + } else if (D == 8192 || D == 8448 || D == 9216) { + } else throw F.toString(16); + } + } + console.log(Date.now() - W); + } + return av; + })(); + UTIF3.decode._decodeLogLuv32 = function(img, data, off, len, tgt, toff) { + var w = img.width, qw = w * 4; + var io = 0, out = new Uint8Array(qw); + while (io < len) { + var oo = 0; + while (oo < qw) { + var c = data[off + io]; + io++; + if (c < 128) { + for (var j = 0; j < c; j++) out[oo + j] = data[off + io + j]; + oo += c; + io += c; + } else { + c = c - 126; + for (var j = 0; j < c; j++) out[oo + j] = data[off + io]; + oo += c; + io++; + } + } + for (var x = 0; x < w; x++) { + tgt[toff + 0] = out[x]; + tgt[toff + 1] = out[x + w]; + tgt[toff + 2] = out[x + w * 2]; + tgt[toff + 4] = out[x + w * 3]; + toff += 6; + } + } + }; + UTIF3.decode._ljpeg_diff = function(data, prm, huff) { + var getbithuff = UTIF3.decode._getbithuff; + var len, diff; + len = getbithuff(data, prm, huff[0], huff); + diff = getbithuff(data, prm, len, 0); + if ((diff & 1 << len - 1) == 0) diff -= (1 << len) - 1; + return diff; + }; + UTIF3.decode._decodeARW = function(img, inp, off, src_length, tgt, toff) { + var raw_width = img["t256"][0], height = img["t257"][0], tiff_bps = img["t258"][0]; + var bin = img.isLE ? UTIF3._binLE : UTIF3._binBE; + var arw2 = raw_width * height == src_length || raw_width * height * 1.5 == src_length; + if (!arw2) { + height += 8; + var prm = [off, 0, 0, 0]; + var huff = new Uint16Array(32770); + var tab = [ + 3857, + 3856, + 3599, + 3342, + 3085, + 2828, + 2571, + 2314, + 2057, + 1800, + 1543, + 1286, + 1029, + 772, + 771, + 768, + 514, + 513 + ]; + var i, c, n, col, row, sum = 0; + var ljpeg_diff = UTIF3.decode._ljpeg_diff; + huff[0] = 15; + for (n = i = 0; i < 18; i++) { + var lim = 32768 >>> (tab[i] >>> 8); + for (var c = 0; c < lim; c++) huff[++n] = tab[i]; + } + for (col = raw_width; col--; ) + for (row = 0; row < height + 1; row += 2) { + if (row == height) row = 1; + sum += ljpeg_diff(inp, prm, huff); + if (row < height) { + var clr = sum & 4095; + UTIF3.decode._putsF(tgt, (row * raw_width + col) * tiff_bps, clr << 16 - tiff_bps); + } + } + return; + } + if (raw_width * height * 1.5 == src_length) { + for (var i = 0; i < src_length; i += 3) { + var b0 = inp[off + i + 0], b1 = inp[off + i + 1], b2 = inp[off + i + 2]; + tgt[toff + i] = b1 << 4 | b0 >>> 4; + tgt[toff + i + 1] = b0 << 4 | b2 >>> 4; + tgt[toff + i + 2] = b2 << 4 | b1 >>> 4; + } + return; + } + var pix = new Uint16Array(16); + var row, col, val, max, min, imax, imin, sh, bit, i, dp; + var data = new Uint8Array(raw_width + 1); + for (row = 0; row < height; row++) { + for (var j = 0; j < raw_width; j++) data[j] = inp[off++]; + for (dp = 0, col = 0; col < raw_width - 30; dp += 16) { + max = 2047 & (val = bin.readUint(data, dp)); + min = 2047 & val >>> 11; + imax = 15 & val >>> 22; + imin = 15 & val >>> 26; + for (sh = 0; sh < 4 && 128 << sh <= max - min; sh++) ; + for (bit = 30, i = 0; i < 16; i++) + if (i == imax) pix[i] = max; + else if (i == imin) pix[i] = min; + else { + pix[i] = ((bin.readUshort(data, dp + (bit >> 3)) >>> (bit & 7) & 127) << sh) + min; + if (pix[i] > 2047) pix[i] = 2047; + bit += 7; + } + for (i = 0; i < 16; i++, col += 2) { + var clr = pix[i] << 1; + UTIF3.decode._putsF(tgt, (row * raw_width + col) * tiff_bps, clr << 16 - tiff_bps); + } + col -= col & 1 ? 1 : 31; + } + } + }; + UTIF3.decode._decodeNikon = function(img, imgs, data, off, src_length, tgt, toff) { + var nikon_tree = [ + [ + 0, + 0, + 1, + 5, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + /* 12-bit lossy */ + 5, + 4, + 3, + 6, + 2, + 7, + 1, + 0, + 8, + 9, + 11, + 10, + 12 + ], + [ + 0, + 0, + 1, + 5, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + /* 12-bit lossy after split */ + 57, + 90, + 56, + 39, + 22, + 5, + 4, + 3, + 2, + 1, + 0, + 11, + 12, + 12 + ], + [ + 0, + 0, + 1, + 4, + 2, + 3, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + /* 12-bit lossless */ + 5, + 4, + 6, + 3, + 7, + 2, + 8, + 1, + 9, + 0, + 10, + 11, + 12 + ], + [ + 0, + 0, + 1, + 4, + 3, + 1, + 1, + 1, + 1, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + /* 14-bit lossy */ + 5, + 6, + 4, + 7, + 8, + 3, + 9, + 2, + 1, + 0, + 10, + 11, + 12, + 13, + 14 + ], + [ + 0, + 0, + 1, + 5, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + /* 14-bit lossy after split */ + 8, + 92, + 75, + 58, + 41, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + 0, + 13, + 14 + ], + [ + 0, + 0, + 1, + 4, + 2, + 2, + 3, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + /* 14-bit lossless */ + 7, + 6, + 8, + 5, + 9, + 4, + 10, + 3, + 11, + 12, + 2, + 0, + 1, + 13, + 14 + ] + ]; + var raw_width = img["t256"][0], height = img["t257"][0], tiff_bps = img["t258"][0]; + var tree = 0, split = 0; + var make_decoder = UTIF3.decode._make_decoder; + var getbithuff = UTIF3.decode._getbithuff; + var mn = imgs[0].exifIFD.makerNote, md = mn["t150"] ? mn["t150"] : mn["t140"], mdo = 0; + var ver0 = md[mdo++], ver1 = md[mdo++]; + if (ver0 == 73 || ver1 == 88) mdo += 2110; + if (ver0 == 70) tree = 2; + if (tiff_bps == 14) tree += 3; + var vpred = [[0, 0], [0, 0]], bin = img.isLE ? UTIF3._binLE : UTIF3._binBE; + for (var i = 0; i < 2; i++) for (var j = 0; j < 2; j++) { + vpred[i][j] = bin.readShort(md, mdo); + mdo += 2; + } + var max = 1 << tiff_bps & 32767, step = 0; + var csize = bin.readShort(md, mdo); + mdo += 2; + if (csize > 1) step = Math.floor(max / (csize - 1)); + if (ver0 == 68 && ver1 == 32 && step > 0) split = bin.readShort(md, 562); + var i; + var row, col; + var len, shl, diff; + var min_v = 0; + var hpred = [0, 0]; + var huff = make_decoder(nikon_tree[tree]); + var prm = [off, 0, 0, 0]; + for (min_v = row = 0; row < height; row++) { + if (split && row == split) { + huff = make_decoder(nikon_tree[tree + 1]); + } + for (col = 0; col < raw_width; col++) { + i = getbithuff(data, prm, huff[0], huff); + len = i & 15; + shl = i >>> 4; + diff = (getbithuff(data, prm, len - shl, 0) << 1) + 1 << shl >>> 1; + if ((diff & 1 << len - 1) == 0) + diff -= (1 << len) - (shl == 0 ? 1 : 0); + if (col < 2) hpred[col] = vpred[row & 1][col] += diff; + else hpred[col & 1] += diff; + var clr = Math.min(Math.max(hpred[col & 1], 0), (1 << tiff_bps) - 1); + var bti = (row * raw_width + col) * tiff_bps; + UTIF3.decode._putsF(tgt, bti, clr << 16 - tiff_bps); + } + } + }; + UTIF3.decode._putsF = function(dt, pos, val) { + val = val << 8 - (pos & 7); + var o = pos >>> 3; + dt[o] |= val >>> 16; + dt[o + 1] |= val >>> 8; + dt[o + 2] |= val; + }; + UTIF3.decode._getbithuff = function(data, prm, nbits, huff) { + var zero_after_ff = 0; + var get_byte = UTIF3.decode._get_byte; + var c; + var off = prm[0], bitbuf = prm[1], vbits = prm[2], reset = prm[3]; + if (nbits == 0 || vbits < 0) return 0; + while (!reset && vbits < nbits && (c = data[off++]) != -1 && !(reset = zero_after_ff && c == 255 && data[off++])) { + bitbuf = (bitbuf << 8) + c; + vbits += 8; + } + c = bitbuf << 32 - vbits >>> 32 - nbits; + if (huff) { + vbits -= huff[c + 1] >>> 8; + c = huff[c + 1] & 255; + } else + vbits -= nbits; + if (vbits < 0) throw "e"; + prm[0] = off; + prm[1] = bitbuf; + prm[2] = vbits; + prm[3] = reset; + return c; + }; + UTIF3.decode._make_decoder = function(source) { + var max, len, h, i, j; + var huff = []; + for (max = 16; max != 0 && !source[max]; max--) ; + var si = 17; + huff[0] = max; + for (h = len = 1; len <= max; len++) + for (i = 0; i < source[len]; i++, ++si) + for (j = 0; j < 1 << max - len; j++) + if (h <= 1 << max) + huff[h++] = len << 8 | source[si]; + return huff; + }; + UTIF3.decode._decodeNewJPEG = function(img, data, off, len, tgt, toff) { + len = Math.min(len, data.length - off); + var tables = img["t347"], tlen = tables ? tables.length : 0, buff = new Uint8Array(tlen + len); + if (tables) { + var SOI = 216, EOI2 = 217, boff = 0; + for (var i = 0; i < tlen - 1; i++) { + if (tables[i] == 255 && tables[i + 1] == EOI2) break; + buff[boff++] = tables[i]; + } + var byte1 = data[off], byte2 = data[off + 1]; + if (byte1 != 255 || byte2 != SOI) { + buff[boff++] = byte1; + buff[boff++] = byte2; + } + for (var i = 2; i < len; i++) buff[boff++] = data[off + i]; + } else for (var i = 0; i < len; i++) buff[i] = data[off + i]; + if (img["t262"][0] == 32803 || img["t259"][0] == 7 && img["t262"][0] == 34892) { + var bps = img["t258"][0]; + var out = UTIF3.LosslessJpegDecode(buff), olen = out.length; + if (false) { + } else if (bps == 16) { + if (img.isLE) for (var i = 0; i < olen; i++) { + tgt[toff + (i << 1)] = out[i] & 255; + tgt[toff + (i << 1) + 1] = out[i] >>> 8; + } + else for (var i = 0; i < olen; i++) { + tgt[toff + (i << 1)] = out[i] >>> 8; + tgt[toff + (i << 1) + 1] = out[i] & 255; + } + } else if (bps == 14 || bps == 12 || bps == 10) { + var rst = 16 - bps; + for (var i = 0; i < olen; i++) UTIF3.decode._putsF(tgt, i * bps, out[i] << rst); + } else if (bps == 8) { + for (var i = 0; i < olen; i++) tgt[toff + i] = out[i]; + } else throw new Error("unsupported bit depth " + bps); + } else { + var parser3 = new UTIF3.JpegDecoder(); + parser3.parse(buff); + var decoded = parser3.getData({ "width": parser3.width, "height": parser3.height, "forceRGB": true, "isSourcePDF": false }); + for (var i = 0; i < decoded.length; i++) tgt[toff + i] = decoded[i]; + } + if (img["t262"][0] == 6) img["t262"][0] = 2; + }; + UTIF3.decode._decodeOldJPEGInit = function(img, data, off, len) { + var SOI = 216, EOI2 = 217, DQT = 219, DHT = 196, DRI = 221, SOF0 = 192, SOS2 = 218; + var joff = 0, soff = 0, tables, sosMarker2, isTiled = false, i, j, k; + var jpgIchgFmt = img["t513"], jifoff = jpgIchgFmt ? jpgIchgFmt[0] : 0; + var jpgIchgFmtLen = img["t514"], jiflen = jpgIchgFmtLen ? jpgIchgFmtLen[0] : 0; + var soffTag = img["t324"] || img["t273"] || jpgIchgFmt; + var ycbcrss = img["t530"], ssx = 0, ssy = 0; + var spp = img["t277"] ? img["t277"][0] : 1; + var jpgresint = img["t515"]; + if (soffTag) { + soff = soffTag[0]; + isTiled = soffTag.length > 1; + } + if (!isTiled) { + if (data[off] == 255 && data[off + 1] == SOI) return { jpegOffset: off }; + if (jpgIchgFmt != null) { + if (data[off + jifoff] == 255 && data[off + jifoff + 1] == SOI) joff = off + jifoff; + else log("JPEGInterchangeFormat does not point to SOI"); + if (jpgIchgFmtLen == null) log("JPEGInterchangeFormatLength field is missing"); + else if (jifoff >= soff || jifoff + jiflen <= soff) log("JPEGInterchangeFormatLength field value is invalid"); + if (joff != null) return { jpegOffset: joff }; + } + } + if (ycbcrss != null) { + ssx = ycbcrss[0]; + ssy = ycbcrss[1]; + } + if (jpgIchgFmt != null) { + if (jpgIchgFmtLen != null) + if (jiflen >= 2 && jifoff + jiflen <= soff) { + if (data[off + jifoff + jiflen - 2] == 255 && data[off + jifoff + jiflen - 1] == SOI) tables = new Uint8Array(jiflen - 2); + else tables = new Uint8Array(jiflen); + for (i = 0; i < tables.length; i++) tables[i] = data[off + jifoff + i]; + log("Incorrect JPEG interchange format: using JPEGInterchangeFormat offset to derive tables"); + } else log("JPEGInterchangeFormat+JPEGInterchangeFormatLength > offset to first strip or tile"); + } + if (tables == null) { + var ooff = 0, out = []; + out[ooff++] = 255; + out[ooff++] = SOI; + var qtables = img["t519"]; + if (qtables == null) throw new Error("JPEGQTables tag is missing"); + for (i = 0; i < qtables.length; i++) { + out[ooff++] = 255; + out[ooff++] = DQT; + out[ooff++] = 0; + out[ooff++] = 67; + out[ooff++] = i; + for (j = 0; j < 64; j++) out[ooff++] = data[off + qtables[i] + j]; + } + for (k = 0; k < 2; k++) { + var htables = img[k == 0 ? "t520" : "t521"]; + if (htables == null) throw new Error((k == 0 ? "JPEGDCTables" : "JPEGACTables") + " tag is missing"); + for (i = 0; i < htables.length; i++) { + out[ooff++] = 255; + out[ooff++] = DHT; + var nc = 19; + for (j = 0; j < 16; j++) nc += data[off + htables[i] + j]; + out[ooff++] = nc >>> 8; + out[ooff++] = nc & 255; + out[ooff++] = i | k << 4; + for (j = 0; j < 16; j++) out[ooff++] = data[off + htables[i] + j]; + for (j = 0; j < nc; j++) out[ooff++] = data[off + htables[i] + 16 + j]; + } + } + out[ooff++] = 255; + out[ooff++] = SOF0; + out[ooff++] = 0; + out[ooff++] = 8 + 3 * spp; + out[ooff++] = 8; + out[ooff++] = img.height >>> 8 & 255; + out[ooff++] = img.height & 255; + out[ooff++] = img.width >>> 8 & 255; + out[ooff++] = img.width & 255; + out[ooff++] = spp; + if (spp == 1) { + out[ooff++] = 1; + out[ooff++] = 17; + out[ooff++] = 0; + } else for (i = 0; i < 3; i++) { + out[ooff++] = i + 1; + out[ooff++] = i != 0 ? 17 : (ssx & 15) << 4 | ssy & 15; + out[ooff++] = i; + } + if (jpgresint != null && jpgresint[0] != 0) { + out[ooff++] = 255; + out[ooff++] = DRI; + out[ooff++] = 0; + out[ooff++] = 4; + out[ooff++] = jpgresint[0] >>> 8 & 255; + out[ooff++] = jpgresint[0] & 255; + } + tables = new Uint8Array(out); + } + var sofpos = -1; + i = 0; + while (i < tables.length - 1) { + if (tables[i] == 255 && tables[i + 1] == SOF0) { + sofpos = i; + break; + } + i++; + } + if (sofpos == -1) { + var tmptab = new Uint8Array(tables.length + 10 + 3 * spp); + tmptab.set(tables); + var tmpoff = tables.length; + sofpos = tables.length; + tables = tmptab; + tables[tmpoff++] = 255; + tables[tmpoff++] = SOF0; + tables[tmpoff++] = 0; + tables[tmpoff++] = 8 + 3 * spp; + tables[tmpoff++] = 8; + tables[tmpoff++] = img.height >>> 8 & 255; + tables[tmpoff++] = img.height & 255; + tables[tmpoff++] = img.width >>> 8 & 255; + tables[tmpoff++] = img.width & 255; + tables[tmpoff++] = spp; + if (spp == 1) { + tables[tmpoff++] = 1; + tables[tmpoff++] = 17; + tables[tmpoff++] = 0; + } else for (i = 0; i < 3; i++) { + tables[tmpoff++] = i + 1; + tables[tmpoff++] = i != 0 ? 17 : (ssx & 15) << 4 | ssy & 15; + tables[tmpoff++] = i; + } + } + if (data[soff] == 255 && data[soff + 1] == SOS2) { + var soslen = data[soff + 2] << 8 | data[soff + 3]; + sosMarker2 = new Uint8Array(soslen + 2); + sosMarker2[0] = data[soff]; + sosMarker2[1] = data[soff + 1]; + sosMarker2[2] = data[soff + 2]; + sosMarker2[3] = data[soff + 3]; + for (i = 0; i < soslen - 2; i++) sosMarker2[i + 4] = data[soff + i + 4]; + } else { + sosMarker2 = new Uint8Array(2 + 6 + 2 * spp); + var sosoff = 0; + sosMarker2[sosoff++] = 255; + sosMarker2[sosoff++] = SOS2; + sosMarker2[sosoff++] = 0; + sosMarker2[sosoff++] = 6 + 2 * spp; + sosMarker2[sosoff++] = spp; + if (spp == 1) { + sosMarker2[sosoff++] = 1; + sosMarker2[sosoff++] = 0; + } else for (i = 0; i < 3; i++) { + sosMarker2[sosoff++] = i + 1; + sosMarker2[sosoff++] = i << 4 | i; + } + sosMarker2[sosoff++] = 0; + sosMarker2[sosoff++] = 63; + sosMarker2[sosoff++] = 0; + } + return { jpegOffset: off, tables, sosMarker: sosMarker2, sofPosition: sofpos }; + }; + UTIF3.decode._decodeOldJPEG = function(img, data, off, len, tgt, toff) { + var i, dlen, tlen, buff, buffoff; + var jpegData = UTIF3.decode._decodeOldJPEGInit(img, data, off, len); + if (jpegData.jpegOffset != null) { + dlen = off + len - jpegData.jpegOffset; + buff = new Uint8Array(dlen); + for (i = 0; i < dlen; i++) buff[i] = data[jpegData.jpegOffset + i]; + } else { + tlen = jpegData.tables.length; + buff = new Uint8Array(tlen + jpegData.sosMarker.length + len + 2); + buff.set(jpegData.tables); + buffoff = tlen; + buff[jpegData.sofPosition + 5] = img.height >>> 8 & 255; + buff[jpegData.sofPosition + 6] = img.height & 255; + buff[jpegData.sofPosition + 7] = img.width >>> 8 & 255; + buff[jpegData.sofPosition + 8] = img.width & 255; + if (data[off] != 255 || data[off + 1] != SOS) { + buff.set(jpegData.sosMarker, buffoff); + buffoff += sosMarker.length; + } + for (i = 0; i < len; i++) buff[buffoff++] = data[off + i]; + buff[buffoff++] = 255; + buff[buffoff++] = EOI; + } + var parser3 = new UTIF3.JpegDecoder(); + parser3.parse(buff); + var decoded = parser3.getData({ "width": parser3.width, "height": parser3.height, "forceRGB": true, "isSourcePDF": false }); + for (var i = 0; i < decoded.length; i++) tgt[toff + i] = decoded[i]; + if (img["t262"] && img["t262"][0] == 6) img["t262"][0] = 2; + }; + UTIF3.decode._decodePackBits = function(data, off, len, tgt, toff) { + var sa = new Int8Array(data.buffer), ta = new Int8Array(tgt.buffer), lim = off + len; + while (off < lim) { + var n = sa[off]; + off++; + if (n >= 0 && n < 128) for (var i = 0; i < n + 1; i++) { + ta[toff] = sa[off]; + toff++; + off++; + } + if (n >= -127 && n < 0) { + for (var i = 0; i < -n + 1; i++) { + ta[toff] = sa[off]; + toff++; + } + off++; + } + } + return toff; + }; + UTIF3.decode._decodeThunder = function(data, off, len, tgt, toff) { + var d2 = [0, 1, 0, -1], d3 = [0, 1, 2, 3, 0, -3, -2, -1]; + var lim = off + len, qoff = toff * 2, px = 0; + while (off < lim) { + var b = data[off], msk = b >>> 6, n = b & 63; + off++; + if (msk == 3) { + px = n & 15; + tgt[qoff >>> 1] |= px << 4 * (1 - qoff & 1); + qoff++; + } + if (msk == 0) for (var i = 0; i < n; i++) { + tgt[qoff >>> 1] |= px << 4 * (1 - qoff & 1); + qoff++; + } + if (msk == 2) for (var i = 0; i < 2; i++) { + var d = n >>> 3 * (1 - i) & 7; + if (d != 4) { + px += d3[d]; + tgt[qoff >>> 1] |= px << 4 * (1 - qoff & 1); + qoff++; + } + } + if (msk == 1) for (var i = 0; i < 3; i++) { + var d = n >>> 2 * (2 - i) & 3; + if (d != 2) { + px += d2[d]; + tgt[qoff >>> 1] |= px << 4 * (1 - qoff & 1); + qoff++; + } + } + } + }; + UTIF3.decode._dmap = { "1": 0, "011": 1, "000011": 2, "0000011": 3, "010": -1, "000010": -2, "0000010": -3 }; + UTIF3.decode._lens = (function() { + var addKeys = function(lens, arr, i0, inc) { + for (var i = 0; i < arr.length; i++) lens[arr[i]] = i0 + i * inc; + }; + var termW = "00110101,000111,0111,1000,1011,1100,1110,1111,10011,10100,00111,01000,001000,000011,110100,110101,101010,101011,0100111,0001100,0001000,0010111,0000011,0000100,0101000,0101011,0010011,0100100,0011000,00000010,00000011,00011010,00011011,00010010,00010011,00010100,00010101,00010110,00010111,00101000,00101001,00101010,00101011,00101100,00101101,00000100,00000101,00001010,00001011,01010010,01010011,01010100,01010101,00100100,00100101,01011000,01011001,01011010,01011011,01001010,01001011,00110010,00110011,00110100"; + var termB = "0000110111,010,11,10,011,0011,0010,00011,000101,000100,0000100,0000101,0000111,00000100,00000111,000011000,0000010111,0000011000,0000001000,00001100111,00001101000,00001101100,00000110111,00000101000,00000010111,00000011000,000011001010,000011001011,000011001100,000011001101,000001101000,000001101001,000001101010,000001101011,000011010010,000011010011,000011010100,000011010101,000011010110,000011010111,000001101100,000001101101,000011011010,000011011011,000001010100,000001010101,000001010110,000001010111,000001100100,000001100101,000001010010,000001010011,000000100100,000000110111,000000111000,000000100111,000000101000,000001011000,000001011001,000000101011,000000101100,000001011010,000001100110,000001100111"; + var makeW = "11011,10010,010111,0110111,00110110,00110111,01100100,01100101,01101000,01100111,011001100,011001101,011010010,011010011,011010100,011010101,011010110,011010111,011011000,011011001,011011010,011011011,010011000,010011001,010011010,011000,010011011"; + var makeB = "0000001111,000011001000,000011001001,000001011011,000000110011,000000110100,000000110101,0000001101100,0000001101101,0000001001010,0000001001011,0000001001100,0000001001101,0000001110010,0000001110011,0000001110100,0000001110101,0000001110110,0000001110111,0000001010010,0000001010011,0000001010100,0000001010101,0000001011010,0000001011011,0000001100100,0000001100101"; + var makeA = "00000001000,00000001100,00000001101,000000010010,000000010011,000000010100,000000010101,000000010110,000000010111,000000011100,000000011101,000000011110,000000011111"; + termW = termW.split(","); + termB = termB.split(","); + makeW = makeW.split(","); + makeB = makeB.split(","); + makeA = makeA.split(","); + var lensW = {}, lensB = {}; + addKeys(lensW, termW, 0, 1); + addKeys(lensW, makeW, 64, 64); + addKeys(lensW, makeA, 1792, 64); + addKeys(lensB, termB, 0, 1); + addKeys(lensB, makeB, 64, 64); + addKeys(lensB, makeA, 1792, 64); + return [lensW, lensB]; + })(); + UTIF3.decode._decodeG4 = function(data, off, slen, tgt, toff, w, fo) { + var U = UTIF3.decode, boff = off << 3, len = 0, wrd = ""; + var line = [], pline = []; + for (var i = 0; i < w; i++) pline.push(0); + pline = U._makeDiff(pline); + var a0 = 0, a1 = 0, a2 = 0, b1 = 0, b2 = 0, clr = 0; + var y = 0, mode = "", toRead = 0; + var bipl = Math.ceil(w / 8) * 8; + while (boff >>> 3 < off + slen) { + b1 = U._findDiff(pline, a0 + (a0 == 0 ? 0 : 1), 1 - clr), b2 = U._findDiff(pline, b1, clr); + var bit = 0; + if (fo == 1) bit = data[boff >>> 3] >>> 7 - (boff & 7) & 1; + if (fo == 2) bit = data[boff >>> 3] >>> (boff & 7) & 1; + boff++; + wrd += bit; + if (mode == "H") { + if (U._lens[clr][wrd] != null) { + var dl = U._lens[clr][wrd]; + wrd = ""; + len += dl; + if (dl < 64) { + U._addNtimes(line, len, clr); + a0 += len; + clr = 1 - clr; + len = 0; + toRead--; + if (toRead == 0) mode = ""; + } + } + } else { + if (wrd == "0001") { + wrd = ""; + U._addNtimes(line, b2 - a0, clr); + a0 = b2; + } + if (wrd == "001") { + wrd = ""; + mode = "H"; + toRead = 2; + } + if (U._dmap[wrd] != null) { + a1 = b1 + U._dmap[wrd]; + U._addNtimes(line, a1 - a0, clr); + a0 = a1; + wrd = ""; + clr = 1 - clr; + } + } + if (line.length == w && mode == "") { + U._writeBits(line, tgt, toff * 8 + y * bipl); + clr = 0; + y++; + a0 = 0; + pline = U._makeDiff(line); + line = []; + } + } + }; + UTIF3.decode._findDiff = function(line, x, clr) { + for (var i = 0; i < line.length; i += 2) if (line[i] >= x && line[i + 1] == clr) return line[i]; + }; + UTIF3.decode._makeDiff = function(line) { + var out = []; + if (line[0] == 1) out.push(0, 1); + for (var i = 1; i < line.length; i++) if (line[i - 1] != line[i]) out.push(i, line[i]); + out.push(line.length, 0, line.length, 1); + return out; + }; + UTIF3.decode._decodeG2 = function(data, off, slen, tgt, toff, w, fo) { + var U = UTIF3.decode, boff = off << 3, len = 0, wrd = ""; + var line = []; + var clr = 0; + var y = 0; + var bipl = Math.ceil(w / 8) * 8; + while (boff >>> 3 < off + slen) { + var bit = 0; + if (fo == 1) bit = data[boff >>> 3] >>> 7 - (boff & 7) & 1; + if (fo == 2) bit = data[boff >>> 3] >>> (boff & 7) & 1; + boff++; + wrd += bit; + len = U._lens[clr][wrd]; + if (len != null) { + U._addNtimes(line, len, clr); + wrd = ""; + if (len < 64) clr = 1 - clr; + if (line.length == w) { + U._writeBits(line, tgt, toff * 8 + y * bipl); + line = []; + y++; + clr = 0; + if ((boff & 7) != 0) boff += 8 - (boff & 7); + if (len >= 64) boff += 8; + } + } + } + }; + UTIF3.decode._decodeG3 = function(data, off, slen, tgt, toff, w, fo, twoDim) { + var U = UTIF3.decode, boff = off << 3, len = 0, wrd = ""; + var line = [], pline = []; + for (var i = 0; i < w; i++) line.push(0); + var a0 = 0, a1 = 0, a2 = 0, b1 = 0, b2 = 0, clr = 0; + var y = -1, mode = "", toRead = 0, is1D = true; + var bipl = Math.ceil(w / 8) * 8; + while (boff >>> 3 < off + slen) { + b1 = U._findDiff(pline, a0 + (a0 == 0 ? 0 : 1), 1 - clr), b2 = U._findDiff(pline, b1, clr); + var bit = 0; + if (fo == 1) bit = data[boff >>> 3] >>> 7 - (boff & 7) & 1; + if (fo == 2) bit = data[boff >>> 3] >>> (boff & 7) & 1; + boff++; + wrd += bit; + if (is1D) { + if (U._lens[clr][wrd] != null) { + var dl = U._lens[clr][wrd]; + wrd = ""; + len += dl; + if (dl < 64) { + U._addNtimes(line, len, clr); + clr = 1 - clr; + len = 0; + } + } + } else { + if (mode == "H") { + if (U._lens[clr][wrd] != null) { + var dl = U._lens[clr][wrd]; + wrd = ""; + len += dl; + if (dl < 64) { + U._addNtimes(line, len, clr); + a0 += len; + clr = 1 - clr; + len = 0; + toRead--; + if (toRead == 0) mode = ""; + } + } + } else { + if (wrd == "0001") { + wrd = ""; + U._addNtimes(line, b2 - a0, clr); + a0 = b2; + } + if (wrd == "001") { + wrd = ""; + mode = "H"; + toRead = 2; + } + if (U._dmap[wrd] != null) { + a1 = b1 + U._dmap[wrd]; + U._addNtimes(line, a1 - a0, clr); + a0 = a1; + wrd = ""; + clr = 1 - clr; + } + } + } + if (wrd.endsWith("000000000001")) { + if (y >= 0) U._writeBits(line, tgt, toff * 8 + y * bipl); + if (twoDim) { + if (fo == 1) is1D = (data[boff >>> 3] >>> 7 - (boff & 7) & 1) == 1; + if (fo == 2) is1D = (data[boff >>> 3] >>> (boff & 7) & 1) == 1; + boff++; + } + wrd = ""; + clr = 0; + y++; + a0 = 0; + pline = U._makeDiff(line); + line = []; + } + } + if (line.length == w) U._writeBits(line, tgt, toff * 8 + y * bipl); + }; + UTIF3.decode._addNtimes = function(arr, n, val) { + for (var i = 0; i < n; i++) arr.push(val); + }; + UTIF3.decode._writeBits = function(bits, tgt, boff) { + for (var i = 0; i < bits.length; i++) tgt[boff + i >>> 3] |= bits[i] << 7 - (boff + i & 7); + }; + UTIF3.decode._decodeLZW = UTIF3.decode._decodeLZW = (function() { + var e, U, Z, u, K = 0, V = 0, g = 0, N = 0, O = function() { + var S = e >>> 3, A = U[S] << 16 | U[S + 1] << 8 | U[S + 2], j = A >>> 24 - (e & 7) - V & (1 << V) - 1; + e += V; + return j; + }, h = new Uint32Array(4096 * 4), w = 0, m = function(S) { + if (S == w) return; + w = S; + g = 1 << S; + N = g + 1; + for (var A = 0; A < N + 1; A++) { + h[4 * A] = h[4 * A + 3] = A; + h[4 * A + 1] = 65535; + h[4 * A + 2] = 1; + } + }, i = function(S) { + V = S + 1; + K = N + 1; + }, D = function(S) { + var A = S << 2, j = h[A + 2], a = u + j - 1; + while (A != 65535) { + Z[a--] = h[A]; + A = h[A + 1]; + } + u += j; + }, L = function(S, A) { + var j = K << 2, a = S << 2; + h[j] = h[(A << 2) + 3]; + h[j + 1] = a; + h[j + 2] = h[a + 2] + 1; + h[j + 3] = h[a + 3]; + K++; + if (K + 1 == 1 << V && V != 12) V++; + }, T = function(S, A, j, a, n, q) { + e = A << 3; + U = S; + Z = a; + u = n; + var B = A + j << 3, _ = 0, t = 0; + m(q); + i(q); + while (e < B && (_ = O()) != N) { + if (_ == g) { + i(q); + _ = O(); + if (_ == N) break; + D(_); + } else { + if (_ < K) { + D(_); + L(t, _); + } else { + L(t, t); + D(K - 1); + } + } + t = _; + } + return u; + }; + return T; + })(); + UTIF3.tags = {}; + UTIF3._types = (function() { + var main2 = new Array(250); + main2.fill(0); + main2 = main2.concat([0, 0, 0, 0, 4, 3, 3, 3, 3, 3, 0, 0, 3, 0, 0, 0, 3, 0, 0, 2, 2, 2, 2, 4, 3, 0, 0, 3, 4, 4, 3, 3, 5, 5, 3, 2, 5, 5, 0, 0, 0, 0, 4, 4, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 3, 5, 5, 3, 0, 3, 3, 4, 4, 4, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + var rest = { 33432: 2, 33434: 5, 33437: 5, 34665: 4, 34850: 3, 34853: 4, 34855: 3, 34864: 3, 34866: 4, 36864: 7, 36867: 2, 36868: 2, 37121: 7, 37377: 10, 37378: 5, 37380: 10, 37381: 5, 37383: 3, 37384: 3, 37385: 3, 37386: 5, 37510: 7, 37520: 2, 37521: 2, 37522: 2, 40960: 7, 40961: 3, 40962: 4, 40963: 4, 40965: 4, 41486: 5, 41487: 5, 41488: 3, 41985: 3, 41986: 3, 41987: 3, 41988: 5, 41989: 3, 41990: 3, 41993: 3, 41994: 3, 41995: 7, 41996: 3, 42032: 2, 42033: 2, 42034: 5, 42036: 2, 42037: 2, 59932: 7 }; + return { + basic: { + main: main2, + rest + }, + gps: { + main: [1, 2, 5, 2, 5, 1, 5, 5, 0, 9], + rest: { 18: 2, 29: 2 } + } + }; + })(); + UTIF3._readIFD = function(bin, data, offset, ifds, depth, prm) { + var cnt = bin.readUshort(data, offset); + offset += 2; + var ifd = {}; + if (prm.debug) log(" ".repeat(depth), ifds.length - 1, ">>>----------------"); + for (var i = 0; i < cnt; i++) { + var tag = bin.readUshort(data, offset); + offset += 2; + var type = bin.readUshort(data, offset); + offset += 2; + var num = bin.readUint(data, offset); + offset += 4; + var voff = bin.readUint(data, offset); + offset += 4; + var arr = []; + if (type == 1 || type == 7) { + var no = num < 5 ? offset - 4 : voff; + if (no + num > data.buffer.byteLength) num = data.buffer.byteLength - no; + arr = new Uint8Array(data.buffer, no, num); + } + if (type == 2) { + var o0 = num < 5 ? offset - 4 : voff, c = data[o0], len = Math.max(0, Math.min(num - 1, data.length - o0)); + if (c < 128 || len == 0) arr.push(bin.readASCII(data, o0, len)); + else arr = new Uint8Array(data.buffer, o0, len); + } + if (type == 3) { + for (var j = 0; j < num; j++) arr.push(bin.readUshort(data, (num < 3 ? offset - 4 : voff) + 2 * j)); + } + if (type == 4 || type == 13) { + for (var j = 0; j < num; j++) arr.push(bin.readUint(data, (num < 2 ? offset - 4 : voff) + 4 * j)); + } + if (type == 5 || type == 10) { + var ri = type == 5 ? bin.readUint : bin.readInt; + for (var j = 0; j < num; j++) arr.push([ri(data, voff + j * 8), ri(data, voff + j * 8 + 4)]); + } + if (type == 8) { + for (var j = 0; j < num; j++) arr.push(bin.readShort(data, (num < 3 ? offset - 4 : voff) + 2 * j)); + } + if (type == 9) { + for (var j = 0; j < num; j++) arr.push(bin.readInt(data, (num < 2 ? offset - 4 : voff) + 4 * j)); + } + if (type == 11) { + for (var j = 0; j < num; j++) arr.push(bin.readFloat(data, voff + j * 4)); + } + if (type == 12) { + for (var j = 0; j < num; j++) arr.push(bin.readDouble(data, voff + j * 8)); + } + if (num != 0 && arr.length == 0) { + log(tag, "unknown TIFF tag type: ", type, "num:", num); + if (i == 0) return; + continue; + } + if (prm.debug) log(" ".repeat(depth), tag, type, UTIF3.tags[tag], arr); + ifd["t" + tag] = arr; + if (tag == 330 && ifd["t272"] && ifd["t272"][0] == "DSLR-A100") { + } else if (tag == 330 || tag == 34665 || tag == 34853 || tag == 50740 && bin.readUshort(data, bin.readUint(arr, 0)) < 300 || tag == 61440) { + var oarr = tag == 50740 ? [bin.readUint(arr, 0)] : arr; + var subfd = []; + for (var j = 0; j < oarr.length; j++) UTIF3._readIFD(bin, data, oarr[j], subfd, depth + 1, prm); + if (tag == 330) ifd.subIFD = subfd; + if (tag == 34665) ifd.exifIFD = subfd[0]; + if (tag == 34853) ifd.gpsiIFD = subfd[0]; + if (tag == 50740) ifd.dngPrvt = subfd[0]; + if (tag == 61440) ifd.fujiIFD = subfd[0]; + } + if (tag == 37500 && prm.parseMN) { + var mn = arr; + if (bin.readASCII(mn, 0, 5) == "Nikon") ifd.makerNote = UTIF3["decode"](mn.slice(10).buffer)[0]; + else if (bin.readASCII(mn, 0, 5) == "OLYMP" || bin.readASCII(mn, 0, 9) == "OM SYSTEM") { + var inds = [8208, 8224, 8240, 8256, 8272]; + var subsub = []; + UTIF3._readIFD(bin, mn, mn[1] == 77 ? 16 : mn[5] == 85 ? 12 : 8, subsub, depth + 1, prm); + var obj = ifd.makerNote = subsub.pop(); + for (var j = 0; j < inds.length; j++) { + var k = "t" + inds[j]; + if (obj[k] == null) continue; + UTIF3._readIFD(bin, mn, obj[k][0], subsub, depth + 1, prm); + obj[k] = subsub.pop(); + } + if (obj["t12288"]) { + UTIF3._readIFD(bin, obj["t12288"], 0, subsub, depth + 1, prm); + obj["t12288"] = subsub.pop(); + } + } else if (bin.readUshort(data, voff) < 300 && bin.readUshort(data, voff + 4) <= 12) { + var subsub = []; + UTIF3._readIFD(bin, data, voff, subsub, depth + 1, prm); + ifd.makerNote = subsub[0]; + } + } + } + ifds.push(ifd); + if (prm.debug) log(" ".repeat(depth), "<<<---------------"); + return offset; + }; + UTIF3._writeIFD = function(bin, types, data, offset, ifd) { + var keys = Object.keys(ifd), knum = keys.length; + if (ifd["exifIFD"]) knum--; + if (ifd["gpsiIFD"]) knum--; + bin.writeUshort(data, offset, knum); + offset += 2; + var eoff = offset + knum * 12 + 4; + for (var ki = 0; ki < keys.length; ki++) { + var key = keys[ki]; + if (key == "t34665" || key == "t34853") continue; + if (key == "exifIFD") key = "t34665"; + if (key == "gpsiIFD") key = "t34853"; + var tag = parseInt(key.slice(1)), type = types.main[tag]; + if (type == null) type = types.rest[tag]; + if (type == null || type == 0) throw new Error("unknown type of tag: " + tag); + var val = ifd[key]; + if (tag == 34665) { + var outp = UTIF3._writeIFD(bin, types, data, eoff, ifd["exifIFD"]); + val = [eoff]; + eoff = outp[1]; + } + if (tag == 34853) { + var outp = UTIF3._writeIFD(bin, UTIF3._types.gps, data, eoff, ifd["gpsiIFD"]); + val = [eoff]; + eoff = outp[1]; + } + if (type == 2) val = val[0] + "\0"; + var num = val.length; + bin.writeUshort(data, offset, tag); + offset += 2; + bin.writeUshort(data, offset, type); + offset += 2; + bin.writeUint(data, offset, num); + offset += 4; + var dlen = [-1, 1, 1, 2, 4, 8, 0, 1, 0, 4, 8, 0, 8][type] * num; + var toff = offset; + if (dlen > 4) { + bin.writeUint(data, offset, eoff); + toff = eoff; + } + if (type == 1 || type == 7) { + for (var i = 0; i < num; i++) data[toff + i] = val[i]; + } else if (type == 2) { + bin.writeASCII(data, toff, val); + } else if (type == 3) { + for (var i = 0; i < num; i++) bin.writeUshort(data, toff + 2 * i, val[i]); + } else if (type == 4) { + for (var i = 0; i < num; i++) bin.writeUint(data, toff + 4 * i, val[i]); + } else if (type == 5 || type == 10) { + var wr = type == 5 ? bin.writeUint : bin.writeInt; + for (var i = 0; i < num; i++) { + var v = val[i], nu = v[0], de = v[1]; + if (nu == null) throw "e"; + wr(data, toff + 8 * i, nu); + wr(data, toff + 8 * i + 4, de); + } + } else if (type == 9) { + for (var i = 0; i < num; i++) bin.writeInt(data, toff + 4 * i, val[i]); + } else if (type == 12) { + for (var i = 0; i < num; i++) bin.writeDouble(data, toff + 8 * i, val[i]); + } else throw type; + if (dlen > 4) { + dlen += dlen & 1; + eoff += dlen; + } + offset += 4; + } + return [offset, eoff]; + }; + UTIF3.toRGBA8 = function(out, scl) { + function gamma(x2) { + return x2 < 31308e-7 ? 12.92 * x2 : 1.055 * Math.pow(x2, 1 / 2.4) - 0.055; + } + var w = out.width, h = out.height, area = w * h, qarea = area * 4, data = out.data; + var img = new Uint8Array(area * 4); + var intp = out["t262"] ? out["t262"][0] : 2, bps = out["t258"] ? Math.min(32, out["t258"][0]) : 1; + if (out["t262"] == null && bps == 1) intp = 0; + var smpls = out["t277"] ? out["t277"][0] : out["t258"] ? out["t258"].length : [1, 1, 3, 1, 1, 4, 3][intp]; + var sfmt = out["t339"] ? out["t339"][0] : null; + if (intp == 1 && bps == 32 && sfmt != 3) throw "e"; + var bpl = Math.ceil(smpls * bps * w / 8); + if (false) { + } else if (intp == 0) { + scl = 1 / 256; + for (var y = 0; y < h; y++) { + var off = y * bpl, io = y * w; + if (bps == 1) for (var i = 0; i < w; i++) { + var qi = io + i << 2, px = data[off + (i >> 3)] >> 7 - (i & 7) & 1; + img[qi] = img[qi + 1] = img[qi + 2] = (1 - px) * 255; + img[qi + 3] = 255; + } + if (bps == 4) for (var i = 0; i < w; i++) { + var qi = io + i << 2, px = data[off + (i >> 1)] >> 4 - 4 * (i & 1) & 15; + img[qi] = img[qi + 1] = img[qi + 2] = (15 - px) * 17; + img[qi + 3] = 255; + } + if (bps == 8) for (var i = 0; i < w; i++) { + var qi = io + i << 2, px = data[off + i]; + img[qi] = img[qi + 1] = img[qi + 2] = 255 - px; + img[qi + 3] = 255; + } + if (bps == 16) for (var i = 0; i < w; i++) { + var qi = io + i << 2, o = off + 2 * i, px = data[o + 1] << 8 | data[o]; + img[qi] = img[qi + 1] = img[qi + 2] = Math.min(255, 255 - ~~(px * scl)); + img[qi + 3] = 255; + } + } + } else if (intp == 1) { + if (scl == null) scl = 1 / 256; + var f32 = (data.length & 3) == 0 ? new Float32Array(data.buffer) : null; + for (var y = 0; y < h; y++) { + var off = y * bpl, io = y * w; + if (bps == 1) for (var i = 0; i < w; i++) { + var qi = io + i << 2, px = data[off + (i >> 3)] >> 7 - (i & 7) & 1; + img[qi] = img[qi + 1] = img[qi + 2] = px * 255; + img[qi + 3] = 255; + } + if (bps == 2) for (var i = 0; i < w; i++) { + var qi = io + i << 2, px = data[off + (i >> 2)] >> 6 - 2 * (i & 3) & 3; + img[qi] = img[qi + 1] = img[qi + 2] = px * 85; + img[qi + 3] = 255; + } + if (bps == 8) for (var i = 0; i < w; i++) { + var qi = io + i << 2, px = data[off + i * smpls]; + img[qi] = img[qi + 1] = img[qi + 2] = px; + img[qi + 3] = 255; + } + if (bps == 16) for (var i = 0; i < w; i++) { + var qi = io + i << 2, o = off + 2 * i, px = data[o + 1] << 8 | data[o]; + img[qi] = img[qi + 1] = img[qi + 2] = Math.min(255, ~~(px * scl)); + img[qi + 3] = 255; + } + if (bps == 32) for (var i = 0; i < w; i++) { + var qi = io + i << 2, o = (off >>> 2) + i, px = f32[o]; + img[qi] = img[qi + 1] = img[qi + 2] = ~~(0.5 + 255 * px); + img[qi + 3] = 255; + } + } + } else if (intp == 2) { + if (bps == 8) { + if (smpls == 1) for (var i = 0; i < area; i++) { + img[4 * i] = img[4 * i + 1] = img[4 * i + 2] = data[i]; + img[4 * i + 3] = 255; + } + if (smpls == 3) for (var i = 0; i < area; i++) { + var qi = i << 2, ti = i * 3; + img[qi] = data[ti]; + img[qi + 1] = data[ti + 1]; + img[qi + 2] = data[ti + 2]; + img[qi + 3] = 255; + } + if (smpls >= 4) for (var i = 0; i < area; i++) { + var qi = i << 2, ti = i * smpls; + img[qi] = data[ti]; + img[qi + 1] = data[ti + 1]; + img[qi + 2] = data[ti + 2]; + img[qi + 3] = data[ti + 3]; + } + } else if (bps == 16) { + if (smpls == 4) for (var i = 0; i < area; i++) { + var qi = i << 2, ti = i * 8 + 1; + img[qi] = data[ti]; + img[qi + 1] = data[ti + 2]; + img[qi + 2] = data[ti + 4]; + img[qi + 3] = data[ti + 6]; + } + if (smpls == 3) for (var i = 0; i < area; i++) { + var qi = i << 2, ti = i * 6 + 1; + img[qi] = data[ti]; + img[qi + 1] = data[ti + 2]; + img[qi + 2] = data[ti + 4]; + img[qi + 3] = 255; + } + } else if (bps == 32) { + var ndt = new Float32Array(data.buffer); + var min = 0; + for (var i = 0; i < ndt.length; i++) min = Math.min(min, ndt[i]); + if (min < 0) for (var i = 0; i < data.length; i += 4) { + var t = data[i]; + data[i] = data[i + 3]; + data[i + 3] = t; + t = data[i + 1]; + data[i + 1] = data[i + 2]; + data[i + 2] = t; + } + var pmap = []; + for (var i = 0; i < 65536; i++) pmap.push(gamma(i / 65535)); + for (var i = 0; i < ndt.length; i++) { + var cv = Math.max(0, Math.min(1, ndt[i])); + ndt[i] = pmap[~~(0.5 + cv * 65535)]; + } + if (smpls == 3) for (var i = 0; i < area; i++) { + var qi = i << 2, ti = i * 3; + img[qi] = ~~(0.5 + ndt[ti] * 255); + img[qi + 1] = ~~(0.5 + ndt[ti + 1] * 255); + img[qi + 2] = ~~(0.5 + ndt[ti + 2] * 255); + img[qi + 3] = 255; + } + else if (smpls == 4) for (var i = 0; i < area; i++) { + var qi = i << 2, ti = i * 4; + img[qi] = ~~(0.5 + ndt[ti] * 255); + img[qi + 1] = ~~(0.5 + ndt[ti + 1] * 255); + img[qi + 2] = ~~(0.5 + ndt[ti + 2] * 255); + img[qi + 3] = ~~(0.5 + ndt[ti + 3] * 255); + } + else throw smpls; + } else throw bps; + } else if (intp == 3) { + var map = out["t320"]; + var cn = 1 << bps; + var nexta = bps == 8 && smpls > 1 && out["t338"] && out["t338"][0] != 0; + for (var y = 0; y < h; y++) + for (var x = 0; x < w; x++) { + var i = y * w + x; + var qi = i << 2, mi = 0; + var dof = y * bpl; + if (false) { + } else if (bps == 1) mi = data[dof + (x >>> 3)] >>> 7 - (x & 7) & 1; + else if (bps == 2) mi = data[dof + (x >>> 2)] >>> 6 - 2 * (x & 3) & 3; + else if (bps == 4) mi = data[dof + (x >>> 1)] >>> 4 - 4 * (x & 1) & 15; + else if (bps == 8) mi = data[dof + x * smpls]; + else throw bps; + img[qi] = map[mi] >> 8; + img[qi + 1] = map[cn + mi] >> 8; + img[qi + 2] = map[cn + cn + mi] >> 8; + img[qi + 3] = nexta ? data[dof + x * smpls + 1] : 255; + } + } else if (intp == 5) { + var gotAlpha = smpls > 4 ? 1 : 0; + for (var i = 0; i < area; i++) { + var qi = i << 2, si = i * smpls; + if (window.UDOC) { + var C = data[si], M = data[si + 1], Y = data[si + 2], K = data[si + 3]; + var c = UDOC.C.cmykToRgb([C * (1 / 255), M * (1 / 255), Y * (1 / 255), K * (1 / 255)]); + img[qi] = ~~(0.5 + 255 * c[0]); + img[qi + 1] = ~~(0.5 + 255 * c[1]); + img[qi + 2] = ~~(0.5 + 255 * c[2]); + } else { + var C = 255 - data[si], M = 255 - data[si + 1], Y = 255 - data[si + 2], K = (255 - data[si + 3]) * (1 / 255); + img[qi] = ~~(C * K + 0.5); + img[qi + 1] = ~~(M * K + 0.5); + img[qi + 2] = ~~(Y * K + 0.5); + } + img[qi + 3] = 255 * (1 - gotAlpha) + data[si + 4] * gotAlpha; + } + } else if (intp == 6 && out["t278"]) { + var rps = out["t278"][0]; + for (var y = 0; y < h; y += rps) { + var i = y * w, len = rps * w; + for (var j = 0; j < len; j++) { + var qi = 4 * (i + j), si = 3 * i + 4 * (j >>> 1); + var Y = data[si + (j & 1)], Cb = data[si + 2] - 128, Cr = data[si + 3] - 128; + var r = Y + ((Cr >> 2) + (Cr >> 3) + (Cr >> 5)); + var g = Y - ((Cb >> 2) + (Cb >> 4) + (Cb >> 5)) - ((Cr >> 1) + (Cr >> 3) + (Cr >> 4) + (Cr >> 5)); + var b = Y + (Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6)); + img[qi] = Math.max(0, Math.min(255, r)); + img[qi + 1] = Math.max(0, Math.min(255, g)); + img[qi + 2] = Math.max(0, Math.min(255, b)); + img[qi + 3] = 255; + } + } + } else if (intp == 32845) { + for (var y = 0; y < h; y++) + for (var x = 0; x < w; x++) { + var si = (y * w + x) * 6, qi = (y * w + x) * 4; + var L = data[si + 1] << 8 | data[si]; + var L = Math.pow(2, (L + 0.5) / 256 - 64); + var u = (data[si + 3] + 0.5) / 410; + var v = (data[si + 5] + 0.5) / 410; + var sX = 9 * u / (6 * u - 16 * v + 12); + var sY = 4 * v / (6 * u - 16 * v + 12); + var bY = L; + var X = sX * bY / sY, Y = bY, Z = (1 - sX - sY) * bY / sY; + var r = 2.69 * X - 1.276 * Y - 0.414 * Z; + var g = -1.022 * X + 1.978 * Y + 0.044 * Z; + var b = 0.061 * X - 0.224 * Y + 1.163 * Z; + img[qi] = gamma(Math.min(r, 1)) * 255; + img[qi + 1] = gamma(Math.min(g, 1)) * 255; + img[qi + 2] = gamma(Math.min(b, 1)) * 255; + img[qi + 3] = 255; + } + } else log("Unknown Photometric interpretation: " + intp); + return img; + }; + UTIF3.replaceIMG = function(imgs) { + if (imgs == null) imgs = document.getElementsByTagName("img"); + var sufs = ["tif", "tiff", "dng", "cr2", "nef"]; + for (var i = 0; i < imgs.length; i++) { + var img = imgs[i], src = img.getAttribute("src"); + if (src == null) continue; + var suff = src.split(".").pop().toLowerCase(); + if (sufs.indexOf(suff) == -1) continue; + var xhr = new XMLHttpRequest(); + UTIF3._xhrs.push(xhr); + UTIF3._imgs.push(img); + xhr.open("GET", src); + xhr.responseType = "arraybuffer"; + xhr.onload = UTIF3._imgLoaded; + xhr.send(); + } + }; + UTIF3._xhrs = []; + UTIF3._imgs = []; + UTIF3._imgLoaded = function(e) { + var ind = UTIF3._xhrs.indexOf(e.target), img = UTIF3._imgs[ind]; + UTIF3._xhrs.splice(ind, 1); + UTIF3._imgs.splice(ind, 1); + img.setAttribute("src", UTIF3.bufferToURI(e.target.response)); + }; + UTIF3.bufferToURI = function(buff) { + var ifds = UTIF3.decode(buff); + var vsns = ifds, ma = 0, page = vsns[0]; + if (ifds[0].subIFD) vsns = vsns.concat(ifds[0].subIFD); + for (var i = 0; i < vsns.length; i++) { + var img = vsns[i]; + if (img["t258"] == null || img["t258"].length < 3) continue; + var ar = img["t256"] * img["t257"]; + if (ar > ma) { + ma = ar; + page = img; + } + } + UTIF3.decodeImage(buff, page, ifds); + var rgba = UTIF3.toRGBA8(page), w = page.width, h = page.height; + var cnv = document.createElement("canvas"); + cnv.width = w; + cnv.height = h; + var ctx = cnv.getContext("2d"); + var imgd = new ImageData(new Uint8ClampedArray(rgba.buffer), w, h); + ctx.putImageData(imgd, 0, 0); + return cnv.toDataURL(); + }; + UTIF3._binBE = { + nextZero: function(data, o) { + while (data[o] != 0) o++; + return o; + }, + readUshort: function(buff, p) { + return buff[p] << 8 | buff[p + 1]; + }, + readShort: function(buff, p) { + var a = UTIF3._binBE.ui8; + a[0] = buff[p + 1]; + a[1] = buff[p + 0]; + return UTIF3._binBE.i16[0]; + }, + readInt: function(buff, p) { + var a = UTIF3._binBE.ui8; + a[0] = buff[p + 3]; + a[1] = buff[p + 2]; + a[2] = buff[p + 1]; + a[3] = buff[p + 0]; + return UTIF3._binBE.i32[0]; + }, + readUint: function(buff, p) { + var a = UTIF3._binBE.ui8; + a[0] = buff[p + 3]; + a[1] = buff[p + 2]; + a[2] = buff[p + 1]; + a[3] = buff[p + 0]; + return UTIF3._binBE.ui32[0]; + }, + readASCII: function(buff, p, l) { + var s = ""; + for (var i = 0; i < l; i++) s += String.fromCharCode(buff[p + i]); + return s; + }, + readFloat: function(buff, p) { + var a = UTIF3._binBE.ui8; + for (var i = 0; i < 4; i++) a[i] = buff[p + 3 - i]; + return UTIF3._binBE.fl32[0]; + }, + readDouble: function(buff, p) { + var a = UTIF3._binBE.ui8; + for (var i = 0; i < 8; i++) a[i] = buff[p + 7 - i]; + return UTIF3._binBE.fl64[0]; + }, + writeUshort: function(buff, p, n) { + buff[p] = n >> 8 & 255; + buff[p + 1] = n & 255; + }, + writeInt: function(buff, p, n) { + var a = UTIF3._binBE.ui8; + UTIF3._binBE.i32[0] = n; + buff[p + 3] = a[0]; + buff[p + 2] = a[1]; + buff[p + 1] = a[2]; + buff[p + 0] = a[3]; + }, + writeUint: function(buff, p, n) { + buff[p] = n >> 24 & 255; + buff[p + 1] = n >> 16 & 255; + buff[p + 2] = n >> 8 & 255; + buff[p + 3] = n >> 0 & 255; + }, + writeASCII: function(buff, p, s) { + for (var i = 0; i < s.length; i++) buff[p + i] = s.charCodeAt(i); + }, + writeDouble: function(buff, p, n) { + UTIF3._binBE.fl64[0] = n; + for (var i = 0; i < 8; i++) buff[p + i] = UTIF3._binBE.ui8[7 - i]; + } + }; + UTIF3._binBE.ui8 = new Uint8Array(8); + UTIF3._binBE.i16 = new Int16Array(UTIF3._binBE.ui8.buffer); + UTIF3._binBE.i32 = new Int32Array(UTIF3._binBE.ui8.buffer); + UTIF3._binBE.ui32 = new Uint32Array(UTIF3._binBE.ui8.buffer); + UTIF3._binBE.fl32 = new Float32Array(UTIF3._binBE.ui8.buffer); + UTIF3._binBE.fl64 = new Float64Array(UTIF3._binBE.ui8.buffer); + UTIF3._binLE = { + nextZero: UTIF3._binBE.nextZero, + readUshort: function(buff, p) { + return buff[p + 1] << 8 | buff[p]; + }, + readShort: function(buff, p) { + var a = UTIF3._binBE.ui8; + a[0] = buff[p + 0]; + a[1] = buff[p + 1]; + return UTIF3._binBE.i16[0]; + }, + readInt: function(buff, p) { + var a = UTIF3._binBE.ui8; + a[0] = buff[p + 0]; + a[1] = buff[p + 1]; + a[2] = buff[p + 2]; + a[3] = buff[p + 3]; + return UTIF3._binBE.i32[0]; + }, + readUint: function(buff, p) { + var a = UTIF3._binBE.ui8; + a[0] = buff[p + 0]; + a[1] = buff[p + 1]; + a[2] = buff[p + 2]; + a[3] = buff[p + 3]; + return UTIF3._binBE.ui32[0]; + }, + readASCII: UTIF3._binBE.readASCII, + readFloat: function(buff, p) { + var a = UTIF3._binBE.ui8; + for (var i = 0; i < 4; i++) a[i] = buff[p + i]; + return UTIF3._binBE.fl32[0]; + }, + readDouble: function(buff, p) { + var a = UTIF3._binBE.ui8; + for (var i = 0; i < 8; i++) a[i] = buff[p + i]; + return UTIF3._binBE.fl64[0]; + }, + writeUshort: function(buff, p, n) { + buff[p] = n & 255; + buff[p + 1] = n >> 8 & 255; + }, + writeInt: function(buff, p, n) { + var a = UTIF3._binBE.ui8; + UTIF3._binBE.i32[0] = n; + buff[p + 0] = a[0]; + buff[p + 1] = a[1]; + buff[p + 2] = a[2]; + buff[p + 3] = a[3]; + }, + writeUint: function(buff, p, n) { + buff[p] = n >>> 0 & 255; + buff[p + 1] = n >>> 8 & 255; + buff[p + 2] = n >>> 16 & 255; + buff[p + 3] = n >>> 24 & 255; + }, + writeASCII: UTIF3._binBE.writeASCII + }; + UTIF3._copyTile = function(tb, tw, th, b, w, h, xoff, yoff) { + var xlim = Math.min(tw, w - xoff); + var ylim = Math.min(th, h - yoff); + for (var y = 0; y < ylim; y++) { + var tof = (yoff + y) * w + xoff; + var sof = y * tw; + for (var x = 0; x < xlim; x++) b[tof + x] = tb[sof + x]; + } + }; + UTIF3.LosslessJpegDecode = /* @__PURE__ */ (function() { + var b, O; + function l() { + return b[O++]; + } + function m() { + return b[O++] << 8 | b[O++]; + } + function a0(h) { + var V = l(), I = [0, 0, 0, 255], f = [], G = 8; + for (var w = 0; w < 16; w++) f[w] = l(); + for (var w = 0; w < 16; w++) { + for (var x = 0; x < f[w]; x++) { + var T = z(I, 0, w + 1, 1); + I[T + 3] = l(); + } + } + var E = new Uint8Array(1 << G); + h[V] = [new Uint8Array(I), E]; + for (var w = 0; w < 1 << G; w++) { + var s = G, _ = w, Y = 0, F = 0; + while (I[Y + 3] == 255 && s != 0) { + F = _ >> --s & 1; + Y = I[Y + F]; + } + E[w] = Y; + } + } + function z(h, V, I, f) { + if (h[V + 3] != 255) return 0; + if (I == 0) return V; + for (var w = 0; w < 2; w++) { + if (h[V + w] == 0) { + h[V + w] = h.length; + h.push(0, 0, f, 255); + } + var x = z(h, h[V + w], I - 1, f + 1); + if (x != 0) return x; + } + return 0; + } + function i(h) { + var V = h.b, I = h.f; + while (V < 25 && h.a < h.d) { + var f = h.data[h.a++]; + if (f == 255 && !h.c) h.a++; + I = I << 8 | f; + V += 8; + } + if (V < 0) throw "e"; + h.b = V; + h.f = I; + } + function H(h, V) { + if (V.b < h) i(V); + return V.f >> (V.b -= h) & 65535 >> 16 - h; + } + function g(h, V) { + var I = h[0], f = 0, w = 255, x = 0; + if (V.b < 16) i(V); + var T = V.f >> V.b - 8 & 255; + f = h[1][T]; + w = I[f + 3]; + V.b -= I[f + 2]; + while (w == 255) { + x = V.f >> --V.b & 1; + f = I[f + x]; + w = I[f + 3]; + } + return w; + } + function P(h, V) { + if (h < 32768 >> 16 - V) h += -(1 << V) + 1; + return h; + } + function a2(h, V) { + var I = g(h, V); + if (I == 0) return 0; + if (I == 16) return -32768; + var f = H(I, V); + return P(f, I); + } + function X(h, V, I, f, w, x) { + var T = 0; + for (var G = 0; G < x; G++) { + var s = G * V; + for (var _ = 0; _ < V; _ += w) { + T++; + for (var Y = 0; Y < w; Y++) h[s + _ + Y] = a2(f[Y], I); + } + if (I.e != 0 && T % I.e == 0 && G != 0) { + var F = I.a, t = I.data; + while (t[F] != 255 || !(208 <= t[F + 1] && t[F + 1] <= 215)) F--; + I.a = F + 2; + I.f = 0; + I.b = 0; + } + } + } + function o(h, V) { + return P(H(h, V), h); + } + function a1(h, V, I, f, w) { + var x = b.length - O; + for (var T = 0; T < x; T += 4) { + var G = b[O + T]; + b[O + T] = b[O + T + 3]; + b[O + T + 3] = G; + var G = b[O + T + 1]; + b[O + T + 1] = b[O + T + 2]; + b[O + T + 2] = G; + } + for (var E = 0; E < w; E++) { + var s = 32768, _ = 32768; + for (var Y = 0; Y < V; Y += 2) { + var F = g(f, I), t = g(f, I); + if (F != 0) s += o(F, I); + if (t != 0) _ += o(t, I); + h[E * V + Y] = s & 65535; + h[E * V + Y + 1] = _ & 65535; + } + } + } + function C(h) { + b = h; + O = 0; + if (m() != 65496) throw "e"; + var V = [], I = 0, f = 0, w = 0, x = [], T = [], G = [], E = 0, s = 0, _ = 0; + while (true) { + var Y = m(); + if (Y == 65535) { + O--; + continue; + } + var F = m(); + if (Y == 65475) { + f = l(); + s = m(); + _ = m(); + E = l(); + for (var t = 0; t < E; t++) { + var a = l(), J = l(), r = l(); + if (r != 0) throw "e"; + V[a] = [t, J >> 4, J & 15]; + } + } else if (Y == 65476) { + var a3 = O + F - 2; + while (O < a3) a0(T); + } else if (Y == 65498) { + O++; + for (var t = 0; t < E; t++) { + var a5 = l(), v = V[a5]; + G[v[0]] = T[l() >>> 4]; + x[v[0]] = v.slice(1); + } + I = l(); + O += 2; + break; + } else if (Y == 65501) { + w = m(); + } else { + O += F - 2; + } + } + var a4 = f > 8 ? Uint16Array : Uint8Array, $ = new a4(s * _ * E), M = { b: 0, f: 0, c: I == 8, a: O, data: b, d: b.length, e: w }; + if (M.c) a1($, _ * E, M, G[0], s); + else { + var c = [], p = 0, D = 0; + for (var t = 0; t < E; t++) { + var N = x[t], S = N[0], K = N[1]; + if (S > p) p = S; + if (K > D) D = K; + c.push(S * K); + } + if (p != 1 || D != 1) { + if (E != 3 || c[1] != 1 || c[2] != 1) throw "e"; + if (p != 2 || D != 1 && D != 2) throw "e"; + var u = [], Z = 0; + for (var t = 0; t < E; t++) { + for (var R = 0; R < c[t]; R++) u.push(G[t]); + Z += c[t]; + } + var B = _ / p, e = s / D, d = B * e; + X($, B * Z, M, u, Z, e); + j($, I, B, e, Z - 2, Z, Z, f); + var A = new Uint16Array(d * c[0]); + if (p == 2 && D == 2) { + for (var t = 0; t < d; t++) { + A[4 * t] = $[6 * t]; + A[4 * t + 1] = $[6 * t + 1]; + A[4 * t + 2] = $[6 * t + 2]; + A[4 * t + 3] = $[6 * t + 3]; + } + j(A, I, B * 4, e, 0, 1, 1, f); + for (var t = 0; t < d; t++) { + $[6 * t] = A[4 * t]; + $[6 * t + 1] = A[4 * t + 1]; + $[6 * t + 2] = A[4 * t + 2]; + $[6 * t + 3] = A[4 * t + 3]; + } + } + if (p == 2 && D == 1) { + for (var t = 0; t < d; t++) { + A[2 * t] = $[4 * t]; + A[2 * t + 1] = $[4 * t + 1]; + } + j(A, I, B * 2, e, 0, 1, 1, f); + for (var t = 0; t < d; t++) { + $[4 * t] = A[2 * t]; + $[4 * t + 1] = A[2 * t + 1]; + } + } + var n = $.slice(0); + for (var K = 0; K < s; K++) { + if (D == 2) for (var S = 0; S < _; S++) { + var q = (K * _ + S) * E, k = ((K >>> 1) * B + (S >>> 1)) * Z, y = (K & 1) * 2 + (S & 1); + $[q] = n[k + y]; + $[q + 1] = n[k + 4]; + $[q + 2] = n[k + 5]; + } + else for (var S = 0; S < _; S++) { + var q = (K * _ + S) * E, k = (K * B + (S >>> 1)) * Z, y = S & 1; + $[q] = n[k + y]; + $[q + 1] = n[k + 2]; + $[q + 2] = n[k + 3]; + } + } + } else { + X($, _ * E, M, G, E, s); + if (w == 0) j($, I, _, s, 0, E, E, f); + else { + var U = Math.floor(w / _); + for (var K = 0; K < s; K += U) { + var L = $.slice(K * _ * E, (K + U) * _ * E); + j(L, I, _, U, 0, E, E, f); + $.set(L, K * _ * E); + } + } + } + } + return $; + } + function j(h, V, I, f, w, x, G, E) { + var s = I * G; + for (var _ = w; _ < x; _++) h[_] += 1 << E - 1; + for (var Y = G; Y < s; Y += G) for (var _ = w; _ < x; _++) h[Y + _] += h[Y + _ - G]; + for (var F = 1; F < f; F++) { + var t = F * s; + for (var _ = w; _ < x; _++) h[t + _] += h[t + _ - s]; + for (var Y = G; Y < s; Y += G) { + for (var _ = w; _ < x; _++) { + var a = t + Y + _, J = a - s, r = h[a - G], Q = 0; + if (V == 0) Q = 0; + else if (V == 1) Q = r; + else if (V == 2) Q = h[J]; + else if (V == 3) Q = h[J - G]; + else if (V == 4) Q = r + (h[J] - h[J - G]); + else if (V == 5) Q = r + (h[J] - h[J - G] >>> 1); + else if (V == 6) Q = h[J] + (r - h[J - G] >>> 1); + else if (V == 7) Q = r + h[J] >>> 1; + else throw V; + h[a] += Q; + } + } + } + } + return C; + })(); + (function() { + var G = 0, F = 1, i = 2, b = 3, J = 4, N = 5, E = 6, s = 7, c = 8, T = 9, a3 = 10, f = 11, q = 12, M = 13, m = 14, x = 15, L = 16, $ = 17, p = 18; + function a5(t) { + var Z = UTIF3._binBE.readUshort, u = { b: Z(t, 0), i: t[2], C: t[3], u: t[4], q: Z(t, 5), k: Z(t, 7), e: Z(t, 9), l: Z(t, 11), s: t[13], d: Z(t, 14) }; + if (u.b != 18771 || u.i > 1 || u.q < 6 || u.q % 6 || u.e < 768 || u.e % 24 || u.l != 768 || u.k < u.l || u.k % u.l || u.k - u.e >= u.l || u.s > 16 || u.s != u.k / u.l || u.s != Math.ceil(u.e / u.l) || u.d != u.q / 6 || u.u != 12 && u.u != 14 && u.u != 16 || u.C != 16 && u.C != 0) { + throw "Invalid data"; + } + if (u.i == 0) { + throw "Not implemented. We need this file!"; + } + u.h = u.C == 16; + u.m = (u.h ? u.l * 2 / 3 : u.l >>> 1) | 0; + u.A = u.m + 2; + u.f = 64; + u.g = (1 << u.u) - 1; + u.n = 4 * u.u; + return u; + } + function a7(t, Z) { + var u = new Array(Z.s), e = 4 * Z.s, Q = 16 + e; + if (e & 12) Q += 16 - (e & 12); + for (var V = 0, O = 16; V < Z.s; O += 4) { + var o = UTIF3._binBE.readUint(t, O); + u[V] = t.slice(Q, Q + o); + u[V].j = 0; + u[V].a = 0; + Q += o; + V++; + } + if (Q != t.length) throw "Invalid data"; + return u; + } + function a6(t, Z) { + for (var u = -Z[4], e = 0; u <= Z[4]; e++, u++) { + t[e] = u <= -Z[3] ? -4 : u <= -Z[2] ? -3 : u <= -Z[1] ? -2 : u < -Z[0] ? -1 : u <= Z[0] ? 0 : u < Z[1] ? 1 : u < Z[2] ? 2 : u < Z[3] ? 3 : 4; + } + } + function a1(t, Z, u) { + var e = [Z, 3 * Z + 18, 5 * Z + 67, 7 * Z + 276, u]; + t.o = Z; + t.w = (e[4] + 2 * Z) / (2 * Z + 1) + 1 | 0; + t.v = Math.ceil(Math.log2(t.w)); + t.t = 9; + a6(t.c, e); + } + function a2(t) { + var Z = { c: new Int8Array(2 << t.u) }; + a1(Z, 0, t.g); + return Z; + } + function D(t) { + var Z = [[], [], []], u = Math.max(2, t.w + 32 >>> 6); + for (var e = 0; e < 3; e++) { + for (var Q = 0; Q < 41; Q++) { + Z[e][Q] = [u, 1]; + } + } + return Z; + } + function a4(t) { + for (var Z = -1, u = 0; !u; Z++) { + u = t[t.j] >>> 7 - t.a & 1; + t.a++; + t.a &= 7; + if (!t.a) t.j++; + } + return Z; + } + function K(t, Z) { + var u = 0, e = 8 - t.a, Q = t.j, V = t.a; + if (Z) { + if (Z >= e) { + do { + u <<= e; + Z -= e; + u |= t[t.j] & (1 << e) - 1; + t.j++; + e = 8; + } while (Z >= 8); + } + if (Z) { + u <<= Z; + e -= Z; + u |= t[t.j] >>> e & (1 << Z) - 1; + } + t.a = 8 - e; + } + return u; + } + function a0(t, Z) { + var u = 0; + if (Z < t) { + while (u <= 14 && Z << ++u < t) ; + } + return u; + } + function r(t, Z, u, e, Q, V, O, o) { + if (o == null) o = 0; + var X = V + 1, k = X % 2, j = 0, I = 0, a = 0, l, R, w = e[Q], S = e[Q - 1], H = e[Q - 2][X], g = S[X - 1], Y = S[X], P = S[X + 1], A = w[X - 1], v = w[X + 1], y = Math.abs, d, C, n, h; + if (k) { + d = y(P - Y); + C = y(H - Y); + n = y(g - Y); + } + if (k) { + h = d > n && C < d ? H + g : d < n && C < n ? H + P : P + g; + h = h + 2 * Y >>> 2; + if (o) { + w[X] = h; + return; + } + l = Z.t * Z.c[t.g + Y - H] + Z.c[t.g + g - Y]; + } else { + h = Y > g && Y > P || Y < g && Y < P ? v + A + 2 * Y >>> 2 : A + v >>> 1; + l = Z.t * Z.c[t.g + Y - g] + Z.c[t.g + g - A]; + } + R = y(l); + var W = a4(u); + if (W < t.n - Z.v - 1) { + var z = a0(O[R][0], O[R][1]); + a = K(u, z) + (W << z); + } else { + a = K(u, Z.v) + 1; + } + a = a & 1 ? -1 - (a >>> 1) : a >>> 1; + O[R][0] += y(a); + if (O[R][1] == t.f) { + O[R][0] >>>= 1; + O[R][1] >>>= 1; + } + O[R][1]++; + h = l < 0 ? h - a : h + a; + if (t.i) { + if (h < 0) h += Z.w; + else if (h > t.g) h -= Z.w; + } + w[X] = h >= 0 ? Math.min(h, t.g) : 0; + } + function U(t, Z, u) { + var e = t[0].length; + for (var Q = Z; Q <= u; Q++) { + t[Q][0] = t[Q - 1][1]; + t[Q][e - 1] = t[Q - 1][e - 2]; + } + } + function B(t) { + U(t, s, q); + U(t, i, J); + U(t, x, $); + } + function _(t, Z, u, e, Q, V, O, o, X, k, j, I, a) { + var l = 0, R = 1, w = Q < M && Q > J; + while (R < t.m) { + if (l < t.m) { + r(t, Z, u, e, Q, l, O[X], t.h && (w && k || !w && (j || (l & I) == a))); + r(t, Z, u, e, V, l, O[X], t.h && (!w && k || w && (j || (l & I) == a))); + l += 2; + } + if (l > 8) { + r(t, Z, u, e, Q, R, o[X]); + r(t, Z, u, e, V, R, o[X]); + R += 2; + } + } + B(e); + } + function a8(t, Z, u, e, Q, V) { + _(t, Z, u, e, i, s, Q, V, 0, 0, 1, 0, 8); + _(t, Z, u, e, c, x, Q, V, 1, 0, 1, 0, 8); + _(t, Z, u, e, b, T, Q, V, 2, 1, 0, 3, 0); + _(t, Z, u, e, a3, L, Q, V, 0, 0, 0, 3, 2); + _(t, Z, u, e, J, f, Q, V, 1, 0, 0, 3, 2); + _(t, Z, u, e, q, $, Q, V, 2, 1, 0, 3, 0); + } + function a9(t, Z, u, e, Q, V) { + var O = V.length, o = t.l; + if (Q + 1 == t.s) o = t.e - Q * t.l; + var X = 6 * t.e * e + Q * t.l; + for (var k = 0; k < 6; k++) { + for (var j = 0; j < o; j++) { + var I = V[k % O][j % O], a; + if (I == 0) { + a = i + (k >>> 1); + } else if (I == 2) { + a = x + (k >>> 1); + } else { + a = s + k; + } + var l = t.h ? (j * 2 / 3 & 2147483646 | j % 3 & 1) + (j % 3 >>> 1) : j >>> 1; + Z[X + j] = u[a][l + 1]; + } + X += t.e; + } + } + UTIF3._decompressRAF = function(t, Z) { + var u = a5(t), e = a7(t, u), Q = a2(u), V = new Int16Array(u.e * u.q); + if (Z == null) { + Z = u.h ? [[1, 1, 0, 1, 1, 2], [1, 1, 2, 1, 1, 0], [2, 0, 1, 0, 2, 1], [1, 1, 2, 1, 1, 0], [1, 1, 0, 1, 1, 2], [0, 2, 1, 2, 0, 1]] : [[0, 1], [3, 2]]; + } + var O = [[G, b], [F, J], [N, f], [E, q], [M, L], [m, $]], o = []; + for (var X = 0; X < p; X++) { + o[X] = new Uint16Array(u.A); + } + for (var k = 0; k < u.s; k++) { + var j = D(Q), I = D(Q); + for (var X = 0; X < p; X++) { + for (var a = 0; a < u.A; a++) { + o[X][a] = 0; + } + } + for (var l = 0; l < u.d; l++) { + a8(u, Q, e[k], o, j, I); + for (var X = 0; X < 6; X++) { + for (var a = 0; a < u.A; a++) { + o[O[X][0]][a] = o[O[X][1]][a]; + } + } + a9(u, V, o, l, k, Z); + for (var X = i; X < p; X++) { + if ([N, E, M, m].indexOf(X) == -1) { + for (var a = 0; a < u.A; a++) { + o[X][a] = 0; + } + } + } + B(o); + } + } + return V; + }; + })(); + })(UTIF2, pako); + })(); + } +}); + +// cli.ts +import { readFile } from "node:fs/promises"; +import { extname } from "node:path"; + +// packages/docx-engine/src/types.ts +var TOTAL_PAGES_MARK = "\uE000"; +var PAGE_MARK = "\uE001"; + +// packages/docx-engine/src/chart.ts +var import_jszip = __toESM(require_lib3(), 1); + +// node_modules/fast-xml-parser/src/util.js +var nameStartChar = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; +var nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; +var nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*"; +var regexName = new RegExp("^" + nameRegexp + "$"); +function getAllMatches(string, regex) { + const matches = []; + let match = regex.exec(string); + while (match) { + const allmatches = []; + allmatches.startIndex = regex.lastIndex - match[0].length; + const len = match.length; + for (let index = 0; index < len; index++) { + allmatches.push(match[index]); + } + matches.push(allmatches); + match = regex.exec(string); + } + return matches; +} +var isName = function(string) { + const match = regexName.exec(string); + return !(match === null || typeof match === "undefined"); +}; +function isExist(v) { + return typeof v !== "undefined"; +} +var DANGEROUS_PROPERTY_NAMES = [ + // '__proto__', + // 'constructor', + // 'prototype', + "hasOwnProperty", + "toString", + "valueOf", + "__defineGetter__", + "__defineSetter__", + "__lookupGetter__", + "__lookupSetter__" +]; +var criticalProperties = ["__proto__", "constructor", "prototype"]; + +// node_modules/fast-xml-parser/src/validator.js +var defaultOptions = { + allowBooleanAttributes: false, + //A tag can have attributes without any value + unpairedTags: [] +}; +function validate(xmlData, options) { + options = Object.assign({}, defaultOptions, options); + const tags = []; + let tagFound = false; + let reachedRoot = false; + if (xmlData[0] === "\uFEFF") { + xmlData = xmlData.substr(1); + } + for (let i = 0; i < xmlData.length; i++) { + if (xmlData[i] === "<" && xmlData[i + 1] === "?") { + i += 2; + i = readPI(xmlData, i); + if (i.err) return i; + } else if (xmlData[i] === "<") { + let tagStartPos = i; + i++; + if (xmlData[i] === "!") { + i = readCommentAndCDATA(xmlData, i); + continue; + } else { + let closingTag = false; + if (xmlData[i] === "/") { + closingTag = true; + i++; + } + let tagName = ""; + for (; i < xmlData.length && xmlData[i] !== ">" && xmlData[i] !== " " && xmlData[i] !== " " && xmlData[i] !== "\n" && xmlData[i] !== "\r"; i++) { + tagName += xmlData[i]; + } + tagName = tagName.trim(); + if (tagName[tagName.length - 1] === "/") { + tagName = tagName.substring(0, tagName.length - 1); + i--; + } + if (!validateTagName(tagName)) { + let msg; + if (tagName.trim().length === 0) { + msg = "Invalid space after '<'."; + } else { + msg = "Tag '" + tagName + "' is an invalid name."; + } + return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i)); + } + const result = readAttributeStr(xmlData, i); + if (result === false) { + return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i)); + } + let attrStr = result.value; + i = result.index; + if (attrStr[attrStr.length - 1] === "/") { + const attrStrStart = i - attrStr.length; + attrStr = attrStr.substring(0, attrStr.length - 1); + const isValid = validateAttributeString(attrStr, options); + if (isValid === true) { + tagFound = true; + } else { + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line)); + } + } else if (closingTag) { + if (!result.tagClosed) { + return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i)); + } else if (attrStr.trim().length > 0) { + return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); + } else if (tags.length === 0) { + return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos)); + } else { + const otg = tags.pop(); + if (tagName !== otg.tagName) { + let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); + return getErrorObject( + "InvalidTag", + "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.", + getLineNumberForPosition(xmlData, tagStartPos) + ); + } + if (tags.length == 0) { + reachedRoot = true; + } + } + } else { + const isValid = validateAttributeString(attrStr, options); + if (isValid !== true) { + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line)); + } + if (reachedRoot === true) { + return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i)); + } else if (options.unpairedTags.indexOf(tagName) !== -1) { + } else { + tags.push({ tagName, tagStartPos }); + } + tagFound = true; + } + for (i++; i < xmlData.length; i++) { + if (xmlData[i] === "<") { + if (xmlData[i + 1] === "!") { + i++; + i = readCommentAndCDATA(xmlData, i); + continue; + } else if (xmlData[i + 1] === "?") { + i = readPI(xmlData, ++i); + if (i.err) return i; + } else { + break; + } + } else if (xmlData[i] === "&") { + const afterAmp = validateAmpersand(xmlData, i); + if (afterAmp == -1) + return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i)); + i = afterAmp; + } else { + if (reachedRoot === true && !isWhiteSpace(xmlData[i])) { + return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i)); + } + } + } + if (xmlData[i] === "<") { + i--; + } + } + } else { + if (isWhiteSpace(xmlData[i])) { + continue; + } + return getErrorObject("InvalidChar", "char '" + xmlData[i] + "' is not expected.", getLineNumberForPosition(xmlData, i)); + } + } + if (!tagFound) { + return getErrorObject("InvalidXml", "Start tag expected.", 1); + } else if (tags.length == 1) { + return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos)); + } else if (tags.length > 0) { + return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t) => t.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 }); + } + return true; +} +function isWhiteSpace(char) { + return char === " " || char === " " || char === "\n" || char === "\r"; +} +function readPI(xmlData, i) { + const start = i; + for (; i < xmlData.length; i++) { + if (xmlData[i] == "?" || xmlData[i] == " ") { + const tagname = xmlData.substr(start, i - start); + if (i > 5 && tagname === "xml") { + return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i)); + } else if (xmlData[i] == "?" && xmlData[i + 1] == ">") { + i++; + break; + } else { + continue; + } + } + } + return i; +} +function readCommentAndCDATA(xmlData, i) { + if (xmlData.length > i + 5 && xmlData[i + 1] === "-" && xmlData[i + 2] === "-") { + for (i += 3; i < xmlData.length; i++) { + if (xmlData[i] === "-" && xmlData[i + 1] === "-" && xmlData[i + 2] === ">") { + i += 2; + break; + } + } + } else if (xmlData.length > i + 8 && xmlData[i + 1] === "D" && xmlData[i + 2] === "O" && xmlData[i + 3] === "C" && xmlData[i + 4] === "T" && xmlData[i + 5] === "Y" && xmlData[i + 6] === "P" && xmlData[i + 7] === "E") { + let angleBracketsCount = 1; + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === "<") { + angleBracketsCount++; + } else if (xmlData[i] === ">") { + angleBracketsCount--; + if (angleBracketsCount === 0) { + break; + } + } + } + } else if (xmlData.length > i + 9 && xmlData[i + 1] === "[" && xmlData[i + 2] === "C" && xmlData[i + 3] === "D" && xmlData[i + 4] === "A" && xmlData[i + 5] === "T" && xmlData[i + 6] === "A" && xmlData[i + 7] === "[") { + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === "]" && xmlData[i + 1] === "]" && xmlData[i + 2] === ">") { + i += 2; + break; + } + } + } + return i; +} +var doubleQuote = '"'; +var singleQuote = "'"; +function readAttributeStr(xmlData, i) { + let attrStr = ""; + let startChar = ""; + let tagClosed = false; + for (; i < xmlData.length; i++) { + if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) { + if (startChar === "") { + startChar = xmlData[i]; + } else if (startChar !== xmlData[i]) { + } else { + startChar = ""; + } + } else if (xmlData[i] === ">") { + if (startChar === "") { + tagClosed = true; + break; + } + } + attrStr += xmlData[i]; + } + if (startChar !== "") { + return false; + } + return { + value: attrStr, + index: i, + tagClosed + }; +} +var validAttrStrRegxp = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g"); +function validateAttributeString(attrStr, options) { + const matches = getAllMatches(attrStr, validAttrStrRegxp); + const attrNames = {}; + for (let i = 0; i < matches.length; i++) { + if (matches[i][1].length === 0) { + return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' has no space in starting.", getPositionFromMatch(matches[i])); + } else if (matches[i][3] !== void 0 && matches[i][4] === void 0) { + return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' is without value.", getPositionFromMatch(matches[i])); + } else if (matches[i][3] === void 0 && !options.allowBooleanAttributes) { + return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i][2] + "' is not allowed.", getPositionFromMatch(matches[i])); + } + const attrName = matches[i][2]; + if (!validateAttrName(attrName)) { + return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i])); + } + if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) { + attrNames[attrName] = 1; + } else { + return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i])); + } + } + return true; +} +function validateNumberAmpersand(xmlData, i) { + let re = /\d/; + if (xmlData[i] === "x") { + i++; + re = /[\da-fA-F]/; + } + for (; i < xmlData.length; i++) { + if (xmlData[i] === ";") + return i; + if (!xmlData[i].match(re)) + break; + } + return -1; +} +function validateAmpersand(xmlData, i) { + i++; + if (xmlData[i] === ";") + return -1; + if (xmlData[i] === "#") { + i++; + return validateNumberAmpersand(xmlData, i); + } + let count = 0; + for (; i < xmlData.length; i++, count++) { + if (xmlData[i].match(/\w/) && count < 20) + continue; + if (xmlData[i] === ";") + break; + return -1; + } + return i; +} +function getErrorObject(code, message, lineNumber) { + return { + err: { + code, + msg: message, + line: lineNumber.line || lineNumber, + col: lineNumber.col + } + }; +} +function validateAttrName(attrName) { + return isName(attrName); +} +function validateTagName(tagname) { + return isName(tagname); +} +function getLineNumberForPosition(xmlData, index) { + const lines = xmlData.substring(0, index).split(/\r?\n/); + return { + line: lines.length, + // column number is last line's length + 1, because column numbering starts at 1: + col: lines[lines.length - 1].length + 1 + }; +} +function getPositionFromMatch(match) { + return match.startIndex + match[1].length; +} + +// node_modules/@nodable/entities/src/entities.js +var CURRENCY = { + cent: "\xA2", + pound: "\xA3", + curren: "\xA4", + yen: "\xA5", + euro: "\u20AC", + dollar: "$", + fnof: "\u0192", + inr: "\u20B9", + af: "\u060B", + birr: "\u1265\u122D", + peso: "\u20B1", + rub: "\u20BD", + won: "\u20A9", + yuan: "\xA5", + cedil: "\xB8" +}; +var XML = { + amp: "&", + apos: "'", + gt: ">", + lt: "<", + quot: '"' +}; +var COMMON_HTML = { + nbsp: "\xA0", + copy: "\xA9", + reg: "\xAE", + trade: "\u2122", + mdash: "\u2014", + ndash: "\u2013", + hellip: "\u2026", + laquo: "\xAB", + raquo: "\xBB", + lsquo: "\u2018", + rsquo: "\u2019", + ldquo: "\u201C", + rdquo: "\u201D", + bull: "\u2022", + para: "\xB6", + sect: "\xA7", + deg: "\xB0", + frac12: "\xBD", + frac14: "\xBC", + frac34: "\xBE" +}; + +// node_modules/@nodable/entities/src/EntityDecoder.js +var ENTITY_ACTION = Object.freeze({ + /** Resolve and expand the entity normally. */ + ALLOW: "allow", + /** Silently skip this entity — it will not be registered. */ + BLOCK: "block", + /** Throw an error, aborting entity registration entirely. */ + THROW: "throw" +}); +var SPECIAL_CHARS = new Set("!?\\\\/[]$%{}^&*()<>|+"); +function validateEntityName(name) { + if (name[0] === "#") { + throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${name}"`); + } + for (const ch of name) { + if (SPECIAL_CHARS.has(ch)) { + throw new Error(`[EntityReplacer] Invalid character '${ch}' in entity name: "${name}"`); + } + } + return name; +} +function mergeEntityMaps(...maps) { + const out = /* @__PURE__ */ Object.create(null); + for (const map of maps) { + if (!map) continue; + for (const key of Object.keys(map)) { + const raw = map[key]; + if (typeof raw === "string") { + out[key] = raw; + } else if (raw && typeof raw === "object" && raw.val !== void 0) { + const val = raw.val; + if (typeof val === "string") { + out[key] = val; + } + } + } + } + return out; +} +var LIMIT_TIER_EXTERNAL = "external"; +var LIMIT_TIER_BASE = "base"; +var LIMIT_TIER_ALL = "all"; +function parseLimitTiers(raw) { + if (!raw || raw === LIMIT_TIER_EXTERNAL) return /* @__PURE__ */ new Set([LIMIT_TIER_EXTERNAL]); + if (raw === LIMIT_TIER_ALL) return /* @__PURE__ */ new Set([LIMIT_TIER_ALL]); + if (raw === LIMIT_TIER_BASE) return /* @__PURE__ */ new Set([LIMIT_TIER_BASE]); + if (Array.isArray(raw)) return new Set(raw); + return /* @__PURE__ */ new Set([LIMIT_TIER_EXTERNAL]); +} +var NCR_LEVEL = Object.freeze({ allow: 0, leave: 1, remove: 2, throw: 3 }); +var XML10_ALLOWED_C0 = /* @__PURE__ */ new Set([9, 10, 13]); +function parseNCRConfig(ncr) { + if (!ncr) { + return { xmlVersion: 1, onLevel: NCR_LEVEL.allow, nullLevel: NCR_LEVEL.remove }; + } + const xmlVersion = ncr.xmlVersion === 1.1 ? 1.1 : 1; + const onLevel = NCR_LEVEL[ncr.onNCR] ?? NCR_LEVEL.allow; + const nullLevel = NCR_LEVEL[ncr.nullNCR] ?? NCR_LEVEL.remove; + const clampedNull = Math.max(nullLevel, NCR_LEVEL.remove); + return { xmlVersion, onLevel, nullLevel: clampedNull }; +} +var EntityDecoder = class { + /** + * @param {object} [options] + * @param {object|null} [options.namedEntities] — extra named entities merged into base map + * @param {object} [options.limit] — security limits + * @param {number} [options.limit.maxTotalExpansions=0] — 0 = unlimited + * @param {number} [options.limit.maxExpandedLength=0] — 0 = unlimited + * @param {'external'|'base'|'all'|string[]} [options.limit.applyLimitsTo='external'] + * Which entity tiers count against the security limits: + * - 'external' (default) — only input/runtime + persistent external entities + * - 'base' — only DEFAULT_XML_ENTITIES + namedEntities + * - 'all' — every entity regardless of tier + * - string[] — explicit combination, e.g. ['external', 'base'] + * @param {((resolved: string, original: string) => string)|null} [options.postCheck=null] + * @param {string[]} [options.remove=[]] — entity names (e.g. ['nbsp', '#13']) to delete (replace with empty string) + * @param {string[]} [options.leave=[]] — entity names to keep as literal (unchanged in output) + * @param {object} [options.ncr] — Numeric Character Reference controls + * @param {1.0|1.1} [options.ncr.xmlVersion=1.0] + * XML version governing which codepoint ranges are restricted: + * - 1.0 — C0 controls U+0001–U+001F (except U+0009/000A/000D) are prohibited + * - 1.1 — C0 controls are allowed when written as NCRs; C1 (U+007F–U+009F) decoded as-is + * @param {'allow'|'leave'|'remove'|'throw'} [options.ncr.onNCR='allow'] + * Base action for numeric references. Severity order: allow < leave < remove < throw. + * For codepoint ranges that carry a minimum level (surrogates → remove, XML 1.0 C0 → remove), + * the effective action is max(onNCR, rangeMinimum). + * @param {'remove'|'throw'} [options.ncr.nullNCR='remove'] + * Action for U+0000 (null). 'allow' and 'leave' are clamped to 'remove' since null is never safe. + * @param {((name: string, value: string) => 'allow'|'block'|'throw')|null} [options.onExternalEntity=null] + * Hook called when an external entity is registered via `setExternalEntities()` or + * `addExternalEntity()`. Return `ENTITY_ACTION.ALLOW` to accept the entity, + * `ENTITY_ACTION.BLOCK` to silently skip it, or `ENTITY_ACTION.THROW` to abort with an error. + * @param {((name: string, value: string) => 'allow'|'block'|'throw')|null} [options.onInputEntity=null] + * Hook called when an input entity is registered via `addInputEntities()`. Return + * `ENTITY_ACTION.ALLOW` to accept, `ENTITY_ACTION.BLOCK` to silently skip, or + * `ENTITY_ACTION.THROW` to abort with an error. + */ + constructor(options = {}) { + this._limit = options.limit || {}; + this._maxTotalExpansions = this._limit.maxTotalExpansions || 0; + this._maxExpandedLength = this._limit.maxExpandedLength || 0; + this._postCheck = typeof options.postCheck === "function" ? options.postCheck : (r) => r; + this._limitTiers = parseLimitTiers(this._limit.applyLimitsTo ?? LIMIT_TIER_EXTERNAL); + this._numericAllowed = options.numericAllowed ?? true; + this._baseMap = mergeEntityMaps(XML, options.namedEntities || null); + this._externalMap = /* @__PURE__ */ Object.create(null); + this._inputMap = /* @__PURE__ */ Object.create(null); + this._totalExpansions = 0; + this._expandedLength = 0; + this._removeSet = new Set(options.remove && Array.isArray(options.remove) ? options.remove : []); + this._leaveSet = new Set(options.leave && Array.isArray(options.leave) ? options.leave : []); + const ncrCfg = parseNCRConfig(options.ncr); + this._ncrXmlVersion = ncrCfg.xmlVersion; + this._ncrOnLevel = ncrCfg.onLevel; + this._ncrNullLevel = ncrCfg.nullLevel; + this._onExternalEntity = typeof options.onExternalEntity === "function" ? options.onExternalEntity : null; + this._onInputEntity = typeof options.onInputEntity === "function" ? options.onInputEntity : null; + } + // ------------------------------------------------------------------------- + // Private: registration hook dispatch + // ------------------------------------------------------------------------- + /** + * Invoke a registration hook for a single entity name/value pair. + * Returns true when the entity should be accepted, false when it should be + * silently skipped (BLOCK), and throws when the hook returns THROW. + * + * @param {((name: string, value: string) => 'allow'|'block'|'throw')|null} hook + * @param {string} name + * @param {string} value + * @param {string} context — used in error messages ('external' | 'input') + * @returns {boolean} true = accept, false = skip + */ + _applyRegistrationHook(hook, name, value, context) { + if (!hook) return true; + const action = hook(name, value); + if (action === ENTITY_ACTION.BLOCK) return false; + if (action === ENTITY_ACTION.THROW) { + throw new Error( + `[EntityDecoder] Registration of ${context} entity "&${name};" was rejected by hook` + ); + } + return true; + } + // ------------------------------------------------------------------------- + // Persistent external entity registration + // ------------------------------------------------------------------------- + /** + * Replace the full set of persistent external entities. + * All keys are validated — throws on invalid characters. + * If `onExternalEntity` is set, it is called once per entry; entries that + * return `ENTITY_ACTION.BLOCK` are silently omitted, `ENTITY_ACTION.THROW` + * aborts the whole call. + * @param {Record} map + */ + setExternalEntities(map) { + if (map) { + for (const key of Object.keys(map)) { + validateEntityName(key); + } + } + if (!this._onExternalEntity) { + this._externalMap = mergeEntityMaps(map); + return; + } + const flat = mergeEntityMaps(map); + const filtered = /* @__PURE__ */ Object.create(null); + for (const [name, value] of Object.entries(flat)) { + if (this._applyRegistrationHook(this._onExternalEntity, name, value, "external")) { + filtered[name] = value; + } + } + this._externalMap = filtered; + } + /** + * Add a single persistent external entity. + * If `onExternalEntity` is set it is called before the entity is stored; + * `ENTITY_ACTION.BLOCK` silently skips storage, `ENTITY_ACTION.THROW` raises. + * @param {string} key + * @param {string} value + */ + addExternalEntity(key, value) { + validateEntityName(key); + if (typeof value === "string" && value.indexOf("&") === -1) { + if (this._applyRegistrationHook(this._onExternalEntity, key, value, "external")) { + this._externalMap[key] = value; + } + } + } + // ------------------------------------------------------------------------- + // Input / runtime entity registration (per document) + // ------------------------------------------------------------------------- + /** + * Inject DOCTYPE entities for the current document. + * Also resets per-document expansion counters. + * If `onInputEntity` is set it is called once per entry; entries returning + * `ENTITY_ACTION.BLOCK` are silently omitted, `ENTITY_ACTION.THROW` aborts. + * @param {Record} map + */ + addInputEntities(map) { + this._totalExpansions = 0; + this._expandedLength = 0; + if (!this._onInputEntity) { + this._inputMap = mergeEntityMaps(map); + return; + } + const flat = mergeEntityMaps(map); + const filtered = /* @__PURE__ */ Object.create(null); + for (const [name, value] of Object.entries(flat)) { + if (this._applyRegistrationHook(this._onInputEntity, name, value, "input")) { + filtered[name] = value; + } + } + this._inputMap = filtered; + } + // ------------------------------------------------------------------------- + // Per-document reset + // ------------------------------------------------------------------------- + /** + * Wipe input/runtime entities and reset counters. + * Call this before processing each new document. + * @returns {this} + */ + reset() { + this._inputMap = /* @__PURE__ */ Object.create(null); + this._totalExpansions = 0; + this._expandedLength = 0; + return this; + } + // ------------------------------------------------------------------------- + // XML version (can be set after construction, e.g. once parser reads ) + // ------------------------------------------------------------------------- + /** + * Update the XML version used for NCR classification. + * Call this as soon as the document's `` declaration is parsed. + * @param {1.0|1.1|number} version + */ + setXmlVersion(version) { + this._ncrXmlVersion = version === 1.1 ? 1.1 : 1; + } + // ------------------------------------------------------------------------- + // Primary API + // ------------------------------------------------------------------------- + /** + * Replace all entity references in `str` in a single pass. + * + * @param {string} str + * @returns {string} + */ + decode(str) { + if (typeof str !== "string" || str.length === 0) return str; + if (str.indexOf("&") === -1) return str; + const original = str; + const chunks = []; + const len = str.length; + let last = 0; + let i = 0; + const limitExpansions = this._maxTotalExpansions > 0; + const limitLength = this._maxExpandedLength > 0; + const checkLimits = limitExpansions || limitLength; + while (i < len) { + if (str.charCodeAt(i) !== 38) { + i++; + continue; + } + let j = i + 1; + while (j < len && str.charCodeAt(j) !== 59 && j - i <= 32) j++; + if (j >= len || str.charCodeAt(j) !== 59) { + i++; + continue; + } + const token = str.slice(i + 1, j); + if (token.length === 0) { + i++; + continue; + } + let replacement; + let tier; + if (this._removeSet.has(token)) { + replacement = ""; + if (tier === void 0) { + tier = LIMIT_TIER_EXTERNAL; + } + } else if (this._leaveSet.has(token)) { + i++; + continue; + } else if (token.charCodeAt(0) === 35) { + const ncrResult = this._resolveNCR(token); + if (ncrResult === void 0) { + i++; + continue; + } + replacement = ncrResult; + tier = LIMIT_TIER_BASE; + } else { + const resolved = this._resolveName(token); + replacement = resolved?.value; + tier = resolved?.tier; + } + if (replacement === void 0) { + i++; + continue; + } + if (i > last) chunks.push(str.slice(last, i)); + chunks.push(replacement); + last = j + 1; + i = last; + if (checkLimits && this._tierCounts(tier)) { + if (limitExpansions) { + this._totalExpansions++; + if (this._totalExpansions > this._maxTotalExpansions) { + throw new Error( + `[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}` + ); + } + } + if (limitLength) { + const delta = replacement.length - (token.length + 2); + if (delta > 0) { + this._expandedLength += delta; + if (this._expandedLength > this._maxExpandedLength) { + throw new Error( + `[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}` + ); + } + } + } + } + } + if (last < len) chunks.push(str.slice(last)); + const result = chunks.length === 0 ? str : chunks.join(""); + return this._postCheck(result, original); + } + // ------------------------------------------------------------------------- + // Private: limit tier check + // ------------------------------------------------------------------------- + /** + * Returns true if a resolved entity of the given tier should count + * against the expansion/length limits. + * @param {string} tier — LIMIT_TIER_EXTERNAL | LIMIT_TIER_BASE + * @returns {boolean} + */ + _tierCounts(tier) { + if (this._limitTiers.has(LIMIT_TIER_ALL)) return true; + return this._limitTiers.has(tier); + } + // ------------------------------------------------------------------------- + // Private: entity resolution + // ------------------------------------------------------------------------- + /** + * Resolve a named entity token (without & and ;). + * Priority: inputMap > externalMap > baseMap + * Returns the resolved value tagged with its limit tier. + * + * @param {string} name + * @returns {{ value: string, tier: string }|undefined} + */ + _resolveName(name) { + if (name in this._inputMap) return { value: this._inputMap[name], tier: LIMIT_TIER_EXTERNAL }; + if (name in this._externalMap) return { value: this._externalMap[name], tier: LIMIT_TIER_EXTERNAL }; + if (name in this._baseMap) return { value: this._baseMap[name], tier: LIMIT_TIER_BASE }; + return void 0; + } + /** + * Classify a codepoint and return the minimum action level that must be applied. + * Returns -1 when no minimum is imposed (normal allow path). + * + * Ranges checked (in priority order): + * 1. U+0000 — null, governed by nullNCR (always ≥ remove) + * 2. U+D800–U+DFFF — surrogates, always prohibited (min: remove) + * 3. U+0001–U+001F \ {0x09,0x0A,0x0D} — XML 1.0 restricted C0 (min: remove) + * (skipped in XML 1.1 — C0 controls are allowed when written as NCRs) + * + * @param {number} cp — codepoint + * @returns {number} — minimum NCR_LEVEL value, or -1 for no restriction + */ + _classifyNCR(cp) { + if (cp === 0) return this._ncrNullLevel; + if (cp >= 55296 && cp <= 57343) return NCR_LEVEL.remove; + if (this._ncrXmlVersion === 1) { + if (cp >= 1 && cp <= 31 && !XML10_ALLOWED_C0.has(cp)) return NCR_LEVEL.remove; + } + return -1; + } + /** + * Execute a resolved NCR action. + * + * @param {number} action — NCR_LEVEL value + * @param {string} token — raw token (e.g. '#38') for error messages + * @param {number} cp — codepoint, used only for error messages + * @returns {string|undefined} + * - decoded character string → 'allow' + * - '' → 'remove' + * - undefined → 'leave' (caller must skip past '&' only) + * - throws Error → 'throw' + */ + _applyNCRAction(action, token, cp) { + switch (action) { + case NCR_LEVEL.allow: + return String.fromCodePoint(cp); + case NCR_LEVEL.remove: + return ""; + case NCR_LEVEL.leave: + return void 0; + // signal: keep literal + case NCR_LEVEL.throw: + throw new Error( + `[EntityDecoder] Prohibited numeric character reference &${token}; (U+${cp.toString(16).toUpperCase().padStart(4, "0")})` + ); + default: + return String.fromCodePoint(cp); + } + } + /** + * Full NCR resolution pipeline for a numeric token. + * + * Steps: + * 1. Parse the codepoint (decimal or hex). + * 2. Validate the raw codepoint range (NaN, <0, >0x10FFFF). + * 3. If numericAllowed is false and no minimum restriction applies → leave as-is. + * 4. Classify the codepoint to find the minimum required action level. + * 5. Resolve effective action = max(onNCR, minimum). + * 6. Apply and return. + * + * @param {string} token — e.g. '#38', '#x26', '#X26' + * @returns {string|undefined} + * - string (incl. '') — replacement ('' = remove) + * - undefined — leave original &token; as-is + */ + _resolveNCR(token) { + const second = token.charCodeAt(1); + let cp; + if (second === 120 || second === 88) { + cp = parseInt(token.slice(2), 16); + } else { + cp = parseInt(token.slice(1), 10); + } + if (Number.isNaN(cp) || cp < 0 || cp > 1114111) return void 0; + const minimum = this._classifyNCR(cp); + if (!this._numericAllowed && minimum < NCR_LEVEL.remove) return void 0; + const effective = minimum === -1 ? this._ncrOnLevel : Math.max(this._ncrOnLevel, minimum); + return this._applyNCRAction(effective, token, cp); + } +}; + +// node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js +var defaultOnDangerousProperty = (name) => { + if (DANGEROUS_PROPERTY_NAMES.includes(name)) { + return "__" + name; + } + return name; +}; +var defaultOptions2 = { + preserveOrder: false, + attributeNamePrefix: "@_", + attributesGroupName: false, + textNodeName: "#text", + ignoreAttributes: true, + removeNSPrefix: false, + // remove NS from tag name or attribute name if true + allowBooleanAttributes: false, + //a tag can have attributes without any value + //ignoreRootElement : false, + parseTagValue: true, + parseAttributeValue: false, + trimValues: true, + //Trim string values of tag and attributes + cdataPropName: false, + numberParseOptions: { + hex: true, + leadingZeros: true, + eNotation: true, + unicode: false + }, + tagValueProcessor: function(tagName, val) { + return val; + }, + attributeValueProcessor: function(attrName, val) { + return val; + }, + stopNodes: [], + //nested tags will not be parsed even for errors + alwaysCreateTextNode: false, + isArray: () => false, + commentPropName: false, + unpairedTags: [], + processEntities: true, + htmlEntities: false, + entityDecoder: null, + ignoreDeclaration: false, + ignorePiTags: false, + transformTagName: false, + transformAttributeName: false, + updateTag: function(tagName, jPath, attrs) { + return tagName; + }, + // skipEmptyListItem: false + captureMetaData: false, + maxNestedTags: 100, + strictReservedNames: true, + jPath: true, + // if true, pass jPath string to callbacks; if false, pass matcher instance + onDangerousProperty: defaultOnDangerousProperty +}; +function validatePropertyName(propertyName, optionName) { + if (typeof propertyName !== "string") { + return; + } + const normalized = propertyName.toLowerCase(); + if (DANGEROUS_PROPERTY_NAMES.some((dangerous) => normalized === dangerous.toLowerCase())) { + throw new Error( + `[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution` + ); + } + if (criticalProperties.some((dangerous) => normalized === dangerous.toLowerCase())) { + throw new Error( + `[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution` + ); + } +} +function normalizeProcessEntities(value, htmlEntities) { + if (typeof value === "boolean") { + return { + enabled: value, + // true or false + maxEntitySize: 1e4, + maxExpansionDepth: 1e4, + maxTotalExpansions: Infinity, + maxExpandedLength: 1e5, + maxEntityCount: 1e3, + allowedTags: null, + tagFilter: null, + appliesTo: "all" + }; + } + if (typeof value === "object" && value !== null) { + return { + enabled: value.enabled !== false, + maxEntitySize: Math.max(1, value.maxEntitySize ?? 1e4), + maxExpansionDepth: Math.max(1, value.maxExpansionDepth ?? 1e4), + maxTotalExpansions: Math.max(1, value.maxTotalExpansions ?? Infinity), + maxExpandedLength: Math.max(1, value.maxExpandedLength ?? 1e5), + maxEntityCount: Math.max(1, value.maxEntityCount ?? 1e3), + allowedTags: value.allowedTags ?? null, + tagFilter: value.tagFilter ?? null, + appliesTo: value.appliesTo ?? "all" + }; + } + return normalizeProcessEntities(true); +} +var buildOptions = function(options) { + const built = Object.assign({}, defaultOptions2, options); + const propertyNameOptions = [ + { value: built.attributeNamePrefix, name: "attributeNamePrefix" }, + { value: built.attributesGroupName, name: "attributesGroupName" }, + { value: built.textNodeName, name: "textNodeName" }, + { value: built.cdataPropName, name: "cdataPropName" }, + { value: built.commentPropName, name: "commentPropName" } + ]; + for (const { value, name } of propertyNameOptions) { + if (value) { + validatePropertyName(value, name); + } + } + if (built.onDangerousProperty === null) { + built.onDangerousProperty = defaultOnDangerousProperty; + } + built.processEntities = normalizeProcessEntities(built.processEntities, built.htmlEntities); + built.unpairedTagsSet = new Set(built.unpairedTags); + if (built.stopNodes && Array.isArray(built.stopNodes)) { + built.stopNodes = built.stopNodes.map((node) => { + if (typeof node === "string" && node.startsWith("*.")) { + return ".." + node.substring(2); + } + return node; + }); + } + return built; +}; + +// node_modules/fast-xml-parser/src/xmlparser/xmlNode.js +var METADATA_SYMBOL; +if (typeof Symbol !== "function") { + METADATA_SYMBOL = "@@xmlMetadata"; +} else { + METADATA_SYMBOL = /* @__PURE__ */ Symbol("XML Node Metadata"); +} +var XmlNode = class { + constructor(tagname) { + this.tagname = tagname; + this.child = []; + this[":@"] = /* @__PURE__ */ Object.create(null); + } + add(key, val) { + if (key === "__proto__") key = "#__proto__"; + this.child.push({ [key]: val }); + } + addChild(node, startIndex) { + if (node.tagname === "__proto__") node.tagname = "#__proto__"; + if (node[":@"] && Object.keys(node[":@"]).length > 0) { + this.child.push({ [node.tagname]: node.child, [":@"]: node[":@"] }); + } else { + this.child.push({ [node.tagname]: node.child }); + } + this.addStartIndex(startIndex); + } + addStartIndex(startIndex) { + if (startIndex !== void 0) { + this.child[this.child.length - 1][METADATA_SYMBOL] = { startIndex }; + } + } + addEndIndex(endIndex) { + const lastChild = this.child[this.child.length - 1]; + if (lastChild !== void 0 && lastChild[METADATA_SYMBOL] !== void 0 && lastChild[METADATA_SYMBOL].endIndex === void 0) { + lastChild[METADATA_SYMBOL].endIndex = endIndex; + } + } + /** symbol used for metadata */ + static getMetaDataSymbol() { + return METADATA_SYMBOL; + } +}; + +// node_modules/xml-naming/src/index.js +var nameStartChar10 = ":A-Za-z_\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u0486\u0488-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD"; +var nameChar10 = nameStartChar10 + "\\-\\.\\d\xB7\u0300-\u036F\u203F-\u2040"; +var nameStartChar11 = ":A-Za-z_\xC0-\u02FF\u0370-\u037D\u037F-\u0486\u0488-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}"; +var nameChar11 = nameStartChar11 + "\\-\\.\\d\xB7\u0300-\u036F\u0487\u203F-\u2040"; +var buildRegexes = (startChar, char, flags = "") => { + const ncStart = startChar.replace(":", ""); + const ncChar = char.replace(":", ""); + const ncNamePat = `[${ncStart}][${ncChar}]*`; + return { + name: new RegExp(`^[${startChar}][${char}]*$`, flags), + ncName: new RegExp(`^${ncNamePat}$`, flags), + qName: new RegExp(`^${ncNamePat}(?::${ncNamePat})?$`, flags), + nmToken: new RegExp(`^[${char}]+$`, flags), + nmTokens: new RegExp(`^[${char}]+(?:\\s+[${char}]+)*$`, flags) + }; +}; +var regexes10 = buildRegexes(nameStartChar10, nameChar10); +var regexes11 = buildRegexes(nameStartChar11, nameChar11, "u"); +var nameStartCharAscii = ":A-Za-z_"; +var nameCharAscii = nameStartCharAscii + "\\-\\.\\d"; +var regexesAscii = buildRegexes(nameStartCharAscii, nameCharAscii); +var getRegexes = (xmlVersion = "1.0", asciiOnly = false) => { + if (asciiOnly) return regexesAscii; + return xmlVersion === "1.1" ? regexes11 : regexes10; +}; +var qName = (str, { xmlVersion = "1.0", asciiOnly = false } = {}) => getRegexes(xmlVersion, asciiOnly).qName.test(str); + +// node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js +var DocTypeReader = class { + constructor(options, xmlVersion) { + this.suppressValidationErr = !options; + this.options = options; + this.xmlVersion = xmlVersion || 1; + } + setXmlVersion(xmlVersion = 1) { + this.xmlVersion = xmlVersion; + } + readDocType(xmlData, i) { + const entities = /* @__PURE__ */ Object.create(null); + let entityCount = 0; + if (xmlData[i + 3] === "O" && xmlData[i + 4] === "C" && xmlData[i + 5] === "T" && xmlData[i + 6] === "Y" && xmlData[i + 7] === "P" && xmlData[i + 8] === "E") { + i = i + 9; + let angleBracketsCount = 1; + let hasBody = false, comment = false; + let quoteChar = null; + let exp = ""; + for (; i < xmlData.length; i++) { + if (quoteChar !== null) { + if (xmlData[i] === quoteChar) quoteChar = null; + exp += xmlData[i]; + continue; + } + if (!hasBody && !comment && (xmlData[i] === '"' || xmlData[i] === "'")) { + quoteChar = xmlData[i]; + exp += xmlData[i]; + continue; + } + if (xmlData[i] === "<" && !comment) { + if (hasBody && hasSeq(xmlData, "!ENTITY", i)) { + i += 7; + let entityName, val; + [entityName, val, i] = this.readEntityExp(xmlData, i + 1, this.suppressValidationErr); + if (val.indexOf("&") === -1) { + if (this.options.enabled !== false && this.options.maxEntityCount != null && entityCount >= this.options.maxEntityCount) { + throw new Error( + `Entity count (${entityCount + 1}) exceeds maximum allowed (${this.options.maxEntityCount})` + ); + } + entities[entityName] = val; + entityCount++; + } + } else if (hasBody && hasSeq(xmlData, "!ELEMENT", i)) { + i += 8; + const { index } = this.readElementExp(xmlData, i + 1); + i = index; + } else if (hasBody && hasSeq(xmlData, "!ATTLIST", i)) { + i += 8; + } else if (hasBody && hasSeq(xmlData, "!NOTATION", i)) { + i += 9; + const { index } = this.readNotationExp(xmlData, i + 1, this.suppressValidationErr); + i = index; + } else if (hasSeq(xmlData, "!--", i)) comment = true; + else throw new Error(`Invalid DOCTYPE`); + angleBracketsCount++; + exp = ""; + } else if (xmlData[i] === ">") { + if (comment) { + if (xmlData[i - 1] === "-" && xmlData[i - 2] === "-") { + comment = false; + angleBracketsCount--; + } + } else { + angleBracketsCount--; + } + if (angleBracketsCount === 0) { + break; + } + } else if (xmlData[i] === "[") { + hasBody = true; + } else { + exp += xmlData[i]; + } + } + if (quoteChar !== null || angleBracketsCount !== 0) { + throw new Error(`Unclosed DOCTYPE`); + } + } else { + throw new Error(`Invalid Tag instead of DOCTYPE`); + } + return { entities, i }; + } + readEntityExp(xmlData, i) { + i = skipWhitespace(xmlData, i); + const startIndex = i; + while (i < xmlData.length && !/\s/.test(xmlData[i]) && xmlData[i] !== '"' && xmlData[i] !== "'") { + i++; + } + let entityName = xmlData.substring(startIndex, i); + validateEntityName2(entityName, { xmlVersion: this.xmlVersion }); + i = skipWhitespace(xmlData, i); + if (!this.suppressValidationErr) { + if (xmlData.substring(i, i + 6).toUpperCase() === "SYSTEM") { + throw new Error("External entities are not supported"); + } else if (xmlData[i] === "%") { + throw new Error("Parameter entities are not supported"); + } + } + let entityValue = ""; + [i, entityValue] = this.readIdentifierVal(xmlData, i, "entity"); + if (this.options.enabled !== false && this.options.maxEntitySize != null && entityValue.length > this.options.maxEntitySize) { + throw new Error( + `Entity "${entityName}" size (${entityValue.length}) exceeds maximum allowed size (${this.options.maxEntitySize})` + ); + } + i--; + return [entityName, entityValue, i]; + } + readNotationExp(xmlData, i) { + i = skipWhitespace(xmlData, i); + const startIndex = i; + while (i < xmlData.length && !/\s/.test(xmlData[i])) { + i++; + } + let notationName = xmlData.substring(startIndex, i); + !this.suppressValidationErr && validateEntityName2(notationName, { xmlVersion: this.xmlVersion }); + i = skipWhitespace(xmlData, i); + const identifierType = xmlData.substring(i, i + 6).toUpperCase(); + if (!this.suppressValidationErr && identifierType !== "SYSTEM" && identifierType !== "PUBLIC") { + throw new Error(`Expected SYSTEM or PUBLIC, found "${identifierType}"`); + } + i += identifierType.length; + i = skipWhitespace(xmlData, i); + let publicIdentifier = null; + let systemIdentifier = null; + if (identifierType === "PUBLIC") { + [i, publicIdentifier] = this.readIdentifierVal(xmlData, i, "publicIdentifier"); + i = skipWhitespace(xmlData, i); + if (xmlData[i] === '"' || xmlData[i] === "'") { + [i, systemIdentifier] = this.readIdentifierVal(xmlData, i, "systemIdentifier"); + } + } else if (identifierType === "SYSTEM") { + [i, systemIdentifier] = this.readIdentifierVal(xmlData, i, "systemIdentifier"); + if (!this.suppressValidationErr && !systemIdentifier) { + throw new Error("Missing mandatory system identifier for SYSTEM notation"); + } + } + return { notationName, publicIdentifier, systemIdentifier, index: --i }; + } + readIdentifierVal(xmlData, i, type) { + let identifierVal = ""; + const startChar = xmlData[i]; + if (startChar !== '"' && startChar !== "'") { + throw new Error(`Expected quoted string, found "${startChar}"`); + } + i++; + const startIndex = i; + while (i < xmlData.length && xmlData[i] !== startChar) { + i++; + } + identifierVal = xmlData.substring(startIndex, i); + if (xmlData[i] !== startChar) { + throw new Error(`Unterminated ${type} value`); + } + i++; + return [i, identifierVal]; + } + readElementExp(xmlData, i) { + i = skipWhitespace(xmlData, i); + const startIndex = i; + while (i < xmlData.length && !/\s/.test(xmlData[i])) { + i++; + } + let elementName = xmlData.substring(startIndex, i); + if (!this.suppressValidationErr && !qName(elementName, { xmlVersion: this.xmlVersion })) { + throw new Error(`Invalid element name: "${elementName}"`); + } + i = skipWhitespace(xmlData, i); + let contentModel = ""; + if (xmlData[i] === "E" && hasSeq(xmlData, "MPTY", i)) i += 4; + else if (xmlData[i] === "A" && hasSeq(xmlData, "NY", i)) i += 2; + else if (xmlData[i] === "(") { + i++; + const startIndex2 = i; + while (i < xmlData.length && xmlData[i] !== ")") { + i++; + } + contentModel = xmlData.substring(startIndex2, i); + if (xmlData[i] !== ")") { + throw new Error("Unterminated content model"); + } + } else if (!this.suppressValidationErr) { + throw new Error(`Invalid Element Expression, found "${xmlData[i]}"`); + } + return { + elementName, + contentModel: contentModel.trim(), + index: i + }; + } + readAttlistExp(xmlData, i) { + i = skipWhitespace(xmlData, i); + let startIndex = i; + while (i < xmlData.length && !/\s/.test(xmlData[i])) { + i++; + } + let elementName = xmlData.substring(startIndex, i); + validateEntityName2(elementName, { xmlVersion: this.xmlVersion }); + i = skipWhitespace(xmlData, i); + startIndex = i; + while (i < xmlData.length && !/\s/.test(xmlData[i])) { + i++; + } + let attributeName = xmlData.substring(startIndex, i); + if (!validateEntityName2(attributeName, { xmlVersion: this.xmlVersion })) { + throw new Error(`Invalid attribute name: "${attributeName}"`); + } + i = skipWhitespace(xmlData, i); + let attributeType = ""; + if (xmlData.substring(i, i + 8).toUpperCase() === "NOTATION") { + attributeType = "NOTATION"; + i += 8; + i = skipWhitespace(xmlData, i); + if (xmlData[i] !== "(") { + throw new Error(`Expected '(', found "${xmlData[i]}"`); + } + i++; + let allowedNotations = []; + while (i < xmlData.length && xmlData[i] !== ")") { + const startIndex2 = i; + while (i < xmlData.length && xmlData[i] !== "|" && xmlData[i] !== ")") { + i++; + } + let notation = xmlData.substring(startIndex2, i); + notation = notation.trim(); + if (!validateEntityName2(notation, { xmlVersion: this.xmlVersion })) { + throw new Error(`Invalid notation name: "${notation}"`); + } + allowedNotations.push(notation); + if (xmlData[i] === "|") { + i++; + i = skipWhitespace(xmlData, i); + } + } + if (xmlData[i] !== ")") { + throw new Error("Unterminated list of notations"); + } + i++; + attributeType += " (" + allowedNotations.join("|") + ")"; + } else { + const startIndex2 = i; + while (i < xmlData.length && !/\s/.test(xmlData[i])) { + i++; + } + attributeType += xmlData.substring(startIndex2, i); + const validTypes = ["CDATA", "ID", "IDREF", "IDREFS", "ENTITY", "ENTITIES", "NMTOKEN", "NMTOKENS"]; + if (!this.suppressValidationErr && !validTypes.includes(attributeType.toUpperCase())) { + throw new Error(`Invalid attribute type: "${attributeType}"`); + } + } + i = skipWhitespace(xmlData, i); + let defaultValue = ""; + if (xmlData.substring(i, i + 8).toUpperCase() === "#REQUIRED") { + defaultValue = "#REQUIRED"; + i += 8; + } else if (xmlData.substring(i, i + 7).toUpperCase() === "#IMPLIED") { + defaultValue = "#IMPLIED"; + i += 7; + } else { + [i, defaultValue] = this.readIdentifierVal(xmlData, i, "ATTLIST"); + } + return { + elementName, + attributeName, + attributeType, + defaultValue, + index: i + }; + } +}; +var skipWhitespace = (data, index) => { + while (index < data.length && /\s/.test(data[index])) { + index++; + } + return index; +}; +function hasSeq(data, seq, i) { + for (let j = 0; j < seq.length; j++) { + if (seq[j] !== data[i + j + 1]) return false; + } + return true; +} +function validateEntityName2(name, xmlVersion) { + if (qName(name, { xmlVersion })) + return name; + else + throw new Error(`Invalid entity name ${name}`); +} + +// node_modules/anynum/digitTable.js +var SCRIPT_ZEROS = [ + // Basic Latin (ASCII) — included for completeness / pass-through + 48, + // 0-9 + // Arabic scripts + 1632, + // Arabic-Indic ٠١٢٣٤٥٦٧٨٩ + 1776, + // Extended Arabic-Indic (Urdu/Persian/Sindhi) ۰۱۲۳ + // Indic scripts + 2406, + // Devanagari ०१२३४५६७८९ + 2534, + // Bengali ০১২৩৪৫৬৭৮৯ + 2662, + // Gurmukhi ੦੧੨੩੪੫੬੭੮੯ + 2790, + // Gujarati ૦૧૨૩૪૫૬૭૮૯ + 2918, + // Odia ୦୧୨୩୪୫୬୭୮୯ + 3046, + // Tamil ௦௧௨௩௪௫௬௭௮௯ + 3174, + // Telugu ౦౧౨౩౪౫౬౭౮౯ + 3302, + // Kannada ೦೧೨೩೪೫೬೭೮೯ + 3430, + // Malayalam ൦൧൨൩൪൫൬൭൮൯ + 3558, + // Sinhala Archaic ෦෧෨෩෪෫෬෭෮෯ + // Southeast Asian scripts + 3664, + // Thai ๐๑๒๓๔๕๖๗๘๙ + 3792, + // Lao ໐໑໒໓໔໕໖໗໘໙ + 3872, + // Tibetan ༠༡༢༣༤༥༦༧༨༩ + 4160, + // Myanmar ၀၁၂၃၄၅၆၇၈၉ + 4240, + // Myanmar Shan ႐႑႒႓႔႕႖႗႘႙ + 6112, + // Khmer ០១២៣៤៥៦៧៨៩ + 6160, + // Mongolian ᠐᠑᠒᠓᠔᠕᠖᠗᠘᠙ + 6470, + // Limbu ᥆᥇᥈᥉᥊᥋᥌᥍᥎᥏ + 6608, + // New Tai Lue ᧐᧑᧒᧓᧔᧕᧖᧗᧘᧙ + 6784, + // Tai Tham Hora ᪀᪁᪂᪃᪄᪅᪆᪇᪈᪉ + 6800, + // Tai Tham Tham ᪐᪑᪒᪓᪔᪕᪖᪗᪘᪙ + 6992, + // Balinese ᭐᭑᭒᭓᭔᭕᭖᭗᭘᭙ + 7088, + // Sundanese ᮰᮱᮲᮳᮴᮵᮶᮷᮸᮹ + 7232, + // Lepcha ᱀᱁᱂᱃᱄᱅᱆᱇᱈᱉ + 7248, + // Ol Chiki ᱐᱑᱒᱓᱔᱕᱖᱗᱘᱙ + // Fullwidth (CJK context) + 65296, + // Fullwidth 0123456789 + // Mathematical digit variants (Unicode math block) + 120782, + // Mathematical Bold + 120792, + // Mathematical Double-Struck + 120802, + // Mathematical Sans-Serif + 120812, + // Mathematical Sans-Serif Bold + 120822, + // Mathematical Monospace + // Other scripts + 66720, + // Osmanya 𐒠𐒡𐒢𐒣𐒤𐒥𐒦𐒧𐒨𐒩 + 68912, + // Hanifi Rohingya 𐴰𐴱𐴲𐴳𐴴𐴵𐴶𐴷𐴸𐴹 + 69734, + // Brahmi 𑁦𑁧𑁨𑁩𑁪𑁫𑁬𑁭𑁮𑁯 + 69872, + // Sora Sompeng 𑃰𑃱𑃲𑃳𑃴𑃵𑃶𑃷𑃸𑃹 + 69942, + // Chakma 𑄶𑄷𑄸𑄹𑄺𑄻𑄼𑄽𑄾𑄿 + 70096, + // Sharada 𑇐𑇑𑇒𑇓𑇔𑇕𑇖𑇗𑇘𑇙 + 70384, + // Khudawadi 𑋰𑋱𑋲𑋳𑋴𑋵𑋶𑋷𑋸𑋹 + 70736, + // Newa 𑑐𑑑𑑒𑑓𑑔𑑕𑑖𑑗𑑘𑑙 + 70864, + // Tirhuta 𑓐𑓑𑓒𑓓𑓔𑓕𑓖𑓗𑓘𑓙 + 71248, + // Modi 𑙐𑙑𑙒𑙓𑙔𑙕𑙖𑙗𑙘𑙙 + 71360, + // Takri 𑛀𑛁𑛂𑛃𑛄𑛅𑛆𑛇𑛈𑛉 + 71472, + // Ahom 𑜰𑜱𑜲𑜳𑜴𑜵𑜶𑜷𑜸𑜹 + 71904, + // Warang Citi 𑣠𑣡𑣢𑣣𑣤𑣥𑣦𑣧𑣨𑣩 + 72016, + // Dives Akuru 𑥐𑥑𑥒𑥓𑥔𑥕𑥖𑥗𑥘𑥙 + 72688, + // Khitan Small Script 𑯰𑯱𑯲𑯳𑯴𑯵𑯶𑯷𑯸𑯹 + 72784, + // Bhaiksuki 𑱐𑱑𑱒𑱓𑱔𑱕𑱖𑱗𑱘𑱙 + 73040, + // Masaram Gondi 𑵐𑵑𑵒𑵓𑵔𑵕𑵖𑵗𑵘𑵙 + 73120, + // Gunjala Gondi 𑶠𑶡𑶢𑶣𑶤𑶥𑶦𑶧𑶨𑶩 + 73552, + // Kawi 𑽐𑽑𑽒𑽓𑽔𑽕𑽖𑽗𑽘𑽙 + 92768, + // Mro 𖩠𖩡𖩢𖩣𖩤𖩥𖩦𖩧𖩨𖩩 + 92864, + // Tangsa 𖫀𖫁𖫂𖫃𖫄𖫅𖫆𖫇𖫈𖫉 + 93008, + // Pahawh Hmong 𖭐𖭑𖭒𖭓𖭔𖭕𖭖𖭗𖭘𖭙 + 123200, + // Nyiakeng Puachue Hmong 𞅀𞅁𞅂𞅃𞅄𞅅𞅆𞅇𞅈𞅉 + 123632, + // Wancho 𞋰𞋱𞋲𞋳𞋴𞋵𞋶𞋷𞋸𞋹 + 124144, + // Nag Mundari 𞓰𞓱𞓲𞓳𞓴𞓵𞓶𞓷𞓸𞓹 + 125264, + // Adlam 𞥐𞥑𞥒𞥓𞥔𞥕𞥖𞥗𞥘𞥙 + 130032 + // Segmented digit symbols 🯰🯱🯲🯳🯴🯵🯶🯷🯸🯹 +]; +var NOT_DIGIT = 255; +var HIGH_MAP = /* @__PURE__ */ new Map(); +var LOW_MAX = 65535; +var LOW_MIN = 1632; +var TABLE_OFFSET = LOW_MIN; +var TABLE_SIZE = LOW_MAX - LOW_MIN + 1; +var TABLE = new Uint8Array(TABLE_SIZE).fill(NOT_DIGIT); +for (const zero of SCRIPT_ZEROS) { + for (let d = 0; d < 10; d++) { + const cp = zero + d; + if (cp <= LOW_MAX) { + TABLE[cp - TABLE_OFFSET] = d; + } else { + HIGH_MAP.set(cp, d); + } + } +} + +// node_modules/anynum/anynum.js +var CHAR_0 = 48; +var CHAR_9 = 57; +var CHAR_MINUS = 45; +var MINUS_SET = /* @__PURE__ */ new Set([8722, 65293, 65123]); +function anynum(str) { + if (typeof str !== "string") return str; + const len = str.length; + if (len === 0) return str; + let firstHit = -1; + for (let i = 0; i < len; i++) { + const cc = str.charCodeAt(i); + if (cc >= CHAR_0 && cc <= CHAR_9 || cc === CHAR_MINUS) continue; + if (cc < TABLE_OFFSET) { + if (MINUS_SET.has(cc)) { + firstHit = i; + break; + } + continue; + } + if (cc >= 55296 && cc <= 56319) { + if (i + 1 < len) { + const low = str.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + const cp = 65536 + (cc - 55296 << 10) + (low - 56320); + if (HIGH_MAP.has(cp)) { + firstHit = i; + break; + } + } + } + continue; + } + if (TABLE[cc - TABLE_OFFSET] !== NOT_DIGIT || MINUS_SET.has(cc)) { + firstHit = i; + break; + } + } + if (firstHit === -1) return str; + const chars = []; + if (firstHit > 0) chars.push(str.slice(0, firstHit)); + for (let i = firstHit; i < len; i++) { + const cc = str.charCodeAt(i); + if (cc >= CHAR_0 && cc <= CHAR_9 || cc === CHAR_MINUS) { + chars.push(str[i]); + continue; + } + if (cc < TABLE_OFFSET) { + chars.push(MINUS_SET.has(cc) ? "-" : str[i]); + continue; + } + if (cc >= 55296 && cc <= 56319) { + if (i + 1 < len) { + const low = str.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + const cp = 65536 + (cc - 55296 << 10) + (low - 56320); + const d2 = HIGH_MAP.get(cp); + if (d2 !== void 0) { + chars.push(String.fromCharCode(d2 + 48)); + i++; + continue; + } + } + } + chars.push(str[i]); + continue; + } + if (MINUS_SET.has(cc)) { + chars.push("-"); + continue; + } + const d = TABLE[cc - TABLE_OFFSET]; + chars.push(d !== NOT_DIGIT ? String.fromCharCode(d + 48) : str[i]); + } + return chars.join(""); +} +var anynum_default = anynum; + +// node_modules/strnum/strnum.js +var hexRegex = /^[-+]?0x[a-fA-F0-9]+$/; +var binRegex = /^0b[01]+$/; +var octRegex = /^0o[0-7]+$/; +var numRegex = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/; +var consider = { + hex: true, + binary: false, + octal: false, + leadingZeros: true, + decimalPoint: ".", + eNotation: true, + //skipLike: /regex/, + infinity: "original", + // "null", "infinity" (Infinity type), "string" ("Infinity" (the string literal)) + unicode: false +}; +function toNumber(str, options = {}) { + options = Object.assign({}, consider, options); + if (!str || typeof str !== "string") return str; + let trimmedStr = str.trim(); + if (trimmedStr.length === 0) return str; + else if (options.skipLike !== void 0 && options.skipLike.test(trimmedStr)) return str; + else if (trimmedStr === "0") return 0; + if (options.unicode) { + trimmedStr = anynum_default(trimmedStr); + if (trimmedStr === "0") return 0; + } + if (options.hex && hexRegex.test(trimmedStr)) { + return parse_int(trimmedStr, 16); + } else if (options.binary && binRegex.test(trimmedStr)) { + return parse_int(trimmedStr, 2); + } else if (options.octal && octRegex.test(trimmedStr)) { + return parse_int(trimmedStr, 8); + } else if (!isFinite(trimmedStr)) { + return handleInfinity(str, Number(trimmedStr), options); + } else if (trimmedStr.includes("e") || trimmedStr.includes("E")) { + return resolveEnotation(str, trimmedStr, options); + } else { + const match = numRegex.exec(trimmedStr); + if (match) { + const sign = match[1] || ""; + const leadingZeros = match[2]; + let numTrimmedByZeros = trimZeros(match[3]); + const decimalAdjacentToLeadingZeros = sign ? ( + // 0., -00., 000. + str[leadingZeros.length + 1] === "." + ) : str[leadingZeros.length] === "."; + if (!options.leadingZeros && (leadingZeros.length > 1 || leadingZeros.length === 1 && !decimalAdjacentToLeadingZeros)) { + return str; + } else { + const num = Number(trimmedStr); + const parsedStr = String(num); + if (num === 0) return num; + if (parsedStr.search(/[eE]/) !== -1) { + if (options.eNotation) return num; + else return str; + } else if (trimmedStr.indexOf(".") !== -1) { + if (parsedStr === "0") return num; + else if (parsedStr === numTrimmedByZeros) return num; + else if (parsedStr === `${sign}${numTrimmedByZeros}`) return num; + else return str; + } + let n = leadingZeros ? numTrimmedByZeros : trimmedStr; + if (leadingZeros) { + return n === parsedStr || sign + n === parsedStr ? num : str; + } else { + return n === parsedStr || n === sign + parsedStr ? num : str; + } + } + } else { + return str; + } + } +} +var eNotationRegx = /^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/; +function resolveEnotation(str, trimmedStr, options) { + if (!options.eNotation) return str; + const notation = trimmedStr.match(eNotationRegx); + if (notation) { + let sign = notation[1] || ""; + const eChar = notation[3].indexOf("e") === -1 ? "E" : "e"; + const leadingZeros = notation[2]; + const eAdjacentToLeadingZeros = sign ? ( + // 0E. + str[leadingZeros.length + 1] === eChar + ) : str[leadingZeros.length] === eChar; + if (leadingZeros.length > 1 && eAdjacentToLeadingZeros) return str; + else if (leadingZeros.length === 1 && (notation[3].startsWith(`.${eChar}`) || notation[3][0] === eChar)) { + return Number(trimmedStr); + } else if (leadingZeros.length > 0) { + if (options.leadingZeros && !eAdjacentToLeadingZeros) { + trimmedStr = (notation[1] || "") + notation[3]; + return Number(trimmedStr); + } else return str; + } else { + return Number(trimmedStr); + } + } else { + return str; + } +} +function trimZeros(numStr) { + if (numStr && numStr.indexOf(".") !== -1) { + let end = numStr.length; + while (end > 0 && numStr.charCodeAt(end - 1) === 48) end--; + numStr = numStr.slice(0, end); + if (numStr === ".") numStr = "0"; + else if (numStr[0] === ".") numStr = "0" + numStr; + else if (numStr[numStr.length - 1] === ".") numStr = numStr.substring(0, numStr.length - 1); + return numStr; + } + return numStr; +} +function parse_int(numStr, base) { + const str = numStr.trim(); + if (base === 2 || base === 8) numStr = str.substring(2); + if (parseInt) return parseInt(numStr, base); + else if (Number.parseInt) return Number.parseInt(numStr, base); + else if (window && window.parseInt) return window.parseInt(numStr, base); + else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported"); +} +function handleInfinity(str, num, options) { + const isPositive = num === Infinity; + switch (options.infinity.toLowerCase()) { + case "null": + return null; + case "infinity": + return num; + // Return Infinity or -Infinity + case "string": + return isPositive ? "Infinity" : "-Infinity"; + case "original": + default: + return str; + } +} + +// node_modules/fast-xml-parser/src/ignoreAttributes.js +function getIgnoreAttributesFn(ignoreAttributes) { + if (typeof ignoreAttributes === "function") { + return ignoreAttributes; + } + if (Array.isArray(ignoreAttributes)) { + return (attrName) => { + for (const pattern of ignoreAttributes) { + if (typeof pattern === "string" && attrName === pattern) { + return true; + } + if (pattern instanceof RegExp && pattern.test(attrName)) { + return true; + } + } + }; + } + return () => false; +} + +// node_modules/path-expression-matcher/src/Expression.js +var Expression = class { + /** + * Create a new Expression + * @param {string} pattern - Pattern string (e.g., "root.users.user", "..user[id]") + * @param {Object} options - Configuration options + * @param {string} options.separator - Path separator (default: '.') + */ + constructor(pattern, options = {}, data) { + this.pattern = pattern; + this.separator = options.separator || "."; + this.segments = this._parse(pattern); + this.data = data; + this._hasDeepWildcard = this.segments.some((seg) => seg.type === "deep-wildcard"); + this._hasAttributeCondition = this.segments.some((seg) => seg.attrName !== void 0); + this._hasPositionSelector = this.segments.some((seg) => seg.position !== void 0); + } + /** + * Parse pattern string into segments + * @private + * @param {string} pattern - Pattern to parse + * @returns {Array} Array of segment objects + */ + _parse(pattern) { + const segments = []; + let i = 0; + let currentPart = ""; + while (i < pattern.length) { + if (pattern[i] === this.separator) { + if (i + 1 < pattern.length && pattern[i + 1] === this.separator) { + if (currentPart.trim()) { + segments.push(this._parseSegment(currentPart.trim())); + currentPart = ""; + } + segments.push({ type: "deep-wildcard" }); + i += 2; + } else { + if (currentPart.trim()) { + segments.push(this._parseSegment(currentPart.trim())); + } + currentPart = ""; + i++; + } + } else { + currentPart += pattern[i]; + i++; + } + } + if (currentPart.trim()) { + segments.push(this._parseSegment(currentPart.trim())); + } + return segments; + } + /** + * Parse a single segment + * @private + * @param {string} part - Segment string (e.g., "user", "ns::user", "user[id]", "ns::user:first") + * @returns {Object} Segment object + */ + _parseSegment(part) { + const segment = { type: "tag" }; + let bracketContent = null; + let withoutBrackets = part; + const bracketMatch = part.match(/^([^\[]+)(\[[^\]]*\])(.*)$/); + if (bracketMatch) { + withoutBrackets = bracketMatch[1] + bracketMatch[3]; + if (bracketMatch[2]) { + const content = bracketMatch[2].slice(1, -1); + if (content) { + bracketContent = content; + } + } + } + let namespace = void 0; + let tagAndPosition = withoutBrackets; + if (withoutBrackets.includes("::")) { + const nsIndex = withoutBrackets.indexOf("::"); + namespace = withoutBrackets.substring(0, nsIndex).trim(); + tagAndPosition = withoutBrackets.substring(nsIndex + 2).trim(); + if (!namespace) { + throw new Error(`Invalid namespace in pattern: ${part}`); + } + } + let tag = void 0; + let positionMatch = null; + if (tagAndPosition.includes(":")) { + const colonIndex = tagAndPosition.lastIndexOf(":"); + const tagPart = tagAndPosition.substring(0, colonIndex).trim(); + const posPart = tagAndPosition.substring(colonIndex + 1).trim(); + const isPositionKeyword = ["first", "last", "odd", "even"].includes(posPart) || /^nth\(\d+\)$/.test(posPart); + if (isPositionKeyword) { + tag = tagPart; + positionMatch = posPart; + } else { + tag = tagAndPosition; + } + } else { + tag = tagAndPosition; + } + if (!tag) { + throw new Error(`Invalid segment pattern: ${part}`); + } + segment.tag = tag; + if (namespace) { + segment.namespace = namespace; + } + if (bracketContent) { + if (bracketContent.includes("=")) { + const eqIndex = bracketContent.indexOf("="); + segment.attrName = bracketContent.substring(0, eqIndex).trim(); + segment.attrValue = bracketContent.substring(eqIndex + 1).trim(); + } else { + segment.attrName = bracketContent.trim(); + } + } + if (positionMatch) { + const nthMatch = positionMatch.match(/^nth\((\d+)\)$/); + if (nthMatch) { + segment.position = "nth"; + segment.positionValue = parseInt(nthMatch[1], 10); + } else { + segment.position = positionMatch; + } + } + return segment; + } + /** + * Get the number of segments + * @returns {number} + */ + get length() { + return this.segments.length; + } + /** + * Check if expression contains deep wildcard + * @returns {boolean} + */ + hasDeepWildcard() { + return this._hasDeepWildcard; + } + /** + * Check if expression has attribute conditions + * @returns {boolean} + */ + hasAttributeCondition() { + return this._hasAttributeCondition; + } + /** + * Check if expression has position selectors + * @returns {boolean} + */ + hasPositionSelector() { + return this._hasPositionSelector; + } + /** + * Get string representation + * @returns {string} + */ + toString() { + return this.pattern; + } +}; + +// node_modules/path-expression-matcher/src/ExpressionSet.js +var ExpressionSet = class { + constructor() { + this._byDepthAndTag = /* @__PURE__ */ new Map(); + this._wildcardByDepth = /* @__PURE__ */ new Map(); + this._deepWildcards = []; + this._deepByTerminalTag = /* @__PURE__ */ new Map(); + this._patterns = /* @__PURE__ */ new Set(); + this._sealed = false; + } + /** + * Add an Expression to the set. + * Duplicate patterns (same pattern string) are silently ignored. + * + * @param {import('./Expression.js').default} expression - A pre-constructed Expression instance + * @returns {this} for chaining + * @throws {TypeError} if called after seal() + * + * @example + * set.add(new Expression('root.users.user')); + * set.add(new Expression('..script')); + */ + add(expression) { + if (this._sealed) { + throw new TypeError( + "ExpressionSet is sealed. Create a new ExpressionSet to add more expressions." + ); + } + if (this._patterns.has(expression.pattern)) return this; + this._patterns.add(expression.pattern); + if (expression.hasDeepWildcard()) { + const lastSeg2 = expression.segments[expression.segments.length - 1]; + if (lastSeg2 && lastSeg2.type !== "deep-wildcard" && lastSeg2.tag !== "*") { + const tag2 = lastSeg2.tag; + if (!this._deepByTerminalTag.has(tag2)) this._deepByTerminalTag.set(tag2, []); + this._deepByTerminalTag.get(tag2).push(expression); + } else { + this._deepWildcards.push(expression); + } + return this; + } + const depth = expression.length; + const lastSeg = expression.segments[expression.segments.length - 1]; + const tag = lastSeg?.tag; + if (!tag || tag === "*") { + if (!this._wildcardByDepth.has(depth)) this._wildcardByDepth.set(depth, []); + this._wildcardByDepth.get(depth).push(expression); + } else { + const key = `${depth}:${tag}`; + if (!this._byDepthAndTag.has(key)) this._byDepthAndTag.set(key, []); + this._byDepthAndTag.get(key).push(expression); + } + return this; + } + /** + * Add multiple expressions at once. + * + * @param {import('./Expression.js').default[]} expressions - Array of Expression instances + * @returns {this} for chaining + * + * @example + * set.addAll([ + * new Expression('root.users.user'), + * new Expression('root.config.setting'), + * ]); + */ + addAll(expressions) { + for (const expr of expressions) this.add(expr); + return this; + } + /** + * Check whether a pattern string is already present in the set. + * + * @param {import('./Expression.js').default} expression + * @returns {boolean} + */ + has(expression) { + return this._patterns.has(expression.pattern); + } + /** + * Number of expressions in the set. + * @type {number} + */ + get size() { + return this._patterns.size; + } + /** + * Seal the set against further modifications. + * Useful to prevent accidental mutations after config is built. + * Calling add() or addAll() on a sealed set throws a TypeError. + * + * @returns {this} + */ + seal() { + this._sealed = true; + return this; + } + /** + * Whether the set has been sealed. + * @type {boolean} + */ + get isSealed() { + return this._sealed; + } + /** + * Test whether the matcher's current path matches any expression in the set. + * + * Evaluation order (cheapest → most expensive): + * 1. Exact depth + tag bucket — O(1) lookup, typically 0–2 expressions + * 2. Depth-only wildcard bucket — O(1) lookup, rare + * 3. Deep-wildcard list — always checked, but usually small + * + * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view) + * @returns {boolean} true if any expression matches the current path + * + * @example + * if (stopNodes.matchesAny(matcher)) { + * // handle stop node + * } + */ + matchesAny(matcher) { + return this.findMatch(matcher) !== null; + } + /** + * Find and return the first Expression that matches the matcher's current path. + * + * Uses the same evaluation order as matchesAny (cheapest → most expensive): + * 1. Exact depth + tag bucket + * 2. Depth-only wildcard bucket + * 3. Deep-wildcard list + * + * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view) + * @returns {import('./Expression.js').default | null} the first matching Expression, or null + * + * @example + * const expr = stopNodes.findMatch(matcher); + * if (expr) { + * // access expr.config, expr.pattern, etc. + * } + */ + findMatch(matcher) { + const depth = matcher.getDepth(); + const tag = matcher.getCurrentTag(); + const exactKey = `${depth}:${tag}`; + const exactBucket = this._byDepthAndTag.get(exactKey); + if (exactBucket) { + for (let i = 0; i < exactBucket.length; i++) { + if (matcher.matches(exactBucket[i])) return exactBucket[i]; + } + } + const wildcardBucket = this._wildcardByDepth.get(depth); + if (wildcardBucket) { + for (let i = 0; i < wildcardBucket.length; i++) { + if (matcher.matches(wildcardBucket[i])) return wildcardBucket[i]; + } + } + const deepBucket = this._deepByTerminalTag.get(tag); + if (deepBucket) { + for (let i = 0; i < deepBucket.length; i++) { + if (matcher.matches(deepBucket[i])) return deepBucket[i]; + } + } + for (let i = 0; i < this._deepWildcards.length; i++) { + if (matcher.matches(this._deepWildcards[i])) return this._deepWildcards[i]; + } + return null; + } +}; + +// node_modules/path-expression-matcher/src/Matcher.js +var MatcherView = class { + /** + * @param {Matcher} matcher - The parent Matcher instance to read from. + */ + constructor(matcher) { + this._matcher = matcher; + } + /** + * Get the path separator used by the parent matcher. + * @returns {string} + */ + get separator() { + return this._matcher.separator; + } + /** + * Get current tag name. + * @returns {string|undefined} + */ + getCurrentTag() { + const path = this._matcher.path; + return path.length > 0 ? path[path.length - 1].tag : void 0; + } + /** + * Get current namespace. + * @returns {string|undefined} + */ + getCurrentNamespace() { + const path = this._matcher.path; + return path.length > 0 ? path[path.length - 1].namespace : void 0; + } + /** + * Get current node's attribute value. + * @param {string} attrName + * @returns {*} + */ + getAttrValue(attrName) { + const path = this._matcher.path; + if (path.length === 0) return void 0; + return path[path.length - 1].values?.[attrName]; + } + /** + * Check if current node has an attribute. + * @param {string} attrName + * @returns {boolean} + */ + hasAttr(attrName) { + const path = this._matcher.path; + if (path.length === 0) return false; + const current = path[path.length - 1]; + return current.values !== void 0 && attrName in current.values; + } + /** + * Get the value of a "kept" attribute from the nearest ancestor (or + * current node) that declared it via `push(tag, attrs, ns, { keep: [...] })`. + * @param {string} attrName + * @returns {*} + */ + getAnyParentAttr(attrName) { + return this._matcher.getAnyParentAttr(attrName); + } + /** + * Check whether any ancestor (or the current node) kept the given + * attribute via `push(tag, attrs, ns, { keep: [...] })`. + * @param {string} attrName + * @returns {boolean} + */ + hasAnyParentAttr(attrName) { + return this._matcher.hasAnyParentAttr(attrName); + } + /** + * Get current node's sibling position (child index in parent). + * @returns {number} + */ + getPosition() { + const path = this._matcher.path; + if (path.length === 0) return -1; + return path[path.length - 1].position ?? 0; + } + /** + * Get current node's repeat counter (occurrence count of this tag name). + * @returns {number} + */ + getCounter() { + const path = this._matcher.path; + if (path.length === 0) return -1; + return path[path.length - 1].counter ?? 0; + } + /** + * Get current node's sibling index (alias for getPosition). + * @returns {number} + * @deprecated Use getPosition() or getCounter() instead + */ + getIndex() { + return this.getPosition(); + } + /** + * Get current path depth. + * @returns {number} + */ + getDepth() { + return this._matcher.path.length; + } + /** + * Get path as string. + * @param {string} [separator] - Optional separator (uses default if not provided) + * @param {boolean} [includeNamespace=true] + * @returns {string} + */ + toString(separator, includeNamespace = true) { + return this._matcher.toString(separator, includeNamespace); + } + /** + * Get path as array of tag names. + * @returns {string[]} + */ + toArray() { + return this._matcher.path.map((n) => n.tag); + } + /** + * Match current path against an Expression. + * @param {Expression} expression + * @returns {boolean} + */ + matches(expression) { + return this._matcher.matches(expression); + } + /** + * Match any expression in the given set against the current path. + * @param {ExpressionSet} exprSet + * @returns {boolean} + */ + matchesAny(exprSet) { + return exprSet.matchesAny(this._matcher); + } +}; +var Matcher = class { + /** + * Create a new Matcher. + * @param {Object} [options={}] + * @param {string} [options.separator='.'] - Default path separator + */ + constructor(options = {}) { + this.separator = options.separator || "."; + this.path = []; + this.siblingStacks = []; + this._pathStringCache = null; + this._view = new MatcherView(this); + this._keptAttrs = []; + } + /** + * Push a new tag onto the path. + * @param {string} tagName + * @param {Object|null} [attrValues=null] + * @param {string|null} [namespace=null] + * @param {Object|null} [options=null] + * @param {string[]} [options.keep] - Names of attributes (from attrValues) + */ + push(tagName, attrValues = null, namespace = null, options = null) { + this._pathStringCache = null; + if (this.path.length > 0) { + this.path[this.path.length - 1].values = void 0; + } + const currentLevel = this.path.length; + let level = this.siblingStacks[currentLevel]; + if (!level) { + level = { counts: /* @__PURE__ */ new Map(), total: 0 }; + this.siblingStacks[currentLevel] = level; + } + const siblingKey = namespace ? `${namespace}:${tagName}` : tagName; + const counter = level.counts.get(siblingKey) || 0; + const position = level.total; + level.counts.set(siblingKey, counter + 1); + level.total++; + const node = { + tag: tagName, + position, + counter + }; + if (namespace !== null && namespace !== void 0) { + node.namespace = namespace; + } + if (attrValues !== null && attrValues !== void 0) { + node.values = attrValues; + } + this.path.push(node); + const depth = this.path.length; + const keep = options !== null ? options.keep : null; + if (keep !== null && keep !== void 0 && keep.length > 0 && attrValues) { + for (let i = 0; i < keep.length; i++) { + const name = keep[i]; + if (attrValues[name] !== void 0) { + this._keptAttrs.push({ depth, name, value: attrValues[name] }); + } + } + } + } + /** + * Pop the last tag from the path. + * @returns {Object|undefined} The popped node + */ + pop() { + if (this.path.length === 0) return void 0; + this._pathStringCache = null; + const node = this.path.pop(); + if (this.siblingStacks.length > this.path.length + 1) { + this.siblingStacks.length = this.path.length + 1; + } + const poppedDepth = this.path.length + 1; + while (this._keptAttrs.length > 0 && this._keptAttrs[this._keptAttrs.length - 1].depth >= poppedDepth) { + this._keptAttrs.pop(); + } + return node; + } + /** + * Update current node's attribute values. + * Useful when attributes are parsed after push. + * @param {Object} attrValues + */ + updateCurrent(attrValues) { + if (this.path.length > 0) { + const current = this.path[this.path.length - 1]; + if (attrValues !== null && attrValues !== void 0) { + current.values = attrValues; + } + } + } + /** + * Get current tag name. + * @returns {string|undefined} + */ + getCurrentTag() { + return this.path.length > 0 ? this.path[this.path.length - 1].tag : void 0; + } + /** + * Get current namespace. + * @returns {string|undefined} + */ + getCurrentNamespace() { + return this.path.length > 0 ? this.path[this.path.length - 1].namespace : void 0; + } + /** + * Get current node's attribute value. + * @param {string} attrName + * @returns {*} + */ + getAttrValue(attrName) { + if (this.path.length === 0) return void 0; + return this.path[this.path.length - 1].values?.[attrName]; + } + /** + * Check if current node has an attribute. + * @param {string} attrName + * @returns {boolean} + */ + hasAttr(attrName) { + if (this.path.length === 0) return false; + const current = this.path[this.path.length - 1]; + return current.values !== void 0 && attrName in current.values; + } + /** + * Get the value of a "kept" attribute from the nearest ancestor (or + * current node) that declared it via `push(tag, attrs, ns, { keep: [...] })`. + * Unlike getAttrValue(), this works regardless of how deep the path has + * gone since the attribute was pushed — but only for attribute names that + * were explicitly marked with `keep` at push time. Cost is proportional to + * the number of currently-kept attributes (typically 0-3), not path depth. + * @param {string} attrName + * @returns {*} the value, or undefined if no ancestor kept this attribute + */ + getAnyParentAttr(attrName) { + const kept = this._keptAttrs; + for (let i = kept.length - 1; i >= 0; i--) { + if (kept[i].name === attrName) return kept[i].value; + } + return void 0; + } + /** + * Check whether any ancestor (or the current node) kept the given + * attribute via `push(tag, attrs, ns, { keep: [...] })`. + * @param {string} attrName + * @returns {boolean} + */ + hasAnyParentAttr(attrName) { + const kept = this._keptAttrs; + for (let i = kept.length - 1; i >= 0; i--) { + if (kept[i].name === attrName) return true; + } + return false; + } + /** + * Get current node's sibling position (child index in parent). + * @returns {number} + */ + getPosition() { + if (this.path.length === 0) return -1; + return this.path[this.path.length - 1].position ?? 0; + } + /** + * Get current node's repeat counter (occurrence count of this tag name). + * @returns {number} + */ + getCounter() { + if (this.path.length === 0) return -1; + return this.path[this.path.length - 1].counter ?? 0; + } + /** + * Get current node's sibling index (alias for getPosition). + * @returns {number} + * @deprecated Use getPosition() or getCounter() instead + */ + getIndex() { + return this.getPosition(); + } + /** + * Get current path depth. + * @returns {number} + */ + getDepth() { + return this.path.length; + } + /** + * Get path as string. + * @param {string} [separator] - Optional separator (uses default if not provided) + * @param {boolean} [includeNamespace=true] + * @returns {string} + */ + toString(separator, includeNamespace = true) { + const sep2 = separator || this.separator; + const isDefault = sep2 === this.separator && includeNamespace === true; + if (isDefault) { + if (this._pathStringCache !== null) { + return this._pathStringCache; + } + const result = this.path.map( + (n) => n.namespace ? `${n.namespace}:${n.tag}` : n.tag + ).join(sep2); + this._pathStringCache = result; + return result; + } + return this.path.map( + (n) => includeNamespace && n.namespace ? `${n.namespace}:${n.tag}` : n.tag + ).join(sep2); + } + /** + * Get path as array of tag names. + * @returns {string[]} + */ + toArray() { + return this.path.map((n) => n.tag); + } + /** + * Reset the path to empty. + */ + reset() { + this._pathStringCache = null; + this.path = []; + this.siblingStacks = []; + this._keptAttrs = []; + } + /** + * Match current path against an Expression. + * @param {Expression} expression + * @returns {boolean} + */ + matches(expression) { + const segments = expression.segments; + if (segments.length === 0) { + return false; + } + if (expression.hasDeepWildcard()) { + return this._matchWithDeepWildcard(segments); + } + return this._matchSimple(segments); + } + /** + * @private + */ + _matchSimple(segments) { + if (this.path.length !== segments.length) { + return false; + } + for (let i = 0; i < segments.length; i++) { + if (!this._matchSegment(segments[i], this.path[i], i === this.path.length - 1)) { + return false; + } + } + return true; + } + /** + * @private + */ + _matchWithDeepWildcard(segments) { + let pathIdx = this.path.length - 1; + let segIdx = segments.length - 1; + while (segIdx >= 0 && pathIdx >= 0) { + const segment = segments[segIdx]; + if (segment.type === "deep-wildcard") { + segIdx--; + if (segIdx < 0) { + return true; + } + const nextSeg = segments[segIdx]; + let found = false; + for (let i = pathIdx; i >= 0; i--) { + if (this._matchSegment(nextSeg, this.path[i], i === this.path.length - 1)) { + pathIdx = i - 1; + segIdx--; + found = true; + break; + } + } + if (!found) { + return false; + } + } else { + if (!this._matchSegment(segment, this.path[pathIdx], pathIdx === this.path.length - 1)) { + return false; + } + pathIdx--; + segIdx--; + } + } + return segIdx < 0; + } + /** + * @private + */ + _matchSegment(segment, node, isCurrentNode) { + if (segment.tag !== "*" && segment.tag !== node.tag) { + return false; + } + if (segment.namespace !== void 0) { + if (segment.namespace !== "*" && segment.namespace !== node.namespace) { + return false; + } + } + if (segment.attrName !== void 0) { + if (!isCurrentNode) { + return false; + } + if (!node.values || !(segment.attrName in node.values)) { + return false; + } + if (segment.attrValue !== void 0) { + if (String(node.values[segment.attrName]) !== String(segment.attrValue)) { + return false; + } + } + } + if (segment.position !== void 0) { + if (!isCurrentNode) { + return false; + } + const counter = node.counter ?? 0; + if (segment.position === "first" && counter !== 0) { + return false; + } else if (segment.position === "odd" && counter % 2 !== 1) { + return false; + } else if (segment.position === "even" && counter % 2 !== 0) { + return false; + } else if (segment.position === "nth" && counter !== segment.positionValue) { + return false; + } + } + return true; + } + /** + * Match any expression in the given set against the current path. + * @param {ExpressionSet} exprSet + * @returns {boolean} + */ + matchesAny(exprSet) { + return exprSet.matchesAny(this); + } + /** + * Create a snapshot of current state. + * @returns {Object} + */ + snapshot() { + return { + path: this.path.map((node) => ({ ...node })), + siblingStacks: this.siblingStacks.map((level) => level ? { counts: new Map(level.counts), total: level.total } : level), + keptAttrs: this._keptAttrs.map((entry) => ({ ...entry })) + }; + } + /** + * Restore state from snapshot. + * @param {Object} snapshot + */ + restore(snapshot) { + this._pathStringCache = null; + this.path = snapshot.path.map((node) => ({ ...node })); + this.siblingStacks = snapshot.siblingStacks.map((level) => level ? { counts: new Map(level.counts), total: level.total } : level); + this._keptAttrs = (snapshot.keptAttrs || []).map((entry) => ({ ...entry })); + } + /** + * Return the read-only {@link MatcherView} for this matcher. + * + * The same instance is returned on every call — no allocation occurs. + * It always reflects the current parser state and is safe to pass to + * user callbacks without risk of accidental mutation. + * + * @returns {MatcherView} + * + * @example + * const view = matcher.readOnly(); + * // pass view to callbacks — it stays in sync automatically + * view.matches(expr); // ✓ + * view.getCurrentTag(); // ✓ + * // view.push(...) // ✗ method does not exist — caught by TypeScript + */ + readOnly() { + return this._view; + } +}; + +// node_modules/is-unsafe/src/contexts/html.js +var HTML_PATTERNS = [ + { + id: "html-script-open", + description: "]/i + }, + { + id: "html-javascript-protocol", + description: "javascript: URI scheme (with optional whitespace/encoding)", + // Handles javascript:, j\u0061vascript:, and whitespace variants + pattern: /j[\t\n\r ]*a[\t\n\r ]*v[\t\n\r ]*a[\t\n\r ]*s[\t\n\r ]*c[\t\n\r ]*r[\t\n\r ]*i[\t\n\r ]*p[\t\n\r ]*t[\t\n\r ]*:/i + }, + { + id: "html-vbscript-protocol", + description: "vbscript: URI scheme", + pattern: /vbscript[\t\n\r ]*:/i + }, + { + id: "html-data-html", + description: "data:text/html URI \u2014 can execute scripts in browsers", + pattern: /data[\t\n\r ]*:[\t\n\r ]*text\/html/i + }, + { + id: "html-data-xhtml", + description: "data:application/xhtml+xml URI", + pattern: /data[\t\n\r ]*:[\t\n\r ]*application\/xhtml/i + }, + { + id: "html-data-svg", + description: "data:image/svg+xml URI \u2014 can execute scripts", + pattern: /data[\t\n\r ]*:[\t\n\r ]*image\/svg\+xml/i + }, + { + id: "html-inline-event-handler", + description: "Inline event handler attributes: onclick=, onerror=, onload=, etc.", + // \bon ensures we match a word boundary so "phonetic=" is not caught + pattern: /\bon\w{1,30}\s*=/i + }, + { + id: "html-entity-obfuscated-script", + description: "HTML-entity-encoded