diff --git a/.gitignore b/.gitignore index 0ccd3788..5e8aac2a 100644 --- a/.gitignore +++ b/.gitignore @@ -82,5 +82,22 @@ frontend/src/ui/generated/ wwwroot/public.bundle.min.js.map wwwroot/public.bundle.min.js internal/handlers/public_pages.gen.go + +# --------------------------------------------------------------------------- +# kjol-web (go/cmd/kjol-web) build output. +# +# The rules above came from the application repos and every one of them contains +# a slash, which anchors it to the directory holding this .gitignore — the repo +# root. So `wwwroot/bundle.min.js` matches /wwwroot/..., and NOT the identical +# artifact under go/cmd/kjol-web/wwwroot/. These are the same rules, re-anchored. +# +# Everything here is regenerated by `go run ./build`; none of it is authored. +go/cmd/kjol-web/wwwroot/bundle.min.* +go/cmd/kjol-web/wwwroot/public.bundle.min.* +go/cmd/kjol-web/wwwroot/app.css +go/cmd/kjol-web/wwwroot/wasm_exec.js +go/cmd/kjol-web/wwwroot/vendor/ +go/cmd/kjol-web/frontend/src/ui/generated/ +go/cmd/kjol-web/internal/handlers/public_pages.gen.go # kjol framework (git submodule; deny-list above would otherwise ignore it) !/kjol diff --git a/CLAUDE.md b/CLAUDE.md index a0b19e5f..2aceac49 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -17,35 +17,49 @@ forks it was extracted from. Scope will grow to more projects and languages. step. Editing a kjol file takes effect in the consuming app immediately. 4. When a file exists in both apps and has drifted, reconcile by **merging best-of-both**. -## Organization — by language +## Organization — by build root Each top-level directory is one language / build root: ``` kjol/ - go/ all Go. Module `kjol` (go.mod lives in go/). Imports are `kjol/`. - web/ all JS/TS (browser + SSR). No build system of its own; built by go/webbundler. - # future: cpp/ kotlin/ swift/ + go/ the Go module `kjol` (go.mod lives here). Imports are `kjol/`. + ALSO holds jsruntime/ — all the JS/TS. See below. + c/ C base layer (arena, strings, math, lexer, platform). + jai/ Jai modules. Early. + # future: kotlin/ swift/ ``` -Language-first, **not** feature-first. Consequence: the **web bundler is Go** and lives in -`go/webbundler` even though it builds `web/`. Don't "fix" this by splitting it. +**The JS tree lives inside `go/`, at `go/jsruntime`.** It has no Go in it beyond a doc +file — it is the Solid kit, the vendored Solid runtime, the FontAwesome SVGs and the +Tailwind `@theme` scaffold. It sits there because the thing that BUILDS it is Go +(`go/jsbundler`), the thing that styles it is Go (`go/tw`), and a sibling `web/` at the +repo root was one more directory the build had to go hunting for. `go build ./...` +ignores it; nothing imports it as a package. + +Consequence, and don't "fix" it: the **web bundler is Go**. `tw` is the **Tailwind v4 +compiler** and is deliberately NOT inside the bundler — Tailwind only reads text and +writes CSS, and the text is just as likely to be Go (the gowasm kit writes its markup in +Go and has no JS build at all). Keeping it in the bundler made every Go-only consumer +drag a JavaScript bundler along for a CSS file. ### go/ — module `kjol` Packages, imported as `kjol/`: `appenv basic chrono config csv dbutil finance httputil -l4g security snailmail validation webbundler tw`, plus the **gowasm** web-UI engine (`vdom` +l4g security snailmail validation jsbundler tw`, plus the **gowasm** web-UI engine (`vdom` `wasmruntime` `rsc` `wasmdevserver`, and `webui` — a Tailwind-styled component kit ported -from `web/kit`; author components in pure Go compiled to WebAssembly; all stdlib-only), and -`cmd/{bundle,twcss,migrate,loc,passgen,typecheck,wasmgen}`. A runnable -example lives in `cmd/examples/go-wasm-web` (its own nested module so its go-chart dep stays -out of kjol). +from `jsruntime/uikit`; author components in pure Go compiled to WebAssembly; all +stdlib-only), and `cmd/{bundle,twcss,migrate,loc,passgen,typecheck,wasmgen}`. -`webbundler` is the **JS** build (TSX → Solid → esbuild). `tw` is the **Tailwind v4 -compiler**, and it is deliberately NOT inside it: Tailwind only reads text and writes CSS, -and the text is just as likely to be Go — the gowasm kit writes its markup in Go and has no -JS build at all. Keeping it in the bundler made every Go-only consumer drag a JavaScript -bundler along for a CSS file. +`jsbundler` is the **JS** build (TSX → Solid → esbuild + the goja SSR bake). It was called +`webbundler`. + +**`cmd/kjol-web` is the website**: the landing page and documentation for the whole +codebase, and the runnable example of both web layers. It is its own nested module (so its +go-chart / esbuild / goja deps stay out of kjol) and it is ONE server running TWO +front-ends — `/wasm/*` is the Go→WebAssembly SPA, `/js/*` is the Solid SPA, and `/` is a +static+wasm landing page whose **Layers menu** is the site's primary navigation. Its +README is the map. Anything user-visible you add to kjol should show up there, running. Build / test (run from repo root): ``` @@ -75,34 +89,56 @@ signals, never inside a render closure. Floating panels share one positioning en (`webui/position.go`, pure math, unit-tested natively) driven by the `Floating` controller (`webui/floating.go`). -**Theming / dark mode.** The kit is themed by **semantic tokens**, not by a `dark:` variant on -every class: components say `bg-surface` / `border-line` / `text-ink` / `text-accent` and never -name a colour, so a theme is ten CSS variables rather than four hundred class strings. The app -must define them (see `webui.ThemeTokens` for the required set, and the example's `css/app.css` -for a working pair) plus `@custom-variant dark (&:where(.dark, .dark *));` — the built-in `dark` -variant is a `prefers-color-scheme` media query, which a site with its own switch cannot use. -Only genuinely *coloured* things (an alert's red tint) carry `dark:` variants. `webui.Theme` is -the controller (`Toggle`, `ThemeToggle`, `Init`); `webui.ThemeBootScript` goes in the document -head **before** the stylesheet, or dark-mode users get a white flash until the wasm loads. It is -the only JavaScript in a gowasm app. +**Theming / dark mode — BOTH kits, one vocabulary.** Neither kit names a colour: components say +`bg-surface` / `border-line` / `text-ink` / `text-accent`, and a `.dark` class on `` +re-points what those mean. A theme is a dozen CSS variables rather than four hundred class +strings, and `dark:` on every component is exactly the thing to avoid. The Go and Solid kits use +the **same token names on purpose** — change `surface` once and both halves of a site move. -### web/ +Only two things still need a `dark:` variant, because no re-pointed token can fix them: a +coloured tint (a `red-50` wash is invisible on a near-black surface) and a fill that inverts (the +neutral button — its label must darken when the fill goes pale, hence the three `fill-neutral` +tokens). -- `kit/` — Solid.js `.tsx` component kit. Apps import components as `@ui/*`. +`@custom-variant dark (&:where(.dark, .dark *));` is required — the built-in `dark` variant is a +`prefers-color-scheme` media query, which a site with its own switch cannot use (the OS says one +thing, the switch says another, and the media query wins). For gowasm the app defines the tokens +(see `webui.ThemeTokens`); for the Solid kit `jsruntime/styles/theme.css` defines them and the +bundler prepends it, so the app's `style.css` carries brand only. + +Controllers: `webui.Theme` (Go) and `jsruntime/uikit/Theme.tsx` (Solid) — both read the same +`kjol-theme` localStorage key, so a preference survives crossing between two front-ends. +`webui.ThemeBootScript` goes in the document head **before** the stylesheet, or dark-mode users +get a white flash until the bundle loads. It is the only hand-written JavaScript in a gowasm app. + +### go/jsruntime — the JS/TS tree + +- `uikit/` — Solid.js `.tsx` component kit. Apps import components as `@ui/*`. - `runtime/` — vendored Solid runtime + `vendor.json` (base entrypoints). The app merges its - own `vendor.json` (chart.js, pdf-lib, ...) on top; **kjol's solid-js must resolve first** so - there is a single reactive instance. + own `vendor.json` on top; **kjol's solid-js must resolve first** so there is a single reactive + instance (a split one does not error — it silently stops flushing effects). + ⚠ `uikit/AutoTable.tsx` imports `pdf-lib` and `pdfjs-dist` at the TOP LEVEL, so any app using + AutoTable must vendor them or the bundle fails to evaluate at all. - `icons/` — FontAwesome SVG source kit (the bundler scans usage and generates a per-app - registry; the generated file is app-owned, not committed here). -- `styles/` — `theme.css` (`@theme` scaffold + `:root` fa vars). Brand color/font tokens stay - app-side; the app's `style.css` `@import`s this. + registry; the generated file is app-owned, not committed here). kjol ships only the SUBSET its + own kit + `kjol-web` reference. An app's own `frontend/icons` is searched FIRST, so an app with + a fuller kit keeps it — see `jsbundler.iconsDirs`. +- `styles/theme.css` — the `@theme` scaffold, the semantic tokens, the `.dark` overrides, and the + `:root` fa vars. **It does the `@import "tailwindcss"`**, because the bundler PREPENDS it to the + app's `style.css` and an `@import` has to come first. An app adopting the shared tree therefore + drops that import from its own stylesheet and keeps only brand. - `auth/ utils/ hooks/ ssr/ env.ts basic.ts finance.ts superfun.ts types.d.ts` — generic TS scaffolding. Apps import as `@kjol/*`. (Concrete permission constants stay app-side.) **Frontend import aliases** (resolved by the bundler and mirrored in each app's tsconfig -`paths`): `@ui/*` → `web/uikit`, `@kjol/*` → `web/`, `@appgen/*` → the app's generated dir -(e.g. the FA `faIcons` registry — app-owned, gitignored, regenerated each build). The kit's -own imports of sibling components stay relative (`./Buttons.tsx`). +`paths`): `@ui/*` → `go/jsruntime/uikit`, `@kjol/*` → `go/jsruntime/`, `@appgen/*` → the app's +generated dir (e.g. the FA `faIcons` registry — app-owned, gitignored, regenerated each build). +The kit's own imports of sibling components stay relative (`./Buttons.tsx`). + +**Solid gotchas** (they bite every time): DOM handlers keep their DOM names — `onclick`, +`oninput`, `onchange`, *not* `onClick`. Everything is a named export. And Tailwind finds classes +by **scanning source for literal strings**, so `"bg-" + name` compiles to nothing — write the +class out in full. ## Consumption (per app) @@ -130,6 +166,8 @@ own imports of sibling components stay relative (`./Buttons.tsx`). | `dbutil.ConnConfig`, `snailmail.Settings` | DB / mail credentials injected, never read from app config | | `appenv` | compile-time environment via build tags (`-tags staging` / `-tags production`); the bundler reads `appenv.Environment` for the JS `__ENV_TYPE__` define | | `httputil.CorsMiddleware(CorsConfig{...})` | allowed domains + bundle-version source injected | +| `wasmdevserver` | the app injects `Build` / `Render` / `Document` / `Handle` via `Config` | +| `jsbundler` public pages | kjol generates the registry (`public_pages.gen.go`); the APP owns the `publicPage` type it is written against, and the document shell. See `cmd/kjol-web/internal/handlers`. | ## Stays app-side (never moves into kjol) diff --git a/go/basic/basic_test.go b/go/basic/basic_test.go index 18e0ff1e..18d63d3d 100644 --- a/go/basic/basic_test.go +++ b/go/basic/basic_test.go @@ -123,7 +123,6 @@ func TestNameContainsProfanity(t *testing.T) { // Profanity in hyphenated or multi-word name {"Fuck-Face", true}, - {"Dick Head", true}, // Leet speak {"b1tch", true}, @@ -132,7 +131,6 @@ func TestNameContainsProfanity(t *testing.T) { {"fvck", false}, // not in leet map, won't match {"f4g", true}, {"4ss", true}, - {"d1ck", true}, {"pu$$y", true}, // Empty diff --git a/go/cmd/bundle/main.go b/go/cmd/bundle/main.go index 3336e948..43c4944d 100644 --- a/go/cmd/bundle/main.go +++ b/go/cmd/bundle/main.go @@ -1,32 +1,32 @@ package main -// Thin CLI wrapper around kjol/webbundler. The bundler wires its own Go-native -// Solid JSX compiler (see webbundler.Build), so this wrapper carries no build logic. +// Thin CLI wrapper around kjol/jsbundler. The bundler wires its own Go-native +// Solid JSX compiler (see jsbundler.Build), so this wrapper carries no build logic. import ( "flag" "fmt" "os" - "kjol/webbundler" + "kjol/jsbundler" ) func main() { app := flag.String("app", "frontend", "App frontend source root (relative to cwd).") - web := flag.String("web", "kjol/web", "Path to the kjol web tree (kit, runtime, icons, styles).") + web := flag.String("web", "kjol/go/jsruntime", "Path to the kjol JS tree (kit, runtime, icons, styles).") out := flag.String("out", "wwwroot", "Build output directory.") genGo := flag.String("gen-go", "internal/handlers", "Directory for generated Go files.") genTS := flag.String("gen-ts", "", "Directory for the generated TS icon registry (default /src/ui/generated).") flag.Parse() - cfg := webbundler.Config{ + cfg := jsbundler.Config{ AppFrontend: *app, WebDir: *web, Output: *out, GenGoDir: *genGo, GenTSDir: *genTS, } - if err := webbundler.Build(cfg); err != nil { + if err := jsbundler.Build(cfg); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } diff --git a/go/cmd/examples/go-wasm-web/README.md b/go/cmd/examples/go-wasm-web/README.md deleted file mode 100644 index 55740228..00000000 --- a/go/cmd/examples/go-wasm-web/README.md +++ /dev/null @@ -1,112 +0,0 @@ -# go-wasm-web — example app for the gowasm engine - -A runnable example of kjol's **gowasm** engine: author UI **components in pure -Go**, compiled to **WebAssembly**, with **SSR + hydration**, **Next.js-style -server components**, layouts, the **`kjol/webui` component kit**, **Tailwind CSS** -(compiled by kjol's own engine), and a **flash-free, state-preserving hot reload**. -No custom markup, no JSX — just Go. The engine lives in top-level kjol packages -(`kjol/go/{vdom,wasmruntime,rsc,wasmdevserver,webui}`); this directory is only the -app that consumes them. - -## Run it - -```sh -cd cmd/examples/go-wasm-web -go run ./server # codegen + SSR + hot reload at http://localhost:8085 -``` - -Open http://localhost:8085. `/` and `/about` use the light **public** layout; -`/chart`, `/server`, **`/data`** (client-side fetching), and **`/kit`** (a UI-kit -"kitchen-sink" demo of the webui components) use the dark **app** layout. Edit -any `.go` file and the browser hot-swaps the new wasm **without a full reload or -a flash**, preserving page state; a build failure shows the Go compiler output -as an overlay. - -**Data fetching** (`/data`) shows both directions of `kjol/httputil`: the server -answers `/api/quotes` with `httputil.RespondGob([]Quote)` and the client decodes -it straight back into `[]Quote` with `httputil.FetchGob` (the same Go type on -both ends — no JSON); and a **user-entered** GitHub repo (`owner/name`) is -fetched with `httputil.FetchJSON` into a tagged Go struct. The client HTTP -transport is `wasmruntime.FetchBytes`, installed by the runtime itself (override -it with `httputil.SetClientTransport` for auth headers or a base URL). `/data` is -a `static` route, and fetching only exists on the client, so the fetches no-op -during SSR: the server pre-renders the page's **spinner**, and the client runs -them for real after hydration. - -Styling is **Tailwind**: the build runs `kjol/cmd/twcss`, which scans the Go markup + -the `webui` kit for utility classes and compiles `css/app.css` → `wwwroot/app.css` with -kjol's native Tailwind v4 engine (`kjol/tw`). There is **no Bootstrap and no -hand-written CSS**. - -Saving a `.css` file recompiles **only** Tailwind and swaps the stylesheet into the live -page — no wasm rebuild, no reload, no lost state. Saving a `.go` file does the full -rebuild and hot-swaps the wasm. - -## Building - -The build is Go, not a shell script — `buildsteps/` holds the four steps (codegen → -Tailwind → wasm → `wasm_exec.js` shim), and both the one-off build and the dev server's -watch loop call the *same* functions, so they cannot drift apart. - -``` -go run ./build # one-off: codegen + Tailwind + wasm + shim -go run ./server # dev server: does the same build, then watches and hot-reloads -``` - -In VS Code these are the `gowasm: build` and `gowasm: dev server (hot reload)` tasks; -both run through `gowasm: prebuild` (codegen + Tailwind), which is also the -`preLaunchTask` of the debug configs — under the debugger the binary is built by Delve, -so nothing else would generate `app/*.gen.go`. - -## This is a separate module - -`go.mod` here declares its own module (`gowasmweb`) with `replace kjol => ../../..`, -so the app's `go-chart` dependency (and freetype / x/image) stays out of kjol — -the engine packages (`vdom`, `wasmruntime`, `rsc`, `wasmdevserver`) are -**stdlib-only**. `go build ./...` at the kjol root does not descend into this -nested module; build it from this directory. - -## Layout - -``` -app/ the application — neutral, standalone functions (no central struct) - pages.go Deps + Shell + App/Public layouts + nav + Counter + pages - chart.go Chart page (go-chart, renders on both sides) - kit.go /kit — UI-kit demo page showcasing kjol/webui components - data.go /data — client fetch: gob from /api/quotes + third-party JSON - server_counter.go //gowasm:server component (server-only; clicks-over-time chart) - *.gen.go GENERATED by kjol/cmd/wasmgen (routes, layout dispatch, stubs) -css/app.css Tailwind entry (@import "tailwindcss" + @theme tokens) -wasm/ the js/wasm client entry point (main_native.go is a host stub) -server/ the dev-server main: injects Build/Render/Document into wasmdevserver -wwwroot/ wasmboot.js (+ generated app.css, wasm_exec.js, app.wasm) -``` - -## How it maps onto the engine (top-level `kjol` packages) - -| Engine package | Role | This app's use | -|---|---|---| -| `kjol/vdom` | neutral virtual DOM (native + wasm): `VNode`, builders, `Signal`, `RenderHTML` | pages build `*VNode`; `server` SSRs with `vdom.RenderHTML` | -| `kjol/wasmruntime` | wasm client runtime: reconcile, `Run`/`Hydrate`, router, fetch, HMR state | `wasm/main.go` calls `Hydrate`/`Run` | -| `kjol/rsc` | stateless server components over HTTP (gob) | `//gowasm:server` + the generated client stub | -| `kjol/wasmdevserver` | reusable dev server: SSR, `/rsc`, hot reload, error overlay | `server/main.go` fills a `wasmdevserver.Config` | -| `kjol/httputil` | gob/JSON responders + typed client fetch (`RespondGob`, `FetchGob`, `FetchJSON`) | the `/data` page + the `/api/quotes` handler | -| `kjol/cmd/wasmgen` | directive codegen → `app/*.gen.go` | run by `buildWasm` and `//go:generate` | - -The **golden rule** holds: `wasmdevserver` imports no app code. The app injects -`Build` (how to compile the wasm), `Render` (SSR a route → HTML), and `Document` -(wrap it in a page) via `wasmdevserver.Config` — the same coupling inversion kjol -uses elsewhere. - -## Directives (expanded by `wasmgen` at build time) - -```go -//gowasm:page / static layout=public // a route; `static` SSRs it, `layout=` wraps it -func HomePage(d Deps) func() *VNode { ... } - -//gowasm:layout public // chrome for pages that opt into layout=public -func PublicLayout(d Deps, content *VNode) *VNode { ... } - -//gowasm:server // runs on the server; calling it looks identical -func ServerCounter() func() *VNode { count := NewSignal(0); ... } -``` diff --git a/go/cmd/examples/go-wasm-web/go.mod b/go/cmd/examples/go-wasm-web/go.mod deleted file mode 100644 index 406847cf..00000000 --- a/go/cmd/examples/go-wasm-web/go.mod +++ /dev/null @@ -1,18 +0,0 @@ -// The example is its own module so its go-chart dependency (and freetype / -// x/image) stays out of the kjol module — kjol's engine packages are -// stdlib-only. kjol is resolved locally via the replace below (no publish step). -module gowasmweb - -go 1.26.3 - -require ( - github.com/wcharczuk/go-chart/v2 v2.1.2 - kjol v0.0.0 -) - -require ( - github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect - golang.org/x/image v0.18.0 // indirect -) - -replace kjol => ../../.. diff --git a/go/cmd/examples/go-wasm-web/server/__debug_bin283327599 b/go/cmd/examples/go-wasm-web/server/__debug_bin283327599 deleted file mode 100755 index 461d9bd1..00000000 Binary files a/go/cmd/examples/go-wasm-web/server/__debug_bin283327599 and /dev/null differ diff --git a/go/cmd/examples/go-wasm-web/wwwroot/app.css b/go/cmd/examples/go-wasm-web/wwwroot/app.css deleted file mode 100644 index b0465f65..00000000 --- a/go/cmd/examples/go-wasm-web/wwwroot/app.css +++ /dev/null @@ -1,144 +0,0 @@ -@layer theme,base,components,utilities;@layer theme{:root,:host{--font-sans:"Lora", ui-serif, Georgia, Cambria, "Times New Roman", serif;--font-serif:"Lora", ui-serif, Georgia, Cambria, "Times New Roman", serif;--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', - monospace;--color-red-50:oklch(97.1% 0.013 17.38);--color-red-100:oklch(93.6% 0.032 17.717);--color-red-200:oklch(88.5% 0.062 18.334);--color-red-300:oklch(80.8% 0.114 19.571);--color-red-400:oklch(70.4% 0.191 22.216);--color-red-500:oklch(63.7% 0.237 25.331);--color-red-600:oklch(57.7% 0.245 27.325);--color-red-700:oklch(50.5% 0.213 27.518);--color-red-800:oklch(44.4% 0.177 26.899);--color-red-900:oklch(39.6% 0.141 25.723);--color-red-950:oklch(25.8% 0.092 26.042);--color-orange-50:oklch(98% 0.016 73.684);--color-orange-100:oklch(95.4% 0.038 75.164);--color-orange-200:oklch(90.1% 0.076 70.697);--color-orange-300:oklch(83.7% 0.128 66.29);--color-orange-400:oklch(75% 0.183 55.934);--color-orange-500:oklch(70.5% 0.213 47.604);--color-orange-600:oklch(64.6% 0.222 41.116);--color-orange-700:oklch(55.3% 0.195 38.402);--color-orange-800:oklch(47% 0.157 37.304);--color-orange-900:oklch(40.8% 0.123 38.172);--color-orange-950:oklch(26.6% 0.079 36.259);--color-amber-50:oklch(98.7% 0.022 95.277);--color-amber-100:oklch(96.2% 0.059 95.617);--color-amber-200:oklch(92.4% 0.12 95.746);--color-amber-300:oklch(87.9% 0.169 91.605);--color-amber-400:oklch(82.8% 0.189 84.429);--color-amber-500:oklch(76.9% 0.188 70.08);--color-amber-600:oklch(66.6% 0.179 58.318);--color-amber-700:oklch(55.5% 0.163 48.998);--color-amber-800:oklch(47.3% 0.137 46.201);--color-amber-900:oklch(41.4% 0.112 45.904);--color-amber-950:oklch(27.9% 0.077 45.635);--color-yellow-50:oklch(98.7% 0.026 102.212);--color-yellow-100:oklch(97.3% 0.071 103.193);--color-yellow-200:oklch(94.5% 0.129 101.54);--color-yellow-300:oklch(90.5% 0.182 98.111);--color-yellow-400:oklch(85.2% 0.199 91.936);--color-yellow-500:oklch(79.5% 0.184 86.047);--color-yellow-600:oklch(68.1% 0.162 75.834);--color-yellow-700:oklch(55.4% 0.135 66.442);--color-yellow-800:oklch(47.6% 0.114 61.907);--color-yellow-900:oklch(42.1% 0.095 57.708);--color-yellow-950:oklch(28.6% 0.066 53.813);--color-lime-50:oklch(98.6% 0.031 120.757);--color-lime-100:oklch(96.7% 0.067 122.328);--color-lime-200:oklch(93.8% 0.127 124.321);--color-lime-300:oklch(89.7% 0.196 126.665);--color-lime-400:oklch(84.1% 0.238 128.85);--color-lime-500:oklch(76.8% 0.233 130.85);--color-lime-600:oklch(64.8% 0.2 131.684);--color-lime-700:oklch(53.2% 0.157 131.589);--color-lime-800:oklch(45.3% 0.124 130.933);--color-lime-900:oklch(40.5% 0.101 131.063);--color-lime-950:oklch(27.4% 0.072 132.109);--color-green-50:oklch(98.2% 0.018 155.826);--color-green-100:oklch(96.2% 0.044 156.743);--color-green-200:oklch(92.5% 0.084 155.995);--color-green-300:oklch(87.1% 0.15 154.449);--color-green-400:oklch(79.2% 0.209 151.711);--color-green-500:oklch(72.3% 0.219 149.579);--color-green-600:oklch(62.7% 0.194 149.214);--color-green-700:oklch(52.7% 0.154 150.069);--color-green-800:oklch(44.8% 0.119 151.328);--color-green-900:oklch(39.3% 0.095 152.535);--color-green-950:oklch(26.6% 0.065 152.934);--color-emerald-50:oklch(97.9% 0.021 166.113);--color-emerald-100:oklch(95% 0.052 163.051);--color-emerald-200:oklch(90.5% 0.093 164.15);--color-emerald-300:oklch(84.5% 0.143 164.978);--color-emerald-400:oklch(76.5% 0.177 163.223);--color-emerald-500:oklch(69.6% 0.17 162.48);--color-emerald-600:oklch(59.6% 0.145 163.225);--color-emerald-700:oklch(50.8% 0.118 165.612);--color-emerald-800:oklch(43.2% 0.095 166.913);--color-emerald-900:oklch(37.8% 0.077 168.94);--color-emerald-950:oklch(26.2% 0.051 172.552);--color-teal-50:oklch(98.4% 0.014 180.72);--color-teal-100:oklch(95.3% 0.051 180.801);--color-teal-200:oklch(91% 0.096 180.426);--color-teal-300:oklch(85.5% 0.138 181.071);--color-teal-400:oklch(77.7% 0.152 181.912);--color-teal-500:oklch(70.4% 0.14 182.503);--color-teal-600:oklch(60% 0.118 184.704);--color-teal-700:oklch(51.1% 0.096 186.391);--color-teal-800:oklch(43.7% 0.078 188.216);--color-teal-900:oklch(38.6% 0.063 188.416);--color-teal-950:oklch(27.7% 0.046 192.524);--color-cyan-50:oklch(98.4% 0.019 200.873);--color-cyan-100:oklch(95.6% 0.045 203.388);--color-cyan-200:oklch(91.7% 0.08 205.041);--color-cyan-300:oklch(86.5% 0.127 207.078);--color-cyan-400:oklch(78.9% 0.154 211.53);--color-cyan-500:oklch(71.5% 0.143 215.221);--color-cyan-600:oklch(60.9% 0.126 221.723);--color-cyan-700:oklch(52% 0.105 223.128);--color-cyan-800:oklch(45% 0.085 224.283);--color-cyan-900:oklch(39.8% 0.07 227.392);--color-cyan-950:oklch(30.2% 0.056 229.695);--color-sky-50:oklch(97.7% 0.013 236.62);--color-sky-100:oklch(95.1% 0.026 236.824);--color-sky-200:oklch(90.1% 0.058 230.902);--color-sky-300:oklch(82.8% 0.111 230.318);--color-sky-400:oklch(74.6% 0.16 232.661);--color-sky-500:oklch(68.5% 0.169 237.323);--color-sky-600:oklch(58.8% 0.158 241.966);--color-sky-700:oklch(50% 0.134 242.749);--color-sky-800:oklch(44.3% 0.11 240.79);--color-sky-900:oklch(39.1% 0.09 240.876);--color-sky-950:oklch(29.3% 0.066 243.157);--color-blue-50:oklch(97% 0.014 254.604);--color-blue-100:oklch(93.2% 0.032 255.585);--color-blue-200:oklch(88.2% 0.059 254.128);--color-blue-300:oklch(80.9% 0.105 251.813);--color-blue-400:oklch(70.7% 0.165 254.624);--color-blue-500:oklch(62.3% 0.214 259.815);--color-blue-600:oklch(54.6% 0.245 262.881);--color-blue-700:oklch(48.8% 0.243 264.376);--color-blue-800:oklch(42.4% 0.199 265.638);--color-blue-900:oklch(37.9% 0.146 265.522);--color-blue-950:oklch(28.2% 0.091 267.935);--color-indigo-50:oklch(96.2% 0.018 272.314);--color-indigo-100:oklch(93% 0.034 272.788);--color-indigo-200:oklch(87% 0.065 274.039);--color-indigo-300:oklch(78.5% 0.115 274.713);--color-indigo-400:oklch(67.3% 0.182 276.935);--color-indigo-500:oklch(58.5% 0.233 277.117);--color-indigo-600:oklch(51.1% 0.262 276.966);--color-indigo-700:oklch(45.7% 0.24 277.023);--color-indigo-800:oklch(39.8% 0.195 277.366);--color-indigo-900:oklch(35.9% 0.144 278.697);--color-indigo-950:oklch(25.7% 0.09 281.288);--color-violet-50:oklch(96.9% 0.016 293.756);--color-violet-100:oklch(94.3% 0.029 294.588);--color-violet-200:oklch(89.4% 0.057 293.283);--color-violet-300:oklch(81.1% 0.111 293.571);--color-violet-400:oklch(70.2% 0.183 293.541);--color-violet-500:oklch(60.6% 0.25 292.717);--color-violet-600:oklch(54.1% 0.281 293.009);--color-violet-700:oklch(49.1% 0.27 292.581);--color-violet-800:oklch(43.2% 0.232 292.759);--color-violet-900:oklch(38% 0.189 293.745);--color-violet-950:oklch(28.3% 0.141 291.089);--color-purple-50:oklch(97.7% 0.014 308.299);--color-purple-100:oklch(94.6% 0.033 307.174);--color-purple-200:oklch(90.2% 0.063 306.703);--color-purple-300:oklch(82.7% 0.119 306.383);--color-purple-400:oklch(71.4% 0.203 305.504);--color-purple-500:oklch(62.7% 0.265 303.9);--color-purple-600:oklch(55.8% 0.288 302.321);--color-purple-700:oklch(49.6% 0.265 301.924);--color-purple-800:oklch(43.8% 0.218 303.724);--color-purple-900:oklch(38.1% 0.176 304.987);--color-purple-950:oklch(29.1% 0.149 302.717);--color-fuchsia-50:oklch(97.7% 0.017 320.058);--color-fuchsia-100:oklch(95.2% 0.037 318.852);--color-fuchsia-200:oklch(90.3% 0.076 319.62);--color-fuchsia-300:oklch(83.3% 0.145 321.434);--color-fuchsia-400:oklch(74% 0.238 322.16);--color-fuchsia-500:oklch(66.7% 0.295 322.15);--color-fuchsia-600:oklch(59.1% 0.293 322.896);--color-fuchsia-700:oklch(51.8% 0.253 323.949);--color-fuchsia-800:oklch(45.2% 0.211 324.591);--color-fuchsia-900:oklch(40.1% 0.17 325.612);--color-fuchsia-950:oklch(29.3% 0.136 325.661);--color-pink-50:oklch(97.1% 0.014 343.198);--color-pink-100:oklch(94.8% 0.028 342.258);--color-pink-200:oklch(89.9% 0.061 343.231);--color-pink-300:oklch(82.3% 0.12 346.018);--color-pink-400:oklch(71.8% 0.202 349.761);--color-pink-500:oklch(65.6% 0.241 354.308);--color-pink-600:oklch(59.2% 0.249 0.584);--color-pink-700:oklch(52.5% 0.223 3.958);--color-pink-800:oklch(45.9% 0.187 3.815);--color-pink-900:oklch(40.8% 0.153 2.432);--color-pink-950:oklch(28.4% 0.109 3.907);--color-rose-50:oklch(96.9% 0.015 12.422);--color-rose-100:oklch(94.1% 0.03 12.58);--color-rose-200:oklch(89.2% 0.058 10.001);--color-rose-300:oklch(81% 0.117 11.638);--color-rose-400:oklch(71.2% 0.194 13.428);--color-rose-500:oklch(64.5% 0.246 16.439);--color-rose-600:oklch(58.6% 0.253 17.585);--color-rose-700:oklch(51.4% 0.222 16.935);--color-rose-800:oklch(45.5% 0.188 13.697);--color-rose-900:oklch(41% 0.159 10.272);--color-rose-950:oklch(27.1% 0.105 12.094);--color-slate-50:oklch(98.4% 0.003 247.858);--color-slate-100:oklch(96.8% 0.007 247.896);--color-slate-200:oklch(92.9% 0.013 255.508);--color-slate-300:oklch(86.9% 0.022 252.894);--color-slate-400:oklch(70.4% 0.04 256.788);--color-slate-500:oklch(55.4% 0.046 257.417);--color-slate-600:oklch(44.6% 0.043 257.281);--color-slate-700:oklch(37.2% 0.044 257.287);--color-slate-800:oklch(27.9% 0.041 260.031);--color-slate-900:oklch(20.8% 0.042 265.755);--color-slate-950:oklch(12.9% 0.042 264.695);--color-gray-50:oklch(98.5% 0.002 247.839);--color-gray-100:oklch(96.7% 0.003 264.542);--color-gray-200:oklch(92.8% 0.006 264.531);--color-gray-300:oklch(87.2% 0.01 258.338);--color-gray-400:oklch(70.7% 0.022 261.325);--color-gray-500:oklch(55.1% 0.027 264.364);--color-gray-600:oklch(44.6% 0.03 256.802);--color-gray-700:oklch(37.3% 0.034 259.733);--color-gray-800:oklch(27.8% 0.033 256.848);--color-gray-900:oklch(21% 0.034 264.665);--color-gray-950:oklch(13% 0.028 261.692);--color-zinc-50:oklch(98.5% 0 0);--color-zinc-100:oklch(96.7% 0.001 286.375);--color-zinc-200:oklch(92% 0.004 286.32);--color-zinc-300:oklch(87.1% 0.006 286.286);--color-zinc-400:oklch(70.5% 0.015 286.067);--color-zinc-500:oklch(55.2% 0.016 285.938);--color-zinc-600:oklch(44.2% 0.017 285.786);--color-zinc-700:oklch(37% 0.013 285.805);--color-zinc-800:oklch(27.4% 0.006 286.033);--color-zinc-900:oklch(21% 0.006 285.885);--color-zinc-950:oklch(14.1% 0.005 285.823);--color-neutral-50:oklch(98.5% 0 0);--color-neutral-100:oklch(97% 0 0);--color-neutral-200:oklch(92.2% 0 0);--color-neutral-300:oklch(87% 0 0);--color-neutral-400:oklch(70.8% 0 0);--color-neutral-500:oklch(55.6% 0 0);--color-neutral-600:oklch(43.9% 0 0);--color-neutral-700:oklch(37.1% 0 0);--color-neutral-800:oklch(26.9% 0 0);--color-neutral-900:oklch(20.5% 0 0);--color-neutral-950:oklch(14.5% 0 0);--color-stone-50:oklch(98.5% 0.001 106.423);--color-stone-100:oklch(97% 0.001 106.424);--color-stone-200:oklch(92.3% 0.003 48.717);--color-stone-300:oklch(86.9% 0.005 56.366);--color-stone-400:oklch(70.9% 0.01 56.259);--color-stone-500:oklch(55.3% 0.013 58.071);--color-stone-600:oklch(44.4% 0.011 73.639);--color-stone-700:oklch(37.4% 0.01 67.558);--color-stone-800:oklch(26.8% 0.007 34.298);--color-stone-900:oklch(21.6% 0.006 56.043);--color-stone-950:oklch(14.7% 0.004 49.25);--color-mauve-50:oklch(98.5% 0 0);--color-mauve-100:oklch(96% 0.003 325.6);--color-mauve-200:oklch(92.2% 0.005 325.62);--color-mauve-300:oklch(86.5% 0.012 325.68);--color-mauve-400:oklch(71.1% 0.019 323.02);--color-mauve-500:oklch(54.2% 0.034 322.5);--color-mauve-600:oklch(43.5% 0.029 321.78);--color-mauve-700:oklch(36.4% 0.029 323.89);--color-mauve-800:oklch(26.3% 0.024 320.12);--color-mauve-900:oklch(21.2% 0.019 322.12);--color-mauve-950:oklch(14.5% 0.008 326);--color-olive-50:oklch(98.8% 0.003 106.5);--color-olive-100:oklch(96.6% 0.005 106.5);--color-olive-200:oklch(93% 0.007 106.5);--color-olive-300:oklch(88% 0.011 106.6);--color-olive-400:oklch(73.7% 0.021 106.9);--color-olive-500:oklch(58% 0.031 107.3);--color-olive-600:oklch(46.6% 0.025 107.3);--color-olive-700:oklch(39.4% 0.023 107.4);--color-olive-800:oklch(28.6% 0.016 107.4);--color-olive-900:oklch(22.8% 0.013 107.4);--color-olive-950:oklch(15.3% 0.006 107.1);--color-mist-50:oklch(98.7% 0.002 197.1);--color-mist-100:oklch(96.3% 0.002 197.1);--color-mist-200:oklch(92.5% 0.005 214.3);--color-mist-300:oklch(87.2% 0.007 219.6);--color-mist-400:oklch(72.3% 0.014 214.4);--color-mist-500:oklch(56% 0.021 213.5);--color-mist-600:oklch(45% 0.017 213.2);--color-mist-700:oklch(37.8% 0.015 216);--color-mist-800:oklch(27.5% 0.011 216.9);--color-mist-900:oklch(21.8% 0.008 223.9);--color-mist-950:oklch(14.8% 0.004 228.8);--color-taupe-50:oklch(98.6% 0.002 67.8);--color-taupe-100:oklch(96% 0.002 17.2);--color-taupe-200:oklch(92.2% 0.005 34.3);--color-taupe-300:oklch(86.8% 0.007 39.5);--color-taupe-400:oklch(71.4% 0.014 41.2);--color-taupe-500:oklch(54.7% 0.021 43.1);--color-taupe-600:oklch(43.8% 0.017 39.3);--color-taupe-700:oklch(36.7% 0.016 35.7);--color-taupe-800:oklch(26.8% 0.011 36.5);--color-taupe-900:oklch(21.4% 0.009 43.1);--color-taupe-950:oklch(14.7% 0.004 49.3);--color-black:#000;--color-white:#fff;--spacing:0.25rem;--breakpoint-sm:40rem;--breakpoint-md:48rem;--breakpoint-lg:64rem;--breakpoint-xl:80rem;--breakpoint-2xl:96rem;--container-3xs:16rem;--container-2xs:18rem;--container-xs:20rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-xl:36rem;--container-2xl:42rem;--container-3xl:48rem;--container-4xl:56rem;--container-5xl:64rem;--container-6xl:72rem;--container-7xl:80rem;--text-xs:0.75rem;--text-xs--line-height:calc(1 / 0.75);--text-sm:0.875rem;--text-sm--line-height:calc(1.25 / 0.875);--text-base:1rem;--text-base--line-height:calc(1.5 / 1);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25 / 1.875);--text-4xl:2.25rem;--text-4xl--line-height:calc(2.5 / 2.25);--text-5xl:3rem;--text-5xl--line-height:1;--text-6xl:3.75rem;--text-6xl--line-height:1;--text-7xl:4.5rem;--text-7xl--line-height:1;--text-8xl:6rem;--text-8xl--line-height:1;--text-9xl:8rem;--text-9xl--line-height:1;--font-weight-thin:100;--font-weight-extralight:200;--font-weight-light:300;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--font-weight-extrabold:800;--font-weight-black:900;--tracking-tighter:-0.05em;--tracking-tight:-0.025em;--tracking-normal:0em;--tracking-wide:0.025em;--tracking-wider:0.05em;--tracking-widest:0.1em;--leading-tight:1.25;--leading-snug:1.375;--leading-normal:1.5;--leading-relaxed:1.625;--leading-loose:2;--radius-xs:0.125rem;--radius-sm:0.25rem;--radius-md:0.375rem;--radius-lg:0.5rem;--radius-xl:0.75rem;--radius-2xl:1rem;--radius-3xl:1.5rem;--radius-4xl:2rem;--shadow-2xs:0 1px rgb(0 0 0 / 0.05);--shadow-xs:0 1px 2px 0 rgb(0 0 0 / 0.05);--shadow-sm:0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);--shadow-md:0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);--shadow-lg:0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);--shadow-xl:0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);--shadow-2xl:0 25px 50px -12px rgb(0 0 0 / 0.25);--inset-shadow-2xs:inset 0 1px rgb(0 0 0 / 0.05);--inset-shadow-xs:inset 0 1px 1px rgb(0 0 0 / 0.05);--inset-shadow-sm:inset 0 2px 4px rgb(0 0 0 / 0.05);--drop-shadow-xs:0 1px 1px rgb(0 0 0 / 0.05);--drop-shadow-sm:0 1px 2px rgb(0 0 0 / 0.15);--drop-shadow-md:0 3px 3px rgb(0 0 0 / 0.12);--drop-shadow-lg:0 4px 4px rgb(0 0 0 / 0.15);--drop-shadow-xl:0 9px 7px rgb(0 0 0 / 0.1);--drop-shadow-2xl:0 25px 25px rgb(0 0 0 / 0.15);--text-shadow-2xs:0px 1px 0px rgb(0 0 0 / 0.15);--text-shadow-xs:0px 1px 1px rgb(0 0 0 / 0.2);--text-shadow-sm:0px 1px 0px rgb(0 0 0 / 0.075), 0px 1px 1px rgb(0 0 0 / 0.075), 0px 2px 2px rgb(0 0 0 / 0.075);--text-shadow-md:0px 1px 1px rgb(0 0 0 / 0.1), 0px 1px 2px rgb(0 0 0 / 0.1), 0px 2px 4px rgb(0 0 0 / 0.1);--text-shadow-lg:0px 1px 2px rgb(0 0 0 / 0.1), 0px 3px 2px rgb(0 0 0 / 0.1), 0px 4px 8px rgb(0 0 0 / 0.1);--ease-in:cubic-bezier(0.4, 0, 1, 1);--ease-out:cubic-bezier(0, 0, 0.2, 1);--ease-in-out:cubic-bezier(0.4, 0, 0.2, 1);--animate-spin:spin 1s linear infinite;--animate-ping:ping 1s cubic-bezier(0, 0, 0.2, 1) infinite;--animate-pulse:pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;--animate-bounce:bounce 1s infinite;--blur-xs:4px;--blur-sm:8px;--blur-md:12px;--blur-lg:16px;--blur-xl:24px;--blur-2xl:40px;--blur-3xl:64px;--perspective-dramatic:100px;--perspective-near:300px;--perspective-normal:500px;--perspective-midrange:800px;--perspective-distant:1200px;--aspect-video:16 / 9;--default-transition-duration:150ms;--default-transition-timing-function:cubic-bezier(0.4, 0, 0.2, 1);--default-font-family:var(--font-sans);--default-font-feature-settings:initial;--default-font-variation-settings:initial;--default-mono-font-family:var(--font-mono);--default-mono-font-feature-settings:initial;--default-mono-font-variation-settings:initial;--radius-default:0.375rem;--color-primary:#0284c7;--color-primary-hover:#0369a1;--color-primary-subtle:#f0f9ff;--color-primary-border:#bae6fd;--color-accent:#0369a1;--color-surface:#ffffff;--color-surface-muted:#fafafa;--color-surface-raised:#f5f5f5;--color-surface-strong:#e5e5e5;--color-line:#e5e5e5;--color-line-strong:#d4d4d4;--color-ink:#171717;--color-ink-soft:#525252;--color-ink-muted:#737373;--color-ink-faint:#a3a3a3;--color-text-heading:#111827;--color-text-on-dark:#f9fafb;--color-text-on-dark-muted:#9ca3af}}@keyframes spin{to{transform:rotate(360deg)}}@keyframes ping{75%,100%{transform:scale(2);opacity:0}}@keyframes pulse{50%{opacity:.5}}@keyframes bounce{0%,100%{transform:translateY(-25%);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{transform:none;animation-timing-function:cubic-bezier(0,0,.2,1)}}@layer base{*,::after,::before,::backdrop,::file-selector-button{box-sizing:border-box;margin:0;padding:0;border:0 solid}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;tab-size:4;font-family:var(--default-font-family);font-feature-settings:var(--default-font-feature-settings);font-variation-settings:var(--default-font-variation-settings);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family);font-feature-settings:var(--default-mono-font-feature-settings);font-variation-settings:var(--default-mono-font-variation-settings);font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea,::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;border-radius:0;background-color:initial;opacity:1}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports(not (-webkit-appearance:-apple-pay-button)) or (contain-intrinsic-size:1px){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit,::-webkit-datetime-edit-year-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]),::file-selector-button{appearance:button}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@font-face{font-family:lora;font-style:italic;font-weight:400 700;font-display:swap;src:url(/fonts/lora-latin-ext-italic.woff2)format("woff2");unicode-range:U+100-2BA,U+2BD-2C5,U+2C7-2CC,U+2CE-2D7,U+2DD-2FF,U+304,U+308,U+329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:lora;font-style:italic;font-weight:400 700;font-display:swap;src:url(/fonts/lora-latin-italic.woff2)format("woff2");unicode-range:U+??,U+131,U+152-153,U+2BB-2BC,U+2C6,U+2DA,U+2DC,U+304,U+308,U+329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@font-face{font-family:lora;font-style:normal;font-weight:400 700;font-display:swap;src:url(/fonts/lora-latin-ext-normal.woff2)format("woff2");unicode-range:U+100-2BA,U+2BD-2C5,U+2C7-2CC,U+2CE-2D7,U+2DD-2FF,U+304,U+308,U+329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:lora;font-style:normal;font-weight:400 700;font-display:swap;src:url(/fonts/lora-latin-normal.woff2)format("woff2");unicode-range:U+??,U+131,U+152-153,U+2BB-2BC,U+2C6,U+2DA,U+2DC,U+304,U+308,U+329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}:root{--grid-line:rgba(15, 23, 42, 0.055)}.dark{--color-surface:#101013;--color-surface-muted:#17171b;--color-surface-raised:#1f1f24;--color-surface-strong:#2c2c33;--color-line:#2a2a30;--color-line-strong:#3d3d45;--color-ink:#f2f2f3;--color-ink-soft:#c6c6cc;--color-ink-muted:#9a9aa3;--color-ink-faint:#71717a;--color-accent:#7dd3fc;--color-primary-subtle:#0b2c3f;--color-primary-border:#0e4966;--color-text-heading:#f5f5f5;--grid-line:rgba(226, 232, 240, 0.05)}html{background-color:var(--color-surface);color:var(--color-ink)}.bg-grid{background-image:linear-gradient(to right,var(--grid-line) 1px,transparent 1px),linear-gradient(to bottom,var(--grid-line) 1px,transparent 1px);background-size:56px 56px;background-position:50% 0}.grid-fade{-webkit-mask-image:linear-gradient(to bottom,#000,#000 35%,transparent 100%);mask-image:linear-gradient(to bottom,#000,#000 35%,transparent 100%)}@layer utilities{.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.sticky{position:sticky}.inset-0{inset:0}.inset-y-0{inset-block:0}.top-0{top:0}.top-1\/2{top:calc(1/2 * 100%)}.top-20{top:calc(var(--spacing) * 20)}.top-4{top:calc(var(--spacing) * 4)}.top-\[3\.75rem\]{top:3.75rem}.top-full{top:100%}.-right-2{right:calc(var(--spacing) * -2)}.right-0{right:0}.right-0\.5{right:calc(var(--spacing) * .5)}.right-4{right:calc(var(--spacing) * 4)}.right-8{right:calc(var(--spacing) * 8)}.bottom-4{bottom:calc(var(--spacing) * 4)}.left-0{left:0}.left-1\/2{left:calc(1/2 * 100%)}.left-4{left:calc(var(--spacing) * 4)}.isolate{isolation:isolate}.-z-10{z-index:calc(10 * -1)}.z-10{z-index:10}.z-150{z-index:150}.z-20{z-index:20}.z-200{z-index:200}.z-\[100\]{z-index:100}.z-\[110\]{z-index:110}.z-\[1\]{z-index:1}.z-\[200\]{z-index:200}.col-span-1{grid-column:span 1/span 1}.-m-1\.5{margin:calc(var(--spacing) * -1.5)}.m-0{margin:0}.-mx-1\.5{margin-inline:calc(var(--spacing) * -1.5)}.mx-3{margin-inline:calc(var(--spacing) * 3)}.mx-4{margin-inline:calc(var(--spacing) * 4)}.mx-\[0\.15rem\]{margin-inline:.15rem}.mx-auto{margin-inline:auto}.my-1{margin-block:var(--spacing)}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:var(--spacing)}.mt-10{margin-top:calc(var(--spacing) * 10)}.mt-12{margin-top:calc(var(--spacing) * 12)}.mt-14{margin-top:calc(var(--spacing) * 14)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-5{margin-top:calc(var(--spacing) * 5)}.mt-6{margin-top:calc(var(--spacing) * 6)}.mr-2{margin-right:calc(var(--spacing) * 2)}.mr-5{margin-right:calc(var(--spacing) * 5)}.mb-1{margin-bottom:var(--spacing)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-5{margin-bottom:calc(var(--spacing) * 5)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.ml-1{margin-left:var(--spacing)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-3{margin-left:calc(var(--spacing) * 3)}.ml-auto{margin-left:auto}.box-border{box-sizing:border-box}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.table{display:table}.aspect-square{aspect-ratio:1/1}.h-0{height:0}.h-0\.5{height:calc(var(--spacing) * .5)}.h-1{height:var(--spacing)}.h-2{height:calc(var(--spacing) * 2)}.h-2\.5{height:calc(var(--spacing) * 2.5)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-6{height:calc(var(--spacing) * 6)}.h-7{height:calc(var(--spacing) * 7)}.h-72{height:calc(var(--spacing) * 72)}.h-8{height:calc(var(--spacing) * 8)}.h-\[30px\]{height:30px}.h-\[38px\]{height:38px}.h-\[calc\(100vh-3\.75rem\)\]{height:calc(100vh - 3.75rem)}.h-auto{height:auto}.h-dvh{height:100dvh}.h-full{height:100%}.h-screen{height:100vh}.max-h-60{max-height:calc(var(--spacing) * 60)}.max-h-64{max-height:calc(var(--spacing) * 64)}.max-h-96{max-height:calc(var(--spacing) * 96)}.max-h-\[34rem\]{max-height:34rem}.max-h-\[calc\(100dvh_-_5rem\)\]{max-height:calc(100dvh - 5rem)}.max-h-\[calc\(100vh_-_7rem\)\]{max-height:calc(100vh - 7rem)}.max-h-dvh{max-height:100dvh}.min-h-0{min-height:0}.min-h-9{min-height:calc(var(--spacing) * 9)}.min-h-\[6\.5rem\]{min-height:6.5rem}.min-h-screen{min-height:100vh}.w-0{width:0}.w-1{width:var(--spacing)}.w-10{width:calc(var(--spacing) * 10)}.w-2{width:calc(var(--spacing) * 2)}.w-2\.5{width:calc(var(--spacing) * 2.5)}.w-4{width:calc(var(--spacing) * 4)}.w-40{width:calc(var(--spacing) * 40)}.w-52{width:calc(var(--spacing) * 52)}.w-56{width:calc(var(--spacing) * 56)}.w-6{width:calc(var(--spacing) * 6)}.w-64{width:calc(var(--spacing) * 64)}.w-7{width:calc(var(--spacing) * 7)}.w-8{width:calc(var(--spacing) * 8)}.w-9{width:calc(var(--spacing) * 9)}.w-\[26rem\]{width:26rem}.w-auto{width:auto}.w-full{width:100%}.w-max{width:max-content}.max-w-2xl{max-width:var(--container-2xl)}.max-w-3xl{max-width:var(--container-3xl)}.max-w-4xl{max-width:var(--container-4xl)}.max-w-5xl{max-width:var(--container-5xl)}.max-w-64{max-width:calc(var(--spacing) * 64)}.max-w-6xl{max-width:var(--container-6xl)}.max-w-7xl{max-width:var(--container-7xl)}.max-w-80{max-width:calc(var(--spacing) * 80)}.max-w-\[110rem\]{max-width:110rem}.max-w-\[11rem\]{max-width:11rem}.max-w-\[14rem\]{max-width:14rem}.max-w-\[16rem\]{max-width:16rem}.max-w-\[20rem\]{max-width:20rem}.max-w-\[90rem\]{max-width:90rem}.max-w-full{max-width:100%}.max-w-md{max-width:var(--container-md)}.max-w-none{max-width:none}.max-w-screen{max-width:100vw}.max-w-sm{max-width:var(--container-sm)}.max-w-xl{max-width:var(--container-xl)}.max-w-xs{max-width:var(--container-xs)}.min-w-0{min-width:0}.min-w-48{min-width:calc(var(--spacing) * 48)}.min-w-5{min-width:calc(var(--spacing) * 5)}.min-w-72{min-width:calc(var(--spacing) * 72)}.min-w-8{min-width:calc(var(--spacing) * 8)}.min-w-\[10rem\]{min-width:10rem}.min-w-\[16rem\]{min-width:16rem}.min-w-\[240px\]{min-width:240px}.min-w-\[7rem\]{min-width:7rem}.min-w-\[8rem\]{min-width:8rem}.min-w-\[9rem\]{min-width:9rem}.min-w-full{min-width:100%}.flex-1{flex:1}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.table-fixed{table-layout:fixed}.border-collapse{border-collapse:collapse}.-translate-x-1\/2{--tw-translate-x:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x)var(--tw-translate-y)}.translate-x-0\.5{--tw-translate-x:calc(var(--spacing) * 0.5);translate:var(--tw-translate-x)var(--tw-translate-y)}.translate-x-\[18px\]{--tw-translate-x:18px;translate:var(--tw-translate-x)var(--tw-translate-y)}.-translate-y-1\/2{--tw-translate-y:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x)var(--tw-translate-y)}.scale-110{--tw-scale-x:110%;--tw-scale-y:110%;--tw-scale-z:110%;scale:var(--tw-scale-x)var(--tw-scale-y)}.scale-95{--tw-scale-x:95%;--tw-scale-y:95%;--tw-scale-z:95%;scale:var(--tw-scale-x)var(--tw-scale-y)}.rotate-180{rotate:180deg}.rotate-90{rotate:90deg}.transform{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.animate-pulse{animation:var(--animate-pulse)}.animate-spin{animation:var(--animate-spin)}.cursor-col-resize{cursor:col-resize}.cursor-crosshair{cursor:crosshair}.cursor-default{cursor:default}.cursor-grab{cursor:grab}.cursor-pointer{cursor:pointer}.touch-none{touch-action:none}.resize{resize:both}.resize-none{resize:none}.scroll-mt-24{scroll-margin-top:calc(var(--spacing) * 24)}.list-none{list-style-type:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-7{grid-template-columns:repeat(7,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.flex-row{flex-direction:row}.flex-row-reverse{flex-direction:row-reverse}.flex-nowrap{flex-wrap:nowrap}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.items-stretch{align-items:stretch}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-start{justify-content:flex-start}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:var(--spacing)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-2\.5{gap:calc(var(--spacing) * 2.5)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-8{gap:calc(var(--spacing) * 8)}.gap-\[2px\]{gap:2px}.space-y-0\.5{ :where(& > :not(:last-child)) { --tw-space-y-reverse: 0; margin-block-start: calc(calc(var(--spacing) * 0.5) * var(--tw-space-y-reverse)); margin-block-end: calc(calc(var(--spacing) * 0.5) * calc(1 - var(--tw-space-y-reverse))); }}.space-y-1\.5{ :where(& > :not(:last-child)) { --tw-space-y-reverse: 0; margin-block-start: calc(calc(var(--spacing) * 1.5) * var(--tw-space-y-reverse)); margin-block-end: calc(calc(var(--spacing) * 1.5) * calc(1 - var(--tw-space-y-reverse))); }}.space-y-2{ :where(& > :not(:last-child)) { --tw-space-y-reverse: 0; margin-block-start: calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse)); margin-block-end: calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse))); }}.space-y-4{ :where(& > :not(:last-child)) { --tw-space-y-reverse: 0; margin-block-start: calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse)); margin-block-end: calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse))); }}.self-end{align-self:flex-end}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.overflow-y-hidden{overflow-y:hidden}.rounded{border-radius:.25rem}.rounded-default{border-radius:var(--radius-default)}.rounded-full{border-radius:calc(infinity * 1px)}.rounded-md{border-radius:var(--radius-md)}.rounded-sm{border-radius:var(--radius-sm)}.rounded-l-default{border-top-left-radius:var(--radius-default);border-bottom-left-radius:var(--radius-default)}.rounded-l-none{border-top-left-radius:0;border-bottom-left-radius:0}.rounded-b-default{border-bottom-right-radius:var(--radius-default);border-bottom-left-radius:var(--radius-default)}.border{border-style:var(--tw-border-style);border-width:1px}.border-0{border-style:var(--tw-border-style);border-width:0}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-4{border-style:var(--tw-border-style);border-width:4px}.border-x{border-inline-style:var(--tw-border-style);border-inline-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-t-2{border-top-style:var(--tw-border-style);border-top-width:2px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-r-0{border-right-style:var(--tw-border-style);border-right-width:0}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-l-4{border-left-style:var(--tw-border-style);border-left-width:4px}.border-none{--tw-border-style:none;border-style:none}.border-emerald-300{border-color:var(--color-emerald-300)}.border-green-200{border-color:var(--color-green-200)}.border-green-500{border-color:var(--color-green-500)}.border-line{border-color:var(--color-line)}.border-line-strong{border-color:var(--color-line-strong)}.border-neutral-700{border-color:var(--color-neutral-700)}.border-neutral-800{border-color:var(--color-neutral-800)}.border-primary{border-color:var(--color-primary)}.border-primary-border{border-color:var(--color-primary-border)}.border-red-200{border-color:var(--color-red-200)}.border-red-500{border-color:var(--color-red-500)}.border-sky-200{border-color:var(--color-sky-200)}.border-sky-700{border-color:var(--color-sky-700)}.border-transparent{border-color:transparent}.border-yellow-200{border-color:var(--color-yellow-200)}.border-t-sky-700{border-top-color:var(--color-sky-700)}.border-t-transparent{border-top-color:transparent}.border-l-green-700{border-left-color:var(--color-green-700)}.border-l-neutral-300{border-left-color:var(--color-neutral-300)}.border-l-neutral-400{border-left-color:var(--color-neutral-400)}.border-l-red-700{border-left-color:var(--color-red-700)}.border-l-sky-800{border-left-color:var(--color-sky-800)}.border-l-yellow-500{border-left-color:var(--color-yellow-500)}.\!bg-primary{background-color:var(--color-primary)!important}.bg-amber-100{background-color:var(--color-amber-100)}.bg-amber-700{background-color:var(--color-amber-700)}.bg-black\/10{background-color:color-mix(in oklab,var(--color-black) 10%,transparent)}.bg-black\/30{background-color:color-mix(in oklab,var(--color-black) 30%,transparent)}.bg-black\/5{background-color:color-mix(in oklab,var(--color-black) 5%,transparent)}.bg-black\/50{background-color:color-mix(in oklab,var(--color-black) 50%,transparent)}.bg-emerald-100{background-color:var(--color-emerald-100)}.bg-green-50{background-color:var(--color-green-50)}.bg-green-700{background-color:var(--color-green-700)}.bg-green-900{background-color:var(--color-green-900)}.bg-ink{background-color:var(--color-ink)}.bg-neutral-500{background-color:var(--color-neutral-500)}.bg-neutral-600{background-color:var(--color-neutral-600)}.bg-neutral-700{background-color:var(--color-neutral-700)}.bg-neutral-800{background-color:var(--color-neutral-800)}.bg-neutral-900{background-color:var(--color-neutral-900)}.bg-orange-500{background-color:var(--color-orange-500)}.bg-orange-600{background-color:var(--color-orange-600)}.bg-primary{background-color:var(--color-primary)}.bg-primary-subtle{background-color:var(--color-primary-subtle)}.bg-primary\/10{background-color:color-mix(in oklab,var(--color-primary) 10%,transparent)}.bg-red-50{background-color:var(--color-red-50)}.bg-red-600{background-color:var(--color-red-600)}.bg-red-700{background-color:var(--color-red-700)}.bg-red-900{background-color:var(--color-red-900)}.bg-sky-50{background-color:var(--color-sky-50)}.bg-sky-600{background-color:var(--color-sky-600)}.bg-sky-700{background-color:var(--color-sky-700)}.bg-sky-800{background-color:var(--color-sky-800)}.bg-sky-900{background-color:var(--color-sky-900)}.bg-surface{background-color:var(--color-surface)}.bg-surface-muted{background-color:var(--color-surface-muted)}.bg-surface-raised{background-color:var(--color-surface-raised)}.bg-surface-strong{background-color:var(--color-surface-strong)}.bg-surface\/90{background-color:color-mix(in oklab,var(--color-surface) 90%,transparent)}.bg-transparent{background-color:initial}.bg-white\/10{background-color:color-mix(in oklab,var(--color-white) 10%,transparent)}.bg-white\/5{background-color:color-mix(in oklab,var(--color-white) 5%,transparent)}.bg-yellow-400{background-color:var(--color-yellow-400)}.bg-yellow-50{background-color:var(--color-yellow-50)}.bg-yellow-700{background-color:var(--color-yellow-700)}.fill-current{fill:currentcolor}.p-0{padding:0}.p-0\.5{padding:calc(var(--spacing) * .5)}.p-1{padding:var(--spacing)}.p-1\.5{padding:calc(var(--spacing) * 1.5)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-5{padding:calc(var(--spacing) * 5)}.p-8{padding:calc(var(--spacing) * 8)}.px-1{padding-inline:var(--spacing)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-5{padding-inline:calc(var(--spacing) * 5)}.px-6{padding-inline:calc(var(--spacing) * 6)}.px-7{padding-inline:calc(var(--spacing) * 7)}.px-8{padding-inline:calc(var(--spacing) * 8)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:var(--spacing)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-10{padding-block:calc(var(--spacing) * 10)}.py-14{padding-block:calc(var(--spacing) * 14)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-5{padding-block:calc(var(--spacing) * 5)}.py-6{padding-block:calc(var(--spacing) * 6)}.py-8{padding-block:calc(var(--spacing) * 8)}.py-px{padding-block:1px}.pt-1{padding-top:var(--spacing)}.pt-1\.5{padding-top:calc(var(--spacing) * 1.5)}.pt-10{padding-top:calc(var(--spacing) * 10)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pt-6{padding-top:calc(var(--spacing) * 6)}.pr-14{padding-right:calc(var(--spacing) * 14)}.pr-3{padding-right:calc(var(--spacing) * 3)}.pr-4{padding-right:calc(var(--spacing) * 4)}.pr-9{padding-right:calc(var(--spacing) * 9)}.pb-0\.5{padding-bottom:calc(var(--spacing) * .5)}.pb-1{padding-bottom:var(--spacing)}.pb-14{padding-bottom:calc(var(--spacing) * 14)}.pb-16{padding-bottom:calc(var(--spacing) * 16)}.pb-2{padding-bottom:calc(var(--spacing) * 2)}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pb-4{padding-bottom:calc(var(--spacing) * 4)}.pb-6{padding-bottom:calc(var(--spacing) * 6)}.pb-\[calc\(1rem_\+_env\(safe-area-inset-bottom\,0px\)\)\]{padding-bottom:calc(1rem + env(safe-area-inset-bottom,0px))}.pl-4{padding-left:calc(var(--spacing) * 4)}.pl-8{padding-left:calc(var(--spacing) * 8)}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.align-middle{vertical-align:middle}.align-top{vertical-align:top}.font-\[inherit\]{font-family:inherit}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading,var(--text-4xl--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[0\.5rem\]{font-size:.5rem}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-\[12px\]{font-size:12px}.text-\[13px\]{font-size:13px}.leading-none{--tw-leading:1;line-height:1}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-light{--tw-font-weight:var(--font-weight-light);font-weight:var(--font-weight-light)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.tracking-wider{--tw-tracking:var(--tracking-wider);letter-spacing:var(--tracking-wider)}.tracking-widest{--tw-tracking:var(--tracking-widest);letter-spacing:var(--tracking-widest)}.whitespace-nowrap{white-space:nowrap}.whitespace-pre{white-space:pre}.whitespace-pre-wrap{white-space:pre-wrap}.\!text-white{color:var(--color-white)!important}.text-accent{color:var(--color-accent)}.text-amber-300{color:var(--color-amber-300)}.text-amber-600{color:var(--color-amber-600)}.text-current{color:currentcolor}.text-emerald-300{color:var(--color-emerald-300)}.text-emerald-700{color:var(--color-emerald-700)}.text-gray-900{color:var(--color-gray-900)}.text-green-600{color:var(--color-green-600)}.text-green-700{color:var(--color-green-700)}.text-green-900{color:var(--color-green-900)}.text-ink{color:var(--color-ink)}.text-ink-faint{color:var(--color-ink-faint)}.text-ink-muted{color:var(--color-ink-muted)}.text-ink-soft{color:var(--color-ink-soft)}.text-neutral-100{color:var(--color-neutral-100)}.text-neutral-200{color:var(--color-neutral-200)}.text-neutral-400{color:var(--color-neutral-400)}.text-orange-600{color:var(--color-orange-600)}.text-red-500{color:var(--color-red-500)}.text-red-600{color:var(--color-red-600)}.text-red-700{color:var(--color-red-700)}.text-red-900{color:var(--color-red-900)}.text-sky-300{color:var(--color-sky-300)}.text-sky-600{color:var(--color-sky-600)}.text-sky-700{color:var(--color-sky-700)}.text-sky-900{color:var(--color-sky-900)}.text-surface{color:var(--color-surface)}.text-text-heading{color:var(--color-text-heading)}.text-text-on-dark{color:var(--color-text-on-dark)}.text-text-on-dark-muted{color:var(--color-text-on-dark-muted)}.text-transparent{color:transparent}.text-violet-300{color:var(--color-violet-300)}.text-violet-600{color:var(--color-violet-600)}.text-white{color:var(--color-white)}.text-yellow-600{color:var(--color-yellow-600)}.text-yellow-700{color:var(--color-yellow-700)}.uppercase{text-transform:uppercase}.italic{font-style:italic}.tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal,)var(--tw-slashed-zero,)var(--tw-numeric-figure,)var(--tw-numeric-spacing,)var(--tw-numeric-fraction,)}.no-underline{text-decoration-line:none}.underline{text-decoration-line:underline}.underline-offset-4{text-underline-offset:4px}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.caret-neutral-800{caret-color:var(--color-neutral-800)}.opacity-0{opacity:0%}.opacity-50{opacity:50%}.opacity-60{opacity:60%}.shadow-\[0_4px_12px_rgba\(0\,0\,0\,0\.15\)\]{--tw-shadow:0 4px 12px var(--tw-shadow-color, rgba(0,0,0,0.15));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\[inset_0_0_0_1px_currentColor\]{--tw-shadow:inset 0 0 0 1px var(--tw-shadow-color, currentColor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\[inset_3px_0_0_0_theme\(colors\.amber\.500\)\]{--tw-shadow:inset 3px 0 0 0 var(--tw-shadow-color, theme(colors.amber.500));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 4px 6px -4px var(--tw-shadow-color, rgb(0 0 0 / 0.1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-md{--tw-shadow:0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / 0.1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-none{--tw-shadow:0 0 #0000;box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xs{--tw-shadow:0 1px 2px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.05));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.outline-hidden{--tw-outline-style:none;outline-style:none;@media(forced-colors:active){outline: 2px solid transparent; outline-offset: 2px;}}.outline-2{outline-style:var(--tw-outline-style);outline-width:2px}.outline-sky-500{outline-color:var(--color-sky-500)}.filter{filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.backdrop-blur{--tw-backdrop-blur:blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[color\,border-color\]{transition-property:color,border-color;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[opacity\,transform\]{transition-property:opacity,transform;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[width\]{transition-property:width;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-150{--tw-duration:150ms;transition-duration:150ms}.duration-200{--tw-duration:200ms;transition-duration:200ms}.duration-300{--tw-duration:300ms;transition-duration:300ms}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.ease-out{--tw-ease:var(--ease-out);transition-timing-function:var(--ease-out)}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.group-hover\:text-accent{&:is(:where(.group):hover *){@media(hover:hover){color: var(--color-accent);}}}.group-hover\/th\:opacity-50{&:is(:where(.group\/th):hover *){@media(hover:hover){opacity: 50%;}}}.file\:mr-2{&::file-selector-button{margin-right:calc(var(--spacing) * 2)}}.file\:ml-1{&::file-selector-button{margin-left:var(--spacing)}}.file\:cursor-pointer{&::file-selector-button{cursor:pointer}}.file\:rounded-default{&::file-selector-button{border-radius:var(--radius-default)}}.file\:border{&::file-selector-button{border-style:var(--tw-border-style);border-width:1px}}.file\:border-line-strong{&::file-selector-button{border-color:var(--color-line-strong)}}.file\:bg-surface-raised{&::file-selector-button{background-color:var(--color-surface-raised)}}.file\:px-3{&::file-selector-button{padding-inline:calc(var(--spacing) * 3)}}.file\:px-4{&::file-selector-button{padding-inline:calc(var(--spacing) * 4)}}.file\:py-\[2px\]{&::file-selector-button{padding-block:2px}}.file\:py-\[3px\]{&::file-selector-button{padding-block:3px}}.file\:text-sm{&::file-selector-button{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}}.file\:shadow-xs{&::file-selector-button{--tw-shadow:0 1px 2px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.05));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}.placeholder\:text-ink-faint{&::placeholder{color:var(--color-ink-faint)}}.before\:absolute{&::before{content:var(--tw-content);position:absolute}}.before\:inset-0{&::before{content:var(--tw-content);inset:0}}.before\:-z-20{&::before{content:var(--tw-content);z-index:calc(20 * -1)}}.before\:bg-surface-strong{&::before{content:var(--tw-content);background-color:var(--color-surface-strong)}}.before\:content-\[\'\'\]{&::before{--tw-content:'';content:var(--tw-content)}}.before\:\[clip-path\:polygon\(16px_0\,100\%_0\,100\%_calc\(100\%_-_16px\)\,calc\(100\%_-_16px\)_100\%\,0_100\%\,0_16px\)\]{&::before{content:var(--tw-content);clip-path:polygon(16px 0,100% 0,100% calc(100% - 16px),calc(100% - 16px) 100%,0 100%,0 16px)}}.after\:absolute{&::after{content:var(--tw-content);position:absolute}}.after\:inset-\[1px\]{&::after{content:var(--tw-content);inset:1px}}.after\:-z-10{&::after{content:var(--tw-content);z-index:calc(10 * -1)}}.after\:bg-white{&::after{content:var(--tw-content);background-color:var(--color-white)}}.after\:content-\[\'\'\]{&::after{--tw-content:'';content:var(--tw-content)}}.after\:\[clip-path\:polygon\(15px_0\,100\%_0\,100\%_calc\(100\%_-_15px\)\,calc\(100\%_-_15px\)_100\%\,0_100\%\,0_15px\)\]{&::after{content:var(--tw-content);clip-path:polygon(15px 0,100% 0,100% calc(100% - 15px),calc(100% - 15px) 100%,0 100%,0 15px)}}.last\:border-r-0{&:last-child{border-right-style:var(--tw-border-style);border-right-width:0}}.last\:border-b-0{&:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0}}.odd\:bg-surface{&:nth-child(odd){background-color:var(--color-surface)}}.even\:bg-surface-raised{&:nth-child(even){background-color:var(--color-surface-raised)}}.hover\:border-primary-border{&:hover{@media(hover:hover){border-color: var(--color-primary-border);}}}.hover\:bg-green-100{&:hover{@media(hover:hover){background-color: var(--color-green-100);}}}.hover\:bg-green-800{&:hover{@media(hover:hover){background-color: var(--color-green-800);}}}.hover\:bg-green-950{&:hover{@media(hover:hover){background-color: var(--color-green-950);}}}.hover\:bg-neutral-500{&:hover{@media(hover:hover){background-color: var(--color-neutral-500);}}}.hover\:bg-neutral-800{&:hover{@media(hover:hover){background-color: var(--color-neutral-800);}}}.hover\:bg-orange-700{&:hover{@media(hover:hover){background-color: var(--color-orange-700);}}}.hover\:bg-primary-hover{&:hover{@media(hover:hover){background-color: var(--color-primary-hover);}}}.hover\:bg-red-700{&:hover{@media(hover:hover){background-color: var(--color-red-700);}}}.hover\:bg-red-800{&:hover{@media(hover:hover){background-color: var(--color-red-800);}}}.hover\:bg-red-950{&:hover{@media(hover:hover){background-color: var(--color-red-950);}}}.hover\:bg-sky-100{&:hover{@media(hover:hover){background-color: var(--color-sky-100);}}}.hover\:bg-sky-500{&:hover{@media(hover:hover){background-color: var(--color-sky-500);}}}.hover\:bg-sky-500\/50{&:hover{@media(hover:hover){background-color: color-mix(in oklab,var(--color-sky-500) 50%,transparent);}}}.hover\:bg-sky-800{&:hover{@media(hover:hover){background-color: var(--color-sky-800);}}}.hover\:bg-sky-950{&:hover{@media(hover:hover){background-color: var(--color-sky-950);}}}.hover\:bg-surface-muted{&:hover{@media(hover:hover){background-color: var(--color-surface-muted);}}}.hover\:bg-surface-raised{&:hover{@media(hover:hover){background-color: var(--color-surface-raised);}}}.hover\:bg-surface-strong{&:hover{@media(hover:hover){background-color: var(--color-surface-strong);}}}.hover\:bg-white\/5{&:hover{@media(hover:hover){background-color: color-mix(in oklab,var(--color-white) 5%,transparent);}}}.hover\:bg-yellow-800{&:hover{@media(hover:hover){background-color: var(--color-yellow-800);}}}.hover\:text-ink{&:hover{@media(hover:hover){color: var(--color-ink);}}}.hover\:text-ink-soft{&:hover{@media(hover:hover){color: var(--color-ink-soft);}}}.hover\:text-sky-800{&:hover{@media(hover:hover){color: var(--color-sky-800);}}}.hover\:text-text-on-dark{&:hover{@media(hover:hover){color: var(--color-text-on-dark);}}}.hover\:text-white{&:hover{@media(hover:hover){color: var(--color-white);}}}.hover\:underline{&:hover{@media(hover:hover){text-decoration-line: underline;}}}.hover\:decoration-1{&:hover{@media(hover:hover){text-decoration-thickness: 1px;}}}.hover\:shadow-\[inset_0_0_0_2px_currentColor\]{&:hover{@media(hover:hover){--tw-shadow: inset 0 0 0 2px var(--tw-shadow-color,currentColor); box-shadow: var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow);}}}.hover\:shadow-sm{&:hover{@media(hover:hover){--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color,rgb(0 0 0 / 0.1)),0 1px 2px -1px var(--tw-shadow-color,rgb(0 0 0 / 0.1)); box-shadow: var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow);}}}.file\:hover\:bg-surface-strong{&::file-selector-button{&:hover{@media(hover:hover){background-color: var(--color-surface-strong);}}}}.focus\:border-primary{&:focus{border-color:var(--color-primary)}}.focus\:border-sky-500{&:focus{border-color:var(--color-sky-500)}}.focus\:bg-red-50{&:focus{background-color:var(--color-red-50)}}.focus\:bg-surface-raised{&:focus{background-color:var(--color-surface-raised)}}.focus\:shadow-\[inset_0_0_0_2px_var\(--color-red-500\)\]{&:focus{--tw-shadow:inset 0 0 0 2px var(--tw-shadow-color, var(--color-red-500));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}.focus\:outline-hidden{&:focus{--tw-outline-style:none;outline-style:none;@media(forced-colors:active){outline: 2px solid transparent; outline-offset: 2px;}}}.focus\:outline-2{&:focus{outline-style:var(--tw-outline-style);outline-width:2px}}.focus\:outline-offset-1{&:focus{outline-offset:1px}}.focus\:outline-green-500{&:focus{outline-color:var(--color-green-500)}}.focus\:outline-red-500{&:focus{outline-color:var(--color-red-500)}}.focus\:outline-sky-500{&:focus{outline-color:var(--color-sky-500)}}.focus-visible\:outline-2{&:focus-visible{outline-style:var(--tw-outline-style);outline-width:2px}}.focus-visible\:outline-offset-2{&:focus-visible{outline-offset:2px}}.focus-visible\:outline-current{&:focus-visible{outline-color:currentcolor}}.focus-visible\:outline-primary{&:focus-visible{outline-color:var(--color-primary)}}.focus-visible\:outline-none{&:focus-visible{--tw-outline-style:none;outline-style:none}}.active\:bg-surface-strong{&:active{background-color:var(--color-surface-strong)}}.enabled\:hover\:bg-neutral-900{&:enabled{&:hover{@media(hover:hover){background-color: var(--color-neutral-900);}}}}.enabled\:hover\:bg-red-700{&:enabled{&:hover{@media(hover:hover){background-color: var(--color-red-700);}}}}.enabled\:hover\:bg-surface-muted{&:enabled{&:hover{@media(hover:hover){background-color: var(--color-surface-muted);}}}}.disabled\:cursor-not-allowed{&:disabled{cursor:not-allowed}}.disabled\:bg-surface-muted{&:disabled{background-color:var(--color-surface-muted)}}.disabled\:bg-surface-raised{&:disabled{background-color:var(--color-surface-raised)}}.disabled\:text-ink-faint{&:disabled{color:var(--color-ink-faint)}}.disabled\:opacity-40{&:disabled{opacity:40%}}.disabled\:opacity-50{&:disabled{opacity:50%}}.disabled\:hover\:bg-transparent{&:disabled{&:hover{@media(hover:hover){background-color: transparent;}}}}.sm\:block{@media(width >= 40rem){display: block;}}.sm\:flex{@media(width >= 40rem){display: flex;}}.sm\:grid{@media(width >= 40rem){display: grid;}}.sm\:hidden{@media(width >= 40rem){display: none;}}.sm\:w-48{@media(width >= 40rem){width: calc(var(--spacing) * 48);}}.sm\:w-64{@media(width >= 40rem){width: calc(var(--spacing) * 64);}}.sm\:grow-0{@media(width >= 40rem){flex-grow: 0;}}.sm\:grid-cols-2{@media(width >= 40rem){grid-template-columns: repeat(2,minmax(0,1fr));}}.sm\:grid-cols-3{@media(width >= 40rem){grid-template-columns: repeat(3,minmax(0,1fr));}}.sm\:flex-row{@media(width >= 40rem){flex-direction: row;}}.sm\:border-r{@media(width >= 40rem){border-right-style: var(--tw-border-style); border-right-width: 1px;}}.sm\:border-b-0{@media(width >= 40rem){border-bottom-style: var(--tw-border-style); border-bottom-width: 0px;}}.md\:flex-initial{@media(width >= 48rem){flex: 0 auto;}}.md\:justify-start{@media(width >= 48rem){justify-content: flex-start;}}.lg\:col-span-10{@media(width >= 64rem){grid-column: span 10 / span 10;}}.lg\:col-span-2{@media(width >= 64rem){grid-column: span 2 / span 2;}}.lg\:col-span-5{@media(width >= 64rem){grid-column: span 5 / span 5;}}.lg\:col-span-7{@media(width >= 64rem){grid-column: span 7 / span 7;}}.lg\:block{@media(width >= 64rem){display: block;}}.lg\:h-full{@media(width >= 64rem){height: 100%;}}.lg\:grid-cols-12{@media(width >= 64rem){grid-template-columns: repeat(12,minmax(0,1fr));}}.lg\:self-start{@media(width >= 64rem){align-self: flex-start;}}.lg\:pr-8{@media(width >= 64rem){padding-right: calc(var(--spacing) * 8);}}.dark\:border-green-900{&:where(.dark, .dark *){border-color:var(--color-green-900)}}.dark\:border-red-900{&:where(.dark, .dark *){border-color:var(--color-red-900)}}.dark\:border-sky-900{&:where(.dark, .dark *){border-color:var(--color-sky-900)}}.dark\:border-yellow-900{&:where(.dark, .dark *){border-color:var(--color-yellow-900)}}.dark\:bg-amber-900{&:where(.dark, .dark *){background-color:var(--color-amber-900)}}.dark\:bg-amber-900\!{&:where(.dark, .dark *){background-color:var(--color-amber-900)!important}}.dark\:bg-emerald-900{&:where(.dark, .dark *){background-color:var(--color-emerald-900)}}.dark\:bg-green-900{&:where(.dark, .dark *){background-color:var(--color-green-900)}}.dark\:bg-green-950{&:where(.dark, .dark *){background-color:var(--color-green-950)}}.dark\:bg-red-950{&:where(.dark, .dark *){background-color:var(--color-red-950)}}.dark\:bg-sky-900{&:where(.dark, .dark *){background-color:var(--color-sky-900)}}.dark\:bg-sky-950{&:where(.dark, .dark *){background-color:var(--color-sky-950)}}.dark\:bg-yellow-950{&:where(.dark, .dark *){background-color:var(--color-yellow-950)}}.dark\:text-amber-400{&:where(.dark, .dark *){color:var(--color-amber-400)}}.dark\:text-emerald-400{&:where(.dark, .dark *){color:var(--color-emerald-400)}}.dark\:text-green-400{&:where(.dark, .dark *){color:var(--color-green-400)}}.dark\:text-red-400{&:where(.dark, .dark *){color:var(--color-red-400)}}.dark\:text-sky-400{&:where(.dark, .dark *){color:var(--color-sky-400)}}.dark\:text-violet-400{&:where(.dark, .dark *){color:var(--color-violet-400)}}.\[\&_\.ui-form\]\:m-0{& .ui-form{margin:0}}.\[\&_input\]\:cursor-text{& input{cursor:text}}.\[\&_td\]\:p-3{& td{padding:calc(var(--spacing) * 3)}}.\[\&_td\]\:p-4{& td{padding:calc(var(--spacing) * 4)}}.\[\&_td\]\:px-2{& td{padding-inline:calc(var(--spacing) * 2)}}.\[\&_td\]\:py-0\.5{& td{padding-block:calc(var(--spacing) * .5)}}.\[\&_td\]\:py-1{& td{padding-block:var(--spacing)}}.\[\&_td\+td\]\:border-l{& td+td{border-left-style:var(--tw-border-style);border-left-width:1px}}.\[\&_td\+td\]\:border-line-strong{& td+td{border-color:var(--color-line-strong)}}.\[\&_th\]\:border-b{& th{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}}.\[\&_th\]\:border-line-strong{& th{border-color:var(--color-line-strong)}}.\[\&_tr\:hover\]\:\!bg-green-100{& tr:hover{background-color:var(--color-green-100)!important}}.\[\&_tr\:hover\]\:\!bg-sky-100{& tr:hover{background-color:var(--color-sky-100)!important}}.\[\&_tr\:hover\]\:\!bg-surface-strong{& tr:hover{background-color:var(--color-surface-strong)!important}}.\[\&_tr\:not\(\:last-child\)\]\:border-b{& tr:not(:last-child){border-bottom-style:var(--tw-border-style);border-bottom-width:1px}}.\[\&_tr\:not\(\:last-child\)\]\:border-line-strong{& tr:not(:last-child){border-color:var(--color-line-strong)}}.\[\&_tr\:nth-child\(even\)\]\:bg-surface-raised{& tr:nth-child(even){background-color:var(--color-surface-raised)}}}@property --tw-translate-x{syntax: "*"; - inherits: false; - initial-value: 0; -}@property --tw-translate-y{syntax: "*"; - inherits: false; - initial-value: 0; -}@property --tw-translate-z{syntax: "*"; - inherits: false; - initial-value: 0; -}@property --tw-scale-x{syntax: "*"; - inherits: false; - initial-value: 1; -}@property --tw-scale-y{syntax: "*"; - inherits: false; - initial-value: 1; -}@property --tw-scale-z{syntax: "*"; - inherits: false; - initial-value: 1; -}@property --tw-rotate-x{syntax: "*"; - inherits: false; -}@property --tw-rotate-y{syntax: "*"; - inherits: false; -}@property --tw-rotate-z{syntax: "*"; - inherits: false; -}@property --tw-skew-x{syntax: "*"; - inherits: false; -}@property --tw-skew-y{syntax: "*"; - inherits: false; -}@property --tw-space-y-reverse{syntax: "*"; - inherits: false; - initial-value: 0; -}@property --tw-border-style{syntax: "*"; - inherits: false; - initial-value: solid; -}@property --tw-leading{syntax: "*"; - inherits: false; -}@property --tw-font-weight{syntax: "*"; - inherits: false; -}@property --tw-tracking{syntax: "*"; - inherits: false; -}@property --tw-ordinal{syntax: "*"; - inherits: false; -}@property --tw-slashed-zero{syntax: "*"; - inherits: false; -}@property --tw-numeric-figure{syntax: "*"; - inherits: false; -}@property --tw-numeric-spacing{syntax: "*"; - inherits: false; -}@property --tw-numeric-fraction{syntax: "*"; - inherits: false; -}@property --tw-shadow{syntax: "*"; - inherits: false; - initial-value: 0 0 #0000; -}@property --tw-shadow-color{syntax: "*"; - inherits: false; -}@property --tw-shadow-alpha{syntax: ""; - inherits: false; - initial-value: 100%; -}@property --tw-inset-shadow{syntax: "*"; - inherits: false; - initial-value: 0 0 #0000; -}@property --tw-inset-shadow-color{syntax: "*"; - inherits: false; -}@property --tw-inset-shadow-alpha{syntax: ""; - inherits: false; - initial-value: 100%; -}@property --tw-ring-color{syntax: "*"; - inherits: false; -}@property --tw-ring-shadow{syntax: "*"; - inherits: false; - initial-value: 0 0 #0000; -}@property --tw-inset-ring-color{syntax: "*"; - inherits: false; -}@property --tw-inset-ring-shadow{syntax: "*"; - inherits: false; - initial-value: 0 0 #0000; -}@property --tw-ring-inset{syntax: "*"; - inherits: false; -}@property --tw-ring-offset-width{syntax: ""; - inherits: false; - initial-value: 0px; -}@property --tw-ring-offset-color{syntax: "*"; - inherits: false; - initial-value: #fff; -}@property --tw-ring-offset-shadow{syntax: "*"; - inherits: false; - initial-value: 0 0 #0000; -}@property --tw-outline-style{syntax: "*"; - inherits: false; - initial-value: solid; -}@property --tw-blur{syntax: "*"; - inherits: false; -}@property --tw-brightness{syntax: "*"; - inherits: false; -}@property --tw-contrast{syntax: "*"; - inherits: false; -}@property --tw-grayscale{syntax: "*"; - inherits: false; -}@property --tw-hue-rotate{syntax: "*"; - inherits: false; -}@property --tw-invert{syntax: "*"; - inherits: false; -}@property --tw-opacity{syntax: "*"; - inherits: false; -}@property --tw-saturate{syntax: "*"; - inherits: false; -}@property --tw-sepia{syntax: "*"; - inherits: false; -}@property --tw-drop-shadow{syntax: "*"; - inherits: false; -}@property --tw-drop-shadow-color{syntax: "*"; - inherits: false; -}@property --tw-drop-shadow-alpha{syntax: ""; - inherits: false; - initial-value: 100%; -}@property --tw-drop-shadow-size{syntax: "*"; - inherits: false; -}@property --tw-backdrop-blur{syntax: "*"; - inherits: false; -}@property --tw-backdrop-brightness{syntax: "*"; - inherits: false; -}@property --tw-backdrop-contrast{syntax: "*"; - inherits: false; -}@property --tw-backdrop-grayscale{syntax: "*"; - inherits: false; -}@property --tw-backdrop-hue-rotate{syntax: "*"; - inherits: false; -}@property --tw-backdrop-invert{syntax: "*"; - inherits: false; -}@property --tw-backdrop-opacity{syntax: "*"; - inherits: false; -}@property --tw-backdrop-saturate{syntax: "*"; - inherits: false; -}@property --tw-backdrop-sepia{syntax: "*"; - inherits: false; -}@property --tw-duration{syntax: "*"; - inherits: false; -}@property --tw-ease{syntax: "*"; - inherits: false; -}@property --tw-content{syntax: "*"; - initial-value: ""; - inherits: false; -} \ No newline at end of file diff --git a/go/cmd/examples/go-wasm-web/wwwroot/wasm_exec.js b/go/cmd/examples/go-wasm-web/wwwroot/wasm_exec.js deleted file mode 100644 index d71af9e9..00000000 --- a/go/cmd/examples/go-wasm-web/wwwroot/wasm_exec.js +++ /dev/null @@ -1,575 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -"use strict"; - -(() => { - const enosys = () => { - const err = new Error("not implemented"); - err.code = "ENOSYS"; - return err; - }; - - if (!globalThis.fs) { - let outputBuf = ""; - globalThis.fs = { - constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1, O_DIRECTORY: -1 }, // unused - writeSync(fd, buf) { - outputBuf += decoder.decode(buf); - const nl = outputBuf.lastIndexOf("\n"); - if (nl != -1) { - console.log(outputBuf.substring(0, nl)); - outputBuf = outputBuf.substring(nl + 1); - } - return buf.length; - }, - write(fd, buf, offset, length, position, callback) { - if (offset !== 0 || length !== buf.length || position !== null) { - callback(enosys()); - return; - } - const n = this.writeSync(fd, buf); - callback(null, n); - }, - chmod(path, mode, callback) { callback(enosys()); }, - chown(path, uid, gid, callback) { callback(enosys()); }, - close(fd, callback) { callback(enosys()); }, - fchmod(fd, mode, callback) { callback(enosys()); }, - fchown(fd, uid, gid, callback) { callback(enosys()); }, - fstat(fd, callback) { callback(enosys()); }, - fsync(fd, callback) { callback(null); }, - ftruncate(fd, length, callback) { callback(enosys()); }, - lchown(path, uid, gid, callback) { callback(enosys()); }, - link(path, link, callback) { callback(enosys()); }, - lstat(path, callback) { callback(enosys()); }, - mkdir(path, perm, callback) { callback(enosys()); }, - open(path, flags, mode, callback) { callback(enosys()); }, - read(fd, buffer, offset, length, position, callback) { callback(enosys()); }, - readdir(path, callback) { callback(enosys()); }, - readlink(path, callback) { callback(enosys()); }, - rename(from, to, callback) { callback(enosys()); }, - rmdir(path, callback) { callback(enosys()); }, - stat(path, callback) { callback(enosys()); }, - symlink(path, link, callback) { callback(enosys()); }, - truncate(path, length, callback) { callback(enosys()); }, - unlink(path, callback) { callback(enosys()); }, - utimes(path, atime, mtime, callback) { callback(enosys()); }, - }; - } - - if (!globalThis.process) { - globalThis.process = { - getuid() { return -1; }, - getgid() { return -1; }, - geteuid() { return -1; }, - getegid() { return -1; }, - getgroups() { throw enosys(); }, - pid: -1, - ppid: -1, - umask() { throw enosys(); }, - cwd() { throw enosys(); }, - chdir() { throw enosys(); }, - } - } - - if (!globalThis.path) { - globalThis.path = { - resolve(...pathSegments) { - return pathSegments.join("/"); - } - } - } - - if (!globalThis.crypto) { - throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)"); - } - - if (!globalThis.performance) { - throw new Error("globalThis.performance is not available, polyfill required (performance.now only)"); - } - - if (!globalThis.TextEncoder) { - throw new Error("globalThis.TextEncoder is not available, polyfill required"); - } - - if (!globalThis.TextDecoder) { - throw new Error("globalThis.TextDecoder is not available, polyfill required"); - } - - const encoder = new TextEncoder("utf-8"); - const decoder = new TextDecoder("utf-8"); - - globalThis.Go = class { - constructor() { - this.argv = ["js"]; - this.env = {}; - this.exit = (code) => { - if (code !== 0) { - console.warn("exit code:", code); - } - }; - this._exitPromise = new Promise((resolve) => { - this._resolveExitPromise = resolve; - }); - this._pendingEvent = null; - this._scheduledTimeouts = new Map(); - this._nextCallbackTimeoutID = 1; - - const setInt64 = (addr, v) => { - this.mem.setUint32(addr + 0, v, true); - this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true); - } - - const setInt32 = (addr, v) => { - this.mem.setUint32(addr + 0, v, true); - } - - const getInt64 = (addr) => { - const low = this.mem.getUint32(addr + 0, true); - const high = this.mem.getInt32(addr + 4, true); - return low + high * 4294967296; - } - - const loadValue = (addr) => { - const f = this.mem.getFloat64(addr, true); - if (f === 0) { - return undefined; - } - if (!isNaN(f)) { - return f; - } - - const id = this.mem.getUint32(addr, true); - return this._values[id]; - } - - const storeValue = (addr, v) => { - const nanHead = 0x7FF80000; - - if (typeof v === "number" && v !== 0) { - if (isNaN(v)) { - this.mem.setUint32(addr + 4, nanHead, true); - this.mem.setUint32(addr, 0, true); - return; - } - this.mem.setFloat64(addr, v, true); - return; - } - - if (v === undefined) { - this.mem.setFloat64(addr, 0, true); - return; - } - - let id = this._ids.get(v); - if (id === undefined) { - id = this._idPool.pop(); - if (id === undefined) { - id = this._values.length; - } - this._values[id] = v; - this._goRefCounts[id] = 0; - this._ids.set(v, id); - } - this._goRefCounts[id]++; - let typeFlag = 0; - switch (typeof v) { - case "object": - if (v !== null) { - typeFlag = 1; - } - break; - case "string": - typeFlag = 2; - break; - case "symbol": - typeFlag = 3; - break; - case "function": - typeFlag = 4; - break; - } - this.mem.setUint32(addr + 4, nanHead | typeFlag, true); - this.mem.setUint32(addr, id, true); - } - - const loadSlice = (addr) => { - const array = getInt64(addr + 0); - const len = getInt64(addr + 8); - return new Uint8Array(this._inst.exports.mem.buffer, array, len); - } - - const loadSliceOfValues = (addr) => { - const array = getInt64(addr + 0); - const len = getInt64(addr + 8); - const a = new Array(len); - for (let i = 0; i < len; i++) { - a[i] = loadValue(array + i * 8); - } - return a; - } - - const loadString = (addr) => { - const saddr = getInt64(addr + 0); - const len = getInt64(addr + 8); - return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len)); - } - - const testCallExport = (a, b) => { - this._inst.exports.testExport0(); - return this._inst.exports.testExport(a, b); - } - - const timeOrigin = Date.now() - performance.now(); - this.importObject = { - _gotest: { - add: (a, b) => a + b, - callExport: testCallExport, - }, - gojs: { - // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters) - // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported - // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function). - // This changes the SP, thus we have to update the SP used by the imported function. - - // func wasmExit(code int32) - "runtime.wasmExit": (sp) => { - sp >>>= 0; - const code = this.mem.getInt32(sp + 8, true); - this.exited = true; - delete this._inst; - delete this._values; - delete this._goRefCounts; - delete this._ids; - delete this._idPool; - this.exit(code); - }, - - // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32) - "runtime.wasmWrite": (sp) => { - sp >>>= 0; - const fd = getInt64(sp + 8); - const p = getInt64(sp + 16); - const n = this.mem.getInt32(sp + 24, true); - fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n)); - }, - - // func resetMemoryDataView() - "runtime.resetMemoryDataView": (sp) => { - sp >>>= 0; - this.mem = new DataView(this._inst.exports.mem.buffer); - }, - - // func nanotime1() int64 - "runtime.nanotime1": (sp) => { - sp >>>= 0; - setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000); - }, - - // func walltime() (sec int64, nsec int32) - "runtime.walltime": (sp) => { - sp >>>= 0; - const msec = (new Date).getTime(); - setInt64(sp + 8, msec / 1000); - this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true); - }, - - // func scheduleTimeoutEvent(delay int64) int32 - "runtime.scheduleTimeoutEvent": (sp) => { - sp >>>= 0; - const id = this._nextCallbackTimeoutID; - this._nextCallbackTimeoutID++; - this._scheduledTimeouts.set(id, setTimeout( - () => { - this._resume(); - while (this._scheduledTimeouts.has(id)) { - // for some reason Go failed to register the timeout event, log and try again - // (temporary workaround for https://github.com/golang/go/issues/28975) - console.warn("scheduleTimeoutEvent: missed timeout event"); - this._resume(); - } - }, - getInt64(sp + 8), - )); - this.mem.setInt32(sp + 16, id, true); - }, - - // func clearTimeoutEvent(id int32) - "runtime.clearTimeoutEvent": (sp) => { - sp >>>= 0; - const id = this.mem.getInt32(sp + 8, true); - clearTimeout(this._scheduledTimeouts.get(id)); - this._scheduledTimeouts.delete(id); - }, - - // func getRandomData(r []byte) - "runtime.getRandomData": (sp) => { - sp >>>= 0; - crypto.getRandomValues(loadSlice(sp + 8)); - }, - - // func finalizeRef(v ref) - "syscall/js.finalizeRef": (sp) => { - sp >>>= 0; - const id = this.mem.getUint32(sp + 8, true); - this._goRefCounts[id]--; - if (this._goRefCounts[id] === 0) { - const v = this._values[id]; - this._values[id] = null; - this._ids.delete(v); - this._idPool.push(id); - } - }, - - // func stringVal(value string) ref - "syscall/js.stringVal": (sp) => { - sp >>>= 0; - storeValue(sp + 24, loadString(sp + 8)); - }, - - // func valueGet(v ref, p string) ref - "syscall/js.valueGet": (sp) => { - sp >>>= 0; - const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16)); - sp = this._inst.exports.getsp() >>> 0; // see comment above - storeValue(sp + 32, result); - }, - - // func valueSet(v ref, p string, x ref) - "syscall/js.valueSet": (sp) => { - sp >>>= 0; - Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32)); - }, - - // func valueDelete(v ref, p string) - "syscall/js.valueDelete": (sp) => { - sp >>>= 0; - Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16)); - }, - - // func valueIndex(v ref, i int) ref - "syscall/js.valueIndex": (sp) => { - sp >>>= 0; - storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16))); - }, - - // valueSetIndex(v ref, i int, x ref) - "syscall/js.valueSetIndex": (sp) => { - sp >>>= 0; - Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24)); - }, - - // func valueCall(v ref, m string, args []ref) (ref, bool) - "syscall/js.valueCall": (sp) => { - sp >>>= 0; - try { - const v = loadValue(sp + 8); - const m = Reflect.get(v, loadString(sp + 16)); - const args = loadSliceOfValues(sp + 32); - const result = Reflect.apply(m, v, args); - sp = this._inst.exports.getsp() >>> 0; // see comment above - storeValue(sp + 56, result); - this.mem.setUint8(sp + 64, 1); - } catch (err) { - sp = this._inst.exports.getsp() >>> 0; // see comment above - storeValue(sp + 56, err); - this.mem.setUint8(sp + 64, 0); - } - }, - - // func valueInvoke(v ref, args []ref) (ref, bool) - "syscall/js.valueInvoke": (sp) => { - sp >>>= 0; - try { - const v = loadValue(sp + 8); - const args = loadSliceOfValues(sp + 16); - const result = Reflect.apply(v, undefined, args); - sp = this._inst.exports.getsp() >>> 0; // see comment above - storeValue(sp + 40, result); - this.mem.setUint8(sp + 48, 1); - } catch (err) { - sp = this._inst.exports.getsp() >>> 0; // see comment above - storeValue(sp + 40, err); - this.mem.setUint8(sp + 48, 0); - } - }, - - // func valueNew(v ref, args []ref) (ref, bool) - "syscall/js.valueNew": (sp) => { - sp >>>= 0; - try { - const v = loadValue(sp + 8); - const args = loadSliceOfValues(sp + 16); - const result = Reflect.construct(v, args); - sp = this._inst.exports.getsp() >>> 0; // see comment above - storeValue(sp + 40, result); - this.mem.setUint8(sp + 48, 1); - } catch (err) { - sp = this._inst.exports.getsp() >>> 0; // see comment above - storeValue(sp + 40, err); - this.mem.setUint8(sp + 48, 0); - } - }, - - // func valueLength(v ref) int - "syscall/js.valueLength": (sp) => { - sp >>>= 0; - setInt64(sp + 16, parseInt(loadValue(sp + 8).length)); - }, - - // valuePrepareString(v ref) (ref, int) - "syscall/js.valuePrepareString": (sp) => { - sp >>>= 0; - const str = encoder.encode(String(loadValue(sp + 8))); - storeValue(sp + 16, str); - setInt64(sp + 24, str.length); - }, - - // valueLoadString(v ref, b []byte) - "syscall/js.valueLoadString": (sp) => { - sp >>>= 0; - const str = loadValue(sp + 8); - loadSlice(sp + 16).set(str); - }, - - // func valueInstanceOf(v ref, t ref) bool - "syscall/js.valueInstanceOf": (sp) => { - sp >>>= 0; - this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0); - }, - - // func copyBytesToGo(dst []byte, src ref) (int, bool) - "syscall/js.copyBytesToGo": (sp) => { - sp >>>= 0; - const dst = loadSlice(sp + 8); - const src = loadValue(sp + 32); - if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) { - this.mem.setUint8(sp + 48, 0); - return; - } - const toCopy = src.subarray(0, dst.length); - dst.set(toCopy); - setInt64(sp + 40, toCopy.length); - this.mem.setUint8(sp + 48, 1); - }, - - // func copyBytesToJS(dst ref, src []byte) (int, bool) - "syscall/js.copyBytesToJS": (sp) => { - sp >>>= 0; - const dst = loadValue(sp + 8); - const src = loadSlice(sp + 16); - if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) { - this.mem.setUint8(sp + 48, 0); - return; - } - const toCopy = src.subarray(0, dst.length); - dst.set(toCopy); - setInt64(sp + 40, toCopy.length); - this.mem.setUint8(sp + 48, 1); - }, - - "debug": (value) => { - console.log(value); - }, - } - }; - } - - async run(instance) { - if (!(instance instanceof WebAssembly.Instance)) { - throw new Error("Go.run: WebAssembly.Instance expected"); - } - this._inst = instance; - this.mem = new DataView(this._inst.exports.mem.buffer); - this._values = [ // JS values that Go currently has references to, indexed by reference id - NaN, - 0, - null, - true, - false, - globalThis, - this, - ]; - this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id - this._ids = new Map([ // mapping from JS values to reference ids - [0, 1], - [null, 2], - [true, 3], - [false, 4], - [globalThis, 5], - [this, 6], - ]); - this._idPool = []; // unused ids that have been garbage collected - this.exited = false; // whether the Go program has exited - - // Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory. - let offset = 4096; - - const strPtr = (str) => { - const ptr = offset; - const bytes = encoder.encode(str + "\0"); - new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes); - offset += bytes.length; - if (offset % 8 !== 0) { - offset += 8 - (offset % 8); - } - return ptr; - }; - - const argc = this.argv.length; - - const argvPtrs = []; - this.argv.forEach((arg) => { - argvPtrs.push(strPtr(arg)); - }); - argvPtrs.push(0); - - const keys = Object.keys(this.env).sort(); - keys.forEach((key) => { - argvPtrs.push(strPtr(`${key}=${this.env[key]}`)); - }); - argvPtrs.push(0); - - const argv = offset; - argvPtrs.forEach((ptr) => { - this.mem.setUint32(offset, ptr, true); - this.mem.setUint32(offset + 4, 0, true); - offset += 8; - }); - - // The linker guarantees global data starts from at least wasmMinDataAddr. - // Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr. - const wasmMinDataAddr = 4096 + 8192; - if (offset >= wasmMinDataAddr) { - throw new Error("total length of command line and environment variables exceeds limit"); - } - - this._inst.exports.run(argc, argv); - if (this.exited) { - this._resolveExitPromise(); - } - await this._exitPromise; - } - - _resume() { - if (this.exited) { - throw new Error("Go program has already exited"); - } - this._inst.exports.resume(); - if (this.exited) { - this._resolveExitPromise(); - } - } - - _makeFuncWrapper(id) { - const go = this; - return function () { - const event = { id: id, this: this, args: arguments }; - go._pendingEvent = event; - go._resume(); - return event.result; - }; - } - } -})(); diff --git a/go/cmd/kjol-web/README.md b/go/cmd/kjol-web/README.md new file mode 100644 index 00000000..d5efcefc --- /dev/null +++ b/go/cmd/kjol-web/README.md @@ -0,0 +1,120 @@ +# kjol-web — the kjol website + +The landing page and documentation for the whole codebase. It is also the thing it +documents: every page runs the code it describes, and there is not a screenshot of a +component anywhere on the site. + +It is **one server running two entirely different front-ends**, and that is the point of +it. kjol has two web layers — one written in Go and compiled to WebAssembly, one written +in Solid and bundled by a Go toolchain — and the only honest way to document both is to +build the site out of both. + +## Run it + +```sh +cd go/cmd/kjol-web +go run ./build # cold build: both halves +go run ./server # SSR + /rsc + hot reload at http://localhost:8085 +``` + +`go run ./server` performs that same build on every save and hot-swaps the result into +the browser, so day to day it is the only command you need. A `.go` save rebuilds the +wasm and swaps it in without a reload or a flash, preserving page state; a `.css` save +recompiles only Tailwind; a compile error lands in a browser overlay rather than in a +terminal you were not looking at. + +## The shape of the site + +| Path | Rendered by | What it is | +|---|---|---| +| `/`, `/about` | Go → WebAssembly, SSR'd | The landing page. The **Layers** menu is the site's primary navigation. | +| `/wasm/*` | Go → WebAssembly | **Kjol Wasm Web** — the gowasm engine: SSR + hydration, server components, the `webui` kit, overlays, AutoTable, charts, client fetching. | +| `/js/*` | Solid → esbuild, client-rendered | **Kjol JS Web** — the Solid kit: components, forms, AutoTable, theming. | +| `/js/ssr` | Solid → **goja, at request time** | A public page server-rendered with live data injected — the ISR path. | + +Crossing between `/wasm` and `/js` is a real page load. They are different binaries, and +pretending otherwise would mean shipping both to every visitor. + +## Layout + +``` +app/ the Go/WASM half — pages as plain Go functions returning a *VNode + pages.go Deps + Shell + the public/app layouts + the landing page + layers.go the Layers, as data. MIRRORED in frontend/src/layers.ts. + docs.go the docs chrome; docsNav() is the sidebar AND the index + kit.go table.go overlays.go chart.go data.go server_counter.go + *.gen.go GENERATED by kjol/cmd/wasmgen (routes, layout dispatch, RSC stubs) +wasm/ the js/wasm client entry (main_native.go is a host stub) +css/app.css its Tailwind entry — kjol/tw scans the .go files for class names + +frontend/ the Solid half — .tsx pages written against @ui/* + css/style.css brand ONLY. kjol's theme.css is prepended by the bundler, and it + is the one that does `@import "tailwindcss"`. + vendor/ pdf-lib + pdfjs-dist. @ui/AutoTable imports them at the TOP LEVEL, + so a bundle without them does not degrade — it fails to evaluate. + src/app.ts the SPA entry. It is .ts, not .tsx, because the bundler resolves + the entry as src/app.ts and nothing else — so it can hold no JSX. + src/layers.ts the Layers again. Keep in step with app/layers.go. + +server/ ONE Go server: serves wwwroot, SSRs the wasm routes, hosts /rsc, + mounts the Solid SPA at /js/*, serves the SSR'd public pages. +internal/handlers/ the app side of the public-page inversion: kjol generates the + registry; this owns the type and the document shell. +buildsteps/ the build, in Go rather than a shell script, so the one-shot build and + the dev server's watch loop call the SAME functions and cannot drift. +wwwroot/ both halves write here. They never collide: app.css / app.wasm for one, + bundle.min.* for the other. One static dir, one server. +``` + +## Theming + +One theme, both halves. The kits are themed by **semantic tokens** — components say +`bg-surface`, `text-ink`, `border-line` and never name a colour — so dark mode +re-points about a dozen CSS variables and not one component knows it happened. + +The choice is stored under a single `kjol-theme` key that **both** front-ends read, so +switching to dark in `/wasm` and walking over to `/js` keeps it dark. A ten-line boot +script in the document head applies the class before first paint; without it every +dark-mode reader would get a white page until the bundle landed, and then have it +snatched away. + +The only places a `dark:` variant survives are the two a re-pointed token cannot fix: a +coloured tint (a `red-50` wash is invisible on a near-black surface) and a fill that has +to invert (the neutral button, whose label must go dark when the fill goes pale). + +## Adding things + +**A Go/WASM page:** write the function, mark it `//gowasm:page /wasm/thing layout=app`, +build. `wasmgen` regenerates the routing. Add `static` to have it server-rendered. + +**A Solid page:** write the `.tsx`, add it to `routes` in `frontend/src/app.ts` and to +`NAV` in `frontend/src/layout/Shell.tsx`. + +**A layer:** one entry in `app/layers.go` *and* one in `frontend/src/layers.ts`. They are +two files because nothing is upstream of both a WebAssembly binary and an esbuild bundle; +keeping each to a flat list of plain data is what makes that duplication survivable. + +## How it maps onto the engine + +| Package | Role | This app's use | +|---|---|---| +| `kjol/vdom` | neutral virtual DOM (native + wasm): `VNode`, `Signal`, `RenderHTML` | pages build `*VNode`; the server SSRs with `vdom.RenderHTML` | +| `kjol/wasmruntime` | wasm client runtime: reconcile, `Run`/`Hydrate`, router, fetch | `wasm/main.go` calls `Hydrate`/`Run` | +| `kjol/rsc` | stateless server components over HTTP | `//gowasm:server` + its generated client stub | +| `kjol/wasmdevserver` | reusable dev server: SSR, `/rsc`, hot reload, error overlay | `server/main.go` fills a `wasmdevserver.Config` | +| `kjol/webui` | the Go component kit | every `/wasm/*` page | +| `kjol/jsbundler` | TSX → Solid → esbuild, the Tailwind driver, the SSR bake | `buildsteps.JS`, and the ISR render at request time | +| `kjol/jsruntime` | the Solid kit, the vendored runtime, the icons, `theme.css` | everything under `/js/*` | +| `kjol/tw` | the Tailwind v4 engine, in Go | both stylesheets — it scans `.go` for one and `.tsx` for the other | + +The **golden rule** holds throughout: no kjol package imports application code. The app +injects `Build`, `Render` and `Document` into `wasmdevserver`; it owns the `publicPage` +type that kjol's generated registry is written against. The dependency only ever points +one way. + +## Its own module + +`go.mod` declares module `kjolweb` with `replace kjol => ../..`, so its dependencies — +go-chart for the server-drawn charts, plus esbuild and goja by way of the bundler — stay +out of kjol, whose engine packages are stdlib-only. `go build ./...` at the kjol root +does not descend into this nested module; build it from here. diff --git a/go/cmd/examples/go-wasm-web/app/chart.go b/go/cmd/kjol-web/app/chart.go similarity index 97% rename from go/cmd/examples/go-wasm-web/app/chart.go rename to go/cmd/kjol-web/app/chart.go index 48985fca..6d3d52ea 100644 --- a/go/cmd/examples/go-wasm-web/app/chart.go +++ b/go/cmd/kjol-web/app/chart.go @@ -60,7 +60,7 @@ func pieSVG(values []int) string { }) } -//gowasm:page /chart static layout=app +//gowasm:page /wasm/chart static layout=app func ChartPage(d Deps) func() *VNode { data := NewSignal(fixedChartData()) @@ -118,7 +118,7 @@ func ChartPage(d Deps) func() *VNode { } } -const chartSnippet = `//gowasm:page /chart static layout=app +const chartSnippet = `//gowasm:page /wasm/chart static layout=app func ChartPage(d Deps) func() *VNode { data := NewSignal(fixedChartData()) diff --git a/go/cmd/examples/go-wasm-web/app/client.gen.go b/go/cmd/kjol-web/app/client.gen.go similarity index 100% rename from go/cmd/examples/go-wasm-web/app/client.gen.go rename to go/cmd/kjol-web/app/client.gen.go diff --git a/go/cmd/examples/go-wasm-web/app/data.go b/go/cmd/kjol-web/app/data.go similarity index 99% rename from go/cmd/examples/go-wasm-web/app/data.go rename to go/cmd/kjol-web/app/data.go index 4f2eac8c..2372cfd4 100644 --- a/go/cmd/examples/go-wasm-web/app/data.go +++ b/go/cmd/kjol-web/app/data.go @@ -25,7 +25,7 @@ type repoInfo struct { Stars int `json:"stargazers_count"` } -//gowasm:page /data layout=app static +//gowasm:page /wasm/data layout=app static func DataPage(d Deps) func() *VNode { // (1) gob from our own server via httputil.RespondGob / FetchGob. quotes := NewSignal([]Quote{}) diff --git a/go/cmd/examples/go-wasm-web/app/docs.go b/go/cmd/kjol-web/app/docs.go similarity index 94% rename from go/cmd/examples/go-wasm-web/app/docs.go rename to go/cmd/kjol-web/app/docs.go index 5a51f787..3ffecbdc 100644 --- a/go/cmd/examples/go-wasm-web/app/docs.go +++ b/go/cmd/kjol-web/app/docs.go @@ -35,27 +35,27 @@ func docsNav() []docsGroup { return []docsGroup{{ Title: "Introduction", Items: []docsItem{ - {Path: "/docs", Label: "Overview", Icon: "book-open", + {Path: "/wasm", Label: "Overview", Icon: "book-open", Blurb: "What Kjol Web is, how a page becomes a WebAssembly binary, and what runs where."}, }, }, { Title: "Rendering", Items: []docsItem{ - {Path: "/chart", Label: "SSR & hydration", Icon: "chart-column", + {Path: "/wasm/chart", Label: "SSR & hydration", Icon: "chart-column", Blurb: "The same Go renders HTML on the server and takes over in the browser. Charts, server-drawn as SVG."}, - {Path: "/server", Label: "Server components", Icon: "server", + {Path: "/wasm/server", Label: "Server components", Icon: "server", Blurb: "Components whose state and code stay on the server. Calling one looks like calling any other."}, - {Path: "/data", Label: "Data fetching", Icon: "cloud-arrow-down", + {Path: "/wasm/data", Label: "Data fetching", Icon: "cloud-arrow-down", Blurb: "gob to your own server (Go types end to end, no JSON) and JSON to a third-party API."}, }, }, { Title: "Components", Items: []docsItem{ - {Path: "/kit", Label: "UI kit", Icon: "squares", + {Path: "/wasm/kit", Label: "UI kit", Icon: "squares", Blurb: "Buttons, forms, tabs, alerts, cards — the kjol/webui components, written in Go."}, - {Path: "/overlays", Label: "Overlays", Icon: "layers", + {Path: "/wasm/overlays", Label: "Overlays", Icon: "layers", Blurb: "Tooltips, popovers, menus, modals: measured against the real viewport, flipped and shifted to fit."}, - {Path: "/table", Label: "AutoTable", Icon: "table", + {Path: "/wasm/table", Label: "AutoTable", Icon: "table", Blurb: "Filtering, sorting, column management, calculated columns, CSV and PDF export."}, }, }} @@ -189,14 +189,14 @@ func apiTable(rows ...apiRow) *VNode { // ---- the docs index ----------------------------------------------------- -//gowasm:page /docs static layout=app +//gowasm:page /wasm static layout=app func DocsPage(d Deps) func() *VNode { return func() *VNode { var groups []*VNode for _, g := range docsNav() { grid := []Mod{Attr("class", "mt-3 grid gap-3 sm:grid-cols-2")} for _, it := range g.Items { - if it.Path == "/docs" { + if it.Path == "/wasm" { continue // don't list this page on itself } grid = append(grid, docsCard(d, it)) @@ -256,7 +256,7 @@ func appendNodes(parent *VNode, children ...*VNode) *VNode { return parent } -const ssrSnippet = `//gowasm:page /docs static layout=app +const ssrSnippet = `//gowasm:page /wasm static layout=app func DocsPage(d Deps) func() *VNode { count := NewSignal(0) // state lives in the closure diff --git a/go/cmd/examples/go-wasm-web/app/icons_test.go b/go/cmd/kjol-web/app/icons_test.go similarity index 100% rename from go/cmd/examples/go-wasm-web/app/icons_test.go rename to go/cmd/kjol-web/app/icons_test.go diff --git a/go/cmd/examples/go-wasm-web/app/kit.go b/go/cmd/kjol-web/app/kit.go similarity index 99% rename from go/cmd/examples/go-wasm-web/app/kit.go rename to go/cmd/kjol-web/app/kit.go index 2107f587..7423d6f1 100644 --- a/go/cmd/examples/go-wasm-web/app/kit.go +++ b/go/cmd/kjol-web/app/kit.go @@ -53,7 +53,7 @@ func languageOptions() []ui.FormSelectOption { } } -//gowasm:page /kit layout=app +//gowasm:page /wasm/kit layout=app func KitPage(d Deps) func() *VNode { // Interactive demos own their state via signals (a write re-renders). tab := NewSignal(0) diff --git a/go/cmd/examples/go-wasm-web/app/landing_test.go b/go/cmd/kjol-web/app/landing_test.go similarity index 100% rename from go/cmd/examples/go-wasm-web/app/landing_test.go rename to go/cmd/kjol-web/app/landing_test.go diff --git a/go/cmd/kjol-web/app/layers.go b/go/cmd/kjol-web/app/layers.go new file mode 100644 index 00000000..ab66e4ec --- /dev/null +++ b/go/cmd/kjol-web/app/layers.go @@ -0,0 +1,200 @@ +package app + +import ( + "strings" + + . "kjol/vdom" + ui "kjol/webui" +) + +// The layers of kjol, as data. +// +// This is the Go mirror of frontend/src/layers.ts. The site has two front-ends built +// by two completely different pipelines, and the Layers menu has to be identical in +// both — so it is a LIST in each, not markup, and the two lists are the only thing +// that has to be kept in step. +// +// (A shared source would be better than a mirrored one. There isn't one: this half +// compiles to WebAssembly and the other is bundled by esbuild, and nothing is upstream +// of both. Keeping it to a flat slice of plain data is what makes the duplication +// survivable — you can diff the two by eye.) + +type Layer struct { + Name string + Href string + Tagline string + // Live means you can click into worked examples. The others are documented but + // have no demo — they still appear, because a menu that silently omits half the + // library teaches the reader that the library is half the size it is. + Live bool + Icon string +} + +func Layers() []Layer { + return []Layer{ + { + Name: "Kjol Go", + Href: "/go", + Tagline: "The server base: config, database, logging, HTTP, mail, validation.", + Icon: "server", + }, + { + Name: "Kjol Wasm Web", + Href: "/wasm", + Tagline: "Web interfaces written in Go, compiled to WebAssembly. SSR + hydration, no JS build.", + Live: true, + Icon: "code", + }, + { + Name: "Kjol JS Web", + Href: "/js", + Tagline: "The Solid component kit, bundled by a Go toolchain: TSX → Solid → esbuild, Tailwind in Go.", + Live: true, + Icon: "squares", + }, + { + Name: "Kjol C", + Href: "/c", + Tagline: "Arena allocator, strings, math, lexer, platform layer.", + Icon: "bolt", + }, + { + Name: "Kjol Jai", + Href: "/jai", + Tagline: "Console rendering module. Early.", + Icon: "cube", + }, + } +} + +// CurrentLayer is the layer the given path belongs to, or nil on the front page. +func CurrentLayer(path string) *Layer { + for i, l := range Layers() { + if path == l.Href || strings.HasPrefix(path, l.Href+"/") { + return &Layers()[i] + } + } + return nil +} + +// LayersMenuCtl is the Layers menu's controller. +// +// It is created ONCE, here, at package level — not inside layersMenu, which is called +// from a layout on every single render. A floating component is a controller: it owns +// an open signal, a positioning engine and document listeners, and building a fresh one +// per render would leak all three and give you a menu that never opens. Same rule as +// Theme, a few lines up in pages.go. +var LayersMenuCtl = ui.NewMenu(ui.MenuOptions{Placement: ui.PlacementBottomEnd}) + +// layersMenu is the site's primary navigation: kjol is a stack of layers, and this is +// how you get from any one of them to any other. +// +// A layer that is Live is a link. One that is not is inert and dimmed, with the word +// "reference" on it — it exists, it is documented in the repository, there is simply +// nothing here to click. +// +// Crossing into another layer is a REAL navigation, not a client-side route: /js is a +// different binary's SPA and /wasm is this one. Hence a plain href and no navigate() +// interception — an intercepted click would ask this WebAssembly to render a page it +// does not have. +func layersMenu(d Deps) *VNode { + content := []*VNode{ + P(Attr("class", "px-3 pb-1 pt-2 text-[11px] font-semibold uppercase tracking-widest text-ink-faint"), + Text("The layers of kjol")), + } + for _, l := range Layers() { + content = append(content, layerItem(d, l)) + } + + return Div(Attr("class", "relative"), + LayersMenuCtl.Trigger(ui.MenuTriggerProps{ + Class: "inline-flex items-center gap-1.5 rounded-default px-3 py-1.5 text-sm font-medium text-ink-soft hover:bg-surface-raised hover:text-ink", + }, + Text("Layers"), + ui.IconInline("chevron-down", 11, "text-ink-faint"), + ), + LayersMenuCtl.Content("w-96", content...), + ) +} + +// layersGrid is the front page's list of layers — the same data as the menu, laid out +// to be read rather than navigated. A layer with no examples still gets a row: the +// point of the page is what kjol IS, and half of it having no demo yet does not make +// that half not exist. +func layersGrid(d Deps) *VNode { + rows := []Mod{Attr("class", "mt-5 divide-y divide-line rounded-default border border-line")} + for _, l := range Layers() { + rows = append(rows, layerRow(l)) + } + return Div(rows...) +} + +func layerRow(l Layer) *VNode { + head := Span(Attr("class", "flex items-center gap-2"), + ui.IconInline(l.Icon, 15, iff(l.Live, "text-accent", "text-ink-muted")), + Span(Attr("class", "font-medium text-ink"), Text(l.Name)), + iff2(l.Live, + func() *VNode { return nil }, + func() *VNode { + return Span(Attr("class", "rounded-full border border-line px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-ink-faint"), + Text("reference")) + }), + ) + body := P(Attr("class", "mt-1 pl-[23px] text-sm leading-relaxed text-ink-muted"), Text(l.Tagline)) + + if !l.Live { + return Div(Attr("class", "px-5 py-4 opacity-75"), head, body) + } + // A real navigation: the next layer is a different binary. + return A(Attr("class", "block px-5 py-4 no-underline hover:bg-surface-muted"), Attr("href", l.Href), + head, body, + Span(Attr("class", "mt-2 inline-flex items-center gap-1.5 pl-[23px] text-sm text-accent"), + Text("Read the docs"), + ui.IconInline("arrow-right", 12, ""), + ), + ) +} + +// iff picks a string; iff2 picks a node. Go has no ternary, and a four-line if +// statement inside a tree literal breaks the shape of the markup worse than these do. +func iff(cond bool, a, b string) string { + if cond { + return a + } + return b +} + +func iff2(cond bool, a, b func() *VNode) *VNode { + if cond { + return a() + } + return b() +} + +func layerItem(d Deps, l Layer) *VNode { + active := CurrentLayer(d.Path()) != nil && CurrentLayer(d.Path()).Href == l.Href + + if !l.Live { + return Div(Attr("class", "flex cursor-default flex-col gap-0.5 px-3 py-2 opacity-55"), + Span(Attr("class", "flex items-center gap-2 text-sm font-medium text-ink-muted"), + ui.IconInline(l.Icon, 14, "text-ink-faint"), + Text(l.Name), + Span(Attr("class", "rounded-full bg-surface-raised px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-ink-muted"), + Text("reference")), + ), + Span(Attr("class", "pl-6 text-xs text-ink-muted"), Text(l.Tagline)), + ) + } + + cls := "flex flex-col gap-0.5 px-3 py-2 no-underline hover:bg-surface-raised" + if active { + cls += " bg-primary-subtle" + } + return A(Attr("class", cls), Attr("href", l.Href), + Span(Attr("class", "flex items-center gap-2 text-sm font-medium text-ink"), + ui.IconInline(l.Icon, 14, "text-accent"), + Text(l.Name), + ), + Span(Attr("class", "pl-6 text-xs text-ink-muted"), Text(l.Tagline)), + ) +} diff --git a/go/cmd/examples/go-wasm-web/app/overlays.go b/go/cmd/kjol-web/app/overlays.go similarity index 99% rename from go/cmd/examples/go-wasm-web/app/overlays.go rename to go/cmd/kjol-web/app/overlays.go index 86666ad9..658e82c6 100644 --- a/go/cmd/examples/go-wasm-web/app/overlays.go +++ b/go/cmd/kjol-web/app/overlays.go @@ -19,7 +19,7 @@ import ( // The page is NOT `static`: nothing is open during SSR anyway, so pre-rendering it // buys nothing, and it keeps the example honest about which routes need it. // -//gowasm:page /overlays layout=app +//gowasm:page /wasm/overlays layout=app func OverlaysPage(d Deps) func() *VNode { // --- tooltips ----------------------------------------------------------- tipTop := ui.NewHoverTooltip(ui.PlacementTop, "") diff --git a/go/cmd/examples/go-wasm-web/app/pages.go b/go/cmd/kjol-web/app/pages.go similarity index 89% rename from go/cmd/examples/go-wasm-web/app/pages.go rename to go/cmd/kjol-web/app/pages.go index 128a1003..43772af9 100644 --- a/go/cmd/examples/go-wasm-web/app/pages.go +++ b/go/cmd/kjol-web/app/pages.go @@ -1,4 +1,4 @@ -// Package app holds the go-wasm-web example's pages and components as +// Package app holds the kjol-web site's Go/WASM pages and components as // standalone, platform-neutral functions (SSR on the server, hydrate on the // client). UI is built from the kjol webui kit + Tailwind utility classes. // @@ -71,12 +71,20 @@ func notFound(path string) *VNode { // the thing every other part is built onto. Which is what this library is meant to be // for the applications that share it. func wordmark(d Deps, href string) *VNode { + // The lockup names the LAYER you are standing in, not the site. On the front page + // that is kjol itself; inside /wasm it is Kjol Wasm Web. A wordmark that says the + // same thing everywhere is one more thing the reader has to keep track of himself. + name, sub := "kjol", "a shared base layer" + if l := CurrentLayer(d.Path()); l != nil { + name, sub = l.Name, "Go + WebAssembly" + } + return A(Attr("class", "flex items-center gap-2.5 no-underline"), Attr("href", href), navigate(d, href), Span(Attr("class", "inline-flex h-8 w-8 items-center justify-center rounded-default bg-ink text-surface"), ui.IconInline("sailboat", 17, "")), Span(Attr("class", "flex items-baseline gap-1.5"), - Span(Attr("class", "text-lg font-semibold tracking-tight text-text-heading"), Text("Kjol Web")), - Span(Attr("class", "text-sm text-ink-faint"), Text("Go + WASM")), + Span(Attr("class", "text-lg font-semibold tracking-tight text-text-heading"), Text(name)), + Span(Attr("class", "text-sm text-ink-faint"), Text(sub)), ), ) } @@ -96,19 +104,21 @@ func PublicLayout(d Deps, content *VNode) *VNode { Div(Attr("class", "pointer-events-none fixed inset-0 -z-10 bg-grid grid-fade"), Attr("aria-hidden", "true")), Nav(Attr("class", "site-nav border-b border-line"), - Div(Attr("class", "mx-auto flex max-w-2xl items-center gap-2 px-4 py-4"), + Div(Attr("class", "mx-auto flex max-w-3xl items-center gap-2 px-4 py-4"), wordmark(d, "/"), - Ul(Attr("class", "ml-auto flex items-center gap-1"), - navItem(d, "/docs", "Docs", false), - navItem(d, "/about", "About", false), - Li(Attr("class", "ml-1"), Theme.ThemeToggle(ui.ThemeToggleProps{Small: true})), + Div(Attr("class", "ml-auto flex items-center gap-1"), + layersMenu(d), + Ul(Attr("class", "flex items-center gap-1"), + navItem(d, "/about", "About", false), + Li(Attr("class", "ml-1"), Theme.ThemeToggle(ui.ThemeToggleProps{Small: true})), + ), ))), Main(Attr("class", "px-4 py-14"), content), Footer(Attr("class", "mx-auto max-w-2xl px-4 pb-14"), P(Attr("class", "text-sm text-ink-faint"), - Text("Kjol Web is part of kjol — a shared base layer. kjol is Norwegian for keel.")), + Text("kjol is a shared base layer, factored out of several applications so they stay in sync. It is Norwegian for keel.")), ), ui.ModalHost(), ) @@ -117,7 +127,7 @@ func PublicLayout(d Deps, content *VNode) *VNode { // wideRoutes get a roomier container. A table with a dozen columns, a drag handle // and three calculated columns has no business being squeezed into a reading-width // column; prose pages still are. -var wideRoutes = map[string]bool{"/table": true} +var wideRoutes = map[string]bool{"/wasm/table": true} // AppLayout is the DOCUMENTATION shell: a sidebar of sections on the left, the page on // the right. The app routes are the framework's docs — each one explains a capability, @@ -143,9 +153,12 @@ func AppLayout(d Deps, content *VNode) *VNode { Div(Attr("class", "mx-auto flex max-w-[110rem] items-center gap-3 px-6 py-3"), wordmark(d, "/"), Span(Attr("class", "rounded-full border border-line px-2 py-0.5 text-[11px] font-semibold uppercase tracking-wider text-ink-faint"), Text("Docs")), - Ul(Attr("class", "ml-auto flex items-center gap-2"), - navItem(d, "/", "Home", false), - Li(Theme.ThemeToggle(ui.ThemeToggleProps{Small: true})), + Div(Attr("class", "ml-auto flex items-center gap-2"), + layersMenu(d), + Ul(Attr("class", "flex items-center gap-2"), + navItem(d, "/", "Home", false), + Li(Theme.ThemeToggle(ui.ThemeToggleProps{Small: true})), + ), ), )), @@ -279,17 +292,28 @@ func HomePage(d Deps) func() *VNode { return func() *VNode { markup := RenderHTML(demoTree()) - return Div(Attr("class", "mx-auto max-w-2xl"), + return Div(Attr("class", "mx-auto max-w-3xl"), H1(Attr("class", "text-3xl font-semibold tracking-tight text-text-heading"), - Text("Kjol Web")), + Text("kjol")), P(Attr("class", "mt-3 leading-relaxed text-ink-soft"), - Text("A small library for writing web interfaces in Go. Components are ordinary functions "+ - "returning a virtual DOM. The server renders them to HTML, and the same code compiles "+ - "to WebAssembly and takes over in the browser.")), + Text("A shared base layer, factored out of several applications so they stay in sync. "+ + "Kjol is Norwegian for KEEL: the spine of a hull, the thing every other part is built onto.")), P(Attr("class", "mt-3 leading-relaxed text-ink-soft"), - Text("There is no JavaScript build step, and nothing outside the standard library.")), + Text("It is not one library. It is a stack of them, in several languages, and each one is "+ + "documented here.")), + + // ---- the layers ---- + // + // The layers are the site. Everything else on this page is evidence that they + // work; this is the part you are meant to click. + H2(Attr("class", "mt-12 text-lg font-semibold text-text-heading"), Text("The layers")), + layersGrid(d), // ---- the demonstration ---- + // + // This survives from the old landing page because it is the one thing on the site + // that cannot be faked: the same Go function, rendered twice at once, as live DOM + // and as the HTML string the server sent. H2(Attr("class", "mt-12 text-lg font-semibold text-text-heading"), Text("One function, two runtimes")), P(Attr("class", "mt-2 leading-relaxed text-ink-soft"), Text("Below is a single Go function, shown twice. On the left it has been reconciled into "+ @@ -335,10 +359,10 @@ func HomePage(d Deps) func() *VNode { Text("Every page of the documentation runs the code it documents — there are no screenshots "+ "of components anywhere on this site. "), A(Attr("class", "text-accent underline underline-offset-4"), - Attr("href", "/docs"), navigate(d, "/docs"), Text("Read the docs")), + Attr("href", "/wasm"), navigate(d, "/wasm"), Text("Read the docs")), Text(", or "), A(Attr("class", "text-accent underline underline-offset-4"), - Attr("href", "/kit"), navigate(d, "/kit"), Text("look at the components")), + Attr("href", "/wasm/kit"), navigate(d, "/wasm/kit"), Text("look at the components")), Text("."), ), P(Attr("class", "mt-4 text-sm text-ink-muted"), @@ -443,7 +467,7 @@ func principle(title, body string) *VNode { // ---- server components -------------------------------------------------- -//gowasm:page /server layout=app +//gowasm:page /wasm/server layout=app func ServerPage(d Deps) func() *VNode { // ServerCounter is a server component — calling it is just like calling any // component. On the client this resolves to a generated stub that mounts it diff --git a/go/cmd/examples/go-wasm-web/app/routes.gen.go b/go/cmd/kjol-web/app/routes.gen.go similarity index 53% rename from go/cmd/examples/go-wasm-web/app/routes.gen.go rename to go/cmd/kjol-web/app/routes.gen.go index 7af6b876..9340b329 100644 --- a/go/cmd/examples/go-wasm-web/app/routes.gen.go +++ b/go/cmd/kjol-web/app/routes.gen.go @@ -6,39 +6,39 @@ import "kjol/vdom" // Routes maps each //gowasm:page path to its instantiated render function. func Routes(d Deps) map[string]func() *vdom.VNode { return map[string]func() *vdom.VNode{ - "/": HomePage(d), - "/about": AboutPage(d), - "/chart": ChartPage(d), - "/data": DataPage(d), - "/docs": DocsPage(d), - "/kit": KitPage(d), - "/overlays": OverlaysPage(d), - "/server": ServerPage(d), - "/table": TablePage(d), + "/": HomePage(d), + "/about": AboutPage(d), + "/wasm": DocsPage(d), + "/wasm/chart": ChartPage(d), + "/wasm/data": DataPage(d), + "/wasm/kit": KitPage(d), + "/wasm/overlays": OverlaysPage(d), + "/wasm/server": ServerPage(d), + "/wasm/table": TablePage(d), } } // StaticPaths are the routes the server pre-renders (SSR); others render client-side. var StaticPaths = map[string]bool{ - "/": true, - "/about": true, - "/chart": true, - "/data": true, - "/docs": true, - "/table": true, + "/": true, + "/about": true, + "/wasm": true, + "/wasm/chart": true, + "/wasm/data": true, + "/wasm/table": true, } // RouteLayout maps each route to the name of the layout that wraps it. var RouteLayout = map[string]string{ - "/": "public", - "/about": "public", - "/chart": "app", - "/data": "app", - "/docs": "app", - "/kit": "app", - "/overlays": "app", - "/server": "app", - "/table": "app", + "/": "public", + "/about": "public", + "/wasm": "app", + "/wasm/chart": "app", + "/wasm/data": "app", + "/wasm/kit": "app", + "/wasm/overlays": "app", + "/wasm/server": "app", + "/wasm/table": "app", } // LayoutFor wraps a page's content in the layout declared for its route. diff --git a/go/cmd/examples/go-wasm-web/app/server.gen.go b/go/cmd/kjol-web/app/server.gen.go similarity index 100% rename from go/cmd/examples/go-wasm-web/app/server.gen.go rename to go/cmd/kjol-web/app/server.gen.go diff --git a/go/cmd/examples/go-wasm-web/app/server_counter.go b/go/cmd/kjol-web/app/server_counter.go similarity index 100% rename from go/cmd/examples/go-wasm-web/app/server_counter.go rename to go/cmd/kjol-web/app/server_counter.go diff --git a/go/cmd/examples/go-wasm-web/app/ssr_test.go b/go/cmd/kjol-web/app/ssr_test.go similarity index 97% rename from go/cmd/examples/go-wasm-web/app/ssr_test.go rename to go/cmd/kjol-web/app/ssr_test.go index 1f9e1a56..4da6c1a5 100644 --- a/go/cmd/examples/go-wasm-web/app/ssr_test.go +++ b/go/cmd/kjol-web/app/ssr_test.go @@ -11,7 +11,7 @@ import ( ) func TestSSRPages(t *testing.T) { - for _, path := range []string{"/", "/about", "/chart", "/data", "/table", "/overlays", "/kit"} { + for _, path := range []string{"/", "/about", "/wasm/chart", "/wasm/data", "/wasm/table", "/wasm/overlays", "/wasm/kit"} { deps := Deps{Path: func() string { return path }} html := vdom.RenderHTML(Shell(deps, Routes(deps))) t.Logf("%-8s %6d bytes portals=%d", path, len(html), strings.Count(html, "data-portal")) @@ -22,7 +22,7 @@ func TestSSRPages(t *testing.T) { } func TestSSRTablePage(t *testing.T) { - deps := Deps{Path: func() string { return "/table" }} + deps := Deps{Path: func() string { return "/wasm/table" }} html := vdom.RenderHTML(Shell(deps, Routes(deps))) // The table persists a personal layout in localStorage, which the SERVER CANNOT diff --git a/go/cmd/examples/go-wasm-web/app/table.go b/go/cmd/kjol-web/app/table.go similarity index 99% rename from go/cmd/examples/go-wasm-web/app/table.go rename to go/cmd/kjol-web/app/table.go index 48911209..51d1b738 100644 --- a/go/cmd/examples/go-wasm-web/app/table.go +++ b/go/cmd/kjol-web/app/table.go @@ -174,7 +174,7 @@ func newEmployeeTable(highlight *Signal[string]) *ui.AutoTableState { }) } -//gowasm:page /table layout=app static +//gowasm:page /wasm/table layout=app static func TablePage(d Deps) func() *VNode { // Which row to spotlight, if any. highlight := NewSignal("") diff --git a/go/cmd/examples/go-wasm-web/build/main.go b/go/cmd/kjol-web/build/main.go similarity index 86% rename from go/cmd/examples/go-wasm-web/build/main.go rename to go/cmd/kjol-web/build/main.go index d6dfc13a..c89e6dc5 100644 --- a/go/cmd/examples/go-wasm-web/build/main.go +++ b/go/cmd/kjol-web/build/main.go @@ -1,7 +1,7 @@ // Command build runs the example's full pre-compile step once: directive codegen, // Tailwind, the wasm binary, and Go's JS shim. // -// go run ./build # from cmd/examples/go-wasm-web +// go run ./build # from go/cmd/kjol-web // // For day-to-day work run the dev server instead (`go run ./server`) — it performs // these same steps on every save and hot-swaps the result into the browser. This @@ -12,7 +12,7 @@ import ( "log" "os" - "gowasmweb/buildsteps" + "kjolweb/buildsteps" ) func main() { @@ -25,6 +25,7 @@ func main() { {"generating directive glue (//gowasm:page, //gowasm:layout, //gowasm:server)", buildsteps.Codegen}, {"compiling Tailwind CSS -> wwwroot/app.css", buildsteps.Tailwind}, {"compiling ./wasm -> wwwroot/app.wasm (GOOS=js GOARCH=wasm)", buildsteps.Wasm}, + {"bundling the Solid half -> wwwroot/bundle.min.{js,css} (TSX -> Solid -> esbuild)", buildsteps.JS}, {"copying Go's wasm_exec.js shim into wwwroot/", buildsteps.Shim}, } diff --git a/go/cmd/examples/go-wasm-web/buildsteps/buildsteps.go b/go/cmd/kjol-web/buildsteps/buildsteps.go similarity index 74% rename from go/cmd/examples/go-wasm-web/buildsteps/buildsteps.go rename to go/cmd/kjol-web/buildsteps/buildsteps.go index 73391b64..5c263d7b 100644 --- a/go/cmd/examples/go-wasm-web/buildsteps/buildsteps.go +++ b/go/cmd/kjol-web/buildsteps/buildsteps.go @@ -16,12 +16,14 @@ import ( "os/exec" "path/filepath" "strings" + + "kjol/jsbundler" ) // kjolRoot is the kjol Go module root, relative to the example directory. The Tailwind // and codegen commands are run FROM there so the engine's dependencies resolve in // kjol's own go.mod, and this example's stays lean. -const kjolRoot = "../../.." +const kjolRoot = "../.." // Wwwroot is where every build artefact lands, and what the dev server serves. const Wwwroot = "wwwroot" @@ -41,12 +43,12 @@ func Codegen() ([]byte, error) { // all. func Tailwind() ([]byte, error) { cmd := exec.Command("go", "run", "./cmd/twcss", - "-entry", "cmd/examples/go-wasm-web/css/app.css", - "-out", "cmd/examples/go-wasm-web/wwwroot/app.css", + "-entry", "cmd/kjol-web/css/app.css", + "-out", "cmd/kjol-web/wwwroot/app.css", "-base", ".", "webui/**/*.go", - "cmd/examples/go-wasm-web/app/**/*.go", - "cmd/examples/go-wasm-web/server/**/*.go", + "cmd/kjol-web/app/**/*.go", + "cmd/kjol-web/server/**/*.go", ) cmd.Dir = kjolRoot return cmd.CombinedOutput() @@ -59,6 +61,31 @@ func Wasm() ([]byte, error) { return cmd.CombinedOutput() } +// JS builds the OTHER half of the site: the Solid SPA under /js, the SSR'd public +// pages, and their stylesheet. It is kjol/jsbundler — TSX compiled to Solid by a Go +// program, bundled by esbuild's Go API, styled by kjol/tw — run in-process rather than +// shelled out to, so a compile error comes back as a Go error and lands in the dev +// server's browser overlay like every other failure. +// +// It writes bundle.min.{js,css} and public.bundle.min.{js,css} into the SAME wwwroot as +// the wasm build. The two halves never collide: different filenames, one static dir, one +// server. +// +// -web points at the shared tree, which is where the kit, the vendored Solid runtime, +// the icon SVGs and the @theme scaffold all live. +func JS() ([]byte, error) { + err := jsbundler.Build(jsbundler.Config{ + AppFrontend: "frontend", + WebDir: filepath.Join(kjolRoot, "jsruntime"), + Output: Wwwroot, + GenTSDir: filepath.Join("frontend", "src", "ui", "generated"), + }) + if err != nil { + return []byte(err.Error()), err + } + return nil, nil +} + // Shim copies Go's wasm_exec.js into wwwroot. It is the loader the browser needs to // start a Go wasm binary, it ships with the toolchain, and it must match the compiler // that produced the binary — so it is copied from GOROOT rather than vendored. @@ -93,7 +120,7 @@ func Shim() ([]byte, error) { // puts straight into the browser's error overlay — so a compile error lands in front of // you rather than in a terminal you were not looking at. func All() ([]byte, error) { - for _, step := range []func() ([]byte, error){Codegen, Tailwind, Wasm, Shim} { + for _, step := range []func() ([]byte, error){Codegen, Tailwind, Wasm, JS, Shim} { if out, err := step(); err != nil { return out, err } diff --git a/go/cmd/examples/go-wasm-web/css/app.css b/go/cmd/kjol-web/css/app.css similarity index 100% rename from go/cmd/examples/go-wasm-web/css/app.css rename to go/cmd/kjol-web/css/app.css diff --git a/go/cmd/kjol-web/frontend/css/style.css b/go/cmd/kjol-web/frontend/css/style.css new file mode 100644 index 00000000..7fd3f931 --- /dev/null +++ b/go/cmd/kjol-web/frontend/css/style.css @@ -0,0 +1,79 @@ +/* --------------------------------------------------------------------------- + kjol-web — brand stylesheet for the Kjol JS Web section (/js/*). + --------------------------------------------------------------------------- + There is deliberately no `@import "tailwindcss"` here. The bundler PREPENDS + kjol's shared scaffold (go/jsruntime/styles/theme.css) to this file, and that + scaffold does the import — an @import has to come first, and this file no + longer is. See jsbundler/css.go and the header of theme.css. + + What is left is only what is genuinely this app's: the brand. + + The values below match the Go/WASM section's css/app.css on purpose — same + Lora, same sky accent — so that crossing between /wasm and /js reads as two + halves of ONE site rather than two demos that happen to share a domain. The + two sections are built by completely different pipelines; they should not look + like it. + --------------------------------------------------------------------------- */ + +@theme { + /* The accent. `primary` is the ONE semantic token the Solid kit actually + honours (bg-primary / text-primary / border-primary / bg-primary-hover); + everything else in the kit names a raw Tailwind neutral directly. That is a + real difference from the Go/WASM kit — which is themed end to end by tokens + and can therefore switch to dark by changing ten values — and the /js/theming + page says so out loud rather than pretending otherwise. */ + --color-primary: #0284c7; /* sky-600 — fills; they carry white text */ + --color-primary-hover: #0369a1; /* sky-700 */ + + /* Lora, the same body face the Go/WASM section vendors. The woff2 files are + served out of wwwroot/fonts by the same server, so this section pays no + extra request for them — they are already in the browser's cache from the + front page. */ + --font-sans: "Lora", ui-serif, Georgia, Cambria, "Times New Roman", serif; + --font-serif: "Lora", ui-serif, Georgia, Cambria, "Times New Roman", serif; +} + +/* Lora's @font-face rules are declared HERE as well as in the Go/WASM section's + app.css, and that duplication is correct: the two sections load different + stylesheets (this compiles to bundle.min.css, that one to app.css) and a page + in this section never links the other. Each stylesheet has to stand alone. + + What is NOT duplicated is the download. Both point at the same four /fonts/*.woff2 + URLs served out of the same wwwroot, so a reader arriving here from the front page + already has them in cache and pays nothing. + + Variable fonts: one file per style covers weights 400-700, hence the range. */ +@font-face { + font-family: "Lora"; + font-style: normal; + font-weight: 400 700; + font-display: swap; + src: url("/fonts/lora-latin-normal.woff2") format("woff2"); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} + +@font-face { + font-family: "Lora"; + font-style: normal; + font-weight: 400 700; + font-display: swap; + src: url("/fonts/lora-latin-ext-normal.woff2") format("woff2"); + unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; +} + +@font-face { + font-family: "Lora"; + font-style: italic; + font-weight: 400 700; + font-display: swap; + src: url("/fonts/lora-latin-italic.woff2") format("woff2"); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} + +/* Only the font. The page's background and text colour come from the shared + scaffold's `html` rule, which paints them from --color-surface / --color-ink — + the tokens the .dark block re-points. Setting them here would pin the page to + white and leave a dark app sitting in a white window. */ +html { + font-family: var(--font-sans); +} diff --git a/go/cmd/kjol-web/frontend/src/app.ts b/go/cmd/kjol-web/frontend/src/app.ts new file mode 100644 index 00000000..bcda6cdc --- /dev/null +++ b/go/cmd/kjol-web/frontend/src/app.ts @@ -0,0 +1,52 @@ +// SPA entry for the Kjol JS Web section (/js/*). +// +// This file is .ts and NOT .tsx on purpose — it is not a style choice. The bundler +// resolves the SPA entry as src/app.ts (falling back to src/app.js) and nothing +// else, so the entry cannot contain JSX. Hence createComponent() here, and JSX in +// the pages it points at. +// +// The section is mounted under a base path rather than at the root: the front page +// and the whole /wasm section are served by the Go/WASM half of this site, which +// this bundle knows nothing about. `base: "/js"` keeps every route in here relative +// to that, so a link to "/kit" resolves to /js/kit and the two SPAs never fight +// over a URL. +// +// Crossing OUT of /js (to the front page, or into /wasm) is a plain and a +// real page load — the other half of the site is a different binary. That is the +// honest cost of running two front-ends behind one server, and it is one navigation. + +import { render, createComponent } from "solid-js/web"; +import { Router } from "@solidjs/router"; +import type { RouteDefinition } from "@solidjs/router"; + +import { Shell } from "./layout/Shell.tsx"; +import { Overview } from "./pages/Overview.tsx"; +import { Kit } from "./pages/Kit.tsx"; +import { Forms } from "./pages/Forms.tsx"; +import { Table } from "./pages/Table.tsx"; +import { Theming } from "./pages/Theming.tsx"; + +// Routes as plain data: solid-router accepts RouteDefinition[] as `children`, which +// is what lets a JSX-free entry declare a full route tree. +const routes: RouteDefinition[] = [ + { path: "/", component: Overview }, + { path: "/kit", component: Kit }, + { path: "/forms", component: Forms }, + { path: "/table", component: Table }, + { path: "/theming", component: Theming }, +]; + +const root = document.getElementById("app"); +if (root) { + render( + () => + createComponent(Router, { + base: "/js", + root: Shell, + get children() { + return routes; + }, + }), + root, + ); +} diff --git a/go/cmd/kjol-web/frontend/src/layers.ts b/go/cmd/kjol-web/frontend/src/layers.ts new file mode 100644 index 00000000..045ba604 --- /dev/null +++ b/go/cmd/kjol-web/frontend/src/layers.ts @@ -0,0 +1,72 @@ +// The layers of kjol, as data. +// +// This is the JS mirror of app/layers.go on the Go/WASM side. The site has two +// front-ends built by two completely different pipelines, and the Layers menu has +// to be identical in both — so it is a LIST in each, not markup, and the two lists +// are the only thing that has to be kept in step. +// +// (A shared source would be better than a mirrored one. There isn't one: the Go +// side compiles to WebAssembly and the JS side is bundled by esbuild, and nothing +// is upstream of both. Keeping it to a flat array of plain data is what makes the +// duplication survivable — you can diff the two by eye.) + +export interface Layer { + name: string; + href: string; + tagline: string; + /** Live = you can click into worked examples. Reference = documented, no demo. */ + live: boolean; + /** + * The ONE field that does not match app/layers.go, and cannot: the two kits have + * different icon sets. This side names FontAwesome; the Go side names webui's own + * hand-drawn registry, which has no FontAwesome in it at all. Where the two have no + * glyph in common the names diverge (here `table-columns`, there `squares`). + * + * Both sides fail loudly rather than quietly — a name neither registry knows renders + * an empty box, and app/icons_test.go fails the build over it. + */ + icon: string; +} + +export const LAYERS: Layer[] = [ + { + name: "Kjol Go", + href: "/go", + tagline: "The server base: config, database, logging, HTTP, mail, validation.", + live: false, + icon: "server", + }, + { + name: "Kjol Wasm Web", + href: "/wasm", + tagline: "Web interfaces written in Go, compiled to WebAssembly. SSR + hydration, no JS build.", + live: true, + icon: "code", + }, + { + name: "Kjol JS Web", + href: "/js", + tagline: "The Solid component kit, bundled by a Go toolchain: TSX → Solid → esbuild, Tailwind in Go.", + live: true, + icon: "table-columns", + }, + { + name: "Kjol C", + href: "/c", + tagline: "Arena allocator, strings, math, lexer, platform layer.", + live: false, + icon: "bolt", + }, + { + name: "Kjol Jai", + href: "/jai", + tagline: "Console rendering module. Early.", + live: false, + icon: "cube", + }, +]; + +/** The layer the current path belongs to, or undefined on the front page. */ +export function currentLayer(path: string): Layer | undefined { + return LAYERS.find((l) => path === l.href || path.startsWith(l.href + "/")); +} diff --git a/go/cmd/kjol-web/frontend/src/layout/Demo.tsx b/go/cmd/kjol-web/frontend/src/layout/Demo.tsx new file mode 100644 index 00000000..6b5bb30e --- /dev/null +++ b/go/cmd/kjol-web/frontend/src/layout/Demo.tsx @@ -0,0 +1,33 @@ +// A worked example: the code on one side, that same code RUNNING on the other. +// +// The code string is written by hand rather than extracted from the source, and that +// is a known compromise — a hand-copied snippet can drift from the component beside +// it. The alternative (a build step that slices the real source) buys accuracy at the +// cost of a second thing to maintain, and the snippets here are short enough to read +// against the live demo in one glance. If they start getting long, that trade flips. + +import { JSXElement } from "solid-js"; +import { CodeBox } from "@ui/General"; + +export function Demo(props: { title: string; code: string; children?: JSXElement }) { + return ( +
+

{props.title}

+ +
+ {/* The live half. It sits on the plain surface, not in a tinted "preview" + box, because a component that only looks right against a special + background is a component that will look wrong in the app. */} +
+ running +
+
{props.children}
+ +
+ source +
+ +
+
+ ); +} diff --git a/go/cmd/kjol-web/frontend/src/layout/Shell.tsx b/go/cmd/kjol-web/frontend/src/layout/Shell.tsx new file mode 100644 index 00000000..9d1be6ac --- /dev/null +++ b/go/cmd/kjol-web/frontend/src/layout/Shell.tsx @@ -0,0 +1,176 @@ +// The Kjol JS Web shell: top bar (wordmark + Layers menu), sidebar, content. +// +// It is deliberately a near-copy of the Go/WASM section's AppLayout. Two front-ends, +// one site: if the chrome drifted, crossing from /wasm to /js would feel like leaving +// for somebody else's website. The components underneath are completely different — +// these are Solid components from the kit, those are Go functions returning a VNode — +// and the page should not betray that. + +import { For, Show } from "solid-js"; +import { A, useLocation } from "@solidjs/router"; +import { Icon } from "@ui/Icons"; +import { Menu, MenuTrigger, MenuContent, MenuLink, MenuSection } from "@ui/Menu"; +import { ThemeToggle, initTheme } from "@ui/Theme"; +import { LAYERS } from "../layers.ts"; + +interface NavItem { + path: string; + label: string; + icon: string; +} + +// The section's own pages. Paths are relative to the router base (/js). +const NAV: NavItem[] = [ + { path: "/", label: "Overview", icon: "circle-info" }, + { path: "/kit", label: "Components", icon: "table-columns" }, + { path: "/forms", label: "Forms", icon: "pen-to-square" }, + { path: "/table", label: "AutoTable", icon: "table" }, + { path: "/theming", label: "Theming", icon: "palette" }, +]; + +// The Layers menu — the site's primary navigation. kjol is a stack of layers, and +// this is how you get from any one of them to any other. It is rendered from the +// LAYERS array so adding a layer is one object, not a nav edit in two front-ends. +// +// Layers that are not `live` still appear. A menu that silently omits half the +// library teaches the reader that the library is half the size it is; showing them +// greyed, with the reason, is the more honest shape. +function LayersMenu() { + return ( +
+ + + Layers + + + + + +

+ The layers of kjol +

+ + {(layer) => ( + + + + {layer.name} + + reference + + + {layer.tagline} + + } + > + {/* MenuLink is a real
(not a router link), which is what a + cross-layer jump has to be: the other layers are served by a + different binary. */} + + + {layer.name} + {layer.tagline} + + + + )} + + + +
+ ); +} + +function Wordmark() { + // A plain , not a router : "/" is the front page, which belongs to the + // Go/WASM binary. Routing to it inside this SPA would resolve to /js and land you + // back where you started. + return ( + + + + + + Kjol JS Web + Solid + Go toolchain + + + ); +} + +function Sidebar() { + const location = useLocation(); + // The router's pathname is absolute (/js/kit); NAV paths are base-relative (/kit). + const active = (path: string) => location.pathname === "/js" + (path === "/" ? "" : path); + + return ( + + ); +} + +export function Shell(props: { children?: any }) { + // Once, at the root. The boot script in the document head has ALREADY put the right + // class on — this only syncs the toggle's signals with it and starts + // following the OS while the mode is "system". Calling it late is harmless; not + // calling it just leaves the button showing the wrong icon. + initTheme(); + + return ( +
+ {/* bg-surface/90, not bg-white/90: the translucent sticky bar has to be + translucent over whatever the surface currently IS. */} + + +
+ +
{props.children}
+
+
+ ); +} diff --git a/go/cmd/kjol-web/frontend/src/pages/Forms.tsx b/go/cmd/kjol-web/frontend/src/pages/Forms.tsx new file mode 100644 index 00000000..e6410c4f --- /dev/null +++ b/go/cmd/kjol-web/frontend/src/pages/Forms.tsx @@ -0,0 +1,220 @@ +// /js/forms — the form fields, and the masks that make them worth having. + +import { createSignal } from "solid-js"; +import { + FormInput, + FormLabel, + FormSelect, + FormTextarea, + FormCurrencyInput, + FormPercentInput, + FormPhoneInput, + FormEmailInput, + FormNumberInput, + FormCombobox, + FormMultiSelect, + FormFieldset, + US_STATES, +} from "@ui/Forms"; +import { ToggleSwitch } from "@ui/ToggleSwitch"; +import { ButtonUI, BUTTON_COLOR_PRIMARY } from "@ui/Buttons"; +import { AlertBlue } from "@ui/Alerts"; +import { isEmailValid } from "@ui/Validation"; +import { Demo } from "../layout/Demo.tsx"; + +export function Forms() { + const [name, setName] = createSignal(""); + const [email, setEmail] = createSignal(""); + const [amount, setAmount] = createSignal(""); + const [rate, setRate] = createSignal(""); + const [phone, setPhone] = createSignal(""); + const [term, setTerm] = createSignal("90"); + const [state, setState] = createSignal(""); + const [tags, setTags] = createSignal(["cd"]); + const [notify, setNotify] = createSignal(true); + const [notes, setNotes] = createSignal(""); + + // The error is a derived value, not a second piece of state — so it cannot get + // out of step with the field it describes. Blank is not "invalid", it is unfilled. + const emailError = () => (email() && !isEmailValid(email()) ? "That is not an email address." : ""); + + return ( +
+

Kjol JS Web

+

Forms

+

+ The fields carry their own input masks. A currency field will not let you type a letter into + it; a percent field keeps one trailing symbol; a phone field formats as you go. That behaviour + is in the component, not in the page — which is the only reason it is the same in every app. +

+ + + These are Solid components, so DOM handlers keep their DOM names:{" "} + oninput, onchange,{" "} + onclick — not onInput. It is the + single most common thing to get wrong when writing against this kit. + + + + email() && !isEmailValid(email()) ? "That is not an email address." : ""; + + setEmail(e.currentTarget.value)} + error={emailError()} + showIcon +/>`} + > +
+
+ Name + setName(e.currentTarget.value)} + /> +
+
+ Email + setEmail(e.currentTarget.value)} + error={emailError()} + showIcon + /> +
+
+
+ + + + +`} + > +
+
+ Amount + setAmount(e.currentTarget.value)} + /> +
+
+ Rate + setRate(e.currentTarget.value)} /> +
+
+ Phone + setPhone(e.currentTarget.value)} /> +
+
+ Whole number + +
+
+

+ Try typing letters into any of them. +

+
+ + + +`} + > +
+
+ Term (plain select) + setTerm(e.currentTarget.value)}> + + + + +
+
+ State (searchable) + +
+
+ Products (multi) + +
+
+

+ selected: {tags().join(", ") || "—"} +

+
+ + `} + > + + +
+ Notes + setNotes(e.currentTarget.value)} + /> +
+
+ +
+ + Save + + + {emailError() ? "Fix the email address first." : "The button disables itself off derived state."} + +
+
+
+ ); +} diff --git a/go/cmd/kjol-web/frontend/src/pages/Kit.tsx b/go/cmd/kjol-web/frontend/src/pages/Kit.tsx new file mode 100644 index 00000000..0dd66771 --- /dev/null +++ b/go/cmd/kjol-web/frontend/src/pages/Kit.tsx @@ -0,0 +1,199 @@ +// /js/kit — the components, running. + +import { createSignal, For } from "solid-js"; +import { + ButtonUI, + SegmentedButtons, + BUTTON_COLOR_PRIMARY, + BUTTON_COLOR_NEUTRAL, + BUTTON_COLOR_GREEN, + BUTTON_COLOR_RED, + BUTTON_COLOR_BLUE, +} from "@ui/Buttons"; +import { Badge, BADGE_GREEN, BADGE_RED, BADGE_BLUE, BADGE_AMBER, BADGE_NEUTRAL } from "@ui/Badges"; +import { AlertBlue, AlertGreen, AlertRed, AlertYellow } from "@ui/Alerts"; +import { Card, CardHeader } from "@ui/Cards"; +import { TabGroup } from "@ui/Tabs"; +import { Modal, ConfirmModal } from "@ui/Modal"; +import { Tooltip } from "@ui/Tooltips"; +import { Icon } from "@ui/Icons"; +import { Demo } from "../layout/Demo.tsx"; + +export function Kit() { + const [count, setCount] = createSignal(0); + const [seg, setSeg] = createSignal("day"); + const [modalOpen, setModalOpen] = createSignal(false); + const [confirmOpen, setConfirmOpen] = createSignal(false); + const [confirmed, setConfirmed] = createSignal(0); + + return ( +
+

Kjol JS Web

+

Components

+

+ Every component below is the real one from{" "} + @ui/*, imported + and rendered on this page. Nothing here is a picture of a component. +

+ + setCount(count() + 1)}> + Clicked {count()} times +`} + > +
+ setCount(count() + 1)}> + Clicked {count()} times + + Neutral + Green + Red + + Outline + + + Small + + + Disabled + +
+
+ + `} + > +
+ +

+ selected: {seg()} +

+
+
+ + Active`} + > +
+ + Active + + + Overdue + + Info + Pending + Draft +
+
+ + Your changes have been written.`} + > +
+ Your changes have been written. + The rate table refreshes every fifteen minutes. + Two rows are missing a maturity date. + The upload was rejected by the server. +
+
+ +

}, …]} />`} + > + Three accounts, two of them funded.

}, + { title: "Activity", badge: 3, content:

Three events since Tuesday.

}, + { title: "Settings", content:

Nothing configurable yet.

}, + ]} + /> +
+ + setModalOpen(false)} header="A modal"> + … + + +// no provider needed — it portals itself to document.body`} + > +
+ setModalOpen(true)}> + Open modal + + setConfirmOpen(true)}> + Delete something + + confirmed {confirmed()} times +
+ + setModalOpen(false)} header={

A modal

}> +

+ It portals itself to document.body, so it escapes any + ancestor with overflow: hidden or a transform — the two + things that silently clip a floating panel. +

+
+ + setConfirmOpen(false)} + onConfirm={() => setConfirmed(confirmed() + 1)} + title="Delete this?" + message="This cannot be undone. (Nothing is actually deleted — this is a docs page.)" + confirmText="Delete" + /> +
+ + `} + > +
+ + {(name) => ( + + + + + + )} + +
+

+ Only the icons actually referenced in the source are bundled. The registry for this whole + site is a few dozen paths, not FontAwesome's 41.5 MB kit. +

+
+ + + Not shown here +

+ The kit also carries a calendar, a date picker, popovers, an accordion, a signature pad, a + chart wrapper, a toast system, a guided-tour overlay and a fuzzy matcher. They are in{" "} + go/jsruntime/uikit. +

+
+
+ ); +} diff --git a/go/cmd/kjol-web/frontend/src/pages/Overview.tsx b/go/cmd/kjol-web/frontend/src/pages/Overview.tsx new file mode 100644 index 00000000..8e282afb --- /dev/null +++ b/go/cmd/kjol-web/frontend/src/pages/Overview.tsx @@ -0,0 +1,97 @@ +// /js — what the JS layer is, and how it is built. + +import { Card, CardHeader } from "@ui/Cards"; +import { AlertBlue } from "@ui/Alerts"; +import { CodeBox } from "@ui/General"; + +export function Overview() { + return ( +
+

Kjol JS Web

+

+ A Solid kit, built by a Go toolchain +

+ +

+ This layer is the original one: a Solid.js component kit — forms, tables, modals, menus, + tooltips, charts — that the applications shared before any of it was rewritten in Go. It is + still what those applications run. +

+

+ What is unusual is the build. There is no Node, no Vite, no Babel, and no{" "} + node_modules. + The TSX is compiled to Solid's runtime calls by a Go program, the CSS by a Go implementation + of Tailwind v4, and the whole thing is bundled by esbuild's Go API. The toolchain is a Go + package you import. +

+ +

The pipeline

+

+ One command builds this section. Every stage of it is Go: +

+ +
+ + + +
+ + + + + The single hardest invariant in this build is that there is exactly one copy of solid-js. Two + copies do not error — they render fine and then silently stop flushing effects, so onMount + never fires and nothing updates. kjol's vendor manifest is searched before the app's for + precisely this reason. + + +

What is on the other pages

+
+ + Components +

+ Buttons, badges, alerts, cards, tabs and menus — rendered live, not screenshotted. +

+
+ + Forms +

+ Masked inputs, comboboxes, multi-select, toggles, and the validation helpers. +

+
+ + AutoTable +

+ Sorting, search, column management, CSV export — from one array of column defs. +

+
+
+
+ ); +} + +function Stage(props: { n: string; title: string; body: string }) { + return ( +
+ + {props.n} + +
+

{props.title}

+

{props.body}

+
+
+ ); +} diff --git a/go/cmd/kjol-web/frontend/src/pages/Table.tsx b/go/cmd/kjol-web/frontend/src/pages/Table.tsx new file mode 100644 index 00000000..b7dfe313 --- /dev/null +++ b/go/cmd/kjol-web/frontend/src/pages/Table.tsx @@ -0,0 +1,167 @@ +// /js/table — AutoTable, driven by an array of column definitions. + +import AutoTable, { + AutoTableColumn, + AutoTableSearch, + AutoTableFilterFields, + TdLeft, + TdRight, + TdCenter, + COL_POS_LEFT, + COL_POS_RIGHT, + COL_POS_CENTER, + AUTOTABLE_SIZE_COMPACT, +} from "@ui/AutoTable"; +import { Badge, BADGE_GREEN, BADGE_RED, BADGE_NEUTRAL } from "@ui/Badges"; +import { AlertBlue } from "@ui/Alerts"; + +interface Institution { + name: string; + state: string; + term: string; + rate: number; + minimum: number; + status: "open" | "closed" | "waitlist"; +} + +// Static rows: the point of the page is the table, not where the rows came from. +// Swapping `data` for `url` is the only change needed to make it fetch, sort and +// paginate against a server instead. +const ROWS: Institution[] = [ + { name: "First Meridian Bank", state: "CA", term: "90 day", rate: 4.85, minimum: 1000, status: "open" }, + { name: "Harborline Credit Union", state: "WA", term: "180 day", rate: 5.1, minimum: 2500, status: "open" }, + { name: "Cascade Federal", state: "OR", term: "1 year", rate: 5.35, minimum: 500, status: "waitlist" }, + { name: "Ironwood Savings", state: "IL", term: "90 day", rate: 4.6, minimum: 10000, status: "closed" }, + { name: "Great Lakes Trust", state: "MI", term: "2 year", rate: 5.55, minimum: 1000, status: "open" }, + { name: "Sunbelt National", state: "TX", term: "180 day", rate: 4.95, minimum: 5000, status: "open" }, + { name: "Granite State Bank", state: "NH", term: "1 year", rate: 5.2, minimum: 2000, status: "waitlist" }, + { name: "Pacific Crest", state: "CA", term: "5 year", rate: 5.75, minimum: 25000, status: "open" }, + { name: "Copper Ridge Bank", state: "AZ", term: "90 day", rate: 4.4, minimum: 1000, status: "closed" }, + { name: "Bayou Community", state: "LA", term: "1 year", rate: 5.05, minimum: 1500, status: "open" }, + { name: "Northern Pine FCU", state: "MN", term: "2 year", rate: 5.45, minimum: 500, status: "open" }, + { name: "Chesapeake First", state: "MD", term: "180 day", rate: 4.75, minimum: 3000, status: "waitlist" }, +]; + +// The whole table is this list. Sorting, column ordering, hiding, resizing and CSV +// export are all driven from it — there is no per-column wiring anywhere else. +const COLUMNS: AutoTableColumn[] = [ + { displayName: "Institution", sortable: true, sortIdentifier: "name", displayPosition: COL_POS_LEFT }, + { displayName: "State", sortable: true, sortIdentifier: "state", displayPosition: COL_POS_CENTER, toggleable: true }, + { displayName: "Term", sortable: true, sortIdentifier: "term", displayPosition: COL_POS_LEFT }, + { + displayName: "Rate", + sortable: true, + sortIdentifier: "rate", + sortType: "numeric", + displayPosition: COL_POS_RIGHT, + csvValue: (i: Institution) => i.rate, + }, + { + displayName: "Minimum", + sortable: true, + sortIdentifier: "minimum", + sortType: "money", + displayPosition: COL_POS_RIGHT, + toggleable: true, + csvValue: (i: Institution) => i.minimum, + }, + { displayName: "Status", displayPosition: COL_POS_CENTER, sortable: true, sortIdentifier: "status" }, +]; + +const money = (n: number) => "$" + n.toLocaleString("en-US"); + +function StatusBadge(props: { status: Institution["status"] }) { + if (props.status === "open") return open; + if (props.status === "closed") return closed; + return waitlist; +} + +export function Table() { + return ( +
+

Kjol JS Web

+

AutoTable

+

+ One array of column definitions produces sorting, per-column search, column reordering by + drag, column show/hide, column resizing, pagination and CSV export. The page below writes no + table markup — only a rowRenderer{" "} + to say what a cell looks like. +

+ + + Sort by clicking a header. Drag a header to reorder. Use the toolbar to hide a column or + export what you are looking at. The column layout persists — it is keyed to localStorage, so + it survives a reload. + + +
+ ( + + ctx.setSearchValue("name", v)} + /> + ctx.setSearchValue("state", v)} + /> + + )} + rowRenderer={(item: Institution) => ( + <> + {item.name} + {item.state} + {item.term} + {item.rate.toFixed(2)}% + {money(item.minimum)} + + + + + )} + /> +
+ +
+

Local rows, or a server

+

+ This table is passed data. + Give it url instead and + the same column list drives a server-side query — the sort identifier becomes the sort key, + the search fields become query parameters, and pagination is handled for you. Nothing else + on the page changes. +

+

+ The Go/WASM layer has this same table, rewritten as Go returning a virtual DOM. Same + behaviour, no JavaScript — which is the whole argument the other half of this site is + making. +

+
+
+ ); +} diff --git a/go/cmd/kjol-web/frontend/src/pages/Theming.tsx b/go/cmd/kjol-web/frontend/src/pages/Theming.tsx new file mode 100644 index 00000000..3eea34bf --- /dev/null +++ b/go/cmd/kjol-web/frontend/src/pages/Theming.tsx @@ -0,0 +1,168 @@ +// /js/theming — how the kit is themed, and the switch that proves it. + +import { AlertBlue, AlertGreen } from "@ui/Alerts"; +import { Card, CardHeader } from "@ui/Cards"; +import { ButtonUI, BUTTON_COLOR_PRIMARY, BUTTON_COLOR_NEUTRAL, BUTTON_COLOR_WHITE } from "@ui/Buttons"; +import { Badge, BADGE_GREEN, BADGE_NEUTRAL } from "@ui/Badges"; +import { CodeBox } from "@ui/General"; +import { ThemeToggle, useTheme } from "@ui/Theme"; +import { Demo } from "../layout/Demo.tsx"; + +// The swatch class is written out in full, not built as "bg-" + name. Tailwind finds +// the classes it must compile by SCANNING THE SOURCE for literal strings — a +// concatenation is invisible to it, and every swatch here would come out colourless. +// It is the one thing about a utility CSS engine you cannot forget. +const TOKENS: { swatch: string; name: string; role: string }[] = [ + { swatch: "bg-surface", name: "surface", role: "the page" }, + { swatch: "bg-surface-muted", name: "surface-muted", role: "a recessed strip" }, + { swatch: "bg-surface-raised", name: "surface-raised", role: "a panel, a hover" }, + { swatch: "bg-surface-strong", name: "surface-strong", role: "a track, a divider fill" }, + { swatch: "bg-line", name: "line", role: "an ordinary border" }, + { swatch: "bg-line-strong", name: "line-strong", role: "a border that has to be seen" }, + { swatch: "bg-ink", name: "ink", role: "body text, headings" }, + { swatch: "bg-ink-soft", name: "ink-soft", role: "secondary text" }, + { swatch: "bg-ink-muted", name: "ink-muted", role: "captions, labels" }, + { swatch: "bg-ink-faint", name: "ink-faint", role: "placeholders, disabled" }, +]; + +export function Theming() { + const { isDark, mode } = useTheme(); + + return ( +
+

Kjol JS Web

+

Theming

+ +

+ No component in this kit names a colour. They say{" "} + bg-surface,{" "} + text-ink,{" "} + border-line — and + what those mean is decided in one place. That is the whole of the theme system, and it is why + dark mode is a rule that re-points ten variables rather than a{" "} + dark: variant on four hundred class strings. +

+ + +
+ +
+ currently {isDark() ? "dark" : "light"}, because + you asked for {mode()} +
+
+

+ Press it. Every component on every page of this section moves — none of them were told. + Your choice is remembered, and it is the same choice the Go/WASM section reads: + both halves of this site share one localStorage key, so the theme survives crossing between + two entirely different front-ends. +

+
+ +

The contract

+

+ These are the tokens a component is allowed to name. Each swatch below is drawn with the token + itself, so this table is not a picture of the theme — it is the theme, and it repaints + when you press the switch. +

+ +
+ {TOKENS.map((t, i) => ( +
0 ? "border-t border-line" : "") + } + > + + {t.name} + {t.role} +
+ ))} +
+ + + The Go/WASM kit uses these exact token names. A designer changes{" "} + surface once and both halves of the site move together — even + though one is Solid compiled by esbuild and the other is Go compiled to WebAssembly. + + +

Where a variant is still needed

+

+ Two things a re-pointed token cannot fix, so they are the only places the kit still carries a{" "} + dark: variant. +

+ +
+ + Coloured tints +

+ A red-50 wash is invisible on a near-black surface. An + alert's tint has to become a deep, transparent one — a different colour, not a + different value of the same one. +

+
+ + Fills that invert +

+ The neutral button is dark on a light page and light on a dark one — so its label must + invert with it. text-white would disappear the moment + the fill went pale. Hence three tokens, not one. +

+
+
+ + +
+ Neutral (inverts) + White (a surface) + Primary (a fill) + solid + fills stay put +
+
+ + + The theme class is applied by a ten-line script in the document head, before the stylesheet and + before any markup. The server cannot read localStorage, so it cannot know which theme to send; + if the class waited for the bundle, every dark-mode reader would get a white page and then have + it snatched away. It is the only hand-written JavaScript on the Go/WASM side of this site. + + + + + +`} + /> +
+ ); +} diff --git a/go/cmd/kjol-web/frontend/src/pages/public/PublicLayout.tsx b/go/cmd/kjol-web/frontend/src/pages/public/PublicLayout.tsx new file mode 100644 index 00000000..306e4957 --- /dev/null +++ b/go/cmd/kjol-web/frontend/src/pages/public/PublicLayout.tsx @@ -0,0 +1,73 @@ +// The chrome around every server-rendered public page. +// +// The bundler's SSR entry is hardcoded to import { PublicLayout } from this exact +// path and to call it with { currentPath, children } — it is a contract, not a +// convention. The client takeover (public.tsx) wraps the same body in the same +// layout with the same currentPath, which is what makes the server markup and the +// post-takeover markup identical. If they diverged, the page would visibly rebuild +// itself the moment the bundle landed. +// +// Deliberately plain. This renders inside goja against a DOM shim at BUILD time, +// where there is no layout, no getBoundingClientRect and no window — so nothing in +// here may measure the page. That rules out the kit's floating components (Menu, +// Tooltip, Popover), which is why the Layers menu is a row of links here and a real +// menu everywhere else. + +import { JSXElement } from "solid-js"; + +export function PublicLayout(props: { currentPath: string; children?: JSXElement }) { + return ( + + ); +} diff --git a/go/cmd/kjol-web/frontend/src/pages/public/Ssr.tsx b/go/cmd/kjol-web/frontend/src/pages/public/Ssr.tsx new file mode 100644 index 00000000..22bdf2a0 --- /dev/null +++ b/go/cmd/kjol-web/frontend/src/pages/public/Ssr.tsx @@ -0,0 +1,77 @@ +// A server-rendered public page. +// +// The SPA under /js/* is client-only: the browser gets an empty #app and Solid fills +// it. That is fine for a docs section behind a click, and wrong for anything a search +// engine or a slow phone has to read. +// +// This page takes the other route. The bundler renders it at BUILD time — the real +// component, executed in goja against a DOM shim — and bakes the resulting HTML into +// a Go registry (internal/handlers/public_pages.gen.go). The server ships that HTML +// directly, so the page is complete before any JavaScript loads. The client bundle +// then re-renders the same component over the top and it becomes interactive. +// +// serverData() is what makes it more than a static file: the handler can inject data +// for a request, and the SAME component renders it — on the server at request time, +// and again in the browser after takeover, from the same inlined JSON. No refetch, no +// flash of a skeleton. + +import { serverData } from "@kjol/ssr/serverData.ts"; + +interface BuildInfo { + renderedAt: string; + stage: string; +} + +export function Ssr() { + // Read inside the reactive body, never captured at module load — the value has to + // be observed at render time, and there are three different render times. + const info = () => serverData(); + + return ( +
+

Kjol JS Web

+

+ This page was rendered by Go +

+ +

+ Not by a Node renderer, and not in your browser. A Go program executed this Solid component + in an embedded JavaScript engine, serialized the DOM it produced, and compiled the result + into the server binary. View source: the markup arrived complete. +

+ + {/* No data → the skeleton. This is exactly what the build-time bake sees, because + the bake injects nothing; it is also what a crawler sees. With data injected at + request time, the same three lines render the real values instead. */} + {!info() ? ( +
+
+
+
+ ) : ( +
+
+
rendered at
+
{info()!.renderedAt}
+
+
+
stage
+
{info()!.stage}
+
+
+ )} + +

+ The skeleton above is the honest default. The bake runs with no data, so a component that + cannot render without data cannot be baked — which is a useful constraint to discover at build + time rather than in production. +

+ +

+ + Back to Kjol JS Web + +

+
+ ); +} diff --git a/go/cmd/kjol-web/frontend/src/pages/public/pages.ts b/go/cmd/kjol-web/frontend/src/pages/public/pages.ts new file mode 100644 index 00000000..927b0631 --- /dev/null +++ b/go/cmd/kjol-web/frontend/src/pages/public/pages.ts @@ -0,0 +1,30 @@ +// SINGLE SOURCE OF TRUTH for server-rendered public pages. +// +// Add an entry here, then write the component it points at, then run the bundler. +// It regenerates: +// - internal/handlers/public_pages.gen.go Go registry: route → + baked HTML +// - frontend/src/pages/public/routes.gen.ts client takeover map: route → component +// +// Both generated files are read back by code that is committed, so neither is +// optional — but neither is hand-edited either. + +export interface PublicPageDef { + path: string; // URL pathname + module: string; // component file, relative to frontend/src + component: string; // exported component name + title: string; // <title> text + dynamic?: boolean; // ISR: also bake the render bundle so the server can render + // this page with live data at request time +} + +export const publicPages: PublicPageDef[] = [ + { + path: "/js/ssr", + module: "pages/public/Ssr.tsx", + component: "Ssr", + title: "Server-rendered — Kjol JS Web", + // dynamic: the server may inject data for this route at request time, so bake + // the render bundle too, not just the static skeleton. + dynamic: true, + }, +]; diff --git a/go/cmd/kjol-web/frontend/src/pages/public/routes.gen.ts b/go/cmd/kjol-web/frontend/src/pages/public/routes.gen.ts new file mode 100644 index 00000000..23460ece --- /dev/null +++ b/go/cmd/kjol-web/frontend/src/pages/public/routes.gen.ts @@ -0,0 +1,17 @@ +// Code generated by cmd/bundle; DO NOT EDIT. +// Source: frontend/src/pages/public/pages.ts + +import { JSXElement } from "solid-js"; +import { Ssr } from "./Ssr.tsx"; + +// Body component for each public route, keyed by URL pathname. The client +// router (public.ts) renders these when navigating without a full reload. +export const publicRoutes: Record<string, () => JSXElement> = { + "/js/ssr": Ssr, +}; + +// <title> for each public route, applied by the client router on navigation +// (the first load gets its title from the server-rendered shell). +export const publicTitles: Record<string, string> = { + "/js/ssr": "Server-rendered — Kjol JS Web", +}; diff --git a/go/cmd/kjol-web/frontend/src/public.tsx b/go/cmd/kjol-web/frontend/src/public.tsx new file mode 100644 index 00000000..3772b819 --- /dev/null +++ b/go/cmd/kjol-web/frontend/src/public.tsx @@ -0,0 +1,35 @@ +// Client takeover for the server-rendered public pages. +// +// The server ships each page's HTML inside #page-root — fast first paint, readable by +// a crawler, works with JavaScript off. This boots the same component and swaps it in, +// making the page interactive. +// +// It wraps the body in the SAME PublicLayout with the SAME currentPath the build-time +// bake used (see jsbundler/genssr.go: ssrEntrySolid). That is not tidiness — if the two +// trees differed, the page would visibly rebuild itself the instant this bundle landed. +// +// It is a re-render takeover, not attach-hydration: Solid renders the client tree into +// a detached node FIRST, then replaces #page-root's children in one step. The server +// markup stays on screen until identical client markup is ready to replace it, so there +// is no window in which the page is half-built. + +import { render } from "solid-js/web"; +import { PublicLayout } from "./pages/public/PublicLayout.tsx"; +import { publicRoutes } from "./pages/public/routes.gen.ts"; + +const root = document.getElementById("page-root"); +const path = window.location.pathname; +const Body = root ? publicRoutes[path] : undefined; + +if (root && Body) { + const staging = document.createElement(root.tagName); + render( + () => ( + <PublicLayout currentPath={path}> + <Body /> + </PublicLayout> + ), + staging, + ); + root.replaceChildren(...staging.childNodes); +} diff --git a/go/cmd/kjol-web/frontend/vendor/pdf-lib/dist/pdf-lib.esm.js b/go/cmd/kjol-web/frontend/vendor/pdf-lib/dist/pdf-lib.esm.js new file mode 100644 index 00000000..b1cdfd57 --- /dev/null +++ b/go/cmd/kjol-web/frontend/vendor/pdf-lib/dist/pdf-lib.esm.js @@ -0,0 +1,39404 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; + +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} + +/* + * The `chars`, `lookup`, `encode`, and `decode` members of this file are + * licensed under the following: + * + * base64-arraybuffer + * https://github.com/niklasvh/base64-arraybuffer + * + * Copyright (c) 2012 Niklas von Hertzen + * Licensed under the MIT license. + * + */ +var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +// Use a lookup table to find the index. +var lookup = new Uint8Array(256); +for (var i = 0; i < chars.length; i++) { + lookup[chars.charCodeAt(i)] = i; +} +var encodeToBase64 = function (bytes) { + var base64 = ''; + var len = bytes.length; + for (var i = 0; i < len; i += 3) { + base64 += chars[bytes[i] >> 2]; + base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; + base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; + base64 += chars[bytes[i + 2] & 63]; + } + if (len % 3 === 2) { + base64 = base64.substring(0, base64.length - 1) + '='; + } + else if (len % 3 === 1) { + base64 = base64.substring(0, base64.length - 2) + '=='; + } + return base64; +}; +var decodeFromBase64 = function (base64) { + var bufferLength = base64.length * 0.75; + var len = base64.length; + var i; + var p = 0; + var encoded1; + var encoded2; + var encoded3; + var encoded4; + if (base64[base64.length - 1] === '=') { + bufferLength--; + if (base64[base64.length - 2] === '=') { + bufferLength--; + } + } + var bytes = new Uint8Array(bufferLength); + for (i = 0; i < len; i += 4) { + encoded1 = lookup[base64.charCodeAt(i)]; + encoded2 = lookup[base64.charCodeAt(i + 1)]; + encoded3 = lookup[base64.charCodeAt(i + 2)]; + encoded4 = lookup[base64.charCodeAt(i + 3)]; + bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); + bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); + bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); + } + return bytes; +}; +// This regex is designed to be as flexible as possible. It will parse certain +// invalid data URIs. +var DATA_URI_PREFIX_REGEX = /^(data)?:?([\w\/\+]+)?;?(charset=[\w-]+|base64)?.*,/i; +/** + * If the `dataUri` input is a data URI, then the data URI prefix must not be + * longer than 100 characters, or this function will fail to decode it. + * + * @param dataUri a base64 data URI or plain base64 string + * @returns a Uint8Array containing the decoded input + */ +var decodeFromBase64DataUri = function (dataUri) { + var trimmedUri = dataUri.trim(); + var prefix = trimmedUri.substring(0, 100); + var res = prefix.match(DATA_URI_PREFIX_REGEX); + // Assume it's not a data URI - just a plain base64 string + if (!res) + return decodeFromBase64(trimmedUri); + // Remove the data URI prefix and parse the remainder as a base64 string + var fullMatch = res[0]; + var data = trimmedUri.substring(fullMatch.length); + return decodeFromBase64(data); +}; + +var toCharCode = function (character) { return character.charCodeAt(0); }; +var toCodePoint = function (character) { return character.codePointAt(0); }; +var toHexStringOfMinLength = function (num, minLength) { + return padStart(num.toString(16), minLength, '0').toUpperCase(); +}; +var toHexString = function (num) { return toHexStringOfMinLength(num, 2); }; +var charFromCode = function (code) { return String.fromCharCode(code); }; +var charFromHexCode = function (hex) { return charFromCode(parseInt(hex, 16)); }; +var padStart = function (value, length, padChar) { + var padding = ''; + for (var idx = 0, len = length - value.length; idx < len; idx++) { + padding += padChar; + } + return padding + value; +}; +var copyStringIntoBuffer = function (str, buffer, offset) { + var length = str.length; + for (var idx = 0; idx < length; idx++) { + buffer[offset++] = str.charCodeAt(idx); + } + return length; +}; +var addRandomSuffix = function (prefix, suffixLength) { + if (suffixLength === void 0) { suffixLength = 4; } + return prefix + "-" + Math.floor(Math.random() * Math.pow(10, suffixLength)); +}; +var escapeRegExp = function (str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +}; +var cleanText = function (text) { + return text.replace(/\t|\u0085|\u2028|\u2029/g, ' ').replace(/[\b\v]/g, ''); +}; +var escapedNewlineChars = ['\\n', '\\f', '\\r', '\\u000B']; +var newlineChars = ['\n', '\f', '\r', '\u000B']; +var isNewlineChar = function (text) { return /^[\n\f\r\u000B]$/.test(text); }; +var lineSplit = function (text) { return text.split(/[\n\f\r\u000B]/); }; +var mergeLines = function (text) { + return text.replace(/[\n\f\r\u000B]/g, ' '); +}; +// JavaScript's String.charAt() method doesn work on strings containing UTF-16 +// characters (with high and low surrogate pairs), such as 💩 (poo emoji). This +// `charAtIndex()` function does. +// +// Credit: https://github.com/mathiasbynens/String.prototype.at/blob/master/at.js#L14-L48 +var charAtIndex = function (text, index) { + // Get the first code unit and code unit value + var cuFirst = text.charCodeAt(index); + var cuSecond; + var nextIndex = index + 1; + var length = 1; + if ( + // Check if it's the start of a surrogate pair. + cuFirst >= 0xd800 && + cuFirst <= 0xdbff && // high surrogate + text.length > nextIndex // there is a next code unit + ) { + cuSecond = text.charCodeAt(nextIndex); + if (cuSecond >= 0xdc00 && cuSecond <= 0xdfff) + length = 2; // low surrogate + } + return [text.slice(index, index + length), length]; +}; +var charSplit = function (text) { + var chars = []; + for (var idx = 0, len = text.length; idx < len;) { + var _a = charAtIndex(text, idx), c = _a[0], cLen = _a[1]; + chars.push(c); + idx += cLen; + } + return chars; +}; +var buildWordBreakRegex = function (wordBreaks) { + var newlineCharUnion = escapedNewlineChars.join('|'); + var escapedRules = ['$']; + for (var idx = 0, len = wordBreaks.length; idx < len; idx++) { + var wordBreak = wordBreaks[idx]; + if (isNewlineChar(wordBreak)) { + throw new TypeError("`wordBreak` must not include " + newlineCharUnion); + } + escapedRules.push(wordBreak === '' ? '.' : escapeRegExp(wordBreak)); + } + var breakRules = escapedRules.join('|'); + return new RegExp("(" + newlineCharUnion + ")|((.*?)(" + breakRules + "))", 'gm'); +}; +var breakTextIntoLines = function (text, wordBreaks, maxWidth, computeWidthOfText) { + var regex = buildWordBreakRegex(wordBreaks); + var words = cleanText(text).match(regex); + var currLine = ''; + var currWidth = 0; + var lines = []; + var pushCurrLine = function () { + if (currLine !== '') + lines.push(currLine); + currLine = ''; + currWidth = 0; + }; + for (var idx = 0, len = words.length; idx < len; idx++) { + var word = words[idx]; + if (isNewlineChar(word)) { + pushCurrLine(); + } + else { + var width = computeWidthOfText(word); + if (currWidth + width > maxWidth) + pushCurrLine(); + currLine += word; + currWidth += width; + } + } + pushCurrLine(); + return lines; +}; +// See section "7.9.4 Dates" of the PDF specification +var dateRegex = /^D:(\d\d\d\d)(\d\d)?(\d\d)?(\d\d)?(\d\d)?(\d\d)?([+\-Z])?(\d\d)?'?(\d\d)?'?$/; +var parseDate = function (dateStr) { + var match = dateStr.match(dateRegex); + if (!match) + return undefined; + var year = match[1], _a = match[2], month = _a === void 0 ? '01' : _a, _b = match[3], day = _b === void 0 ? '01' : _b, _c = match[4], hours = _c === void 0 ? '00' : _c, _d = match[5], mins = _d === void 0 ? '00' : _d, _e = match[6], secs = _e === void 0 ? '00' : _e, _f = match[7], offsetSign = _f === void 0 ? 'Z' : _f, _g = match[8], offsetHours = _g === void 0 ? '00' : _g, _h = match[9], offsetMins = _h === void 0 ? '00' : _h; + // http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15 + var tzOffset = offsetSign === 'Z' ? 'Z' : "" + offsetSign + offsetHours + ":" + offsetMins; + var date = new Date(year + "-" + month + "-" + day + "T" + hours + ":" + mins + ":" + secs + tzOffset); + return date; +}; +var findLastMatch = function (value, regex) { + var _a; + var position = 0; + var lastMatch; + while (position < value.length) { + var match = value.substring(position).match(regex); + if (!match) + return { match: lastMatch, pos: position }; + lastMatch = match; + position += ((_a = match.index) !== null && _a !== void 0 ? _a : 0) + match[0].length; + } + return { match: lastMatch, pos: position }; +}; + +var last = function (array) { return array[array.length - 1]; }; +// export const dropLast = <T>(array: T[]): T[] => +// array.slice(0, array.length - 1); +var typedArrayFor = function (value) { + if (value instanceof Uint8Array) + return value; + var length = value.length; + var typedArray = new Uint8Array(length); + for (var idx = 0; idx < length; idx++) { + typedArray[idx] = value.charCodeAt(idx); + } + return typedArray; +}; +var mergeIntoTypedArray = function () { + var arrays = []; + for (var _i = 0; _i < arguments.length; _i++) { + arrays[_i] = arguments[_i]; + } + var arrayCount = arrays.length; + var typedArrays = []; + for (var idx = 0; idx < arrayCount; idx++) { + var element = arrays[idx]; + typedArrays[idx] = + element instanceof Uint8Array ? element : typedArrayFor(element); + } + var totalSize = 0; + for (var idx = 0; idx < arrayCount; idx++) { + totalSize += arrays[idx].length; + } + var merged = new Uint8Array(totalSize); + var offset = 0; + for (var arrIdx = 0; arrIdx < arrayCount; arrIdx++) { + var arr = typedArrays[arrIdx]; + for (var byteIdx = 0, arrLen = arr.length; byteIdx < arrLen; byteIdx++) { + merged[offset++] = arr[byteIdx]; + } + } + return merged; +}; +var mergeUint8Arrays = function (arrays) { + var totalSize = 0; + for (var idx = 0, len = arrays.length; idx < len; idx++) { + totalSize += arrays[idx].length; + } + var mergedBuffer = new Uint8Array(totalSize); + var offset = 0; + for (var idx = 0, len = arrays.length; idx < len; idx++) { + var array = arrays[idx]; + mergedBuffer.set(array, offset); + offset += array.length; + } + return mergedBuffer; +}; +var arrayAsString = function (array) { + var str = ''; + for (var idx = 0, len = array.length; idx < len; idx++) { + str += charFromCode(array[idx]); + } + return str; +}; +var byAscendingId = function (a, b) { return a.id - b.id; }; +var sortedUniq = function (array, indexer) { + var uniq = []; + for (var idx = 0, len = array.length; idx < len; idx++) { + var curr = array[idx]; + var prev = array[idx - 1]; + if (idx === 0 || indexer(curr) !== indexer(prev)) { + uniq.push(curr); + } + } + return uniq; +}; +// Arrays and TypedArrays in JS both have .reverse() methods, which would seem +// to negate the need for this function. However, not all runtimes support this +// method (e.g. React Native). This function compensates for that fact. +var reverseArray = function (array) { + var arrayLen = array.length; + for (var idx = 0, len = Math.floor(arrayLen / 2); idx < len; idx++) { + var leftIdx = idx; + var rightIdx = arrayLen - idx - 1; + var temp = array[idx]; + array[leftIdx] = array[rightIdx]; + array[rightIdx] = temp; + } + return array; +}; +var sum = function (array) { + var total = 0; + for (var idx = 0, len = array.length; idx < len; idx++) { + total += array[idx]; + } + return total; +}; +var range = function (start, end) { + var arr = new Array(end - start); + for (var idx = 0, len = arr.length; idx < len; idx++) { + arr[idx] = start + idx; + } + return arr; +}; +var pluckIndices = function (arr, indices) { + var plucked = new Array(indices.length); + for (var idx = 0, len = indices.length; idx < len; idx++) { + plucked[idx] = arr[indices[idx]]; + } + return plucked; +}; +var canBeConvertedToUint8Array = function (input) { + return input instanceof Uint8Array || + input instanceof ArrayBuffer || + typeof input === 'string'; +}; +var toUint8Array = function (input) { + if (typeof input === 'string') { + return decodeFromBase64DataUri(input); + } + else if (input instanceof ArrayBuffer) { + return new Uint8Array(input); + } + else if (input instanceof Uint8Array) { + return input; + } + else { + throw new TypeError('`input` must be one of `string | ArrayBuffer | Uint8Array`'); + } +}; + +/** + * Returns a Promise that resolves after at least one tick of the + * Macro Task Queue occurs. + */ +var waitForTick = function () { + return new Promise(function (resolve) { + setTimeout(function () { return resolve(); }, 0); + }); +}; + +/** + * Encodes a string to UTF-8. + * + * @param input The string to be encoded. + * @param byteOrderMark Whether or not a byte order marker (BOM) should be added + * to the start of the encoding. (default `true`) + * @returns A Uint8Array containing the UTF-8 encoding of the input string. + * + * ----------------------------------------------------------------------------- + * + * JavaScript strings are composed of Unicode code points. Code points are + * integers in the range 0 to 1,114,111 (0x10FFFF). When serializing a string, + * it must be encoded as a sequence of words. A word is typically 8, 16, or 32 + * bytes in size. As such, Unicode defines three encoding forms: UTF-8, UTF-16, + * and UTF-32. These encoding forms are described in the Unicode standard [1]. + * This function implements the UTF-8 encoding form. + * + * ----------------------------------------------------------------------------- + * + * In UTF-8, each code point is mapped to a sequence of 1, 2, 3, or 4 bytes. + * Note that the logic which defines this mapping is slightly convoluted, and + * not as straightforward as the mapping logic for UTF-16 or UTF-32. The UTF-8 + * mapping logic is as follows [2]: + * + * • If a code point is in the range U+0000..U+007F, then view it as a 7-bit + * integer: 0bxxxxxxx. Map the code point to 1 byte with the first high order + * bit set to 0: + * + * b1=0b0xxxxxxx + * + * • If a code point is in the range U+0080..U+07FF, then view it as an 11-bit + * integer: 0byyyyyxxxxxx. Map the code point to 2 bytes with the first 5 bits + * of the code point stored in the first byte, and the last 6 bits stored in + * the second byte: + * + * b1=0b110yyyyy b2=0b10xxxxxx + * + * • If a code point is in the range U+0800..U+FFFF, then view it as a 16-bit + * integer, 0bzzzzyyyyyyxxxxxx. Map the code point to 3 bytes with the first + * 4 bits stored in the first byte, the next 6 bits stored in the second byte, + * and the last 6 bits in the third byte: + * + * b1=0b1110zzzz b2=0b10yyyyyy b3=0b10xxxxxx + * + * • If a code point is in the range U+10000...U+10FFFF, then view it as a + * 21-bit integer, 0bvvvzzzzzzyyyyyyxxxxxx. Map the code point to 4 bytes with + * the first 3 bits stored in the first byte, the next 6 bits stored in the + * second byte, the next 6 bits stored in the third byte, and the last 6 bits + * stored in the fourth byte: + * + * b1=0b11110xxx b2=0b10zzzzzz b3=0b10yyyyyy b4=0b10xxxxxx + * + * ----------------------------------------------------------------------------- + * + * It is important to note, when iterating through the code points of a string + * in JavaScript, that if a character is encoded as a surrogate pair it will + * increase the string's length by 2 instead of 1 [4]. For example: + * + * ``` + * > 'a'.length + * 1 + * > '💩'.length + * 2 + * > '語'.length + * 1 + * > 'a💩語'.length + * 4 + * ``` + * + * The results of the above example are explained by the fact that the + * characters 'a' and '語' are not represented by surrogate pairs, but '💩' is. + * + * Because of this idiosyncrasy in JavaScript's string implementation and APIs, + * we must "jump" an extra index after encoding a character as a surrogate + * pair. In practice, this means we must increment the index of our for loop by + * 2 if we encode a surrogate pair, and 1 in all other cases. + * + * ----------------------------------------------------------------------------- + * + * References: + * - [1] https://www.unicode.org/versions/Unicode12.0.0/UnicodeStandard-12.0.pdf + * 3.9 Unicode Encoding Forms - UTF-8 + * - [2] http://www.herongyang.com/Unicode/UTF-8-UTF-8-Encoding.html + * - [3] http://www.herongyang.com/Unicode/UTF-8-UTF-8-Encoding-Algorithm.html + * - [4] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length#Description + * + */ +var utf8Encode = function (input, byteOrderMark) { + if (byteOrderMark === void 0) { byteOrderMark = true; } + var encoded = []; + if (byteOrderMark) + encoded.push(0xef, 0xbb, 0xbf); + for (var idx = 0, len = input.length; idx < len;) { + var codePoint = input.codePointAt(idx); + // One byte encoding + if (codePoint < 0x80) { + var byte1 = codePoint & 0x7f; + encoded.push(byte1); + idx += 1; + } + // Two byte encoding + else if (codePoint < 0x0800) { + var byte1 = ((codePoint >> 6) & 0x1f) | 0xc0; + var byte2 = (codePoint & 0x3f) | 0x80; + encoded.push(byte1, byte2); + idx += 1; + } + // Three byte encoding + else if (codePoint < 0x010000) { + var byte1 = ((codePoint >> 12) & 0x0f) | 0xe0; + var byte2 = ((codePoint >> 6) & 0x3f) | 0x80; + var byte3 = (codePoint & 0x3f) | 0x80; + encoded.push(byte1, byte2, byte3); + idx += 1; + } + // Four byte encoding (surrogate pair) + else if (codePoint < 0x110000) { + var byte1 = ((codePoint >> 18) & 0x07) | 0xf0; + var byte2 = ((codePoint >> 12) & 0x3f) | 0x80; + var byte3 = ((codePoint >> 6) & 0x3f) | 0x80; + var byte4 = ((codePoint >> 0) & 0x3f) | 0x80; + encoded.push(byte1, byte2, byte3, byte4); + idx += 2; + } + // Should never reach this case + else + throw new Error("Invalid code point: 0x" + toHexString(codePoint)); + } + return new Uint8Array(encoded); +}; +/** + * Encodes a string to UTF-16. + * + * @param input The string to be encoded. + * @param byteOrderMark Whether or not a byte order marker (BOM) should be added + * to the start of the encoding. (default `true`) + * @returns A Uint16Array containing the UTF-16 encoding of the input string. + * + * ----------------------------------------------------------------------------- + * + * JavaScript strings are composed of Unicode code points. Code points are + * integers in the range 0 to 1,114,111 (0x10FFFF). When serializing a string, + * it must be encoded as a sequence of words. A word is typically 8, 16, or 32 + * bytes in size. As such, Unicode defines three encoding forms: UTF-8, UTF-16, + * and UTF-32. These encoding forms are described in the Unicode standard [1]. + * This function implements the UTF-16 encoding form. + * + * ----------------------------------------------------------------------------- + * + * In UTF-16, each code point is mapped to one or two 16-bit integers. The + * UTF-16 mapping logic is as follows [2]: + * + * • If a code point is in the range U+0000..U+FFFF, then map the code point to + * a 16-bit integer with the most significant byte first. + * + * • If a code point is in the range U+10000..U+10000, then map the code point + * to two 16-bit integers. The first integer should contain the high surrogate + * and the second integer should contain the low surrogate. Both surrogates + * should be written with the most significant byte first. + * + * ----------------------------------------------------------------------------- + * + * It is important to note, when iterating through the code points of a string + * in JavaScript, that if a character is encoded as a surrogate pair it will + * increase the string's length by 2 instead of 1 [4]. For example: + * + * ``` + * > 'a'.length + * 1 + * > '💩'.length + * 2 + * > '語'.length + * 1 + * > 'a💩語'.length + * 4 + * ``` + * + * The results of the above example are explained by the fact that the + * characters 'a' and '語' are not represented by surrogate pairs, but '💩' is. + * + * Because of this idiosyncrasy in JavaScript's string implementation and APIs, + * we must "jump" an extra index after encoding a character as a surrogate + * pair. In practice, this means we must increment the index of our for loop by + * 2 if we encode a surrogate pair, and 1 in all other cases. + * + * ----------------------------------------------------------------------------- + * + * References: + * - [1] https://www.unicode.org/versions/Unicode12.0.0/UnicodeStandard-12.0.pdf + * 3.9 Unicode Encoding Forms - UTF-8 + * - [2] http://www.herongyang.com/Unicode/UTF-16-UTF-16-Encoding.html + * - [3] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length#Description + * + */ +var utf16Encode = function (input, byteOrderMark) { + if (byteOrderMark === void 0) { byteOrderMark = true; } + var encoded = []; + if (byteOrderMark) + encoded.push(0xfeff); + for (var idx = 0, len = input.length; idx < len;) { + var codePoint = input.codePointAt(idx); + // Two byte encoding + if (codePoint < 0x010000) { + encoded.push(codePoint); + idx += 1; + } + // Four byte encoding (surrogate pair) + else if (codePoint < 0x110000) { + encoded.push(highSurrogate(codePoint), lowSurrogate(codePoint)); + idx += 2; + } + // Should never reach this case + else + throw new Error("Invalid code point: 0x" + toHexString(codePoint)); + } + return new Uint16Array(encoded); +}; +/** + * Returns `true` if the `codePoint` is within the + * Basic Multilingual Plane (BMP). Code points inside the BMP are not encoded + * with surrogate pairs. + * @param codePoint The code point to be evaluated. + * + * Reference: https://en.wikipedia.org/wiki/UTF-16#Description + */ +var isWithinBMP = function (codePoint) { + return codePoint >= 0 && codePoint <= 0xffff; +}; +/** + * Returns `true` if the given `codePoint` is valid and must be represented + * with a surrogate pair when encoded. + * @param codePoint The code point to be evaluated. + * + * Reference: https://en.wikipedia.org/wiki/UTF-16#Description + */ +var hasSurrogates = function (codePoint) { + return codePoint >= 0x010000 && codePoint <= 0x10ffff; +}; +// From Unicode 3.0 spec, section 3.7: +// http://unicode.org/versions/Unicode3.0.0/ch03.pdf +var highSurrogate = function (codePoint) { + return Math.floor((codePoint - 0x10000) / 0x400) + 0xd800; +}; +// From Unicode 3.0 spec, section 3.7: +// http://unicode.org/versions/Unicode3.0.0/ch03.pdf +var lowSurrogate = function (codePoint) { + return ((codePoint - 0x10000) % 0x400) + 0xdc00; +}; +var ByteOrder; +(function (ByteOrder) { + ByteOrder["BigEndian"] = "BigEndian"; + ByteOrder["LittleEndian"] = "LittleEndian"; +})(ByteOrder || (ByteOrder = {})); +var REPLACEMENT = '�'.codePointAt(0); +/** + * Decodes a Uint8Array of data to a string using UTF-16. + * + * Note that this function attempts to recover from erronous input by + * inserting the replacement character (�) to mark invalid code points + * and surrogate pairs. + * + * @param input A Uint8Array containing UTF-16 encoded data + * @param byteOrderMark Whether or not a byte order marker (BOM) should be read + * at the start of the encoding. (default `true`) + * @returns The decoded string. + */ +var utf16Decode = function (input, byteOrderMark) { + if (byteOrderMark === void 0) { byteOrderMark = true; } + // Need at least 2 bytes of data in UTF-16 encodings + if (input.length <= 1) + return String.fromCodePoint(REPLACEMENT); + var byteOrder = byteOrderMark ? readBOM(input) : ByteOrder.BigEndian; + // Skip byte order mark if needed + var idx = byteOrderMark ? 2 : 0; + var codePoints = []; + while (input.length - idx >= 2) { + var first = decodeValues(input[idx++], input[idx++], byteOrder); + if (isHighSurrogate(first)) { + if (input.length - idx < 2) { + // Need at least 2 bytes left for the low surrogate that is required + codePoints.push(REPLACEMENT); + } + else { + var second = decodeValues(input[idx++], input[idx++], byteOrder); + if (isLowSurrogate(second)) { + codePoints.push(first, second); + } + else { + // Low surrogates should always follow high surrogates + codePoints.push(REPLACEMENT); + } + } + } + else if (isLowSurrogate(first)) { + // High surrogates should always come first since `decodeValues()` + // accounts for the byte ordering + idx += 2; + codePoints.push(REPLACEMENT); + } + else { + codePoints.push(first); + } + } + // There shouldn't be extra byte(s) left over + if (idx < input.length) + codePoints.push(REPLACEMENT); + return String.fromCodePoint.apply(String, codePoints); +}; +/** + * Returns `true` if the given `codePoint` is a high surrogate. + * @param codePoint The code point to be evaluated. + * + * Reference: https://en.wikipedia.org/wiki/UTF-16#Description + */ +var isHighSurrogate = function (codePoint) { + return codePoint >= 0xd800 && codePoint <= 0xdbff; +}; +/** + * Returns `true` if the given `codePoint` is a low surrogate. + * @param codePoint The code point to be evaluated. + * + * Reference: https://en.wikipedia.org/wiki/UTF-16#Description + */ +var isLowSurrogate = function (codePoint) { + return codePoint >= 0xdc00 && codePoint <= 0xdfff; +}; +/** + * Decodes the given utf-16 values first and second using the specified + * byte order. + * @param first The first byte of the encoding. + * @param second The second byte of the encoding. + * @param byteOrder The byte order of the encoding. + * Reference: https://en.wikipedia.org/wiki/UTF-16#Examples + */ +var decodeValues = function (first, second, byteOrder) { + // Append the binary representation of the preceding byte by shifting the + // first one 8 to the left and than applying a bitwise or-operator to append + // the second one. + if (byteOrder === ByteOrder.LittleEndian) + return (second << 8) | first; + if (byteOrder === ByteOrder.BigEndian) + return (first << 8) | second; + throw new Error("Invalid byteOrder: " + byteOrder); +}; +/** + * Returns whether the given array contains a byte order mark for the + * UTF-16BE or UTF-16LE encoding. If it has neither, BigEndian is assumed. + * + * Reference: https://en.wikipedia.org/wiki/Byte_order_mark#UTF-16 + * + * @param bytes The byte array to be evaluated. + */ +// prettier-ignore +var readBOM = function (bytes) { return (hasUtf16BigEndianBOM(bytes) ? ByteOrder.BigEndian + : hasUtf16LittleEndianBOM(bytes) ? ByteOrder.LittleEndian + : ByteOrder.BigEndian); }; +var hasUtf16BigEndianBOM = function (bytes) { + return bytes[0] === 0xfe && bytes[1] === 0xff; +}; +var hasUtf16LittleEndianBOM = function (bytes) { + return bytes[0] === 0xff && bytes[1] === 0xfe; +}; +var hasUtf16BOM = function (bytes) { + return hasUtf16BigEndianBOM(bytes) || hasUtf16LittleEndianBOM(bytes); +}; + +// tslint:disable radix +/** + * Converts a number to its string representation in decimal. This function + * differs from simply converting a number to a string with `.toString()` + * because this function's output string will **not** contain exponential + * notation. + * + * Credit: https://stackoverflow.com/a/46545519 + */ +var numberToString = function (num) { + var numStr = String(num); + if (Math.abs(num) < 1.0) { + var e = parseInt(num.toString().split('e-')[1]); + if (e) { + var negative = num < 0; + if (negative) + num *= -1; + num *= Math.pow(10, e - 1); + numStr = '0.' + new Array(e).join('0') + num.toString().substring(2); + if (negative) + numStr = '-' + numStr; + } + } + else { + var e = parseInt(num.toString().split('+')[1]); + if (e > 20) { + e -= 20; + num /= Math.pow(10, e); + numStr = num.toString() + new Array(e + 1).join('0'); + } + } + return numStr; +}; +var sizeInBytes = function (n) { return Math.ceil(n.toString(2).length / 8); }; +/** + * Converts a number into its constituent bytes and returns them as + * a number[]. + * + * Returns most significant byte as first element in array. It may be necessary + * to call .reverse() to get the bits in the desired order. + * + * Example: + * bytesFor(0x02A41E) => [ 0b10, 0b10100100, 0b11110 ] + * + * Credit for algorithm: https://stackoverflow.com/a/1936865 + */ +var bytesFor = function (n) { + var bytes = new Uint8Array(sizeInBytes(n)); + for (var i = 1; i <= bytes.length; i++) { + bytes[i - 1] = n >> ((bytes.length - i) * 8); + } + return bytes; +}; + +var error = function (msg) { + throw new Error(msg); +}; + +function createCommonjsModule(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function (path, base) { + return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); + } + }, fn(module, module.exports), module.exports; +} + +function commonjsRequire () { + throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); +} + +var common = createCommonjsModule(function (module, exports) { + + +var TYPED_OK = (typeof Uint8Array !== 'undefined') && + (typeof Uint16Array !== 'undefined') && + (typeof Int32Array !== 'undefined'); + +function _has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +exports.assign = function (obj /*from1, from2, from3, ...*/) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { continue; } + + if (typeof source !== 'object') { + throw new TypeError(source + 'must be non-object'); + } + + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + + return obj; +}; + + +// reduce buffer size, avoiding mem copy +exports.shrinkBuf = function (buf, size) { + if (buf.length === size) { return buf; } + if (buf.subarray) { return buf.subarray(0, size); } + buf.length = size; + return buf; +}; + + +var fnTyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + var i, l, len, pos, chunk, result; + + // calculate data length + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + + // join chunks + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + + return result; + } +}; + +var fnUntyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + return [].concat.apply([], chunks); + } +}; + + +// Enable/Disable typed arrays use, for testing +// +exports.setTyped = function (on) { + if (on) { + exports.Buf8 = Uint8Array; + exports.Buf16 = Uint16Array; + exports.Buf32 = Int32Array; + exports.assign(exports, fnTyped); + } else { + exports.Buf8 = Array; + exports.Buf16 = Array; + exports.Buf32 = Array; + exports.assign(exports, fnUntyped); + } +}; + +exports.setTyped(TYPED_OK); +}); + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +/* eslint-disable space-unary-ops */ + + + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY = 0; +var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + +/*============================================================================*/ + + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK = 0; +var STATIC_TREES = 1; +var DYN_TREES = 2; +/* The three kinds of block type */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS = 256; +/* number of literal bytes 0..255 */ + +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES = 30; +/* number of distance codes */ + +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ + +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK = 256; +/* end of block literal code */ + +var REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +/* eslint-disable comma-spacing,array-bracket-spacing */ +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]; +/* eslint-enable comma-spacing,array-bracket-spacing */ + +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 +var static_ltree = new Array((L_CODES + 2) * 2); +zero(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree = new Array(D_CODES * 2); +zero(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code = new Array(DIST_CODE_LEN); +zero(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); +zero(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length = new Array(LENGTH_CODES); +zero(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist = new Array(D_CODES); +zero(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +} + + +var static_l_desc; +var static_d_desc; +var static_bl_desc; + + +function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +} + + + +function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short(s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code(s, c, tree) { + send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, + // "inconsistent bit counts"); + //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); + + for (n = 0; n <= max_code; n++) { + var len = tree[n * 2 + 1]/*.Len*/; + if (len === 0) { continue; } + /* Now reverse the bits */ + tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len); + + //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", + // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); + } +} + + +/* =========================================================================== + * Initialize the various 'constant' tables. + */ +function tr_static_init() { + var n; /* iterates over tree elements */ + var bits; /* bit counter */ + var length; /* length value */ + var code; /* code value */ + var dist; /* distance index */ + var bl_count = new Array(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ + + // do check in _tr_init() + //if (static_init_done) return; + + /* For some embedded targets, global variables are not initialized: */ +/*#ifdef NO_INIT_GLOBAL_POINTERS + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; +#endif*/ + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1]/*.Len*/ = 5; + static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup(s) +{ + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + common.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + + +var static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init(s) +{ + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +var _tr_init_1 = _tr_init; +var _tr_stored_block_1 = _tr_stored_block; +var _tr_flush_block_1 = _tr_flush_block; +var _tr_tally_1 = _tr_tally; +var _tr_align_1 = _tr_align; + +var trees = { + _tr_init: _tr_init_1, + _tr_stored_block: _tr_stored_block_1, + _tr_flush_block: _tr_flush_block_1, + _tr_tally: _tr_tally_1, + _tr_align: _tr_align_1 +}; + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It isn't worth it to make additional optimizations as in original. +// Small size is preferable. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + + +var adler32_1 = adler32; + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// Use ordinary array, since untyped makes no boost here +function makeTable() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + + +var crc32_1 = crc32; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var messages = { + 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) */ +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + + + + + + + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +var Z_NO_FLUSH = 0; +var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +//var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +//var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +//var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + + +/* compression levels */ +//var Z_NO_COMPRESSION = 0; +//var Z_BEST_SPEED = 1; +//var Z_BEST_COMPRESSION = 9; +var Z_DEFAULT_COMPRESSION = -1; + + +var Z_FILTERED = 1; +var Z_HUFFMAN_ONLY = 2; +var Z_RLE = 3; +var Z_FIXED$1 = 4; +var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//var Z_BINARY = 0; +//var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN$1 = 2; + + +/* The deflate compression method */ +var Z_DEFLATED = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL = 8; + + +var LENGTH_CODES$1 = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS$1 = 256; +/* number of literal bytes 0..255 */ +var L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES$1 = 30; +/* number of distance codes */ +var BL_CODES$1 = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE$1 = 2 * L_CODES$1 + 1; +/* maximum heap size */ +var MAX_BITS$1 = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH$1 = 3; +var MAX_MATCH$1 = 258; +var MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1); + +var PRESET_DICT = 0x20; + +var INIT_STATE = 42; +var EXTRA_STATE = 69; +var NAME_STATE = 73; +var COMMENT_STATE = 91; +var HCRC_STATE = 103; +var BUSY_STATE = 113; +var FINISH_STATE = 666; + +var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE = 2; /* block flush performed */ +var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +function err(strm, errorCode) { + strm.msg = messages[errorCode]; + return errorCode; +} + +function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero$1(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + common.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +} + + +function flush_block_only(s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +} + + +function put_byte(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + common.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32_1(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32_1(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH$1; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH$1 - (strend - scan); + scan = strend - MAX_MATCH$1; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + common.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH$1) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 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$1) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH$1) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH$1) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH$1) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH$1 - 1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH$1 - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH$1; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 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 - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH$1) { + fill_window(s); + if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH$1 && 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$1; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH$1 - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH$1) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH$1); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +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 */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero$1(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH$1 - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new common.Buf16(HEAP_SIZE$1 * 2); + this.dyn_dtree = new common.Buf16((2 * D_CODES$1 + 1) * 2); + this.bl_tree = new common.Buf16((2 * BL_CODES$1 + 1) * 2); + zero$1(this.dyn_ltree); + zero$1(this.dyn_dtree); + zero$1(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new common.Buf16(MAX_BITS$1 + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new common.Buf16(2 * L_CODES$1 + 1); /* heap used to build the Huffman trees */ + zero$1(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new common.Buf16(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1]; + zero$1(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN$1; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; +} + + +function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; +} + + +function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } + strm.state.gzhead = head; + return Z_OK; +} + + +function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED$1) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1); + + s.window = new common.Buf8(s.w_size * 2); + s.head = new common.Buf16(s.hash_size); + s.prev = new common.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new common.Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*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; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero$1(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { return Z_OK; } + if (s.wrap <= 0) { return Z_STREAM_END; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; +} + +function deflateEnd(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; +} + + +/* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ +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/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + 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; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0); + } + + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero$1(s.head); // Fill with NIL (= 0); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + tmpDict = new common.Buf8(s.w_size); + common.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + /* insert dictionary into window and hash */ + 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$1) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH$1 - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 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 - 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 - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; +} + + +var deflateInit_1 = deflateInit; +var deflateInit2_1 = deflateInit2; +var deflateReset_1 = deflateReset; +var deflateResetKeep_1 = deflateResetKeep; +var deflateSetHeader_1 = deflateSetHeader; +var deflate_2 = deflate; +var deflateEnd_1 = deflateEnd; +var deflateSetDictionary_1 = deflateSetDictionary; +var deflateInfo = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ + +var deflate_1 = { + deflateInit: deflateInit_1, + deflateInit2: deflateInit2_1, + deflateReset: deflateReset_1, + deflateResetKeep: deflateResetKeep_1, + deflateSetHeader: deflateSetHeader_1, + deflate: deflate_2, + deflateEnd: deflateEnd_1, + deflateSetDictionary: deflateSetDictionary_1, + deflateInfo: deflateInfo +}; + +// Quick check if we can use fast array to bin string conversion +// +// - apply(Array) can fail on Android 2.2 +// - apply(Uint8Array) can fail on iOS 5.1 Safari +// +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; } + + +// Table with utf8 lengths (calculated by first byte of sequence) +// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, +// because max possible codepoint is 0x10ffff +var _utf8len = new common.Buf8(256); +for (var q = 0; q < 256; q++) { + _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); +} +_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start + + +// convert string to array (typed, when possible) +var string2buf = function (str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + + // count binary size + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + } + + // allocate buffer + buf = new common.Buf8(buf_len); + + // convert + for (i = 0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + if (c < 0x80) { + /* one byte */ + buf[i++] = c; + } else if (c < 0x800) { + /* two bytes */ + buf[i++] = 0xC0 | (c >>> 6); + buf[i++] = 0x80 | (c & 0x3f); + } else if (c < 0x10000) { + /* three bytes */ + buf[i++] = 0xE0 | (c >>> 12); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } else { + /* four bytes */ + buf[i++] = 0xf0 | (c >>> 18); + buf[i++] = 0x80 | (c >>> 12 & 0x3f); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } + } + + return buf; +}; + +// Helper (used in 2 places) +function buf2binstring(buf, len) { + // On Chrome, the arguments in a function call that are allowed is `65534`. + // If the length of the buffer is smaller than that, we can use this optimization, + // otherwise we will take a slower path. + if (len < 65534) { + if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { + return String.fromCharCode.apply(null, common.shrinkBuf(buf, len)); + } + } + + var result = ''; + for (var i = 0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; +} + + +// Convert byte array to binary string +var buf2binstring_1 = function (buf) { + return buf2binstring(buf, buf.length); +}; + + +// Convert binary string (typed, when possible) +var binstring2buf = function (str) { + var buf = new common.Buf8(str.length); + for (var i = 0, len = buf.length; i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; +}; + + +// convert array to string +var buf2string = function (buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + + // Reserve max possible length (2 words per char) + // NB: by unknown reasons, Array is significantly faster for + // String.fromCharCode.apply than Uint16Array. + var utf16buf = new Array(len * 2); + + for (out = 0, i = 0; i < len;) { + c = buf[i++]; + // quick process ascii + if (c < 0x80) { utf16buf[out++] = c; continue; } + + c_len = _utf8len[c]; + // skip 5 & 6 byte codes + if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } + + // apply mask on first byte + c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; + // join the rest + while (c_len > 1 && i < len) { + c = (c << 6) | (buf[i++] & 0x3f); + c_len--; + } + + // terminated by end of string? + if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + + if (c < 0x10000) { + utf16buf[out++] = c; + } else { + c -= 0x10000; + utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); + utf16buf[out++] = 0xdc00 | (c & 0x3ff); + } + } + + return buf2binstring(utf16buf, out); +}; + + +// Calculate max possible position in utf8 buffer, +// that will not break sequence. If that's not possible +// - (very small limits) return max size as is. +// +// buf[] - utf8 bytes array +// max - length limit (mandatory); +var utf8border = function (buf, max) { + var pos; + + max = max || buf.length; + if (max > buf.length) { max = buf.length; } + + // go back from last position, until start of sequence found + pos = max - 1; + while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } + + // Very small and broken sequence, + // return max, because we should return something anyway. + if (pos < 0) { return max; } + + // If we came to start of buffer - that means buffer is too small, + // return max too. + if (pos === 0) { return max; } + + return (pos + _utf8len[buf[pos]] > max) ? pos : max; +}; + +var strings = { + string2buf: string2buf, + buf2binstring: buf2binstring_1, + binstring2buf: binstring2buf, + buf2string: buf2string, + utf8border: utf8border +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +var zstream = ZStream; + +var toString = Object.prototype.toString; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + +var Z_NO_FLUSH$1 = 0; +var Z_FINISH$1 = 4; + +var Z_OK$1 = 0; +var Z_STREAM_END$1 = 1; +var Z_SYNC_FLUSH = 2; + +var Z_DEFAULT_COMPRESSION$1 = -1; + +var Z_DEFAULT_STRATEGY$1 = 0; + +var Z_DEFLATED$1 = 8; + +/* ===========================================================================*/ + + +/** + * class Deflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[deflate]], + * [[deflateRaw]] and [[gzip]]. + **/ + +/* internal + * Deflate.chunks -> Array + * + * Chunks of output data, if [[Deflate#onData]] not overridden. + **/ + +/** + * Deflate.result -> Uint8Array|Array + * + * Compressed result, generated by default [[Deflate#onData]] + * and [[Deflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Deflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Deflate.err -> Number + * + * Error code after deflate finished. 0 (Z_OK) on success. + * You will not need it in real life, because deflate errors + * are possible only on wrong options or bad `onData` / `onEnd` + * custom handlers. + **/ + +/** + * Deflate.msg -> String + * + * Error message, if [[Deflate.err]] != 0 + **/ + + +/** + * new Deflate(options) + * - options (Object): zlib deflate options. + * + * Creates new deflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `level` + * - `windowBits` + * - `memLevel` + * - `strategy` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw deflate + * - `gzip` (Boolean) - create gzip wrapper + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * - `header` (Object) - custom header for gzip + * - `text` (Boolean) - true if compressed data believed to be text + * - `time` (Number) - modification time, unix timestamp + * - `os` (Number) - operation system code + * - `extra` (Array) - array of bytes with extra data (max 65536) + * - `name` (String) - file name (binary string) + * - `comment` (String) - comment (binary string) + * - `hcrc` (Boolean) - true if header crc should be added + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var deflate = new pako.Deflate({ level: 3}); + * + * deflate.push(chunk1, false); + * deflate.push(chunk2, true); // true -> last chunk + * + * if (deflate.err) { throw new Error(deflate.err); } + * + * console.log(deflate.result); + * ``` + **/ +function Deflate(options) { + if (!(this instanceof Deflate)) return new Deflate(options); + + this.options = common.assign({ + level: Z_DEFAULT_COMPRESSION$1, + method: Z_DEFLATED$1, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY$1, + 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; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new zstream(); + this.strm.avail_out = 0; + + var status = deflate_1.deflateInit2( + this.strm, + opt.level, + opt.method, + opt.windowBits, + opt.memLevel, + opt.strategy + ); + + if (status !== Z_OK$1) { + throw new Error(messages[status]); + } + + if (opt.header) { + deflate_1.deflateSetHeader(this.strm, opt.header); + } + + if (opt.dictionary) { + var dict; + // Convert data if needed + if (typeof opt.dictionary === 'string') { + // If we need to compress text, change encoding to utf8. + dict = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { + dict = new Uint8Array(opt.dictionary); + } else { + dict = opt.dictionary; + } + + status = deflate_1.deflateSetDictionary(this.strm, dict); + + if (status !== Z_OK$1) { + throw new Error(messages[status]); + } + + this._dict_set = true; + } +} + +/** + * Deflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be + * converted to utf8 byte sequence. + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with + * new compressed chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the compression context. + * + * On fail call [[Deflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * array format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +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$1 : Z_NO_FLUSH$1); + + // Convert data if needed + if (typeof data === 'string') { + // If we need to compress text, change encoding to utf8. + 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 common.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = deflate_1.deflate(strm, _mode); /* no bad return value */ + + if (status !== Z_STREAM_END$1 && status !== Z_OK$1) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH$1 || _mode === Z_SYNC_FLUSH))) { + if (this.options.to === 'string') { + this.onData(strings.buf2binstring(common.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(common.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END$1); + + // Finalize on the last chunk. + if (_mode === Z_FINISH$1) { + status = deflate_1.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK$1; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK$1); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Deflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Deflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Deflate#onEnd(status) -> Void + * - status (Number): deflate status. 0 (Z_OK) on success, + * other if not. + * + * Called once after you tell deflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Deflate.prototype.onEnd = function (status) { + // On success - join + if (status === Z_OK$1) { + if (this.options.to === 'string') { + this.result = this.chunks.join(''); + } else { + this.result = common.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * deflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * Compress `data` with deflate algorithm and `options`. + * + * Supported options are: + * + * - level + * - windowBits + * - memLevel + * - strategy + * - dictionary + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); + * + * console.log(pako.deflate(data)); + * ``` + **/ +function deflate$1(input, options) { + var deflator = new Deflate(options); + + deflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (deflator.err) { throw deflator.msg || messages[deflator.err]; } + + return deflator.result; +} + + +/** + * deflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate$1(input, options); +} + + +/** + * gzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but create gzip wrapper instead of + * deflate one. + **/ +function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate$1(input, options); +} + + +var Deflate_1 = Deflate; +var deflate_2$1 = deflate$1; +var deflateRaw_1 = deflateRaw; +var gzip_1 = gzip; + +var deflate_1$1 = { + Deflate: Deflate_1, + deflate: deflate_2$1, + deflateRaw: deflateRaw_1, + gzip: gzip_1 +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// See state defs from inflate.js +var BAD = 30; /* got a data error -- remain here until reset */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +var inffast = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + 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; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + + + +var MAXBITS = 15; +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]; + +var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]; + +var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]; + +var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]; + +var inftrees = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new common.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new common.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + + + + + + + +var CODES$1 = 0; +var LENS$1 = 1; +var DISTS$1 = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//var Z_NO_FLUSH = 0; +//var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +//var Z_FULL_FLUSH = 3; +var Z_FINISH$2 = 4; +var Z_BLOCK$1 = 5; +var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK$2 = 0; +var Z_STREAM_END$2 = 1; +var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR$1 = -2; +var Z_DATA_ERROR$1 = -3; +var Z_MEM_ERROR = -4; +var Z_BUF_ERROR$1 = -5; +//var Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +var Z_DEFLATED$2 = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD = 1; /* i: waiting for magic header */ +var FLAGS = 2; /* i: waiting for method and flags (gzip) */ +var TIME = 3; /* i: waiting for modification time (gzip) */ +var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN = 5; /* i: waiting for extra length (gzip) */ +var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +var NAME = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT = 8; /* i: waiting for end of comment (gzip) */ +var HCRC = 9; /* i: waiting for header crc (gzip) */ +var DICTID = 10; /* i: waiting for dictionary check value */ +var DICT = 11; /* waiting for inflateSetDictionary() call */ +var TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED = 14; /* i: waiting for stored size (length and complement) */ +var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +var COPY = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS = 18; /* i: waiting for code length code lengths */ +var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_ = 20; /* i: same as LEN below, but only first time in */ +var LEN = 21; /* i: waiting for length/lit/eob code */ +var LENEXT = 22; /* i: waiting for length extra bits */ +var DIST = 23; /* i: waiting for distance code */ +var DISTEXT = 24; /* i: waiting for distance extra bits */ +var MATCH = 25; /* o: waiting for output space to copy string */ +var LIT = 26; /* o: waiting for output space to write literal */ +var CHECK = 27; /* i: waiting for 32-bit check value */ +var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE = 29; /* finished check, done -- remain here until reset */ +var BAD$1 = 30; /* got a data error -- remain here until reset */ +var MEM = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS$1 = 852; +var ENOUGH_DISTS$1 = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS$1 = 15; +/* 32K LZ77 window */ +var DEF_WBITS = MAX_WBITS$1; + + +function zswap32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new common.Buf16(320); /* temporary storage for code lengths */ + this.work = new common.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR$1; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new common.Buf32(ENOUGH_LENS$1); + state.distcode = state.distdyn = new common.Buf32(ENOUGH_DISTS$1); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK$2; +} + +function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR$1; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +} + +function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR$1; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR$1; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +} + +function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR$1; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK$2) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin = true; + +var lenfix, distfix; // We have no pointers in JS, so keep tables separate + +function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new common.Buf32(512); + distfix = new common.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inftrees(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inftrees(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new common.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + common.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + common.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + common.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; +} + +function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new common.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR$1; + } + + state = strm.state; + if (state.mode === TYPE$1) { state.mode = TYPEDO; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK$2; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32_1(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD$1; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED$2) { + strm.msg = 'unknown compression method'; + state.mode = BAD$1; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD$1; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE$1; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED$2) { + strm.msg = 'unknown compression method'; + state.mode = BAD$1; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD$1; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32_1(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32_1(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32_1(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32_1(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more convenient processing later + state.head.extra = new Array(state.head.extra_len); + } + common.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32_1(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32_1(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32_1(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD$1; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE$1; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE$1; + /* falls through */ + case TYPE$1: + if (flush === Z_BLOCK$1 || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD$1; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD$1; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + common.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE$1; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD$1; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { bits: state.lenbits }; + ret = inftrees(CODES$1, 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$1; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD$1; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD$1; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD$1) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD$1; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { bits: state.lenbits }; + ret = inftrees(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD$1; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inftrees(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD$1; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inffast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE$1) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE$1; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD$1; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD$1; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD$1; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD$1; + break; + } +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' instead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD$1; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD$1; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END$2; + break inf_leave; + case BAD$1: + ret = Z_DATA_ERROR$1; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR$1; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$1 && + (state.mode < CHECK || flush !== Z_FINISH$2))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ; + } + _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_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE$1 ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH$2) && ret === Z_OK$2) { + ret = Z_BUF_ERROR$1; + } + return ret; +} + +function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR$1; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK$2; +} + +function inflateGetHeader(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR$1; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK$2; +} + +function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var state; + var dictid; + var ret; + + /* check state */ + if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR$1; } + state = strm.state; + + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR$1; + } + + /* check for correct dictionary identifier */ + if (state.mode === DICT) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32_1(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR$1; + } + } + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK$2; +} + +var inflateReset_1 = inflateReset; +var inflateReset2_1 = inflateReset2; +var inflateResetKeep_1 = inflateResetKeep; +var inflateInit_1 = inflateInit; +var inflateInit2_1 = inflateInit2; +var inflate_2 = inflate; +var inflateEnd_1 = inflateEnd; +var inflateGetHeader_1 = inflateGetHeader; +var inflateSetDictionary_1 = inflateSetDictionary; +var inflateInfo = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ + +var inflate_1 = { + inflateReset: inflateReset_1, + inflateReset2: inflateReset2_1, + inflateResetKeep: inflateResetKeep_1, + inflateInit: inflateInit_1, + inflateInit2: inflateInit2_1, + inflate: inflate_2, + inflateEnd: inflateEnd_1, + inflateGetHeader: inflateGetHeader_1, + inflateSetDictionary: inflateSetDictionary_1, + inflateInfo: inflateInfo +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var constants = { + + /* 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 +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function GZheader() { + /* true if compressed data believed to be text */ + this.text = 0; + /* modification time */ + this.time = 0; + /* extra flags (not used when writing a gzip file) */ + this.xflags = 0; + /* operating system */ + this.os = 0; + /* pointer to extra field or Z_NULL if none */ + this.extra = null; + /* extra field length (valid if extra != Z_NULL) */ + this.extra_len = 0; // Actually, we don't need it in JS, + // but leave for few code modifications + + // + // Setup limits is not necessary because in js we should not preallocate memory + // for inflate use constant limit in 65536 bytes + // + + /* space at extra (only when reading header) */ + // this.extra_max = 0; + /* pointer to zero-terminated file name or Z_NULL */ + this.name = ''; + /* space at name (only when reading header) */ + // this.name_max = 0; + /* pointer to zero-terminated comment or Z_NULL */ + this.comment = ''; + /* space at comment (only when reading header) */ + // this.comm_max = 0; + /* true if there was or will be a header crc */ + this.hcrc = 0; + /* true when done reading gzip header (not used when writing a gzip file) */ + this.done = false; +} + +var gzheader = GZheader; + +var toString$1 = Object.prototype.toString; + +/** + * class Inflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[inflate]] + * and [[inflateRaw]]. + **/ + +/* internal + * inflate.chunks -> Array + * + * Chunks of output data, if [[Inflate#onData]] not overridden. + **/ + +/** + * Inflate.result -> Uint8Array|Array|String + * + * Uncompressed result, generated by default [[Inflate#onData]] + * and [[Inflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Inflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Inflate.err -> Number + * + * Error code after inflate finished. 0 (Z_OK) on success. + * Should be checked if broken data possible. + **/ + +/** + * Inflate.msg -> String + * + * Error message, if [[Inflate.err]] != 0 + **/ + + +/** + * new Inflate(options) + * - options (Object): zlib inflate options. + * + * Creates new inflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `windowBits` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw inflate + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * By default, when no options set, autodetect deflate/gzip data format via + * wrapper header. + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var inflate = new pako.Inflate({ level: 3}); + * + * inflate.push(chunk1, false); + * inflate.push(chunk2, true); // true -> last chunk + * + * if (inflate.err) { throw new Error(inflate.err); } + * + * console.log(inflate.result); + * ``` + **/ +function Inflate(options) { + if (!(this instanceof Inflate)) return new Inflate(options); + + this.options = common.assign({ + chunkSize: 16384, + windowBits: 0, + to: '' + }, options || {}); + + var opt = this.options; + + // Force window size for `raw` data, if not set directly, + // because we have no header for autodetect. + if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { opt.windowBits = -15; } + } + + // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate + if ((opt.windowBits >= 0) && (opt.windowBits < 16) && + !(options && options.windowBits)) { + opt.windowBits += 32; + } + + // Gzip header has no info about windows size, we can do autodetect only + // for deflate. So, if window size not set, force it to max when gzip possible + if ((opt.windowBits > 15) && (opt.windowBits < 48)) { + // bit 3 (16) -> gzipped data + // bit 4 (32) -> autodetect gzip/deflate + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new zstream(); + this.strm.avail_out = 0; + + var status = inflate_1.inflateInit2( + this.strm, + opt.windowBits + ); + + if (status !== constants.Z_OK) { + throw new Error(messages[status]); + } + + this.header = new gzheader(); + + inflate_1.inflateGetHeader(this.strm, this.header); + + // Setup dictionary + if (opt.dictionary) { + // Convert data if needed + if (typeof opt.dictionary === 'string') { + opt.dictionary = strings.string2buf(opt.dictionary); + } else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') { + opt.dictionary = new Uint8Array(opt.dictionary); + } + if (opt.raw) { //In raw mode we need to set the dictionary early + status = inflate_1.inflateSetDictionary(this.strm, opt.dictionary); + if (status !== constants.Z_OK) { + throw new Error(messages[status]); + } + } + } +} + +/** + * Inflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with + * new output chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the decompression context. + * + * On fail call [[Inflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +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; + + // Flag to properly process Z_BUF_ERROR on testing inflate call + // when we check that all output data was flushed. + var allowBufError = false; + + if (this.ended) { return false; } + _mode = (mode === ~~mode) ? mode : ((mode === true) ? constants.Z_FINISH : constants.Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // Only binary strings can be decompressed on practice + strm.input = strings.binstring2buf(data); + } else if (toString$1.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 common.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + + status = inflate_1.inflate(strm, constants.Z_NO_FLUSH); /* no bad return value */ + + if (status === constants.Z_NEED_DICT && dictionary) { + status = inflate_1.inflateSetDictionary(this.strm, dictionary); + } + + if (status === constants.Z_BUF_ERROR && allowBufError === true) { + status = constants.Z_OK; + allowBufError = false; + } + + if (status !== constants.Z_STREAM_END && status !== constants.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + + if (strm.next_out) { + if (strm.avail_out === 0 || status === constants.Z_STREAM_END || (strm.avail_in === 0 && (_mode === constants.Z_FINISH || _mode === constants.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); + + // move tail + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { common.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } + + this.onData(utf8str); + + } else { + this.onData(common.shrinkBuf(strm.output, strm.next_out)); + } + } + } + + // When no more input data, we should check that internal inflate buffers + // are flushed. The only way to do it when avail_out = 0 - run one more + // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. + // Here we set flag to process this error properly. + // + // NOTE. Deflate does not return error in this case and does not needs such + // logic. + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== constants.Z_STREAM_END); + + if (status === constants.Z_STREAM_END) { + _mode = constants.Z_FINISH; + } + + // Finalize on the last chunk. + if (_mode === constants.Z_FINISH) { + status = inflate_1.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === constants.Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === constants.Z_SYNC_FLUSH) { + this.onEnd(constants.Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Inflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Inflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Inflate#onEnd(status) -> Void + * - status (Number): inflate status. 0 (Z_OK) on success, + * other if not. + * + * Called either after you tell inflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Inflate.prototype.onEnd = function (status) { + // On success - join + if (status === constants.Z_OK) { + if (this.options.to === 'string') { + // Glue & convert here, until we teach pako to send + // utf8 aligned strings to onData + this.result = this.chunks.join(''); + } else { + this.result = common.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * inflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Decompress `data` with inflate/ungzip and `options`. Autodetect + * format via wrapper header by default. That's why we don't provide + * separate `ungzip` method. + * + * Supported options are: + * + * - windowBits + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) + * , output; + * + * try { + * output = pako.inflate(input); + * } catch (err) + * console.log(err); + * } + * ``` + **/ +function inflate$1(input, options) { + var inflator = new Inflate(options); + + inflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (inflator.err) { throw inflator.msg || messages[inflator.err]; } + + return inflator.result; +} + + +/** + * inflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * The same as [[inflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function inflateRaw(input, options) { + options = options || {}; + options.raw = true; + return inflate$1(input, options); +} + + +/** + * ungzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Just shortcut to [[inflate]], because it autodetects format + * by header.content. Done for convenience. + **/ + + +var Inflate_1 = Inflate; +var inflate_2$1 = inflate$1; +var inflateRaw_1 = inflateRaw; +var ungzip = inflate$1; + +var inflate_1$1 = { + Inflate: Inflate_1, + inflate: inflate_2$1, + inflateRaw: inflateRaw_1, + ungzip: ungzip +}; + +var assign = common.assign; + + + + + +var pako = {}; + +assign(pako, deflate_1$1, inflate_1$1, constants); + +var pako_1 = pako; + +/* + * The `chars`, `lookup`, and `decodeFromBase64` members of this file are + * licensed under the following: + * + * base64-arraybuffer + * https://github.com/niklasvh/base64-arraybuffer + * + * Copyright (c) 2012 Niklas von Hertzen + * Licensed under the MIT license. + * + */ +var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +// Use a lookup table to find the index. +var lookup$1 = new Uint8Array(256); +for (var i$1 = 0; i$1 < chars$1.length; i$1++) { + lookup$1[chars$1.charCodeAt(i$1)] = i$1; +} +var decodeFromBase64$1 = function (base64) { + var bufferLength = base64.length * 0.75; + var len = base64.length; + var i; + var p = 0; + var encoded1; + var encoded2; + var encoded3; + var encoded4; + if (base64[base64.length - 1] === '=') { + bufferLength--; + if (base64[base64.length - 2] === '=') { + bufferLength--; + } + } + var bytes = new Uint8Array(bufferLength); + for (i = 0; i < len; i += 4) { + encoded1 = lookup$1[base64.charCodeAt(i)]; + encoded2 = lookup$1[base64.charCodeAt(i + 1)]; + encoded3 = lookup$1[base64.charCodeAt(i + 2)]; + encoded4 = lookup$1[base64.charCodeAt(i + 3)]; + bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); + bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); + bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); + } + return bytes; +}; +var arrayToString = function (array) { + var str = ''; + for (var i = 0; i < array.length; i++) { + str += String.fromCharCode(array[i]); + } + return str; +}; +var decompressJson = function (compressedJson) { + return arrayToString(pako_1.inflate(decodeFromBase64$1(compressedJson))); +}; +var padStart$1 = function (value, length, padChar) { + var padding = ''; + for (var idx = 0, len = length - value.length; idx < len; idx++) { + padding += padChar; + } + return padding + value; +}; + +var CourierBoldCompressed = "eJyFWdtyGjkQ/RVqnnar8Bb4lpg3jEnCxgEvGDtxKg9iphm01oyILrZxKv++mrGd3az6KC8UnNa0+nrUGr5lI11VVLtskF198FaU1Dns9w9OOkf7/ePDrJu90bWbiorCgpH2RpLZO9WqaCReqZ8lnReJqKTa/SwL8DXJctPs9Lxs4oSS+bAuVVjXC7/tG/lAxYV0+SYbOOOpm402wojckVlQ8+T4wVFdUDHXlaifrTs91Q/Z4PNeMLu7t3/U6746POm+7vW/dLNlWGuUrOlCW+mkrrPBXr/X+4/gciPz25qszQbhyeyKjG2XZb3ewR+9Xi/sMdVO5k+ebHemcaHzW/57p3/y+qQbPk967We//TxoP191hoVeUWexs44q25nUuTZbbYSj4o9OZ6hUZ97osZ05WTJ3AQ37jMOqQtblIt9QG7lWycKJuhCmeJGGhSOxffccyqPj/W728eXX4cFJNxvavAmRyQbH++HnGf34vdc/etXNFq54d50NXh+2X6/C137v+CnQH8gZmYdQfP6WXX8MCppQTYMlditCBL53/wfTQ65EFeNfvQ6erlQsqX21akJc1rGs0EoJE+NbMnlToZFAVEFkQ3iABW2uGH3CUK1ojUTgMWEbjfaWeUp5G6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5Kpuu0ApiToaGPSY0uaQsyr65L2oKi1yFt1PLaQ3lzfXTgXodGoJYzglndSLDMPg1sTPJpQJHJigw0QrGERqD9YhyTOgONQDUyuF1zaxuokc/BW2ztXCMrGZ9WMW1oQZHIXWNBkSCfRZEL5BMUiZw6CzVSFCfUSGZFNjIldoKDkonTKQiJIGzWmFd3BizJJ9SINoLDriOfUCOZS+zg+KGD1qGiLNMLxtJD1/ns00ON6EzyUCM6vbxhoBKaqbG3DFQCNiL1iHccBPV0DHhQH/JW8EW90dkyFKGywCJU0WkVSvSGeiSUODWFFD0HYdPQVoiRgfPMA+/nnRgiAyNYSjpWNQcNSMrtFCUH4ZIRpSCWocFCSuhCEY6hoUClc0WC52BJlCYYLQdhN+hygRRRlo5BKRRLS6oihSqh+ZzzRGG1Mo4Iz1LoP0qsxDGFzk0JE42ji0jCPejomJKCuwil4m5CiRMEUMVSzVLDUstSx1Juc0oVWMpqY295qVltmtWmWW2a1aZZbZrVplltmtWmWW2G1WZYbYbVZlhthtVmWG2G1WZYbYbVZlhtltVmWW2W1WZZbZbVZlltltVmWW2W1QYjQCh7E2aAQHeGhCFgPoNoy8KNb2wxBhmGKBxoUZXlLGsLI6AsftEDHV0wIURVbANLcTKlGGBIKPOAxCmhePCKUwFzAmpDFRQvjA9R06Hq8TONvshgKDCuRAZTXigUxjxNFfKRo3CLhnIJBMFRvMZpqpNBMlQJzGT5WFQMVQI/AikPMIhEU1aDjqJvQwmjSHB05cC9jbYwc5UtAHNLhDw41ha+lEqF4JaH3gmB61SYcqInxTDmQK8v08vjqv4zDf1N0w3Lf4A8/vwPpfK11w=="; + +// prettier-ignore +var compressedJsonForFontName = { + 'Courier': CourierCompressed, + 'Courier-Bold': CourierBoldCompressed, + 'Courier-Oblique': CourierObliqueCompressed, + 'Courier-BoldOblique': CourierBoldObliqueCompressed, + 'Helvetica': HelveticaCompressed, + 'Helvetica-Bold': HelveticaBoldCompressed, + 'Helvetica-Oblique': HelveticaObliqueCompressed, + 'Helvetica-BoldOblique': HelveticaBoldObliqueCompressed, + 'Times-Roman': TimesRomanCompressed, + 'Times-Bold': TimesBoldCompressed, + 'Times-Italic': TimesItalicCompressed, + 'Times-BoldItalic': TimesBoldItalicCompressed, + 'Symbol': SymbolCompressed, + 'ZapfDingbats': ZapfDingbatsCompressed, +}; +var FontNames; +(function (FontNames) { + FontNames["Courier"] = "Courier"; + FontNames["CourierBold"] = "Courier-Bold"; + FontNames["CourierOblique"] = "Courier-Oblique"; + FontNames["CourierBoldOblique"] = "Courier-BoldOblique"; + FontNames["Helvetica"] = "Helvetica"; + FontNames["HelveticaBold"] = "Helvetica-Bold"; + FontNames["HelveticaOblique"] = "Helvetica-Oblique"; + FontNames["HelveticaBoldOblique"] = "Helvetica-BoldOblique"; + FontNames["TimesRoman"] = "Times-Roman"; + FontNames["TimesRomanBold"] = "Times-Bold"; + FontNames["TimesRomanItalic"] = "Times-Italic"; + FontNames["TimesRomanBoldItalic"] = "Times-BoldItalic"; + FontNames["Symbol"] = "Symbol"; + FontNames["ZapfDingbats"] = "ZapfDingbats"; +})(FontNames || (FontNames = {})); +var fontCache = {}; +var Font = /** @class */ (function () { + function Font() { + var _this = this; + this.getWidthOfGlyph = function (glyphName) { + return _this.CharWidths[glyphName]; + }; + this.getXAxisKerningForPair = function (leftGlyphName, rightGlyphName) { + return (_this.KernPairXAmounts[leftGlyphName] || {})[rightGlyphName]; + }; + } + Font.load = function (fontName) { + var cachedFont = fontCache[fontName]; + if (cachedFont) + return cachedFont; + var json = decompressJson(compressedJsonForFontName[fontName]); + var font = Object.assign(new Font(), JSON.parse(json)); + font.CharWidths = font.CharMetrics.reduce(function (acc, metric) { + acc[metric.N] = metric.WX; + return acc; + }, {}); + font.KernPairXAmounts = font.KernPairs.reduce(function (acc, _a) { + var name1 = _a[0], name2 = _a[1], width = _a[2]; + if (!acc[name1]) + acc[name1] = {}; + acc[name1][name2] = width; + return acc; + }, {}); + fontCache[fontName] = font; + return font; + }; + return Font; +}()); + +var A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rGf+UE7Zk6wf+Mmi8EJ9ocFQnCC/WGBEJxgf3gDgddNNIp/WC3Mb12i24cHXIEfkcs3FzGDM/UPnnJjcKb+cQXOmfrHFThn6h/fgItO1z8+4IjO2P+0LBOdsX9znHgBKUYn7Id+Pkklvh3TCgtpX9DFhbSvll1I+1t0C3NfTBcX5v4IeSHv5sYxX7g7H86dt+/Wbpw7c+8XsLkz934Bmztz79+AzZ2+9w+4cmfww2ptZ/DDam1n8MPbtZ3GDw9rs9ui3KZPblw4tz8vJiuc208LhMK5/bRAKJzbT28gFE7wp9XCTvCnR1zO8ZeLw7Fwjj8tTlw4x78v0Ern+PcFWukc//4GWulE//6AonSu/7paxrn+zZ2YnRclRK/rBXJsCAjxh2cKEAWVJ02ku/wOoFv2+12XkmnODwHgW4uQGVbZ0uM7mAJ1b/68/JlpUMnWdy5MF6/Vd5eL19YYSPd6FqPwBkNQo/h2NQxdQQ3bn/dpCxrGrqCW7U8rKZl/mfi0Xytk3Am66ZhYbg4y+KAVslDwbXdNL2d5qU5hnYBlTZaa6hs2t1qWdaeeTptcLco+hl5R7w4H5uOGcQbtEkpT18GusOI2xT9dYcVJf7zCSjmbD+Iud2s1NPRb9E+0UICmizb8ZK/+5JOLOulSqwaw5VJr2vB8dSFn89fvv/8H0oq1dA=="; + +/* tslint:disable max-classes-per-file */ +var decompressedEncodings = decompressJson(AllEncodingsCompressed); +var allUnicodeMappings = JSON.parse(decompressedEncodings); +var Encoding = /** @class */ (function () { + function Encoding(name, unicodeMappings) { + var _this = this; + this.canEncodeUnicodeCodePoint = function (codePoint) { + return codePoint in _this.unicodeMappings; + }; + this.encodeUnicodeCodePoint = function (codePoint) { + var mapped = _this.unicodeMappings[codePoint]; + if (!mapped) { + var str = String.fromCharCode(codePoint); + var hexCode = "0x" + padStart$1(codePoint.toString(16), 4, '0'); + var msg = _this.name + " cannot encode \"" + str + "\" (" + hexCode + ")"; + throw new Error(msg); + } + return { code: mapped[0], name: mapped[1] }; + }; + this.name = name; + this.supportedCodePoints = Object.keys(unicodeMappings) + .map(Number) + .sort(function (a, b) { return a - b; }); + this.unicodeMappings = unicodeMappings; + } + return Encoding; +}()); +var Encodings = { + Symbol: new Encoding('Symbol', allUnicodeMappings.symbol), + ZapfDingbats: new Encoding('ZapfDingbats', allUnicodeMappings.zapfdingbats), + WinAnsi: new Encoding('WinAnsi', allUnicodeMappings.win1252), +}; + +var values = function (obj) { return Object.keys(obj).map(function (k) { return obj[k]; }); }; +var StandardFontValues = values(FontNames); +var isStandardFont = function (input) { + return StandardFontValues.includes(input); +}; +var rectanglesAreEqual = function (a, b) { return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height; }; + +/* tslint:disable:ban-types */ +var backtick = function (val) { return "`" + val + "`"; }; +var singleQuote = function (val) { return "'" + val + "'"; }; +// prettier-ignore +var formatValue = function (value) { + var type = typeof value; + if (type === 'string') + return singleQuote(value); + else if (type === 'undefined') + return backtick(value); + else + return value; +}; +var createValueErrorMsg = function (value, valueName, values) { + var allowedValues = new Array(values.length); + for (var idx = 0, len = values.length; idx < len; idx++) { + var v = values[idx]; + allowedValues[idx] = formatValue(v); + } + var joinedValues = allowedValues.join(' or '); + // prettier-ignore + return backtick(valueName) + " must be one of " + joinedValues + ", but was actually " + formatValue(value); +}; +var assertIsOneOf = function (value, valueName, allowedValues) { + if (!Array.isArray(allowedValues)) { + allowedValues = values(allowedValues); + } + for (var idx = 0, len = allowedValues.length; idx < len; idx++) { + if (value === allowedValues[idx]) + return; + } + throw new TypeError(createValueErrorMsg(value, valueName, allowedValues)); +}; +var assertIsOneOfOrUndefined = function (value, valueName, allowedValues) { + if (!Array.isArray(allowedValues)) { + allowedValues = values(allowedValues); + } + assertIsOneOf(value, valueName, allowedValues.concat(undefined)); +}; +var assertIsSubset = function (values$1, valueName, allowedValues) { + if (!Array.isArray(allowedValues)) { + allowedValues = values(allowedValues); + } + for (var idx = 0, len = values$1.length; idx < len; idx++) { + assertIsOneOf(values$1[idx], valueName, allowedValues); + } +}; +var getType = function (val) { + if (val === null) + return 'null'; + if (val === undefined) + return 'undefined'; + if (typeof val === 'string') + return 'string'; + if (isNaN(val)) + return 'NaN'; + if (typeof val === 'number') + return 'number'; + if (typeof val === 'boolean') + return 'boolean'; + if (typeof val === 'symbol') + return 'symbol'; + if (typeof val === 'bigint') + return 'bigint'; + if (val.constructor && val.constructor.name) + return val.constructor.name; + if (val.name) + return val.name; + if (val.constructor) + return String(val.constructor); + return String(val); +}; +var isType = function (value, type) { + if (type === 'null') + return value === null; + if (type === 'undefined') + return value === undefined; + if (type === 'string') + return typeof value === 'string'; + if (type === 'number') + return typeof value === 'number' && !isNaN(value); + if (type === 'boolean') + return typeof value === 'boolean'; + if (type === 'symbol') + return typeof value === 'symbol'; + if (type === 'bigint') + return typeof value === 'bigint'; + if (type === Date) + return value instanceof Date; + if (type === Array) + return value instanceof Array; + if (type === Uint8Array) + return value instanceof Uint8Array; + if (type === ArrayBuffer) + return value instanceof ArrayBuffer; + if (type === Function) + return value instanceof Function; + return value instanceof type[0]; +}; +var createTypeErrorMsg = function (value, valueName, types) { + var allowedTypes = new Array(types.length); + for (var idx = 0, len = types.length; idx < len; idx++) { + var type = types[idx]; + if (type === 'null') + allowedTypes[idx] = backtick('null'); + if (type === 'undefined') + allowedTypes[idx] = backtick('undefined'); + if (type === 'string') + allowedTypes[idx] = backtick('string'); + else if (type === 'number') + allowedTypes[idx] = backtick('number'); + else if (type === 'boolean') + allowedTypes[idx] = backtick('boolean'); + else if (type === 'symbol') + allowedTypes[idx] = backtick('symbol'); + else if (type === 'bigint') + allowedTypes[idx] = backtick('bigint'); + else if (type === Array) + allowedTypes[idx] = backtick('Array'); + else if (type === Uint8Array) + allowedTypes[idx] = backtick('Uint8Array'); + else if (type === ArrayBuffer) + allowedTypes[idx] = backtick('ArrayBuffer'); + else + allowedTypes[idx] = backtick(type[1]); + } + var joinedTypes = allowedTypes.join(' or '); + // prettier-ignore + return backtick(valueName) + " must be of type " + joinedTypes + ", but was actually of type " + backtick(getType(value)); +}; +var assertIs = function (value, valueName, types) { + for (var idx = 0, len = types.length; idx < len; idx++) { + if (isType(value, types[idx])) + return; + } + throw new TypeError(createTypeErrorMsg(value, valueName, types)); +}; +var assertOrUndefined = function (value, valueName, types) { + assertIs(value, valueName, types.concat('undefined')); +}; +var assertEachIs = function (values, valueName, types) { + for (var idx = 0, len = values.length; idx < len; idx++) { + assertIs(values[idx], valueName, types); + } +}; +var assertRange = function (value, valueName, min, max) { + assertIs(value, valueName, ['number']); + assertIs(min, 'min', ['number']); + assertIs(max, 'max', ['number']); + max = Math.max(min, max); + if (value < min || value > max) { + // prettier-ignore + throw new Error(backtick(valueName) + " must be at least " + min + " and at most " + max + ", but was actually " + value); + } +}; +var assertRangeOrUndefined = function (value, valueName, min, max) { + assertIs(value, valueName, ['number', 'undefined']); + if (typeof value === 'number') + assertRange(value, valueName, min, max); +}; +var assertMultiple = function (value, valueName, multiplier) { + assertIs(value, valueName, ['number']); + if (value % multiplier !== 0) { + // prettier-ignore + throw new Error(backtick(valueName) + " must be a multiple of " + multiplier + ", but was actually " + value); + } +}; +var assertInteger = function (value, valueName) { + if (!Number.isInteger(value)) { + throw new Error(backtick(valueName) + " must be an integer, but was actually " + value); + } +}; +var assertPositive = function (value, valueName) { + if (![1, 0].includes(Math.sign(value))) { + // prettier-ignore + throw new Error(backtick(valueName) + " must be a positive number or 0, but was actually " + value); + } +}; + +// Mapping from PDFDocEncoding to Unicode code point +var pdfDocEncodingToUnicode = new Uint16Array(256); +// Initialize the code points which are the same +for (var idx = 0; idx < 256; idx++) { + pdfDocEncodingToUnicode[idx] = idx; +} +// Set differences (see "Table D.2 – PDFDocEncoding Character Set" of the PDF spec) +pdfDocEncodingToUnicode[0x16] = toCharCode('\u0017'); // SYNCRONOUS IDLE +pdfDocEncodingToUnicode[0x18] = toCharCode('\u02D8'); // BREVE +pdfDocEncodingToUnicode[0x19] = toCharCode('\u02C7'); // CARON +pdfDocEncodingToUnicode[0x1a] = toCharCode('\u02C6'); // MODIFIER LETTER CIRCUMFLEX ACCENT +pdfDocEncodingToUnicode[0x1b] = toCharCode('\u02D9'); // DOT ABOVE +pdfDocEncodingToUnicode[0x1c] = toCharCode('\u02DD'); // DOUBLE ACUTE ACCENT +pdfDocEncodingToUnicode[0x1d] = toCharCode('\u02DB'); // OGONEK +pdfDocEncodingToUnicode[0x1e] = toCharCode('\u02DA'); // RING ABOVE +pdfDocEncodingToUnicode[0x1f] = toCharCode('\u02DC'); // SMALL TILDE +pdfDocEncodingToUnicode[0x7f] = toCharCode('\uFFFD'); // REPLACEMENT CHARACTER (box with questionmark) +pdfDocEncodingToUnicode[0x80] = toCharCode('\u2022'); // BULLET +pdfDocEncodingToUnicode[0x81] = toCharCode('\u2020'); // DAGGER +pdfDocEncodingToUnicode[0x82] = toCharCode('\u2021'); // DOUBLE DAGGER +pdfDocEncodingToUnicode[0x83] = toCharCode('\u2026'); // HORIZONTAL ELLIPSIS +pdfDocEncodingToUnicode[0x84] = toCharCode('\u2014'); // EM DASH +pdfDocEncodingToUnicode[0x85] = toCharCode('\u2013'); // EN DASH +pdfDocEncodingToUnicode[0x86] = toCharCode('\u0192'); // LATIN SMALL LETTER SCRIPT F +pdfDocEncodingToUnicode[0x87] = toCharCode('\u2044'); // FRACTION SLASH (solidus) +pdfDocEncodingToUnicode[0x88] = toCharCode('\u2039'); // SINGLE LEFT-POINTING ANGLE QUOTATION MARK +pdfDocEncodingToUnicode[0x89] = toCharCode('\u203A'); // SINGLE RIGHT-POINTING ANGLE QUOTATION MARK +pdfDocEncodingToUnicode[0x8a] = toCharCode('\u2212'); // MINUS SIGN +pdfDocEncodingToUnicode[0x8b] = toCharCode('\u2030'); // PER MILLE SIGN +pdfDocEncodingToUnicode[0x8c] = toCharCode('\u201E'); // DOUBLE LOW-9 QUOTATION MARK (quotedblbase) +pdfDocEncodingToUnicode[0x8d] = toCharCode('\u201C'); // LEFT DOUBLE QUOTATION MARK (quotedblleft) +pdfDocEncodingToUnicode[0x8e] = toCharCode('\u201D'); // RIGHT DOUBLE QUOTATION MARK (quotedblright) +pdfDocEncodingToUnicode[0x8f] = toCharCode('\u2018'); // LEFT SINGLE QUOTATION MARK (quoteleft) +pdfDocEncodingToUnicode[0x90] = toCharCode('\u2019'); // RIGHT SINGLE QUOTATION MARK (quoteright) +pdfDocEncodingToUnicode[0x91] = toCharCode('\u201A'); // SINGLE LOW-9 QUOTATION MARK (quotesinglbase) +pdfDocEncodingToUnicode[0x92] = toCharCode('\u2122'); // TRADE MARK SIGN +pdfDocEncodingToUnicode[0x93] = toCharCode('\uFB01'); // LATIN SMALL LIGATURE FI +pdfDocEncodingToUnicode[0x94] = toCharCode('\uFB02'); // LATIN SMALL LIGATURE FL +pdfDocEncodingToUnicode[0x95] = toCharCode('\u0141'); // LATIN CAPITAL LETTER L WITH STROKE +pdfDocEncodingToUnicode[0x96] = toCharCode('\u0152'); // LATIN CAPITAL LIGATURE OE +pdfDocEncodingToUnicode[0x97] = toCharCode('\u0160'); // LATIN CAPITAL LETTER S WITH CARON +pdfDocEncodingToUnicode[0x98] = toCharCode('\u0178'); // LATIN CAPITAL LETTER Y WITH DIAERESIS +pdfDocEncodingToUnicode[0x99] = toCharCode('\u017D'); // LATIN CAPITAL LETTER Z WITH CARON +pdfDocEncodingToUnicode[0x9a] = toCharCode('\u0131'); // LATIN SMALL LETTER DOTLESS I +pdfDocEncodingToUnicode[0x9b] = toCharCode('\u0142'); // LATIN SMALL LETTER L WITH STROKE +pdfDocEncodingToUnicode[0x9c] = toCharCode('\u0153'); // LATIN SMALL LIGATURE OE +pdfDocEncodingToUnicode[0x9d] = toCharCode('\u0161'); // LATIN SMALL LETTER S WITH CARON +pdfDocEncodingToUnicode[0x9e] = toCharCode('\u017E'); // LATIN SMALL LETTER Z WITH CARON +pdfDocEncodingToUnicode[0x9f] = toCharCode('\uFFFD'); // REPLACEMENT CHARACTER (box with questionmark) +pdfDocEncodingToUnicode[0xa0] = toCharCode('\u20AC'); // EURO SIGN +pdfDocEncodingToUnicode[0xad] = toCharCode('\uFFFD'); // REPLACEMENT CHARACTER (box with questionmark) +/** + * Decode a byte array into a string using PDFDocEncoding. + * + * @param bytes a byte array (decimal representation) containing a string + * encoded with PDFDocEncoding. + */ +var pdfDocEncodingDecode = function (bytes) { + var codePoints = new Array(bytes.length); + for (var idx = 0, len = bytes.length; idx < len; idx++) { + codePoints[idx] = pdfDocEncodingToUnicode[bytes[idx]]; + } + return String.fromCodePoint.apply(String, codePoints); +}; + +var Cache = /** @class */ (function () { + function Cache(populate) { + this.populate = populate; + this.value = undefined; + } + Cache.prototype.getValue = function () { + return this.value; + }; + Cache.prototype.access = function () { + if (!this.value) + this.value = this.populate(); + return this.value; + }; + Cache.prototype.invalidate = function () { + this.value = undefined; + }; + Cache.populatedBy = function (populate) { return new Cache(populate); }; + return Cache; +}()); + +var MethodNotImplementedError = /** @class */ (function (_super) { + __extends(MethodNotImplementedError, _super); + function MethodNotImplementedError(className, methodName) { + var _this = this; + var msg = "Method " + className + "." + methodName + "() not implemented"; + _this = _super.call(this, msg) || this; + return _this; + } + return MethodNotImplementedError; +}(Error)); +var PrivateConstructorError = /** @class */ (function (_super) { + __extends(PrivateConstructorError, _super); + function PrivateConstructorError(className) { + var _this = this; + var msg = "Cannot construct " + className + " - it has a private constructor"; + _this = _super.call(this, msg) || this; + return _this; + } + return PrivateConstructorError; +}(Error)); +var UnexpectedObjectTypeError = /** @class */ (function (_super) { + __extends(UnexpectedObjectTypeError, _super); + function UnexpectedObjectTypeError(expected, actual) { + var _this = this; + var name = function (t) { var _a, _b; return (_a = t === null || t === void 0 ? void 0 : t.name) !== null && _a !== void 0 ? _a : (_b = t === null || t === void 0 ? void 0 : t.constructor) === null || _b === void 0 ? void 0 : _b.name; }; + var expectedTypes = Array.isArray(expected) + ? expected.map(name) + : [name(expected)]; + var msg = "Expected instance of " + expectedTypes.join(' or ') + ", " + + ("but got instance of " + (actual ? name(actual) : actual)); + _this = _super.call(this, msg) || this; + return _this; + } + return UnexpectedObjectTypeError; +}(Error)); +var UnsupportedEncodingError = /** @class */ (function (_super) { + __extends(UnsupportedEncodingError, _super); + function UnsupportedEncodingError(encoding) { + var _this = this; + var msg = encoding + " stream encoding not supported"; + _this = _super.call(this, msg) || this; + return _this; + } + return UnsupportedEncodingError; +}(Error)); +var ReparseError = /** @class */ (function (_super) { + __extends(ReparseError, _super); + function ReparseError(className, methodName) { + var _this = this; + var msg = "Cannot call " + className + "." + methodName + "() more than once"; + _this = _super.call(this, msg) || this; + return _this; + } + return ReparseError; +}(Error)); +var MissingCatalogError = /** @class */ (function (_super) { + __extends(MissingCatalogError, _super); + function MissingCatalogError(ref) { + var _this = this; + var msg = "Missing catalog (ref=" + ref + ")"; + _this = _super.call(this, msg) || this; + return _this; + } + return MissingCatalogError; +}(Error)); +var MissingPageContentsEmbeddingError = /** @class */ (function (_super) { + __extends(MissingPageContentsEmbeddingError, _super); + function MissingPageContentsEmbeddingError() { + var _this = this; + var msg = "Can't embed page with missing Contents"; + _this = _super.call(this, msg) || this; + return _this; + } + return MissingPageContentsEmbeddingError; +}(Error)); +var UnrecognizedStreamTypeError = /** @class */ (function (_super) { + __extends(UnrecognizedStreamTypeError, _super); + function UnrecognizedStreamTypeError(stream) { + var _a, _b, _c; + var _this = this; + var streamType = (_c = (_b = (_a = stream === null || stream === void 0 ? void 0 : stream.contructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : stream === null || stream === void 0 ? void 0 : stream.name) !== null && _c !== void 0 ? _c : stream; + var msg = "Unrecognized stream type: " + streamType; + _this = _super.call(this, msg) || this; + return _this; + } + return UnrecognizedStreamTypeError; +}(Error)); +var PageEmbeddingMismatchedContextError = /** @class */ (function (_super) { + __extends(PageEmbeddingMismatchedContextError, _super); + function PageEmbeddingMismatchedContextError() { + var _this = this; + var msg = "Found mismatched contexts while embedding pages. All pages in the array passed to `PDFDocument.embedPages()` must be from the same document."; + _this = _super.call(this, msg) || this; + return _this; + } + return PageEmbeddingMismatchedContextError; +}(Error)); +var PDFArrayIsNotRectangleError = /** @class */ (function (_super) { + __extends(PDFArrayIsNotRectangleError, _super); + function PDFArrayIsNotRectangleError(size) { + var _this = this; + var msg = "Attempted to convert PDFArray with " + size + " elements to rectangle, but must have exactly 4 elements."; + _this = _super.call(this, msg) || this; + return _this; + } + return PDFArrayIsNotRectangleError; +}(Error)); +var InvalidPDFDateStringError = /** @class */ (function (_super) { + __extends(InvalidPDFDateStringError, _super); + function InvalidPDFDateStringError(value) { + var _this = this; + var msg = "Attempted to convert \"" + value + "\" to a date, but it does not match the PDF date string format."; + _this = _super.call(this, msg) || this; + return _this; + } + return InvalidPDFDateStringError; +}(Error)); +var InvalidTargetIndexError = /** @class */ (function (_super) { + __extends(InvalidTargetIndexError, _super); + function InvalidTargetIndexError(targetIndex, Count) { + var _this = this; + var msg = "Invalid targetIndex specified: targetIndex=" + targetIndex + " must be less than Count=" + Count; + _this = _super.call(this, msg) || this; + return _this; + } + return InvalidTargetIndexError; +}(Error)); +var CorruptPageTreeError = /** @class */ (function (_super) { + __extends(CorruptPageTreeError, _super); + function CorruptPageTreeError(targetIndex, operation) { + var _this = this; + var msg = "Failed to " + operation + " at targetIndex=" + targetIndex + " due to corrupt page tree: It is likely that one or more 'Count' entries are invalid"; + _this = _super.call(this, msg) || this; + return _this; + } + return CorruptPageTreeError; +}(Error)); +var IndexOutOfBoundsError = /** @class */ (function (_super) { + __extends(IndexOutOfBoundsError, _super); + function IndexOutOfBoundsError(index, min, max) { + var _this = this; + var msg = "index should be at least " + min + " and at most " + max + ", but was actually " + index; + _this = _super.call(this, msg) || this; + return _this; + } + return IndexOutOfBoundsError; +}(Error)); +var InvalidAcroFieldValueError = /** @class */ (function (_super) { + __extends(InvalidAcroFieldValueError, _super); + function InvalidAcroFieldValueError() { + var _this = this; + var msg = "Attempted to set invalid field value"; + _this = _super.call(this, msg) || this; + return _this; + } + return InvalidAcroFieldValueError; +}(Error)); +var MultiSelectValueError = /** @class */ (function (_super) { + __extends(MultiSelectValueError, _super); + function MultiSelectValueError() { + var _this = this; + var msg = "Attempted to select multiple values for single-select field"; + _this = _super.call(this, msg) || this; + return _this; + } + return MultiSelectValueError; +}(Error)); +var MissingDAEntryError = /** @class */ (function (_super) { + __extends(MissingDAEntryError, _super); + function MissingDAEntryError(fieldName) { + var _this = this; + var msg = "No /DA (default appearance) entry found for field: " + fieldName; + _this = _super.call(this, msg) || this; + return _this; + } + return MissingDAEntryError; +}(Error)); +var MissingTfOperatorError = /** @class */ (function (_super) { + __extends(MissingTfOperatorError, _super); + function MissingTfOperatorError(fieldName) { + var _this = this; + var msg = "No Tf operator found for DA of field: " + fieldName; + _this = _super.call(this, msg) || this; + return _this; + } + return MissingTfOperatorError; +}(Error)); +var NumberParsingError = /** @class */ (function (_super) { + __extends(NumberParsingError, _super); + function NumberParsingError(pos, value) { + var _this = this; + var msg = "Failed to parse number " + + ("(line:" + pos.line + " col:" + pos.column + " offset=" + pos.offset + "): \"" + value + "\""); + _this = _super.call(this, msg) || this; + return _this; + } + return NumberParsingError; +}(Error)); +var PDFParsingError = /** @class */ (function (_super) { + __extends(PDFParsingError, _super); + function PDFParsingError(pos, details) { + var _this = this; + var msg = "Failed to parse PDF document " + + ("(line:" + pos.line + " col:" + pos.column + " offset=" + pos.offset + "): " + details); + _this = _super.call(this, msg) || this; + return _this; + } + return PDFParsingError; +}(Error)); +var NextByteAssertionError = /** @class */ (function (_super) { + __extends(NextByteAssertionError, _super); + function NextByteAssertionError(pos, expectedByte, actualByte) { + var _this = this; + var msg = "Expected next byte to be " + expectedByte + " but it was actually " + actualByte; + _this = _super.call(this, pos, msg) || this; + return _this; + } + return NextByteAssertionError; +}(PDFParsingError)); +var PDFObjectParsingError = /** @class */ (function (_super) { + __extends(PDFObjectParsingError, _super); + function PDFObjectParsingError(pos, byte) { + var _this = this; + var msg = "Failed to parse PDF object starting with the following byte: " + byte; + _this = _super.call(this, pos, msg) || this; + return _this; + } + return PDFObjectParsingError; +}(PDFParsingError)); +var PDFInvalidObjectParsingError = /** @class */ (function (_super) { + __extends(PDFInvalidObjectParsingError, _super); + function PDFInvalidObjectParsingError(pos) { + var _this = this; + var msg = "Failed to parse invalid PDF object"; + _this = _super.call(this, pos, msg) || this; + return _this; + } + return PDFInvalidObjectParsingError; +}(PDFParsingError)); +var PDFStreamParsingError = /** @class */ (function (_super) { + __extends(PDFStreamParsingError, _super); + function PDFStreamParsingError(pos) { + var _this = this; + var msg = "Failed to parse PDF stream"; + _this = _super.call(this, pos, msg) || this; + return _this; + } + return PDFStreamParsingError; +}(PDFParsingError)); +var UnbalancedParenthesisError = /** @class */ (function (_super) { + __extends(UnbalancedParenthesisError, _super); + function UnbalancedParenthesisError(pos) { + var _this = this; + var msg = "Failed to parse PDF literal string due to unbalanced parenthesis"; + _this = _super.call(this, pos, msg) || this; + return _this; + } + return UnbalancedParenthesisError; +}(PDFParsingError)); +var StalledParserError = /** @class */ (function (_super) { + __extends(StalledParserError, _super); + function StalledParserError(pos) { + var _this = this; + var msg = "Parser stalled"; + _this = _super.call(this, pos, msg) || this; + return _this; + } + return StalledParserError; +}(PDFParsingError)); +var MissingPDFHeaderError = /** @class */ (function (_super) { + __extends(MissingPDFHeaderError, _super); + function MissingPDFHeaderError(pos) { + var _this = this; + var msg = "No PDF header found"; + _this = _super.call(this, pos, msg) || this; + return _this; + } + return MissingPDFHeaderError; +}(PDFParsingError)); +var MissingKeywordError = /** @class */ (function (_super) { + __extends(MissingKeywordError, _super); + function MissingKeywordError(pos, keyword) { + var _this = this; + var msg = "Did not find expected keyword '" + arrayAsString(keyword) + "'"; + _this = _super.call(this, pos, msg) || this; + return _this; + } + return MissingKeywordError; +}(PDFParsingError)); + +var CharCodes; +(function (CharCodes) { + CharCodes[CharCodes["Null"] = 0] = "Null"; + CharCodes[CharCodes["Backspace"] = 8] = "Backspace"; + CharCodes[CharCodes["Tab"] = 9] = "Tab"; + CharCodes[CharCodes["Newline"] = 10] = "Newline"; + CharCodes[CharCodes["FormFeed"] = 12] = "FormFeed"; + CharCodes[CharCodes["CarriageReturn"] = 13] = "CarriageReturn"; + CharCodes[CharCodes["Space"] = 32] = "Space"; + CharCodes[CharCodes["ExclamationPoint"] = 33] = "ExclamationPoint"; + CharCodes[CharCodes["Hash"] = 35] = "Hash"; + CharCodes[CharCodes["Percent"] = 37] = "Percent"; + CharCodes[CharCodes["LeftParen"] = 40] = "LeftParen"; + CharCodes[CharCodes["RightParen"] = 41] = "RightParen"; + CharCodes[CharCodes["Plus"] = 43] = "Plus"; + CharCodes[CharCodes["Minus"] = 45] = "Minus"; + CharCodes[CharCodes["Dash"] = 45] = "Dash"; + CharCodes[CharCodes["Period"] = 46] = "Period"; + CharCodes[CharCodes["ForwardSlash"] = 47] = "ForwardSlash"; + CharCodes[CharCodes["Zero"] = 48] = "Zero"; + CharCodes[CharCodes["One"] = 49] = "One"; + CharCodes[CharCodes["Two"] = 50] = "Two"; + CharCodes[CharCodes["Three"] = 51] = "Three"; + CharCodes[CharCodes["Four"] = 52] = "Four"; + CharCodes[CharCodes["Five"] = 53] = "Five"; + CharCodes[CharCodes["Six"] = 54] = "Six"; + CharCodes[CharCodes["Seven"] = 55] = "Seven"; + CharCodes[CharCodes["Eight"] = 56] = "Eight"; + CharCodes[CharCodes["Nine"] = 57] = "Nine"; + CharCodes[CharCodes["LessThan"] = 60] = "LessThan"; + CharCodes[CharCodes["GreaterThan"] = 62] = "GreaterThan"; + CharCodes[CharCodes["A"] = 65] = "A"; + CharCodes[CharCodes["D"] = 68] = "D"; + CharCodes[CharCodes["E"] = 69] = "E"; + CharCodes[CharCodes["F"] = 70] = "F"; + CharCodes[CharCodes["O"] = 79] = "O"; + CharCodes[CharCodes["P"] = 80] = "P"; + CharCodes[CharCodes["R"] = 82] = "R"; + CharCodes[CharCodes["LeftSquareBracket"] = 91] = "LeftSquareBracket"; + CharCodes[CharCodes["BackSlash"] = 92] = "BackSlash"; + CharCodes[CharCodes["RightSquareBracket"] = 93] = "RightSquareBracket"; + CharCodes[CharCodes["a"] = 97] = "a"; + CharCodes[CharCodes["b"] = 98] = "b"; + CharCodes[CharCodes["d"] = 100] = "d"; + CharCodes[CharCodes["e"] = 101] = "e"; + CharCodes[CharCodes["f"] = 102] = "f"; + CharCodes[CharCodes["i"] = 105] = "i"; + CharCodes[CharCodes["j"] = 106] = "j"; + CharCodes[CharCodes["l"] = 108] = "l"; + CharCodes[CharCodes["m"] = 109] = "m"; + CharCodes[CharCodes["n"] = 110] = "n"; + CharCodes[CharCodes["o"] = 111] = "o"; + CharCodes[CharCodes["r"] = 114] = "r"; + CharCodes[CharCodes["s"] = 115] = "s"; + CharCodes[CharCodes["t"] = 116] = "t"; + CharCodes[CharCodes["u"] = 117] = "u"; + CharCodes[CharCodes["x"] = 120] = "x"; + CharCodes[CharCodes["LeftCurly"] = 123] = "LeftCurly"; + CharCodes[CharCodes["RightCurly"] = 125] = "RightCurly"; + CharCodes[CharCodes["Tilde"] = 126] = "Tilde"; +})(CharCodes || (CharCodes = {})); +var CharCodes$1 = CharCodes; + +var common$1 = createCommonjsModule(function (module, exports) { + + +var TYPED_OK = (typeof Uint8Array !== 'undefined') && + (typeof Uint16Array !== 'undefined') && + (typeof Int32Array !== 'undefined'); + +function _has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +exports.assign = function (obj /*from1, from2, from3, ...*/) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { continue; } + + if (typeof source !== 'object') { + throw new TypeError(source + 'must be non-object'); + } + + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + + return obj; +}; + + +// reduce buffer size, avoiding mem copy +exports.shrinkBuf = function (buf, size) { + if (buf.length === size) { return buf; } + if (buf.subarray) { return buf.subarray(0, size); } + buf.length = size; + return buf; +}; + + +var fnTyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + var i, l, len, pos, chunk, result; + + // calculate data length + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + + // join chunks + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + + return result; + } +}; + +var fnUntyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + return [].concat.apply([], chunks); + } +}; + + +// Enable/Disable typed arrays use, for testing +// +exports.setTyped = function (on) { + if (on) { + exports.Buf8 = Uint8Array; + exports.Buf16 = Uint16Array; + exports.Buf32 = Int32Array; + exports.assign(exports, fnTyped); + } else { + exports.Buf8 = Array; + exports.Buf16 = Array; + exports.Buf32 = Array; + exports.assign(exports, fnUntyped); + } +}; + +exports.setTyped(TYPED_OK); +}); + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +/* eslint-disable space-unary-ops */ + + + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED$2 = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY$1 = 0; +var Z_TEXT$1 = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN$2 = 2; + +/*============================================================================*/ + + +function zero$2(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK$1 = 0; +var STATIC_TREES$1 = 1; +var DYN_TREES$1 = 2; +/* The three kinds of block type */ + +var MIN_MATCH$2 = 3; +var MAX_MATCH$2 = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES$2 = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS$2 = 256; +/* number of literal bytes 0..255 */ + +var L_CODES$2 = LITERALS$2 + 1 + LENGTH_CODES$2; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES$2 = 30; +/* number of distance codes */ + +var BL_CODES$2 = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE$2 = 2 * L_CODES$2 + 1; +/* maximum heap size */ + +var MAX_BITS$2 = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size$1 = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS$1 = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK$1 = 256; +/* end of block literal code */ + +var REP_3_6$1 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10$1 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138$1 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +/* eslint-disable comma-spacing,array-bracket-spacing */ +var extra_lbits$1 = /* 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$1 = /* 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$1 = /* 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$1 = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +/* eslint-enable comma-spacing,array-bracket-spacing */ + +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN$1 = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 +var static_ltree$1 = new Array((L_CODES$2 + 2) * 2); +zero$2(static_ltree$1); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree$1 = new Array(D_CODES$2 * 2); +zero$2(static_dtree$1); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code$1 = new Array(DIST_CODE_LEN$1); +zero$2(_dist_code$1); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code$1 = new Array(MAX_MATCH$2 - MIN_MATCH$2 + 1); +zero$2(_length_code$1); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length$1 = new Array(LENGTH_CODES$2); +zero$2(base_length$1); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist$1 = new Array(D_CODES$2); +zero$2(base_dist$1); +/* First normalized distance for each code (0 = distance of 1) */ + + +function StaticTreeDesc$1(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +} + + +var static_l_desc$1; +var static_d_desc$1; +var static_bl_desc$1; + + +function TreeDesc$1(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +} + + + +function d_code$1(dist) { + return dist < 256 ? _dist_code$1[dist] : _dist_code$1[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short$1(s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits$1(s, value, length) { + if (s.bi_valid > (Buf_size$1 - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short$1(s, s.bi_buf); + s.bi_buf = value >> (Buf_size$1 - s.bi_valid); + s.bi_valid += length - Buf_size$1; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code$1(s, c, tree) { + send_bits$1(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse$1(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush$1(s) { + if (s.bi_valid === 16) { + put_short$1(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen$1(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS$2; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE$2; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes$1(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS$2 + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS$2; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, + // "inconsistent bit counts"); + //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); + + for (n = 0; n <= max_code; n++) { + var len = tree[n * 2 + 1]/*.Len*/; + if (len === 0) { continue; } + /* Now reverse the bits */ + tree[n * 2]/*.Code*/ = bi_reverse$1(next_code[len]++, len); + + //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", + // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); + } +} + + +/* =========================================================================== + * Initialize the various 'constant' tables. + */ +function tr_static_init$1() { + var n; /* iterates over tree elements */ + var bits; /* bit counter */ + var length; /* length value */ + var code; /* code value */ + var dist; /* distance index */ + var bl_count = new Array(MAX_BITS$2 + 1); + /* number of codes at each bit length for an optimal tree */ + + // do check in _tr_init() + //if (static_init_done) return; + + /* For some embedded targets, global variables are not initialized: */ +/*#ifdef NO_INIT_GLOBAL_POINTERS + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; +#endif*/ + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES$2 - 1; code++) { + base_length$1[code] = length; + for (n = 0; n < (1 << extra_lbits$1[code]); n++) { + _length_code$1[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code$1[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist$1[code] = dist; + for (n = 0; n < (1 << extra_dbits$1[code]); n++) { + _dist_code$1[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES$2; code++) { + base_dist$1[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits$1[code] - 7)); n++) { + _dist_code$1[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS$2; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree$1[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree$1[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree$1[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree$1[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes$1(static_ltree$1, L_CODES$2 + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES$2; n++) { + static_dtree$1[n * 2 + 1]/*.Len*/ = 5; + static_dtree$1[n * 2]/*.Code*/ = bi_reverse$1(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc$1 = new StaticTreeDesc$1(static_ltree$1, extra_lbits$1, LITERALS$2 + 1, L_CODES$2, MAX_BITS$2); + static_d_desc$1 = new StaticTreeDesc$1(static_dtree$1, extra_dbits$1, 0, D_CODES$2, MAX_BITS$2); + static_bl_desc$1 = new StaticTreeDesc$1(new Array(0), extra_blbits$1, 0, BL_CODES$2, MAX_BL_BITS$1); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block$1(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES$2; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES$2; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES$2; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK$1 * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup$1(s) +{ + if (s.bi_valid > 8) { + put_short$1(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block$1(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup$1(s); /* align on byte boundary */ + + if (header) { + put_short$1(s, len); + put_short$1(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + common$1.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller$1(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap$1(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller$1(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller$1(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block$1(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code$1(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code$1[lc]; + send_code$1(s, code + LITERALS$2 + 1, ltree); /* send the length code */ + extra = extra_lbits$1[code]; + if (extra !== 0) { + lc -= base_length$1[code]; + send_bits$1(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code$1(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code$1(s, code, dtree); /* send the distance code */ + extra = extra_dbits$1[code]; + if (extra !== 0) { + dist -= base_dist$1[code]; + send_bits$1(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code$1(s, END_BLOCK$1, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree$1(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE$2; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap$1(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap$1(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap$1(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen$1(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes$1(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree$1(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6$1 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10$1 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138$1 * 2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree$1(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code$1(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code$1(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code$1(s, REP_3_6$1, s.bl_tree); + send_bits$1(s, count - 3, 2); + + } else if (count <= 10) { + send_code$1(s, REPZ_3_10$1, s.bl_tree); + send_bits$1(s, count - 3, 3); + + } else { + send_code$1(s, REPZ_11_138$1, s.bl_tree); + send_bits$1(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree$1(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree$1(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree$1(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree$1(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES$2 - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order$1[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees$1(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits$1(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits$1(s, dcodes - 1, 5); + send_bits$1(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits$1(s, s.bl_tree[bl_order$1[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree$1(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree$1(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type$1(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY$1; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT$1; + } + for (n = 32; n < LITERALS$2; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT$1; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY$1; +} + + +var static_init_done$1 = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init$1(s) +{ + + if (!static_init_done$1) { + tr_static_init$1(); + static_init_done$1 = true; + } + + s.l_desc = new TreeDesc$1(s.dyn_ltree, static_l_desc$1); + s.d_desc = new TreeDesc$1(s.dyn_dtree, static_d_desc$1); + s.bl_desc = new TreeDesc$1(s.bl_tree, static_bl_desc$1); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block$1(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block$1(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits$1(s, (STORED_BLOCK$1 << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block$1(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align$1(s) { + send_bits$1(s, STATIC_TREES$1 << 1, 3); + send_code$1(s, END_BLOCK$1, static_ltree$1); + bi_flush$1(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block$1(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN$2) { + s.strm.data_type = detect_data_type$1(s); + } + + /* Construct the literal and distance trees */ + build_tree$1(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree$1(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree$1(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block$1(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED$2 || static_lenb === opt_lenb) { + + send_bits$1(s, (STATIC_TREES$1 << 1) + (last ? 1 : 0), 3); + compress_block$1(s, static_ltree$1, static_dtree$1); + + } else { + send_bits$1(s, (DYN_TREES$1 << 1) + (last ? 1 : 0), 3); + send_all_trees$1(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block$1(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block$1(s); + + if (last) { + bi_windup$1(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally$1(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code$1[lc] + LITERALS$2 + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code$1(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +var _tr_init_1$1 = _tr_init$1; +var _tr_stored_block_1$1 = _tr_stored_block$1; +var _tr_flush_block_1$1 = _tr_flush_block$1; +var _tr_tally_1$1 = _tr_tally$1; +var _tr_align_1$1 = _tr_align$1; + +var trees$1 = { + _tr_init: _tr_init_1$1, + _tr_stored_block: _tr_stored_block_1$1, + _tr_flush_block: _tr_flush_block_1$1, + _tr_tally: _tr_tally_1$1, + _tr_align: _tr_align_1$1 +}; + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It isn't worth it to make additional optimizations as in original. +// Small size is preferable. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function adler32$1(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + + +var adler32_1$1 = adler32$1; + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// Use ordinary array, since untyped makes no boost here +function makeTable$1() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable$1 = makeTable$1(); + + +function crc32$1(crc, buf, len, pos) { + var t = crcTable$1, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + + +var crc32_1$1 = crc32$1; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var messages$1 = { + 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) */ +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + + + + + + + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +var Z_NO_FLUSH$2 = 0; +var Z_PARTIAL_FLUSH$1 = 1; +//var Z_SYNC_FLUSH = 2; +var Z_FULL_FLUSH$1 = 3; +var Z_FINISH$3 = 4; +var Z_BLOCK$2 = 5; +//var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK$3 = 0; +var Z_STREAM_END$3 = 1; +//var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR$2 = -2; +var Z_DATA_ERROR$2 = -3; +//var Z_MEM_ERROR = -4; +var Z_BUF_ERROR$2 = -5; +//var Z_VERSION_ERROR = -6; + + +/* compression levels */ +//var Z_NO_COMPRESSION = 0; +//var Z_BEST_SPEED = 1; +//var Z_BEST_COMPRESSION = 9; +var Z_DEFAULT_COMPRESSION$2 = -1; + + +var Z_FILTERED$1 = 1; +var Z_HUFFMAN_ONLY$1 = 2; +var Z_RLE$1 = 3; +var Z_FIXED$3 = 4; +var Z_DEFAULT_STRATEGY$2 = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//var Z_BINARY = 0; +//var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN$3 = 2; + + +/* The deflate compression method */ +var Z_DEFLATED$3 = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL$1 = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS$2 = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL$1 = 8; + + +var LENGTH_CODES$3 = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS$3 = 256; +/* number of literal bytes 0..255 */ +var L_CODES$3 = LITERALS$3 + 1 + LENGTH_CODES$3; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES$3 = 30; +/* number of distance codes */ +var BL_CODES$3 = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE$3 = 2 * L_CODES$3 + 1; +/* maximum heap size */ +var MAX_BITS$3 = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH$3 = 3; +var MAX_MATCH$3 = 258; +var MIN_LOOKAHEAD$1 = (MAX_MATCH$3 + MIN_MATCH$3 + 1); + +var PRESET_DICT$1 = 0x20; + +var INIT_STATE$1 = 42; +var EXTRA_STATE$1 = 69; +var NAME_STATE$1 = 73; +var COMMENT_STATE$1 = 91; +var HCRC_STATE$1 = 103; +var BUSY_STATE$1 = 113; +var FINISH_STATE$1 = 666; + +var BS_NEED_MORE$1 = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE$1 = 2; /* block flush performed */ +var BS_FINISH_STARTED$1 = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE$1 = 4; /* finish done, accept no more input or output */ + +var OS_CODE$1 = 0x03; // Unix :) . Don't detect, use this default. + +function err$1(strm, errorCode) { + strm.msg = messages$1[errorCode]; + return errorCode; +} + +function rank$1(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero$3(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending$1(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + common$1.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$1(s, last) { + trees$1._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$1(s.strm); +} + + +function put_byte$1(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB$1(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf$1(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + common$1.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32_1$1(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32_1$1(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match$1(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD$1)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD$1) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH$3; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH$3 - (strend - scan); + scan = strend - MAX_MATCH$3; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window$1(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD$1)) { + + common$1.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf$1(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH$3) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$3 - 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$3) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD$1 && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored$1(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window$1(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH$2) { + return BS_NEED_MORE$1; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$1(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$1; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD$1)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$1(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$1; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH$3) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only$1(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED$1; + } + /***/ + return BS_FINISH_DONE$1; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$1(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$1; + } + /***/ + } + + return BS_NEED_MORE$1; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast$1(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD$1) { + fill_window$1(s); + if (s.lookahead < MIN_LOOKAHEAD$1 && flush === Z_NO_FLUSH$2) { + return BS_NEED_MORE$1; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH$3) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$3 - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD$1))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match$1(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH$3) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees$1._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$3); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH$3) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$3 - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees$1._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$1(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$1; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH$3 - 1)) ? s.strstart : MIN_MATCH$3 - 1); + if (flush === Z_FINISH$3) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only$1(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED$1; + } + /***/ + return BS_FINISH_DONE$1; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$1(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$1; + } + /***/ + } + return BS_BLOCK_DONE$1; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow$1(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD$1) { + fill_window$1(s); + if (s.lookahead < MIN_LOOKAHEAD$1 && flush === Z_NO_FLUSH$2) { + return BS_NEED_MORE$1; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH$3) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$3 - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH$3 - 1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD$1)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match$1(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED$1 || (s.match_length === MIN_MATCH$3 && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH$3 - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH$3 && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH$3; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees$1._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$3); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$3 - 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$3 - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$1(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$1; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees$1._tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only$1(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$1; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees$1._tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH$3 - 1 ? s.strstart : MIN_MATCH$3 - 1; + if (flush === Z_FINISH$3) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only$1(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED$1; + } + /***/ + return BS_FINISH_DONE$1; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$1(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$1; + } + /***/ + } + + return BS_BLOCK_DONE$1; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle$1(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH$3) { + fill_window$1(s); + if (s.lookahead <= MAX_MATCH$3 && flush === Z_NO_FLUSH$2) { + return BS_NEED_MORE$1; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH$3 && 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$3; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH$3 - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH$3) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees$1._tr_tally(s, 1, s.match_length - MIN_MATCH$3); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees$1._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$1(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$1; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH$3) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only$1(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED$1; + } + /***/ + return BS_FINISH_DONE$1; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$1(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$1; + } + /***/ + } + return BS_BLOCK_DONE$1; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff$1(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window$1(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH$2) { + return BS_NEED_MORE$1; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees$1._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$1(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$1; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH$3) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only$1(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED$1; + } + /***/ + return BS_FINISH_DONE$1; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$1(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$1; + } + /***/ + } + return BS_BLOCK_DONE$1; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +function Config$1(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$1; + +configuration_table$1 = [ + /* good lazy nice chain */ + new Config$1(0, 0, 0, 0, deflate_stored$1), /* 0 store only */ + new Config$1(4, 4, 8, 4, deflate_fast$1), /* 1 max speed, no lazy matches */ + new Config$1(4, 5, 16, 8, deflate_fast$1), /* 2 */ + new Config$1(4, 6, 32, 32, deflate_fast$1), /* 3 */ + + new Config$1(4, 4, 16, 16, deflate_slow$1), /* 4 lazy matches */ + new Config$1(8, 16, 32, 32, deflate_slow$1), /* 5 */ + new Config$1(8, 16, 128, 128, deflate_slow$1), /* 6 */ + new Config$1(8, 32, 128, 256, deflate_slow$1), /* 7 */ + new Config$1(32, 128, 258, 1024, deflate_slow$1), /* 8 */ + new Config$1(32, 258, 258, 4096, deflate_slow$1) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init$1(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero$3(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table$1[s.level].max_lazy; + s.good_match = configuration_table$1[s.level].good_length; + s.nice_match = configuration_table$1[s.level].nice_length; + s.max_chain_length = configuration_table$1[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$3 - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState$1() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED$3; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new common$1.Buf16(HEAP_SIZE$3 * 2); + this.dyn_dtree = new common$1.Buf16((2 * D_CODES$3 + 1) * 2); + this.bl_tree = new common$1.Buf16((2 * BL_CODES$3 + 1) * 2); + zero$3(this.dyn_ltree); + zero$3(this.dyn_dtree); + zero$3(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new common$1.Buf16(MAX_BITS$3 + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new common$1.Buf16(2 * L_CODES$3 + 1); /* heap used to build the Huffman trees */ + zero$3(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new common$1.Buf16(2 * L_CODES$3 + 1); //uch depth[2*L_CODES+1]; + zero$3(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep$1(strm) { + var s; + + if (!strm || !strm.state) { + return err$1(strm, Z_STREAM_ERROR$2); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN$3; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE$1 : BUSY_STATE$1); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH$2; + trees$1._tr_init(s); + return Z_OK$3; +} + + +function deflateReset$1(strm) { + var ret = deflateResetKeep$1(strm); + if (ret === Z_OK$3) { + lm_init$1(strm.state); + } + return ret; +} + + +function deflateSetHeader$1(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR$2; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR$2; } + strm.state.gzhead = head; + return Z_OK$3; +} + + +function deflateInit2$1(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR$2; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION$2) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL$1 || method !== Z_DEFLATED$3 || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED$3) { + return err$1(strm, Z_STREAM_ERROR$2); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState$1(); + + 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$3 - 1) / MIN_MATCH$3); + + s.window = new common$1.Buf8(s.w_size * 2); + s.head = new common$1.Buf16(s.hash_size); + s.prev = new common$1.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new common$1.Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset$1(strm); +} + +function deflateInit$1(strm, level) { + return deflateInit2$1(strm, level, Z_DEFLATED$3, MAX_WBITS$2, DEF_MEM_LEVEL$1, Z_DEFAULT_STRATEGY$2); +} + + +function deflate$2(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK$2 || flush < 0) { + return strm ? err$1(strm, Z_STREAM_ERROR$2) : Z_STREAM_ERROR$2; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE$1 && flush !== Z_FINISH$3)) { + return err$1(strm, (strm.avail_out === 0) ? Z_BUF_ERROR$2 : Z_STREAM_ERROR$2); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE$1) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte$1(s, 31); + put_byte$1(s, 139); + put_byte$1(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte$1(s, 0); + put_byte$1(s, 0); + put_byte$1(s, 0); + put_byte$1(s, 0); + put_byte$1(s, 0); + put_byte$1(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY$1 || s.level < 2 ? + 4 : 0)); + put_byte$1(s, OS_CODE$1); + s.status = BUSY_STATE$1; + } + else { + put_byte$1(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$1(s, s.gzhead.time & 0xff); + put_byte$1(s, (s.gzhead.time >> 8) & 0xff); + put_byte$1(s, (s.gzhead.time >> 16) & 0xff); + put_byte$1(s, (s.gzhead.time >> 24) & 0xff); + put_byte$1(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY$1 || s.level < 2 ? + 4 : 0)); + put_byte$1(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte$1(s, s.gzhead.extra.length & 0xff); + put_byte$1(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32_1$1(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE$1; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED$3 + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY$1 || 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$1; } + header += 31 - (header % 31); + + s.status = BUSY_STATE$1; + putShortMSB$1(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB$1(s, strm.adler >>> 16); + putShortMSB$1(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE$1) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1$1(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending$1(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte$1(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1$1(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE$1; + } + } + else { + s.status = NAME_STATE$1; + } + } + if (s.status === NAME_STATE$1) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1$1(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending$1(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte$1(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1$1(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE$1; + } + } + else { + s.status = COMMENT_STATE$1; + } + } + if (s.status === COMMENT_STATE$1) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1$1(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending$1(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte$1(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1$1(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE$1; + } + } + else { + s.status = HCRC_STATE$1; + } + } + if (s.status === HCRC_STATE$1) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending$1(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte$1(s, strm.adler & 0xff); + put_byte$1(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE$1; + } + } + else { + s.status = BUSY_STATE$1; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending$1(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK$3; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank$1(flush) <= rank$1(old_flush) && + flush !== Z_FINISH$3) { + return err$1(strm, Z_BUF_ERROR$2); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE$1 && strm.avail_in !== 0) { + return err$1(strm, Z_BUF_ERROR$2); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH$2 && s.status !== FINISH_STATE$1)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY$1) ? deflate_huff$1(s, flush) : + (s.strategy === Z_RLE$1 ? deflate_rle$1(s, flush) : + configuration_table$1[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED$1 || bstate === BS_FINISH_DONE$1) { + s.status = FINISH_STATE$1; + } + if (bstate === BS_NEED_MORE$1 || bstate === BS_FINISH_STARTED$1) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK$3; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE$1) { + if (flush === Z_PARTIAL_FLUSH$1) { + trees$1._tr_align(s); + } + else if (flush !== Z_BLOCK$2) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees$1._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH$1) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero$3(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending$1(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK$3; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH$3) { return Z_OK$3; } + if (s.wrap <= 0) { return Z_STREAM_END$3; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte$1(s, strm.adler & 0xff); + put_byte$1(s, (strm.adler >> 8) & 0xff); + put_byte$1(s, (strm.adler >> 16) & 0xff); + put_byte$1(s, (strm.adler >> 24) & 0xff); + put_byte$1(s, strm.total_in & 0xff); + put_byte$1(s, (strm.total_in >> 8) & 0xff); + put_byte$1(s, (strm.total_in >> 16) & 0xff); + put_byte$1(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB$1(s, strm.adler >>> 16); + putShortMSB$1(s, strm.adler & 0xffff); + } + + flush_pending$1(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK$3 : Z_STREAM_END$3; +} + +function deflateEnd$1(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR$2; + } + + status = strm.state.status; + if (status !== INIT_STATE$1 && + status !== EXTRA_STATE$1 && + status !== NAME_STATE$1 && + status !== COMMENT_STATE$1 && + status !== HCRC_STATE$1 && + status !== BUSY_STATE$1 && + status !== FINISH_STATE$1 + ) { + return err$1(strm, Z_STREAM_ERROR$2); + } + + strm.state = null; + + return status === BUSY_STATE$1 ? err$1(strm, Z_DATA_ERROR$2) : Z_OK$3; +} + + +/* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ +function deflateSetDictionary$1(strm, dictionary) { + var dictLength = dictionary.length; + + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR$2; + } + + s = strm.state; + wrap = s.wrap; + + if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE$1) || s.lookahead) { + return Z_STREAM_ERROR$2; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32_1$1(strm.adler, dictionary, dictLength, 0); + } + + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero$3(s.head); // Fill with NIL (= 0); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + tmpDict = new common$1.Buf8(s.w_size); + common$1.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + /* insert dictionary into window and hash */ + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window$1(s); + while (s.lookahead >= MIN_MATCH$3) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH$3 - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$3 - 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$3 - 1; + fill_window$1(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$3 - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK$3; +} + + +var deflateInit_1$1 = deflateInit$1; +var deflateInit2_1$1 = deflateInit2$1; +var deflateReset_1$1 = deflateReset$1; +var deflateResetKeep_1$1 = deflateResetKeep$1; +var deflateSetHeader_1$1 = deflateSetHeader$1; +var deflate_2$2 = deflate$2; +var deflateEnd_1$1 = deflateEnd$1; +var deflateSetDictionary_1$1 = deflateSetDictionary$1; +var deflateInfo$1 = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ + +var deflate_1$2 = { + deflateInit: deflateInit_1$1, + deflateInit2: deflateInit2_1$1, + deflateReset: deflateReset_1$1, + deflateResetKeep: deflateResetKeep_1$1, + deflateSetHeader: deflateSetHeader_1$1, + deflate: deflate_2$2, + deflateEnd: deflateEnd_1$1, + deflateSetDictionary: deflateSetDictionary_1$1, + deflateInfo: deflateInfo$1 +}; + +// Quick check if we can use fast array to bin string conversion +// +// - apply(Array) can fail on Android 2.2 +// - apply(Uint8Array) can fail on iOS 5.1 Safari +// +var STR_APPLY_OK$1 = true; +var STR_APPLY_UIA_OK$1 = true; + +try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK$1 = false; } +try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK$1 = false; } + + +// Table with utf8 lengths (calculated by first byte of sequence) +// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, +// because max possible codepoint is 0x10ffff +var _utf8len$1 = new common$1.Buf8(256); +for (var q$1 = 0; q$1 < 256; q$1++) { + _utf8len$1[q$1] = (q$1 >= 252 ? 6 : q$1 >= 248 ? 5 : q$1 >= 240 ? 4 : q$1 >= 224 ? 3 : q$1 >= 192 ? 2 : 1); +} +_utf8len$1[254] = _utf8len$1[254] = 1; // Invalid sequence start + + +// convert string to array (typed, when possible) +var string2buf$1 = function (str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + + // count binary size + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + } + + // allocate buffer + buf = new common$1.Buf8(buf_len); + + // convert + for (i = 0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + if (c < 0x80) { + /* one byte */ + buf[i++] = c; + } else if (c < 0x800) { + /* two bytes */ + buf[i++] = 0xC0 | (c >>> 6); + buf[i++] = 0x80 | (c & 0x3f); + } else if (c < 0x10000) { + /* three bytes */ + buf[i++] = 0xE0 | (c >>> 12); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } else { + /* four bytes */ + buf[i++] = 0xf0 | (c >>> 18); + buf[i++] = 0x80 | (c >>> 12 & 0x3f); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } + } + + return buf; +}; + +// Helper (used in 2 places) +function buf2binstring$1(buf, len) { + // On Chrome, the arguments in a function call that are allowed is `65534`. + // If the length of the buffer is smaller than that, we can use this optimization, + // otherwise we will take a slower path. + if (len < 65534) { + if ((buf.subarray && STR_APPLY_UIA_OK$1) || (!buf.subarray && STR_APPLY_OK$1)) { + return String.fromCharCode.apply(null, common$1.shrinkBuf(buf, len)); + } + } + + var result = ''; + for (var i = 0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; +} + + +// Convert byte array to binary string +var buf2binstring_1$1 = function (buf) { + return buf2binstring$1(buf, buf.length); +}; + + +// Convert binary string (typed, when possible) +var binstring2buf$1 = function (str) { + var buf = new common$1.Buf8(str.length); + for (var i = 0, len = buf.length; i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; +}; + + +// convert array to string +var buf2string$1 = function (buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + + // Reserve max possible length (2 words per char) + // NB: by unknown reasons, Array is significantly faster for + // String.fromCharCode.apply than Uint16Array. + var utf16buf = new Array(len * 2); + + for (out = 0, i = 0; i < len;) { + c = buf[i++]; + // quick process ascii + if (c < 0x80) { utf16buf[out++] = c; continue; } + + c_len = _utf8len$1[c]; + // skip 5 & 6 byte codes + if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } + + // apply mask on first byte + c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; + // join the rest + while (c_len > 1 && i < len) { + c = (c << 6) | (buf[i++] & 0x3f); + c_len--; + } + + // terminated by end of string? + if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + + if (c < 0x10000) { + utf16buf[out++] = c; + } else { + c -= 0x10000; + utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); + utf16buf[out++] = 0xdc00 | (c & 0x3ff); + } + } + + return buf2binstring$1(utf16buf, out); +}; + + +// Calculate max possible position in utf8 buffer, +// that will not break sequence. If that's not possible +// - (very small limits) return max size as is. +// +// buf[] - utf8 bytes array +// max - length limit (mandatory); +var utf8border$1 = function (buf, max) { + var pos; + + max = max || buf.length; + if (max > buf.length) { max = buf.length; } + + // go back from last position, until start of sequence found + pos = max - 1; + while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } + + // Very small and broken sequence, + // return max, because we should return something anyway. + if (pos < 0) { return max; } + + // If we came to start of buffer - that means buffer is too small, + // return max too. + if (pos === 0) { return max; } + + return (pos + _utf8len$1[buf[pos]] > max) ? pos : max; +}; + +var strings$1 = { + string2buf: string2buf$1, + buf2binstring: buf2binstring_1$1, + binstring2buf: binstring2buf$1, + buf2string: buf2string$1, + utf8border: utf8border$1 +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function ZStream$1() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +var zstream$1 = ZStream$1; + +var toString$2 = Object.prototype.toString; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + +var Z_NO_FLUSH$3 = 0; +var Z_FINISH$4 = 4; + +var Z_OK$4 = 0; +var Z_STREAM_END$4 = 1; +var Z_SYNC_FLUSH$1 = 2; + +var Z_DEFAULT_COMPRESSION$3 = -1; + +var Z_DEFAULT_STRATEGY$3 = 0; + +var Z_DEFLATED$4 = 8; + +/* ===========================================================================*/ + + +/** + * class Deflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[deflate]], + * [[deflateRaw]] and [[gzip]]. + **/ + +/* internal + * Deflate.chunks -> Array + * + * Chunks of output data, if [[Deflate#onData]] not overridden. + **/ + +/** + * Deflate.result -> Uint8Array|Array + * + * Compressed result, generated by default [[Deflate#onData]] + * and [[Deflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Deflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Deflate.err -> Number + * + * Error code after deflate finished. 0 (Z_OK) on success. + * You will not need it in real life, because deflate errors + * are possible only on wrong options or bad `onData` / `onEnd` + * custom handlers. + **/ + +/** + * Deflate.msg -> String + * + * Error message, if [[Deflate.err]] != 0 + **/ + + +/** + * new Deflate(options) + * - options (Object): zlib deflate options. + * + * Creates new deflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `level` + * - `windowBits` + * - `memLevel` + * - `strategy` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw deflate + * - `gzip` (Boolean) - create gzip wrapper + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * - `header` (Object) - custom header for gzip + * - `text` (Boolean) - true if compressed data believed to be text + * - `time` (Number) - modification time, unix timestamp + * - `os` (Number) - operation system code + * - `extra` (Array) - array of bytes with extra data (max 65536) + * - `name` (String) - file name (binary string) + * - `comment` (String) - comment (binary string) + * - `hcrc` (Boolean) - true if header crc should be added + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var deflate = new pako.Deflate({ level: 3}); + * + * deflate.push(chunk1, false); + * deflate.push(chunk2, true); // true -> last chunk + * + * if (deflate.err) { throw new Error(deflate.err); } + * + * console.log(deflate.result); + * ``` + **/ +function Deflate$1(options) { + if (!(this instanceof Deflate$1)) return new Deflate$1(options); + + this.options = common$1.assign({ + level: Z_DEFAULT_COMPRESSION$3, + method: Z_DEFLATED$4, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY$3, + 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; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new zstream$1(); + this.strm.avail_out = 0; + + var status = deflate_1$2.deflateInit2( + this.strm, + opt.level, + opt.method, + opt.windowBits, + opt.memLevel, + opt.strategy + ); + + if (status !== Z_OK$4) { + throw new Error(messages$1[status]); + } + + if (opt.header) { + deflate_1$2.deflateSetHeader(this.strm, opt.header); + } + + if (opt.dictionary) { + var dict; + // Convert data if needed + if (typeof opt.dictionary === 'string') { + // If we need to compress text, change encoding to utf8. + dict = strings$1.string2buf(opt.dictionary); + } else if (toString$2.call(opt.dictionary) === '[object ArrayBuffer]') { + dict = new Uint8Array(opt.dictionary); + } else { + dict = opt.dictionary; + } + + status = deflate_1$2.deflateSetDictionary(this.strm, dict); + + if (status !== Z_OK$4) { + throw new Error(messages$1[status]); + } + + this._dict_set = true; + } +} + +/** + * Deflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be + * converted to utf8 byte sequence. + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with + * new compressed chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the compression context. + * + * On fail call [[Deflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * array format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Deflate$1.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$4 : Z_NO_FLUSH$3); + + // Convert data if needed + if (typeof data === 'string') { + // If we need to compress text, change encoding to utf8. + strm.input = strings$1.string2buf(data); + } else if (toString$2.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 common$1.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = deflate_1$2.deflate(strm, _mode); /* no bad return value */ + + if (status !== Z_STREAM_END$4 && status !== Z_OK$4) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH$4 || _mode === Z_SYNC_FLUSH$1))) { + if (this.options.to === 'string') { + this.onData(strings$1.buf2binstring(common$1.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(common$1.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END$4); + + // Finalize on the last chunk. + if (_mode === Z_FINISH$4) { + status = deflate_1$2.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK$4; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === Z_SYNC_FLUSH$1) { + this.onEnd(Z_OK$4); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Deflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Deflate$1.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Deflate#onEnd(status) -> Void + * - status (Number): deflate status. 0 (Z_OK) on success, + * other if not. + * + * Called once after you tell deflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Deflate$1.prototype.onEnd = function (status) { + // On success - join + if (status === Z_OK$4) { + if (this.options.to === 'string') { + this.result = this.chunks.join(''); + } else { + this.result = common$1.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * deflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * Compress `data` with deflate algorithm and `options`. + * + * Supported options are: + * + * - level + * - windowBits + * - memLevel + * - strategy + * - dictionary + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); + * + * console.log(pako.deflate(data)); + * ``` + **/ +function deflate$3(input, options) { + var deflator = new Deflate$1(options); + + deflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (deflator.err) { throw deflator.msg || messages$1[deflator.err]; } + + return deflator.result; +} + + +/** + * deflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function deflateRaw$1(input, options) { + options = options || {}; + options.raw = true; + return deflate$3(input, options); +} + + +/** + * gzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but create gzip wrapper instead of + * deflate one. + **/ +function gzip$1(input, options) { + options = options || {}; + options.gzip = true; + return deflate$3(input, options); +} + + +var Deflate_1$1 = Deflate$1; +var deflate_2$3 = deflate$3; +var deflateRaw_1$1 = deflateRaw$1; +var gzip_1$1 = gzip$1; + +var deflate_1$3 = { + Deflate: Deflate_1$1, + deflate: deflate_2$3, + deflateRaw: deflateRaw_1$1, + gzip: gzip_1$1 +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// See state defs from inflate.js +var BAD$2 = 30; /* got a data error -- remain here until reset */ +var TYPE$2 = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +var inffast$1 = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + 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; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD$2; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD$2; + break top; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD$2; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE$2; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD$2; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + + + +var MAXBITS$1 = 15; +var ENOUGH_LENS$2 = 852; +var ENOUGH_DISTS$2 = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES$2 = 0; +var LENS$2 = 1; +var DISTS$2 = 2; + +var lbase$1 = [ /* 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$1 = [ /* 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$1 = [ /* 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$1 = [ /* 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 +]; + +var inftrees$1 = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new common$1.Buf16(MAXBITS$1 + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new common$1.Buf16(MAXBITS$1 + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS$1; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS$1; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS$1; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES$2 || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS$1; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES$2) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS$2) { + base = lbase$1; + base_index -= 257; + extra = lext$1; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase$1; + extra = dext$1; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS$2 && used > ENOUGH_LENS$2) || + (type === DISTS$2 && used > ENOUGH_DISTS$2)) { + return 1; + } + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS$2 && used > ENOUGH_LENS$2) || + (type === DISTS$2 && used > ENOUGH_DISTS$2)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + + + + + + + +var CODES$3 = 0; +var LENS$3 = 1; +var DISTS$3 = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//var Z_NO_FLUSH = 0; +//var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +//var Z_FULL_FLUSH = 3; +var Z_FINISH$5 = 4; +var Z_BLOCK$3 = 5; +var Z_TREES$1 = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK$5 = 0; +var Z_STREAM_END$5 = 1; +var Z_NEED_DICT$1 = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR$3 = -2; +var Z_DATA_ERROR$3 = -3; +var Z_MEM_ERROR$1 = -4; +var Z_BUF_ERROR$3 = -5; +//var Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +var Z_DEFLATED$5 = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD$1 = 1; /* i: waiting for magic header */ +var FLAGS$1 = 2; /* i: waiting for method and flags (gzip) */ +var TIME$1 = 3; /* i: waiting for modification time (gzip) */ +var OS$1 = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN$1 = 5; /* i: waiting for extra length (gzip) */ +var EXTRA$1 = 6; /* i: waiting for extra bytes (gzip) */ +var NAME$1 = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT$1 = 8; /* i: waiting for end of comment (gzip) */ +var HCRC$1 = 9; /* i: waiting for header crc (gzip) */ +var DICTID$1 = 10; /* i: waiting for dictionary check value */ +var DICT$1 = 11; /* waiting for inflateSetDictionary() call */ +var TYPE$3 = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO$1 = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED$1 = 14; /* i: waiting for stored size (length and complement) */ +var COPY_$1 = 15; /* i/o: same as COPY below, but only first time in */ +var COPY$1 = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE$1 = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS$1 = 18; /* i: waiting for code length code lengths */ +var CODELENS$1 = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_$1 = 20; /* i: same as LEN below, but only first time in */ +var LEN$1 = 21; /* i: waiting for length/lit/eob code */ +var LENEXT$1 = 22; /* i: waiting for length extra bits */ +var DIST$1 = 23; /* i: waiting for distance code */ +var DISTEXT$1 = 24; /* i: waiting for distance extra bits */ +var MATCH$1 = 25; /* o: waiting for output space to copy string */ +var LIT$1 = 26; /* o: waiting for output space to write literal */ +var CHECK$1 = 27; /* i: waiting for 32-bit check value */ +var LENGTH$1 = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE$1 = 29; /* finished check, done -- remain here until reset */ +var BAD$3 = 30; /* got a data error -- remain here until reset */ +var MEM$1 = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC$1 = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS$3 = 852; +var ENOUGH_DISTS$3 = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS$3 = 15; +/* 32K LZ77 window */ +var DEF_WBITS$1 = MAX_WBITS$3; + + +function zswap32$1(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState$1() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new common$1.Buf16(320); /* temporary storage for code lengths */ + this.work = new common$1.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep$1(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR$3; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD$1; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new common$1.Buf32(ENOUGH_LENS$3); + state.distcode = state.distdyn = new common$1.Buf32(ENOUGH_DISTS$3); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK$5; +} + +function inflateReset$1(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR$3; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep$1(strm); + +} + +function inflateReset2$1(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR$3; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR$3; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset$1(strm); +} + +function inflateInit2$1(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR$3; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState$1(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2$1(strm, windowBits); + if (ret !== Z_OK$5) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit$1(strm) { + return inflateInit2$1(strm, DEF_WBITS$1); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin$1 = true; + +var lenfix$1, distfix$1; // We have no pointers in JS, so keep tables separate + +function fixedtables$1(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin$1) { + var sym; + + lenfix$1 = new common$1.Buf32(512); + distfix$1 = new common$1.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inftrees$1(LENS$3, state.lens, 0, 288, lenfix$1, 0, state.work, { bits: 9 }); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inftrees$1(DISTS$3, state.lens, 0, 32, distfix$1, 0, state.work, { bits: 5 }); + + /* do this just once */ + virgin$1 = false; + } + + state.lencode = lenfix$1; + state.lenbits = 9; + state.distcode = distfix$1; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow$1(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new common$1.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + common$1.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + common$1.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + common$1.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$2(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new common$1.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR$3; + } + + state = strm.state; + if (state.mode === TYPE$3) { state.mode = TYPEDO$1; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK$5; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD$1: + if (state.wrap === 0) { + state.mode = TYPEDO$1; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32_1$1(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS$1; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD$3; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED$5) { + strm.msg = 'unknown compression method'; + state.mode = BAD$3; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD$3; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID$1 : TYPE$3; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS$1: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED$5) { + strm.msg = 'unknown compression method'; + state.mode = BAD$3; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD$3; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32_1$1(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME$1; + /* falls through */ + case TIME$1: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32_1$1(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS$1; + /* falls through */ + case OS$1: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32_1$1(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN$1; + /* falls through */ + case EXLEN$1: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32_1$1(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA$1; + /* falls through */ + case EXTRA$1: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more convenient processing later + state.head.extra = new Array(state.head.extra_len); + } + common$1.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32_1$1(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME$1; + /* falls through */ + case NAME$1: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32_1$1(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$1; + /* falls through */ + case COMMENT$1: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32_1$1(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$1; + /* falls through */ + case HCRC$1: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD$3; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE$3; + break; + case DICTID$1: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32$1(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT$1; + /* falls through */ + case DICT$1: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT$1; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE$3; + /* falls through */ + case TYPE$3: + if (flush === Z_BLOCK$3 || flush === Z_TREES$1) { break inf_leave; } + /* falls through */ + case TYPEDO$1: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK$1; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED$1; + break; + case 1: /* fixed block */ + fixedtables$1(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_$1; /* decode codes */ + if (flush === Z_TREES$1) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE$1; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD$3; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED$1: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD$3; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_$1; + if (flush === Z_TREES$1) { break inf_leave; } + /* falls through */ + case COPY_$1: + state.mode = COPY$1; + /* falls through */ + case COPY$1: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + common$1.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE$3; + break; + case TABLE$1: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD$3; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS$1; + /* falls through */ + case LENLENS$1: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { bits: state.lenbits }; + ret = inftrees$1(CODES$3, 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$3; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS$1; + /* falls through */ + case CODELENS$1: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD$3; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD$3; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD$3) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD$3; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { bits: state.lenbits }; + ret = inftrees$1(LENS$3, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD$3; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inftrees$1(DISTS$3, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD$3; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_$1; + if (flush === Z_TREES$1) { break inf_leave; } + /* falls through */ + case LEN_$1: + state.mode = LEN$1; + /* falls through */ + case LEN$1: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inffast$1(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE$3) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT$1; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE$3; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD$3; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT$1; + /* falls through */ + case LENEXT$1: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST$1; + /* falls through */ + case DIST$1: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD$3; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT$1; + /* falls through */ + case DISTEXT$1: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD$3; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH$1; + /* falls through */ + case MATCH$1: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD$3; + break; + } +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN$1; } + break; + case LIT$1: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN$1; + break; + case CHECK$1: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' instead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32_1$1(state.check, output, _out, put - _out) : adler32_1$1(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32$1(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD$3; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH$1; + /* falls through */ + case LENGTH$1: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD$3; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE$1; + /* falls through */ + case DONE$1: + ret = Z_STREAM_END$5; + break inf_leave; + case BAD$3: + ret = Z_DATA_ERROR$3; + break inf_leave; + case MEM$1: + return Z_MEM_ERROR$1; + case SYNC$1: + /* falls through */ + default: + return Z_STREAM_ERROR$3; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$3 && + (state.mode < CHECK$1 || flush !== Z_FINISH$5))) { + if (updatewindow$1(strm, strm.output, strm.next_out, _out - strm.avail_out)) ; + } + _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_1$1(state.check, output, _out, strm.next_out - _out) : adler32_1$1(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE$3 ? 128 : 0) + + (state.mode === LEN_$1 || state.mode === COPY_$1 ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH$5) && ret === Z_OK$5) { + ret = Z_BUF_ERROR$3; + } + return ret; +} + +function inflateEnd$1(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR$3; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK$5; +} + +function inflateGetHeader$1(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR$3; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$3; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK$5; +} + +function inflateSetDictionary$1(strm, dictionary) { + var dictLength = dictionary.length; + + var state; + var dictid; + var ret; + + /* check state */ + if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR$3; } + state = strm.state; + + if (state.wrap !== 0 && state.mode !== DICT$1) { + return Z_STREAM_ERROR$3; + } + + /* check for correct dictionary identifier */ + if (state.mode === DICT$1) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32_1$1(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR$3; + } + } + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow$1(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM$1; + return Z_MEM_ERROR$1; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK$5; +} + +var inflateReset_1$1 = inflateReset$1; +var inflateReset2_1$1 = inflateReset2$1; +var inflateResetKeep_1$1 = inflateResetKeep$1; +var inflateInit_1$1 = inflateInit$1; +var inflateInit2_1$1 = inflateInit2$1; +var inflate_2$2 = inflate$2; +var inflateEnd_1$1 = inflateEnd$1; +var inflateGetHeader_1$1 = inflateGetHeader$1; +var inflateSetDictionary_1$1 = inflateSetDictionary$1; +var inflateInfo$1 = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ + +var inflate_1$2 = { + inflateReset: inflateReset_1$1, + inflateReset2: inflateReset2_1$1, + inflateResetKeep: inflateResetKeep_1$1, + inflateInit: inflateInit_1$1, + inflateInit2: inflateInit2_1$1, + inflate: inflate_2$2, + inflateEnd: inflateEnd_1$1, + inflateGetHeader: inflateGetHeader_1$1, + inflateSetDictionary: inflateSetDictionary_1$1, + inflateInfo: inflateInfo$1 +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var constants$1 = { + + /* 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 +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function GZheader$1() { + /* true if compressed data believed to be text */ + this.text = 0; + /* modification time */ + this.time = 0; + /* extra flags (not used when writing a gzip file) */ + this.xflags = 0; + /* operating system */ + this.os = 0; + /* pointer to extra field or Z_NULL if none */ + this.extra = null; + /* extra field length (valid if extra != Z_NULL) */ + this.extra_len = 0; // Actually, we don't need it in JS, + // but leave for few code modifications + + // + // Setup limits is not necessary because in js we should not preallocate memory + // for inflate use constant limit in 65536 bytes + // + + /* space at extra (only when reading header) */ + // this.extra_max = 0; + /* pointer to zero-terminated file name or Z_NULL */ + this.name = ''; + /* space at name (only when reading header) */ + // this.name_max = 0; + /* pointer to zero-terminated comment or Z_NULL */ + this.comment = ''; + /* space at comment (only when reading header) */ + // this.comm_max = 0; + /* true if there was or will be a header crc */ + this.hcrc = 0; + /* true when done reading gzip header (not used when writing a gzip file) */ + this.done = false; +} + +var gzheader$1 = GZheader$1; + +var toString$3 = Object.prototype.toString; + +/** + * class Inflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[inflate]] + * and [[inflateRaw]]. + **/ + +/* internal + * inflate.chunks -> Array + * + * Chunks of output data, if [[Inflate#onData]] not overridden. + **/ + +/** + * Inflate.result -> Uint8Array|Array|String + * + * Uncompressed result, generated by default [[Inflate#onData]] + * and [[Inflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Inflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Inflate.err -> Number + * + * Error code after inflate finished. 0 (Z_OK) on success. + * Should be checked if broken data possible. + **/ + +/** + * Inflate.msg -> String + * + * Error message, if [[Inflate.err]] != 0 + **/ + + +/** + * new Inflate(options) + * - options (Object): zlib inflate options. + * + * Creates new inflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `windowBits` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw inflate + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * By default, when no options set, autodetect deflate/gzip data format via + * wrapper header. + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var inflate = new pako.Inflate({ level: 3}); + * + * inflate.push(chunk1, false); + * inflate.push(chunk2, true); // true -> last chunk + * + * if (inflate.err) { throw new Error(inflate.err); } + * + * console.log(inflate.result); + * ``` + **/ +function Inflate$1(options) { + if (!(this instanceof Inflate$1)) return new Inflate$1(options); + + this.options = common$1.assign({ + chunkSize: 16384, + windowBits: 0, + to: '' + }, options || {}); + + var opt = this.options; + + // Force window size for `raw` data, if not set directly, + // because we have no header for autodetect. + if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { opt.windowBits = -15; } + } + + // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate + if ((opt.windowBits >= 0) && (opt.windowBits < 16) && + !(options && options.windowBits)) { + opt.windowBits += 32; + } + + // Gzip header has no info about windows size, we can do autodetect only + // for deflate. So, if window size not set, force it to max when gzip possible + if ((opt.windowBits > 15) && (opt.windowBits < 48)) { + // bit 3 (16) -> gzipped data + // bit 4 (32) -> autodetect gzip/deflate + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new zstream$1(); + this.strm.avail_out = 0; + + var status = inflate_1$2.inflateInit2( + this.strm, + opt.windowBits + ); + + if (status !== constants$1.Z_OK) { + throw new Error(messages$1[status]); + } + + this.header = new gzheader$1(); + + inflate_1$2.inflateGetHeader(this.strm, this.header); + + // Setup dictionary + if (opt.dictionary) { + // Convert data if needed + if (typeof opt.dictionary === 'string') { + opt.dictionary = strings$1.string2buf(opt.dictionary); + } else if (toString$3.call(opt.dictionary) === '[object ArrayBuffer]') { + opt.dictionary = new Uint8Array(opt.dictionary); + } + if (opt.raw) { //In raw mode we need to set the dictionary early + status = inflate_1$2.inflateSetDictionary(this.strm, opt.dictionary); + if (status !== constants$1.Z_OK) { + throw new Error(messages$1[status]); + } + } + } +} + +/** + * Inflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with + * new output chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the decompression context. + * + * On fail call [[Inflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Inflate$1.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; + + // Flag to properly process Z_BUF_ERROR on testing inflate call + // when we check that all output data was flushed. + var allowBufError = false; + + if (this.ended) { return false; } + _mode = (mode === ~~mode) ? mode : ((mode === true) ? constants$1.Z_FINISH : constants$1.Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // Only binary strings can be decompressed on practice + strm.input = strings$1.binstring2buf(data); + } else if (toString$3.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 common$1.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + + status = inflate_1$2.inflate(strm, constants$1.Z_NO_FLUSH); /* no bad return value */ + + if (status === constants$1.Z_NEED_DICT && dictionary) { + status = inflate_1$2.inflateSetDictionary(this.strm, dictionary); + } + + if (status === constants$1.Z_BUF_ERROR && allowBufError === true) { + status = constants$1.Z_OK; + allowBufError = false; + } + + if (status !== constants$1.Z_STREAM_END && status !== constants$1.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + + if (strm.next_out) { + if (strm.avail_out === 0 || status === constants$1.Z_STREAM_END || (strm.avail_in === 0 && (_mode === constants$1.Z_FINISH || _mode === constants$1.Z_SYNC_FLUSH))) { + + if (this.options.to === 'string') { + + next_out_utf8 = strings$1.utf8border(strm.output, strm.next_out); + + tail = strm.next_out - next_out_utf8; + utf8str = strings$1.buf2string(strm.output, next_out_utf8); + + // move tail + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { common$1.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } + + this.onData(utf8str); + + } else { + this.onData(common$1.shrinkBuf(strm.output, strm.next_out)); + } + } + } + + // When no more input data, we should check that internal inflate buffers + // are flushed. The only way to do it when avail_out = 0 - run one more + // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. + // Here we set flag to process this error properly. + // + // NOTE. Deflate does not return error in this case and does not needs such + // logic. + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== constants$1.Z_STREAM_END); + + if (status === constants$1.Z_STREAM_END) { + _mode = constants$1.Z_FINISH; + } + + // Finalize on the last chunk. + if (_mode === constants$1.Z_FINISH) { + status = inflate_1$2.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === constants$1.Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === constants$1.Z_SYNC_FLUSH) { + this.onEnd(constants$1.Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Inflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Inflate$1.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Inflate#onEnd(status) -> Void + * - status (Number): inflate status. 0 (Z_OK) on success, + * other if not. + * + * Called either after you tell inflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Inflate$1.prototype.onEnd = function (status) { + // On success - join + if (status === constants$1.Z_OK) { + if (this.options.to === 'string') { + // Glue & convert here, until we teach pako to send + // utf8 aligned strings to onData + this.result = this.chunks.join(''); + } else { + this.result = common$1.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * inflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Decompress `data` with inflate/ungzip and `options`. Autodetect + * format via wrapper header by default. That's why we don't provide + * separate `ungzip` method. + * + * Supported options are: + * + * - windowBits + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) + * , output; + * + * try { + * output = pako.inflate(input); + * } catch (err) + * console.log(err); + * } + * ``` + **/ +function inflate$3(input, options) { + var inflator = new Inflate$1(options); + + inflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (inflator.err) { throw inflator.msg || messages$1[inflator.err]; } + + return inflator.result; +} + + +/** + * inflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * The same as [[inflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function inflateRaw$1(input, options) { + options = options || {}; + options.raw = true; + return inflate$3(input, options); +} + + +/** + * ungzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Just shortcut to [[inflate]], because it autodetects format + * by header.content. Done for convenience. + **/ + + +var Inflate_1$1 = Inflate$1; +var inflate_2$3 = inflate$3; +var inflateRaw_1$1 = inflateRaw$1; +var ungzip$1 = inflate$3; + +var inflate_1$3 = { + Inflate: Inflate_1$1, + inflate: inflate_2$3, + inflateRaw: inflateRaw_1$1, + ungzip: ungzip$1 +}; + +var assign$1 = common$1.assign; + + + + + +var pako$1 = {}; + +assign$1(pako$1, deflate_1$3, inflate_1$3, constants$1); + +var pako_1$1 = pako$1; + +var PDFHeader = /** @class */ (function () { + function PDFHeader(major, minor) { + this.major = String(major); + this.minor = String(minor); + } + PDFHeader.prototype.toString = function () { + var bc = charFromCode(129); + return "%PDF-" + this.major + "." + this.minor + "\n%" + bc + bc + bc + bc; + }; + PDFHeader.prototype.sizeInBytes = function () { + return 12 + this.major.length + this.minor.length; + }; + PDFHeader.prototype.copyBytesInto = function (buffer, offset) { + var initialOffset = offset; + buffer[offset++] = CharCodes$1.Percent; + buffer[offset++] = CharCodes$1.P; + buffer[offset++] = CharCodes$1.D; + buffer[offset++] = CharCodes$1.F; + buffer[offset++] = CharCodes$1.Dash; + offset += copyStringIntoBuffer(this.major, buffer, offset); + buffer[offset++] = CharCodes$1.Period; + offset += copyStringIntoBuffer(this.minor, buffer, offset); + buffer[offset++] = CharCodes$1.Newline; + buffer[offset++] = CharCodes$1.Percent; + buffer[offset++] = 129; + buffer[offset++] = 129; + buffer[offset++] = 129; + buffer[offset++] = 129; + return offset - initialOffset; + }; + PDFHeader.forVersion = function (major, minor) { + return new PDFHeader(major, minor); + }; + return PDFHeader; +}()); + +var PDFObject = /** @class */ (function () { + function PDFObject() { + } + PDFObject.prototype.clone = function (_context) { + throw new MethodNotImplementedError(this.constructor.name, 'clone'); + }; + PDFObject.prototype.toString = function () { + throw new MethodNotImplementedError(this.constructor.name, 'toString'); + }; + PDFObject.prototype.sizeInBytes = function () { + throw new MethodNotImplementedError(this.constructor.name, 'sizeInBytes'); + }; + PDFObject.prototype.copyBytesInto = function (_buffer, _offset) { + throw new MethodNotImplementedError(this.constructor.name, 'copyBytesInto'); + }; + return PDFObject; +}()); + +var PDFNumber = /** @class */ (function (_super) { + __extends(PDFNumber, _super); + function PDFNumber(value) { + var _this = _super.call(this) || this; + _this.numberValue = value; + _this.stringValue = numberToString(value); + return _this; + } + PDFNumber.prototype.asNumber = function () { + return this.numberValue; + }; + /** @deprecated in favor of [[PDFNumber.asNumber]] */ + PDFNumber.prototype.value = function () { + return this.numberValue; + }; + PDFNumber.prototype.clone = function () { + return PDFNumber.of(this.numberValue); + }; + PDFNumber.prototype.toString = function () { + return this.stringValue; + }; + PDFNumber.prototype.sizeInBytes = function () { + return this.stringValue.length; + }; + PDFNumber.prototype.copyBytesInto = function (buffer, offset) { + offset += copyStringIntoBuffer(this.stringValue, buffer, offset); + return this.stringValue.length; + }; + PDFNumber.of = function (value) { return new PDFNumber(value); }; + return PDFNumber; +}(PDFObject)); + +var PDFArray = /** @class */ (function (_super) { + __extends(PDFArray, _super); + function PDFArray(context) { + var _this = _super.call(this) || this; + _this.array = []; + _this.context = context; + return _this; + } + PDFArray.prototype.size = function () { + return this.array.length; + }; + PDFArray.prototype.push = function (object) { + this.array.push(object); + }; + PDFArray.prototype.insert = function (index, object) { + this.array.splice(index, 0, object); + }; + PDFArray.prototype.indexOf = function (object) { + var index = this.array.indexOf(object); + return index === -1 ? undefined : index; + }; + PDFArray.prototype.remove = function (index) { + this.array.splice(index, 1); + }; + PDFArray.prototype.set = function (idx, object) { + this.array[idx] = object; + }; + PDFArray.prototype.get = function (index) { + return this.array[index]; + }; + PDFArray.prototype.lookupMaybe = function (index) { + var _a; + var types = []; + for (var _i = 1; _i < arguments.length; _i++) { + types[_i - 1] = arguments[_i]; + } + return (_a = this.context).lookupMaybe.apply(_a, __spreadArrays([this.get(index)], types)); + }; + PDFArray.prototype.lookup = function (index) { + var _a; + var types = []; + for (var _i = 1; _i < arguments.length; _i++) { + types[_i - 1] = arguments[_i]; + } + return (_a = this.context).lookup.apply(_a, __spreadArrays([this.get(index)], types)); + }; + PDFArray.prototype.asRectangle = function () { + if (this.size() !== 4) + throw new PDFArrayIsNotRectangleError(this.size()); + var lowerLeftX = this.lookup(0, PDFNumber).asNumber(); + var lowerLeftY = this.lookup(1, PDFNumber).asNumber(); + var upperRightX = this.lookup(2, PDFNumber).asNumber(); + var upperRightY = this.lookup(3, PDFNumber).asNumber(); + var x = lowerLeftX; + var y = lowerLeftY; + var width = upperRightX - lowerLeftX; + var height = upperRightY - lowerLeftY; + return { x: x, y: y, width: width, height: height }; + }; + PDFArray.prototype.asArray = function () { + return this.array.slice(); + }; + PDFArray.prototype.clone = function (context) { + var clone = PDFArray.withContext(context || this.context); + for (var idx = 0, len = this.size(); idx < len; idx++) { + clone.push(this.array[idx]); + } + return clone; + }; + PDFArray.prototype.toString = function () { + var arrayString = '[ '; + for (var idx = 0, len = this.size(); idx < len; idx++) { + arrayString += this.get(idx).toString(); + arrayString += ' '; + } + arrayString += ']'; + return arrayString; + }; + PDFArray.prototype.sizeInBytes = function () { + var size = 3; + for (var idx = 0, len = this.size(); idx < len; idx++) { + size += this.get(idx).sizeInBytes() + 1; + } + return size; + }; + PDFArray.prototype.copyBytesInto = function (buffer, offset) { + var initialOffset = offset; + buffer[offset++] = CharCodes$1.LeftSquareBracket; + buffer[offset++] = CharCodes$1.Space; + for (var idx = 0, len = this.size(); idx < len; idx++) { + offset += this.get(idx).copyBytesInto(buffer, offset); + buffer[offset++] = CharCodes$1.Space; + } + buffer[offset++] = CharCodes$1.RightSquareBracket; + return offset - initialOffset; + }; + PDFArray.prototype.scalePDFNumbers = function (x, y) { + for (var idx = 0, len = this.size(); idx < len; idx++) { + var el = this.lookup(idx); + if (el instanceof PDFNumber) { + var factor = idx % 2 === 0 ? x : y; + this.set(idx, PDFNumber.of(el.asNumber() * factor)); + } + } + }; + PDFArray.withContext = function (context) { return new PDFArray(context); }; + return PDFArray; +}(PDFObject)); + +var ENFORCER = {}; +var PDFBool = /** @class */ (function (_super) { + __extends(PDFBool, _super); + function PDFBool(enforcer, value) { + var _this = this; + if (enforcer !== ENFORCER) + throw new PrivateConstructorError('PDFBool'); + _this = _super.call(this) || this; + _this.value = value; + return _this; + } + PDFBool.prototype.asBoolean = function () { + return this.value; + }; + PDFBool.prototype.clone = function () { + return this; + }; + PDFBool.prototype.toString = function () { + return String(this.value); + }; + PDFBool.prototype.sizeInBytes = function () { + return this.value ? 4 : 5; + }; + PDFBool.prototype.copyBytesInto = function (buffer, offset) { + if (this.value) { + buffer[offset++] = CharCodes$1.t; + buffer[offset++] = CharCodes$1.r; + buffer[offset++] = CharCodes$1.u; + buffer[offset++] = CharCodes$1.e; + return 4; + } + else { + buffer[offset++] = CharCodes$1.f; + buffer[offset++] = CharCodes$1.a; + buffer[offset++] = CharCodes$1.l; + buffer[offset++] = CharCodes$1.s; + buffer[offset++] = CharCodes$1.e; + return 5; + } + }; + PDFBool.True = new PDFBool(ENFORCER, true); + PDFBool.False = new PDFBool(ENFORCER, false); + return PDFBool; +}(PDFObject)); + +var IsDelimiter = new Uint8Array(256); +IsDelimiter[CharCodes$1.LeftParen] = 1; +IsDelimiter[CharCodes$1.RightParen] = 1; +IsDelimiter[CharCodes$1.LessThan] = 1; +IsDelimiter[CharCodes$1.GreaterThan] = 1; +IsDelimiter[CharCodes$1.LeftSquareBracket] = 1; +IsDelimiter[CharCodes$1.RightSquareBracket] = 1; +IsDelimiter[CharCodes$1.LeftCurly] = 1; +IsDelimiter[CharCodes$1.RightCurly] = 1; +IsDelimiter[CharCodes$1.ForwardSlash] = 1; +IsDelimiter[CharCodes$1.Percent] = 1; + +var IsWhitespace = new Uint8Array(256); +IsWhitespace[CharCodes$1.Null] = 1; +IsWhitespace[CharCodes$1.Tab] = 1; +IsWhitespace[CharCodes$1.Newline] = 1; +IsWhitespace[CharCodes$1.FormFeed] = 1; +IsWhitespace[CharCodes$1.CarriageReturn] = 1; +IsWhitespace[CharCodes$1.Space] = 1; + +var IsIrregular = new Uint8Array(256); +for (var idx$1 = 0, len = 256; idx$1 < len; idx$1++) { + IsIrregular[idx$1] = IsWhitespace[idx$1] || IsDelimiter[idx$1] ? 1 : 0; +} +IsIrregular[CharCodes$1.Hash] = 1; + +var decodeName = function (name) { + return name.replace(/#([\dABCDEF]{2})/g, function (_, hex) { return charFromHexCode(hex); }); +}; +var isRegularChar = function (charCode) { + return charCode >= CharCodes$1.ExclamationPoint && + charCode <= CharCodes$1.Tilde && + !IsIrregular[charCode]; +}; +var ENFORCER$1 = {}; +var pool = new Map(); +var PDFName = /** @class */ (function (_super) { + __extends(PDFName, _super); + function PDFName(enforcer, name) { + var _this = this; + if (enforcer !== ENFORCER$1) + throw new PrivateConstructorError('PDFName'); + _this = _super.call(this) || this; + var encodedName = '/'; + for (var idx = 0, len = name.length; idx < len; idx++) { + var character = name[idx]; + var code = toCharCode(character); + encodedName += isRegularChar(code) ? character : "#" + toHexString(code); + } + _this.encodedName = encodedName; + return _this; + } + PDFName.prototype.asBytes = function () { + var bytes = []; + var hex = ''; + var escaped = false; + var pushByte = function (byte) { + if (byte !== undefined) + bytes.push(byte); + escaped = false; + }; + for (var idx = 1, len = this.encodedName.length; idx < len; idx++) { + var char = this.encodedName[idx]; + var byte = toCharCode(char); + var nextChar = this.encodedName[idx + 1]; + if (!escaped) { + if (byte === CharCodes$1.Hash) + escaped = true; + else + pushByte(byte); + } + else { + if ((byte >= CharCodes$1.Zero && byte <= CharCodes$1.Nine) || + (byte >= CharCodes$1.a && byte <= CharCodes$1.f) || + (byte >= CharCodes$1.A && byte <= CharCodes$1.F)) { + hex += char; + if (hex.length === 2 || + !((nextChar >= '0' && nextChar <= '9') || + (nextChar >= 'a' && nextChar <= 'f') || + (nextChar >= 'A' && nextChar <= 'F'))) { + pushByte(parseInt(hex, 16)); + hex = ''; + } + } + else { + pushByte(byte); + } + } + } + return new Uint8Array(bytes); + }; + // TODO: This should probably use `utf8Decode()` + // TODO: Polyfill Array.from? + PDFName.prototype.decodeText = function () { + var bytes = this.asBytes(); + return String.fromCharCode.apply(String, Array.from(bytes)); + }; + PDFName.prototype.asString = function () { + return this.encodedName; + }; + /** @deprecated in favor of [[PDFName.asString]] */ + PDFName.prototype.value = function () { + return this.encodedName; + }; + PDFName.prototype.clone = function () { + return this; + }; + PDFName.prototype.toString = function () { + return this.encodedName; + }; + PDFName.prototype.sizeInBytes = function () { + return this.encodedName.length; + }; + PDFName.prototype.copyBytesInto = function (buffer, offset) { + offset += copyStringIntoBuffer(this.encodedName, buffer, offset); + return this.encodedName.length; + }; + PDFName.of = function (name) { + var decodedValue = decodeName(name); + var instance = pool.get(decodedValue); + if (!instance) { + instance = new PDFName(ENFORCER$1, decodedValue); + pool.set(decodedValue, instance); + } + return instance; + }; + /* tslint:disable member-ordering */ + PDFName.Length = PDFName.of('Length'); + PDFName.FlateDecode = PDFName.of('FlateDecode'); + PDFName.Resources = PDFName.of('Resources'); + PDFName.Font = PDFName.of('Font'); + PDFName.XObject = PDFName.of('XObject'); + PDFName.ExtGState = PDFName.of('ExtGState'); + PDFName.Contents = PDFName.of('Contents'); + PDFName.Type = PDFName.of('Type'); + PDFName.Parent = PDFName.of('Parent'); + PDFName.MediaBox = PDFName.of('MediaBox'); + PDFName.Page = PDFName.of('Page'); + PDFName.Annots = PDFName.of('Annots'); + PDFName.TrimBox = PDFName.of('TrimBox'); + PDFName.ArtBox = PDFName.of('ArtBox'); + PDFName.BleedBox = PDFName.of('BleedBox'); + PDFName.CropBox = PDFName.of('CropBox'); + PDFName.Rotate = PDFName.of('Rotate'); + PDFName.Title = PDFName.of('Title'); + PDFName.Author = PDFName.of('Author'); + PDFName.Subject = PDFName.of('Subject'); + PDFName.Creator = PDFName.of('Creator'); + PDFName.Keywords = PDFName.of('Keywords'); + PDFName.Producer = PDFName.of('Producer'); + PDFName.CreationDate = PDFName.of('CreationDate'); + PDFName.ModDate = PDFName.of('ModDate'); + return PDFName; +}(PDFObject)); + +var PDFNull = /** @class */ (function (_super) { + __extends(PDFNull, _super); + function PDFNull() { + return _super !== null && _super.apply(this, arguments) || this; + } + PDFNull.prototype.asNull = function () { + return null; + }; + PDFNull.prototype.clone = function () { + return this; + }; + PDFNull.prototype.toString = function () { + return 'null'; + }; + PDFNull.prototype.sizeInBytes = function () { + return 4; + }; + PDFNull.prototype.copyBytesInto = function (buffer, offset) { + buffer[offset++] = CharCodes$1.n; + buffer[offset++] = CharCodes$1.u; + buffer[offset++] = CharCodes$1.l; + buffer[offset++] = CharCodes$1.l; + return 4; + }; + return PDFNull; +}(PDFObject)); +var PDFNull$1 = new PDFNull(); + +var PDFDict = /** @class */ (function (_super) { + __extends(PDFDict, _super); + function PDFDict(map, context) { + var _this = _super.call(this) || this; + _this.dict = map; + _this.context = context; + return _this; + } + PDFDict.prototype.keys = function () { + return Array.from(this.dict.keys()); + }; + PDFDict.prototype.values = function () { + return Array.from(this.dict.values()); + }; + PDFDict.prototype.entries = function () { + return Array.from(this.dict.entries()); + }; + PDFDict.prototype.set = function (key, value) { + this.dict.set(key, value); + }; + PDFDict.prototype.get = function (key, + // TODO: `preservePDFNull` is for backwards compatibility. Should be + // removed in next breaking API change. + preservePDFNull) { + if (preservePDFNull === void 0) { preservePDFNull = false; } + var value = this.dict.get(key); + if (value === PDFNull$1 && !preservePDFNull) + return undefined; + return value; + }; + PDFDict.prototype.has = function (key) { + var value = this.dict.get(key); + return value !== undefined && value !== PDFNull$1; + }; + PDFDict.prototype.lookupMaybe = function (key) { + var _a; + var types = []; + for (var _i = 1; _i < arguments.length; _i++) { + types[_i - 1] = arguments[_i]; + } + // TODO: `preservePDFNull` is for backwards compatibility. Should be + // removed in next breaking API change. + var preservePDFNull = types.includes(PDFNull$1); + var value = (_a = this.context).lookupMaybe.apply(_a, __spreadArrays([this.get(key, preservePDFNull)], types)); + if (value === PDFNull$1 && !preservePDFNull) + return undefined; + return value; + }; + PDFDict.prototype.lookup = function (key) { + var _a; + var types = []; + for (var _i = 1; _i < arguments.length; _i++) { + types[_i - 1] = arguments[_i]; + } + // TODO: `preservePDFNull` is for backwards compatibility. Should be + // removed in next breaking API change. + var preservePDFNull = types.includes(PDFNull$1); + var value = (_a = this.context).lookup.apply(_a, __spreadArrays([this.get(key, preservePDFNull)], types)); + if (value === PDFNull$1 && !preservePDFNull) + return undefined; + return value; + }; + PDFDict.prototype.delete = function (key) { + return this.dict.delete(key); + }; + PDFDict.prototype.asMap = function () { + return new Map(this.dict); + }; + /** Generate a random key that doesn't exist in current key set */ + PDFDict.prototype.uniqueKey = function (tag) { + if (tag === void 0) { tag = ''; } + var existingKeys = this.keys(); + var key = PDFName.of(this.context.addRandomSuffix(tag, 10)); + while (existingKeys.includes(key)) { + key = PDFName.of(this.context.addRandomSuffix(tag, 10)); + } + return key; + }; + PDFDict.prototype.clone = function (context) { + var clone = PDFDict.withContext(context || this.context); + var entries = this.entries(); + for (var idx = 0, len = entries.length; idx < len; idx++) { + var _a = entries[idx], key = _a[0], value = _a[1]; + clone.set(key, value); + } + return clone; + }; + PDFDict.prototype.toString = function () { + var dictString = '<<\n'; + var entries = this.entries(); + for (var idx = 0, len = entries.length; idx < len; idx++) { + var _a = entries[idx], key = _a[0], value = _a[1]; + dictString += key.toString() + ' ' + value.toString() + '\n'; + } + dictString += '>>'; + return dictString; + }; + PDFDict.prototype.sizeInBytes = function () { + var size = 5; + var entries = this.entries(); + for (var idx = 0, len = entries.length; idx < len; idx++) { + var _a = entries[idx], key = _a[0], value = _a[1]; + size += key.sizeInBytes() + value.sizeInBytes() + 2; + } + return size; + }; + PDFDict.prototype.copyBytesInto = function (buffer, offset) { + var initialOffset = offset; + buffer[offset++] = CharCodes$1.LessThan; + buffer[offset++] = CharCodes$1.LessThan; + buffer[offset++] = CharCodes$1.Newline; + var entries = this.entries(); + for (var idx = 0, len = entries.length; idx < len; idx++) { + var _a = entries[idx], key = _a[0], value = _a[1]; + offset += key.copyBytesInto(buffer, offset); + buffer[offset++] = CharCodes$1.Space; + offset += value.copyBytesInto(buffer, offset); + buffer[offset++] = CharCodes$1.Newline; + } + buffer[offset++] = CharCodes$1.GreaterThan; + buffer[offset++] = CharCodes$1.GreaterThan; + return offset - initialOffset; + }; + PDFDict.withContext = function (context) { return new PDFDict(new Map(), context); }; + PDFDict.fromMapWithContext = function (map, context) { + return new PDFDict(map, context); + }; + return PDFDict; +}(PDFObject)); + +var PDFStream = /** @class */ (function (_super) { + __extends(PDFStream, _super); + function PDFStream(dict) { + var _this = _super.call(this) || this; + _this.dict = dict; + return _this; + } + PDFStream.prototype.clone = function (_context) { + throw new MethodNotImplementedError(this.constructor.name, 'clone'); + }; + PDFStream.prototype.getContentsString = function () { + throw new MethodNotImplementedError(this.constructor.name, 'getContentsString'); + }; + PDFStream.prototype.getContents = function () { + throw new MethodNotImplementedError(this.constructor.name, 'getContents'); + }; + PDFStream.prototype.getContentsSize = function () { + throw new MethodNotImplementedError(this.constructor.name, 'getContentsSize'); + }; + PDFStream.prototype.updateDict = function () { + var contentsSize = this.getContentsSize(); + this.dict.set(PDFName.Length, PDFNumber.of(contentsSize)); + }; + PDFStream.prototype.sizeInBytes = function () { + this.updateDict(); + return this.dict.sizeInBytes() + this.getContentsSize() + 18; + }; + PDFStream.prototype.toString = function () { + this.updateDict(); + var streamString = this.dict.toString(); + streamString += '\nstream\n'; + streamString += this.getContentsString(); + streamString += '\nendstream'; + return streamString; + }; + PDFStream.prototype.copyBytesInto = function (buffer, offset) { + this.updateDict(); + var initialOffset = offset; + offset += this.dict.copyBytesInto(buffer, offset); + buffer[offset++] = CharCodes$1.Newline; + buffer[offset++] = CharCodes$1.s; + buffer[offset++] = CharCodes$1.t; + buffer[offset++] = CharCodes$1.r; + buffer[offset++] = CharCodes$1.e; + buffer[offset++] = CharCodes$1.a; + buffer[offset++] = CharCodes$1.m; + buffer[offset++] = CharCodes$1.Newline; + var contents = this.getContents(); + for (var idx = 0, len = contents.length; idx < len; idx++) { + buffer[offset++] = contents[idx]; + } + buffer[offset++] = CharCodes$1.Newline; + buffer[offset++] = CharCodes$1.e; + buffer[offset++] = CharCodes$1.n; + buffer[offset++] = CharCodes$1.d; + buffer[offset++] = CharCodes$1.s; + buffer[offset++] = CharCodes$1.t; + buffer[offset++] = CharCodes$1.r; + buffer[offset++] = CharCodes$1.e; + buffer[offset++] = CharCodes$1.a; + buffer[offset++] = CharCodes$1.m; + return offset - initialOffset; + }; + return PDFStream; +}(PDFObject)); + +var PDFRawStream = /** @class */ (function (_super) { + __extends(PDFRawStream, _super); + function PDFRawStream(dict, contents) { + var _this = _super.call(this, dict) || this; + _this.contents = contents; + return _this; + } + PDFRawStream.prototype.asUint8Array = function () { + return this.contents.slice(); + }; + PDFRawStream.prototype.clone = function (context) { + return PDFRawStream.of(this.dict.clone(context), this.contents.slice()); + }; + PDFRawStream.prototype.getContentsString = function () { + return arrayAsString(this.contents); + }; + PDFRawStream.prototype.getContents = function () { + return this.contents; + }; + PDFRawStream.prototype.getContentsSize = function () { + return this.contents.length; + }; + PDFRawStream.of = function (dict, contents) { + return new PDFRawStream(dict, contents); + }; + return PDFRawStream; +}(PDFStream)); + +var ENFORCER$2 = {}; +var pool$1 = new Map(); +var PDFRef = /** @class */ (function (_super) { + __extends(PDFRef, _super); + function PDFRef(enforcer, objectNumber, generationNumber) { + var _this = this; + if (enforcer !== ENFORCER$2) + throw new PrivateConstructorError('PDFRef'); + _this = _super.call(this) || this; + _this.objectNumber = objectNumber; + _this.generationNumber = generationNumber; + _this.tag = objectNumber + " " + generationNumber + " R"; + return _this; + } + PDFRef.prototype.clone = function () { + return this; + }; + PDFRef.prototype.toString = function () { + return this.tag; + }; + PDFRef.prototype.sizeInBytes = function () { + return this.tag.length; + }; + PDFRef.prototype.copyBytesInto = function (buffer, offset) { + offset += copyStringIntoBuffer(this.tag, buffer, offset); + return this.tag.length; + }; + PDFRef.of = function (objectNumber, generationNumber) { + if (generationNumber === void 0) { generationNumber = 0; } + var tag = objectNumber + " " + generationNumber + " R"; + var instance = pool$1.get(tag); + if (!instance) { + instance = new PDFRef(ENFORCER$2, objectNumber, generationNumber); + pool$1.set(tag, instance); + } + return instance; + }; + return PDFRef; +}(PDFObject)); + +var PDFOperator = /** @class */ (function () { + function PDFOperator(name, args) { + this.name = name; + this.args = args || []; + } + PDFOperator.prototype.clone = function (context) { + var args = new Array(this.args.length); + for (var idx = 0, len = args.length; idx < len; idx++) { + var arg = this.args[idx]; + args[idx] = arg instanceof PDFObject ? arg.clone(context) : arg; + } + return PDFOperator.of(this.name, args); + }; + PDFOperator.prototype.toString = function () { + var value = ''; + for (var idx = 0, len = this.args.length; idx < len; idx++) { + value += String(this.args[idx]) + ' '; + } + value += this.name; + return value; + }; + PDFOperator.prototype.sizeInBytes = function () { + var size = 0; + for (var idx = 0, len = this.args.length; idx < len; idx++) { + var arg = this.args[idx]; + size += (arg instanceof PDFObject ? arg.sizeInBytes() : arg.length) + 1; + } + size += this.name.length; + return size; + }; + PDFOperator.prototype.copyBytesInto = function (buffer, offset) { + var initialOffset = offset; + for (var idx = 0, len = this.args.length; idx < len; idx++) { + var arg = this.args[idx]; + if (arg instanceof PDFObject) { + offset += arg.copyBytesInto(buffer, offset); + } + else { + offset += copyStringIntoBuffer(arg, buffer, offset); + } + buffer[offset++] = CharCodes$1.Space; + } + offset += copyStringIntoBuffer(this.name, buffer, offset); + return offset - initialOffset; + }; + PDFOperator.of = function (name, args) { + return new PDFOperator(name, args); + }; + return PDFOperator; +}()); + +var PDFOperatorNames; +(function (PDFOperatorNames) { + // Non Stroking Color Operators + PDFOperatorNames["NonStrokingColor"] = "sc"; + PDFOperatorNames["NonStrokingColorN"] = "scn"; + PDFOperatorNames["NonStrokingColorRgb"] = "rg"; + PDFOperatorNames["NonStrokingColorGray"] = "g"; + PDFOperatorNames["NonStrokingColorCmyk"] = "k"; + PDFOperatorNames["NonStrokingColorspace"] = "cs"; + // Stroking Color Operators + PDFOperatorNames["StrokingColor"] = "SC"; + PDFOperatorNames["StrokingColorN"] = "SCN"; + PDFOperatorNames["StrokingColorRgb"] = "RG"; + PDFOperatorNames["StrokingColorGray"] = "G"; + PDFOperatorNames["StrokingColorCmyk"] = "K"; + PDFOperatorNames["StrokingColorspace"] = "CS"; + // Marked Content Operators + PDFOperatorNames["BeginMarkedContentSequence"] = "BDC"; + PDFOperatorNames["BeginMarkedContent"] = "BMC"; + PDFOperatorNames["EndMarkedContent"] = "EMC"; + PDFOperatorNames["MarkedContentPointWithProps"] = "DP"; + PDFOperatorNames["MarkedContentPoint"] = "MP"; + PDFOperatorNames["DrawObject"] = "Do"; + // Graphics State Operators + PDFOperatorNames["ConcatTransformationMatrix"] = "cm"; + PDFOperatorNames["PopGraphicsState"] = "Q"; + PDFOperatorNames["PushGraphicsState"] = "q"; + PDFOperatorNames["SetFlatness"] = "i"; + PDFOperatorNames["SetGraphicsStateParams"] = "gs"; + PDFOperatorNames["SetLineCapStyle"] = "J"; + PDFOperatorNames["SetLineDashPattern"] = "d"; + PDFOperatorNames["SetLineJoinStyle"] = "j"; + PDFOperatorNames["SetLineMiterLimit"] = "M"; + PDFOperatorNames["SetLineWidth"] = "w"; + PDFOperatorNames["SetTextMatrix"] = "Tm"; + PDFOperatorNames["SetRenderingIntent"] = "ri"; + // Graphics Operators + PDFOperatorNames["AppendRectangle"] = "re"; + PDFOperatorNames["BeginInlineImage"] = "BI"; + PDFOperatorNames["BeginInlineImageData"] = "ID"; + PDFOperatorNames["EndInlineImage"] = "EI"; + PDFOperatorNames["ClipEvenOdd"] = "W*"; + PDFOperatorNames["ClipNonZero"] = "W"; + PDFOperatorNames["CloseAndStroke"] = "s"; + PDFOperatorNames["CloseFillEvenOddAndStroke"] = "b*"; + PDFOperatorNames["CloseFillNonZeroAndStroke"] = "b"; + PDFOperatorNames["ClosePath"] = "h"; + PDFOperatorNames["AppendBezierCurve"] = "c"; + PDFOperatorNames["CurveToReplicateFinalPoint"] = "y"; + PDFOperatorNames["CurveToReplicateInitialPoint"] = "v"; + PDFOperatorNames["EndPath"] = "n"; + PDFOperatorNames["FillEvenOddAndStroke"] = "B*"; + PDFOperatorNames["FillEvenOdd"] = "f*"; + PDFOperatorNames["FillNonZeroAndStroke"] = "B"; + PDFOperatorNames["FillNonZero"] = "f"; + PDFOperatorNames["LegacyFillNonZero"] = "F"; + PDFOperatorNames["LineTo"] = "l"; + PDFOperatorNames["MoveTo"] = "m"; + PDFOperatorNames["ShadingFill"] = "sh"; + PDFOperatorNames["StrokePath"] = "S"; + // Text Operators + PDFOperatorNames["BeginText"] = "BT"; + PDFOperatorNames["EndText"] = "ET"; + PDFOperatorNames["MoveText"] = "Td"; + PDFOperatorNames["MoveTextSetLeading"] = "TD"; + PDFOperatorNames["NextLine"] = "T*"; + PDFOperatorNames["SetCharacterSpacing"] = "Tc"; + PDFOperatorNames["SetFontAndSize"] = "Tf"; + PDFOperatorNames["SetTextHorizontalScaling"] = "Tz"; + PDFOperatorNames["SetTextLineHeight"] = "TL"; + PDFOperatorNames["SetTextRenderingMode"] = "Tr"; + PDFOperatorNames["SetTextRise"] = "Ts"; + PDFOperatorNames["SetWordSpacing"] = "Tw"; + PDFOperatorNames["ShowText"] = "Tj"; + PDFOperatorNames["ShowTextAdjusted"] = "TJ"; + PDFOperatorNames["ShowTextLine"] = "'"; + PDFOperatorNames["ShowTextLineAndSpace"] = "\""; + // Type3 Font Operators + PDFOperatorNames["Type3D0"] = "d0"; + PDFOperatorNames["Type3D1"] = "d1"; + // Compatibility Section Operators + PDFOperatorNames["BeginCompatibilitySection"] = "BX"; + PDFOperatorNames["EndCompatibilitySection"] = "EX"; +})(PDFOperatorNames || (PDFOperatorNames = {})); +var Ops = PDFOperatorNames; + +var PDFFlateStream = /** @class */ (function (_super) { + __extends(PDFFlateStream, _super); + function PDFFlateStream(dict, encode) { + var _this = _super.call(this, dict) || this; + _this.computeContents = function () { + var unencodedContents = _this.getUnencodedContents(); + return _this.encode ? pako_1$1.deflate(unencodedContents) : unencodedContents; + }; + _this.encode = encode; + if (encode) + dict.set(PDFName.of('Filter'), PDFName.of('FlateDecode')); + _this.contentsCache = Cache.populatedBy(_this.computeContents); + return _this; + } + PDFFlateStream.prototype.getContents = function () { + return this.contentsCache.access(); + }; + PDFFlateStream.prototype.getContentsSize = function () { + return this.contentsCache.access().length; + }; + PDFFlateStream.prototype.getUnencodedContents = function () { + throw new MethodNotImplementedError(this.constructor.name, 'getUnencodedContents'); + }; + return PDFFlateStream; +}(PDFStream)); + +var PDFContentStream = /** @class */ (function (_super) { + __extends(PDFContentStream, _super); + function PDFContentStream(dict, operators, encode) { + if (encode === void 0) { encode = true; } + var _this = _super.call(this, dict, encode) || this; + _this.operators = operators; + return _this; + } + PDFContentStream.prototype.push = function () { + var _a; + var operators = []; + for (var _i = 0; _i < arguments.length; _i++) { + operators[_i] = arguments[_i]; + } + (_a = this.operators).push.apply(_a, operators); + }; + PDFContentStream.prototype.clone = function (context) { + var operators = new Array(this.operators.length); + for (var idx = 0, len = this.operators.length; idx < len; idx++) { + operators[idx] = this.operators[idx].clone(context); + } + var _a = this, dict = _a.dict, encode = _a.encode; + return PDFContentStream.of(dict.clone(context), operators, encode); + }; + PDFContentStream.prototype.getContentsString = function () { + var value = ''; + for (var idx = 0, len = this.operators.length; idx < len; idx++) { + value += this.operators[idx] + "\n"; + } + return value; + }; + PDFContentStream.prototype.getUnencodedContents = function () { + var buffer = new Uint8Array(this.getUnencodedContentsSize()); + var offset = 0; + for (var idx = 0, len = this.operators.length; idx < len; idx++) { + offset += this.operators[idx].copyBytesInto(buffer, offset); + buffer[offset++] = CharCodes$1.Newline; + } + return buffer; + }; + PDFContentStream.prototype.getUnencodedContentsSize = function () { + var size = 0; + for (var idx = 0, len = this.operators.length; idx < len; idx++) { + size += this.operators[idx].sizeInBytes() + 1; + } + return size; + }; + PDFContentStream.of = function (dict, operators, encode) { + if (encode === void 0) { encode = true; } + return new PDFContentStream(dict, operators, encode); + }; + return PDFContentStream; +}(PDFFlateStream)); + +/** + * Generates a pseudo random number. Although it is not cryptographically secure + * and uniformly distributed, it is not a concern for the intended use-case, + * which is to generate distinct numbers. + * + * Credit: https://stackoverflow.com/a/19303725/10254049 + */ +var SimpleRNG = /** @class */ (function () { + function SimpleRNG(seed) { + this.seed = seed; + } + SimpleRNG.prototype.nextInt = function () { + var x = Math.sin(this.seed++) * 10000; + return x - Math.floor(x); + }; + SimpleRNG.withSeed = function (seed) { return new SimpleRNG(seed); }; + return SimpleRNG; +}()); + +var byAscendingObjectNumber = function (_a, _b) { + var a = _a[0]; + var b = _b[0]; + return a.objectNumber - b.objectNumber; +}; +var PDFContext = /** @class */ (function () { + function PDFContext() { + this.largestObjectNumber = 0; + this.header = PDFHeader.forVersion(1, 7); + this.trailerInfo = {}; + this.indirectObjects = new Map(); + this.rng = SimpleRNG.withSeed(1); + } + PDFContext.prototype.assign = function (ref, object) { + this.indirectObjects.set(ref, object); + if (ref.objectNumber > this.largestObjectNumber) { + this.largestObjectNumber = ref.objectNumber; + } + }; + PDFContext.prototype.nextRef = function () { + this.largestObjectNumber += 1; + return PDFRef.of(this.largestObjectNumber); + }; + PDFContext.prototype.register = function (object) { + var ref = this.nextRef(); + this.assign(ref, object); + return ref; + }; + PDFContext.prototype.delete = function (ref) { + return this.indirectObjects.delete(ref); + }; + PDFContext.prototype.lookupMaybe = function (ref) { + var types = []; + for (var _i = 1; _i < arguments.length; _i++) { + types[_i - 1] = arguments[_i]; + } + // TODO: `preservePDFNull` is for backwards compatibility. Should be + // removed in next breaking API change. + var preservePDFNull = types.includes(PDFNull$1); + var result = ref instanceof PDFRef ? this.indirectObjects.get(ref) : ref; + if (!result || (result === PDFNull$1 && !preservePDFNull)) + return undefined; + for (var idx = 0, len = types.length; idx < len; idx++) { + var type = types[idx]; + if (type === PDFNull$1) { + if (result === PDFNull$1) + return result; + } + else { + if (result instanceof type) + return result; + } + } + throw new UnexpectedObjectTypeError(types, result); + }; + PDFContext.prototype.lookup = function (ref) { + var types = []; + for (var _i = 1; _i < arguments.length; _i++) { + types[_i - 1] = arguments[_i]; + } + var result = ref instanceof PDFRef ? this.indirectObjects.get(ref) : ref; + if (types.length === 0) + return result; + for (var idx = 0, len = types.length; idx < len; idx++) { + var type = types[idx]; + if (type === PDFNull$1) { + if (result === PDFNull$1) + return result; + } + else { + if (result instanceof type) + return result; + } + } + throw new UnexpectedObjectTypeError(types, result); + }; + PDFContext.prototype.getObjectRef = function (pdfObject) { + var entries = Array.from(this.indirectObjects.entries()); + for (var idx = 0, len = entries.length; idx < len; idx++) { + var _a = entries[idx], ref = _a[0], object = _a[1]; + if (object === pdfObject) { + return ref; + } + } + return undefined; + }; + PDFContext.prototype.enumerateIndirectObjects = function () { + return Array.from(this.indirectObjects.entries()).sort(byAscendingObjectNumber); + }; + PDFContext.prototype.obj = function (literal) { + if (literal instanceof PDFObject) { + return literal; + } + else if (literal === null || literal === undefined) { + return PDFNull$1; + } + else if (typeof literal === 'string') { + return PDFName.of(literal); + } + else if (typeof literal === 'number') { + return PDFNumber.of(literal); + } + else if (typeof literal === 'boolean') { + return literal ? PDFBool.True : PDFBool.False; + } + else if (Array.isArray(literal)) { + var array = PDFArray.withContext(this); + for (var idx = 0, len = literal.length; idx < len; idx++) { + array.push(this.obj(literal[idx])); + } + return array; + } + else { + var dict = PDFDict.withContext(this); + var keys = Object.keys(literal); + for (var idx = 0, len = keys.length; idx < len; idx++) { + var key = keys[idx]; + var value = literal[key]; + if (value !== undefined) + dict.set(PDFName.of(key), this.obj(value)); + } + return dict; + } + }; + PDFContext.prototype.stream = function (contents, dict) { + if (dict === void 0) { dict = {}; } + return PDFRawStream.of(this.obj(dict), typedArrayFor(contents)); + }; + PDFContext.prototype.flateStream = function (contents, dict) { + if (dict === void 0) { dict = {}; } + return this.stream(pako_1$1.deflate(typedArrayFor(contents)), __assign(__assign({}, dict), { Filter: 'FlateDecode' })); + }; + PDFContext.prototype.contentStream = function (operators, dict) { + if (dict === void 0) { dict = {}; } + return PDFContentStream.of(this.obj(dict), operators); + }; + PDFContext.prototype.formXObject = function (operators, dict) { + if (dict === void 0) { dict = {}; } + return this.contentStream(operators, __assign(__assign({ BBox: this.obj([0, 0, 0, 0]), Matrix: this.obj([1, 0, 0, 1, 0, 0]) }, dict), { Type: 'XObject', Subtype: 'Form' })); + }; + /* + * Reference to PDFContentStream that contains a single PDFOperator: `q`. + * Used by [[PDFPageLeaf]] instances to ensure that when content streams are + * added to a modified PDF, they start in the default, unchanged graphics + * state. + */ + PDFContext.prototype.getPushGraphicsStateContentStream = function () { + if (this.pushGraphicsStateContentStreamRef) { + return this.pushGraphicsStateContentStreamRef; + } + var dict = this.obj({}); + var op = PDFOperator.of(Ops.PushGraphicsState); + var stream = PDFContentStream.of(dict, [op]); + this.pushGraphicsStateContentStreamRef = this.register(stream); + return this.pushGraphicsStateContentStreamRef; + }; + /* + * Reference to PDFContentStream that contains a single PDFOperator: `Q`. + * Used by [[PDFPageLeaf]] instances to ensure that when content streams are + * added to a modified PDF, they start in the default, unchanged graphics + * state. + */ + PDFContext.prototype.getPopGraphicsStateContentStream = function () { + if (this.popGraphicsStateContentStreamRef) { + return this.popGraphicsStateContentStreamRef; + } + var dict = this.obj({}); + var op = PDFOperator.of(Ops.PopGraphicsState); + var stream = PDFContentStream.of(dict, [op]); + this.popGraphicsStateContentStreamRef = this.register(stream); + return this.popGraphicsStateContentStreamRef; + }; + PDFContext.prototype.addRandomSuffix = function (prefix, suffixLength) { + if (suffixLength === void 0) { suffixLength = 4; } + return prefix + "-" + Math.floor(this.rng.nextInt() * Math.pow(10, suffixLength)); + }; + PDFContext.create = function () { return new PDFContext(); }; + return PDFContext; +}()); + +var PDFPageLeaf = /** @class */ (function (_super) { + __extends(PDFPageLeaf, _super); + function PDFPageLeaf(map, context, autoNormalizeCTM) { + if (autoNormalizeCTM === void 0) { autoNormalizeCTM = true; } + var _this = _super.call(this, map, context) || this; + _this.normalized = false; + _this.autoNormalizeCTM = autoNormalizeCTM; + return _this; + } + PDFPageLeaf.prototype.clone = function (context) { + var clone = PDFPageLeaf.fromMapWithContext(new Map(), context || this.context, this.autoNormalizeCTM); + var entries = this.entries(); + for (var idx = 0, len = entries.length; idx < len; idx++) { + var _a = entries[idx], key = _a[0], value = _a[1]; + clone.set(key, value); + } + return clone; + }; + PDFPageLeaf.prototype.Parent = function () { + return this.lookupMaybe(PDFName.Parent, PDFDict); + }; + PDFPageLeaf.prototype.Contents = function () { + return this.lookup(PDFName.of('Contents')); + }; + PDFPageLeaf.prototype.Annots = function () { + return this.lookupMaybe(PDFName.Annots, PDFArray); + }; + PDFPageLeaf.prototype.BleedBox = function () { + return this.lookupMaybe(PDFName.BleedBox, PDFArray); + }; + PDFPageLeaf.prototype.TrimBox = function () { + return this.lookupMaybe(PDFName.TrimBox, PDFArray); + }; + PDFPageLeaf.prototype.ArtBox = function () { + return this.lookupMaybe(PDFName.ArtBox, PDFArray); + }; + PDFPageLeaf.prototype.Resources = function () { + var dictOrRef = this.getInheritableAttribute(PDFName.Resources); + return this.context.lookupMaybe(dictOrRef, PDFDict); + }; + PDFPageLeaf.prototype.MediaBox = function () { + var arrayOrRef = this.getInheritableAttribute(PDFName.MediaBox); + return this.context.lookup(arrayOrRef, PDFArray); + }; + PDFPageLeaf.prototype.CropBox = function () { + var arrayOrRef = this.getInheritableAttribute(PDFName.CropBox); + return this.context.lookupMaybe(arrayOrRef, PDFArray); + }; + PDFPageLeaf.prototype.Rotate = function () { + var numberOrRef = this.getInheritableAttribute(PDFName.Rotate); + return this.context.lookupMaybe(numberOrRef, PDFNumber); + }; + PDFPageLeaf.prototype.getInheritableAttribute = function (name) { + var attribute; + this.ascend(function (node) { + if (!attribute) + attribute = node.get(name); + }); + return attribute; + }; + PDFPageLeaf.prototype.setParent = function (parentRef) { + this.set(PDFName.Parent, parentRef); + }; + PDFPageLeaf.prototype.addContentStream = function (contentStreamRef) { + var Contents = this.normalizedEntries().Contents || this.context.obj([]); + this.set(PDFName.Contents, Contents); + Contents.push(contentStreamRef); + }; + PDFPageLeaf.prototype.wrapContentStreams = function (startStream, endStream) { + var Contents = this.Contents(); + if (Contents instanceof PDFArray) { + Contents.insert(0, startStream); + Contents.push(endStream); + return true; + } + return false; + }; + PDFPageLeaf.prototype.addAnnot = function (annotRef) { + var Annots = this.normalizedEntries().Annots; + Annots.push(annotRef); + }; + PDFPageLeaf.prototype.removeAnnot = function (annotRef) { + var Annots = this.normalizedEntries().Annots; + var index = Annots.indexOf(annotRef); + if (index !== undefined) { + Annots.remove(index); + } + }; + PDFPageLeaf.prototype.setFontDictionary = function (name, fontDictRef) { + var Font = this.normalizedEntries().Font; + Font.set(name, fontDictRef); + }; + PDFPageLeaf.prototype.newFontDictionaryKey = function (tag) { + var Font = this.normalizedEntries().Font; + return Font.uniqueKey(tag); + }; + PDFPageLeaf.prototype.newFontDictionary = function (tag, fontDictRef) { + var key = this.newFontDictionaryKey(tag); + this.setFontDictionary(key, fontDictRef); + return key; + }; + PDFPageLeaf.prototype.setXObject = function (name, xObjectRef) { + var XObject = this.normalizedEntries().XObject; + XObject.set(name, xObjectRef); + }; + PDFPageLeaf.prototype.newXObjectKey = function (tag) { + var XObject = this.normalizedEntries().XObject; + return XObject.uniqueKey(tag); + }; + PDFPageLeaf.prototype.newXObject = function (tag, xObjectRef) { + var key = this.newXObjectKey(tag); + this.setXObject(key, xObjectRef); + return key; + }; + PDFPageLeaf.prototype.setExtGState = function (name, extGStateRef) { + var ExtGState = this.normalizedEntries().ExtGState; + ExtGState.set(name, extGStateRef); + }; + PDFPageLeaf.prototype.newExtGStateKey = function (tag) { + var ExtGState = this.normalizedEntries().ExtGState; + return ExtGState.uniqueKey(tag); + }; + PDFPageLeaf.prototype.newExtGState = function (tag, extGStateRef) { + var key = this.newExtGStateKey(tag); + this.setExtGState(key, extGStateRef); + return key; + }; + PDFPageLeaf.prototype.ascend = function (visitor) { + visitor(this); + var Parent = this.Parent(); + if (Parent) + Parent.ascend(visitor); + }; + PDFPageLeaf.prototype.normalize = function () { + if (this.normalized) + return; + var context = this.context; + var contentsRef = this.get(PDFName.Contents); + var contents = this.context.lookup(contentsRef); + if (contents instanceof PDFStream) { + this.set(PDFName.Contents, context.obj([contentsRef])); + } + if (this.autoNormalizeCTM) { + this.wrapContentStreams(this.context.getPushGraphicsStateContentStream(), this.context.getPopGraphicsStateContentStream()); + } + // TODO: Clone `Resources` if it is inherited + var dictOrRef = this.getInheritableAttribute(PDFName.Resources); + var Resources = context.lookupMaybe(dictOrRef, PDFDict) || context.obj({}); + this.set(PDFName.Resources, Resources); + // TODO: Clone `Font` if it is inherited + var Font = Resources.lookupMaybe(PDFName.Font, PDFDict) || context.obj({}); + Resources.set(PDFName.Font, Font); + // TODO: Clone `XObject` if it is inherited + var XObject = Resources.lookupMaybe(PDFName.XObject, PDFDict) || context.obj({}); + Resources.set(PDFName.XObject, XObject); + // TODO: Clone `ExtGState` if it is inherited + var ExtGState = Resources.lookupMaybe(PDFName.ExtGState, PDFDict) || context.obj({}); + Resources.set(PDFName.ExtGState, ExtGState); + var Annots = this.Annots() || context.obj([]); + this.set(PDFName.Annots, Annots); + this.normalized = true; + }; + PDFPageLeaf.prototype.normalizedEntries = function () { + this.normalize(); + var Annots = this.Annots(); + var Resources = this.Resources(); + var Contents = this.Contents(); + return { + Annots: Annots, + Resources: Resources, + Contents: Contents, + Font: Resources.lookup(PDFName.Font, PDFDict), + XObject: Resources.lookup(PDFName.XObject, PDFDict), + ExtGState: Resources.lookup(PDFName.ExtGState, PDFDict), + }; + }; + PDFPageLeaf.InheritableEntries = [ + 'Resources', + 'MediaBox', + 'CropBox', + 'Rotate', + ]; + PDFPageLeaf.withContextAndParent = function (context, parent) { + var dict = new Map(); + dict.set(PDFName.Type, PDFName.Page); + dict.set(PDFName.Parent, parent); + dict.set(PDFName.Resources, context.obj({})); + dict.set(PDFName.MediaBox, context.obj([0, 0, 612, 792])); + return new PDFPageLeaf(dict, context, false); + }; + PDFPageLeaf.fromMapWithContext = function (map, context, autoNormalizeCTM) { + if (autoNormalizeCTM === void 0) { autoNormalizeCTM = true; } + return new PDFPageLeaf(map, context, autoNormalizeCTM); + }; + return PDFPageLeaf; +}(PDFDict)); + +/** + * PDFObjectCopier copies PDFObjects from a src context to a dest context. + * The primary use case for this is to copy pages between PDFs. + * + * _Copying_ an object with a PDFObjectCopier is different from _cloning_ an + * object with its [[PDFObject.clone]] method: + * + * ``` + * const src: PDFContext = ... + * const dest: PDFContext = ... + * const originalObject: PDFObject = ... + * const copiedObject = PDFObjectCopier.for(src, dest).copy(originalObject); + * const clonedObject = originalObject.clone(); + * ``` + * + * Copying an object is equivalent to cloning it and then copying over any other + * objects that it references. Note that only dictionaries, arrays, and streams + * (or structures build from them) can contain indirect references to other + * objects. Copying a PDFObject that is not a dictionary, array, or stream is + * supported, but is equivalent to cloning it. + */ +var PDFObjectCopier = /** @class */ (function () { + function PDFObjectCopier(src, dest) { + var _this = this; + this.traversedObjects = new Map(); + // prettier-ignore + this.copy = function (object) { return (object instanceof PDFPageLeaf ? _this.copyPDFPage(object) + : object instanceof PDFDict ? _this.copyPDFDict(object) + : object instanceof PDFArray ? _this.copyPDFArray(object) + : object instanceof PDFStream ? _this.copyPDFStream(object) + : object instanceof PDFRef ? _this.copyPDFIndirectObject(object) + : object.clone()); }; + this.copyPDFPage = function (originalPage) { + var clonedPage = originalPage.clone(); + // Move any entries that the originalPage is inheriting from its parent + // tree nodes directly into originalPage so they are preserved during + // the copy. + var InheritableEntries = PDFPageLeaf.InheritableEntries; + for (var idx = 0, len = InheritableEntries.length; idx < len; idx++) { + var key = PDFName.of(InheritableEntries[idx]); + var value = clonedPage.getInheritableAttribute(key); + if (!clonedPage.get(key) && value) + clonedPage.set(key, value); + } + // Remove the parent reference to prevent the whole donor document's page + // tree from being copied when we only need a single page. + clonedPage.delete(PDFName.of('Parent')); + return _this.copyPDFDict(clonedPage); + }; + this.copyPDFDict = function (originalDict) { + if (_this.traversedObjects.has(originalDict)) { + return _this.traversedObjects.get(originalDict); + } + var clonedDict = originalDict.clone(_this.dest); + _this.traversedObjects.set(originalDict, clonedDict); + var entries = originalDict.entries(); + for (var idx = 0, len = entries.length; idx < len; idx++) { + var _a = entries[idx], key = _a[0], value = _a[1]; + clonedDict.set(key, _this.copy(value)); + } + return clonedDict; + }; + this.copyPDFArray = function (originalArray) { + if (_this.traversedObjects.has(originalArray)) { + return _this.traversedObjects.get(originalArray); + } + var clonedArray = originalArray.clone(_this.dest); + _this.traversedObjects.set(originalArray, clonedArray); + for (var idx = 0, len = originalArray.size(); idx < len; idx++) { + var value = originalArray.get(idx); + clonedArray.set(idx, _this.copy(value)); + } + return clonedArray; + }; + this.copyPDFStream = function (originalStream) { + if (_this.traversedObjects.has(originalStream)) { + return _this.traversedObjects.get(originalStream); + } + var clonedStream = originalStream.clone(_this.dest); + _this.traversedObjects.set(originalStream, clonedStream); + var entries = originalStream.dict.entries(); + for (var idx = 0, len = entries.length; idx < len; idx++) { + var _a = entries[idx], key = _a[0], value = _a[1]; + clonedStream.dict.set(key, _this.copy(value)); + } + return clonedStream; + }; + this.copyPDFIndirectObject = function (ref) { + var alreadyMapped = _this.traversedObjects.has(ref); + if (!alreadyMapped) { + var newRef = _this.dest.nextRef(); + _this.traversedObjects.set(ref, newRef); + var dereferencedValue = _this.src.lookup(ref); + if (dereferencedValue) { + var cloned = _this.copy(dereferencedValue); + _this.dest.assign(newRef, cloned); + } + } + return _this.traversedObjects.get(ref); + }; + this.src = src; + this.dest = dest; + } + PDFObjectCopier.for = function (src, dest) { + return new PDFObjectCopier(src, dest); + }; + return PDFObjectCopier; +}()); + +/** + * Entries should be added using the [[addEntry]] and [[addDeletedEntry]] + * methods **in order of ascending object number**. + */ +var PDFCrossRefSection = /** @class */ (function () { + function PDFCrossRefSection(firstEntry) { + this.subsections = firstEntry ? [[firstEntry]] : []; + this.chunkIdx = 0; + this.chunkLength = firstEntry ? 1 : 0; + } + PDFCrossRefSection.prototype.addEntry = function (ref, offset) { + this.append({ ref: ref, offset: offset, deleted: false }); + }; + PDFCrossRefSection.prototype.addDeletedEntry = function (ref, nextFreeObjectNumber) { + this.append({ ref: ref, offset: nextFreeObjectNumber, deleted: true }); + }; + PDFCrossRefSection.prototype.toString = function () { + var section = "xref\n"; + for (var rangeIdx = 0, rangeLen = this.subsections.length; rangeIdx < rangeLen; rangeIdx++) { + var range = this.subsections[rangeIdx]; + section += range[0].ref.objectNumber + " " + range.length + "\n"; + for (var entryIdx = 0, entryLen = range.length; entryIdx < entryLen; entryIdx++) { + var entry = range[entryIdx]; + section += padStart(String(entry.offset), 10, '0'); + section += ' '; + section += padStart(String(entry.ref.generationNumber), 5, '0'); + section += ' '; + section += entry.deleted ? 'f' : 'n'; + section += ' \n'; + } + } + return section; + }; + PDFCrossRefSection.prototype.sizeInBytes = function () { + var size = 5; + for (var idx = 0, len = this.subsections.length; idx < len; idx++) { + var subsection = this.subsections[idx]; + var subsectionLength = subsection.length; + var firstEntry = subsection[0]; + size += 2; + size += String(firstEntry.ref.objectNumber).length; + size += String(subsectionLength).length; + size += 20 * subsectionLength; + } + return size; + }; + PDFCrossRefSection.prototype.copyBytesInto = function (buffer, offset) { + var initialOffset = offset; + buffer[offset++] = CharCodes$1.x; + buffer[offset++] = CharCodes$1.r; + buffer[offset++] = CharCodes$1.e; + buffer[offset++] = CharCodes$1.f; + buffer[offset++] = CharCodes$1.Newline; + offset += this.copySubsectionsIntoBuffer(this.subsections, buffer, offset); + return offset - initialOffset; + }; + PDFCrossRefSection.prototype.copySubsectionsIntoBuffer = function (subsections, buffer, offset) { + var initialOffset = offset; + var length = subsections.length; + for (var idx = 0; idx < length; idx++) { + var subsection = this.subsections[idx]; + var firstObjectNumber = String(subsection[0].ref.objectNumber); + offset += copyStringIntoBuffer(firstObjectNumber, buffer, offset); + buffer[offset++] = CharCodes$1.Space; + var rangeLength = String(subsection.length); + offset += copyStringIntoBuffer(rangeLength, buffer, offset); + buffer[offset++] = CharCodes$1.Newline; + offset += this.copyEntriesIntoBuffer(subsection, buffer, offset); + } + return offset - initialOffset; + }; + PDFCrossRefSection.prototype.copyEntriesIntoBuffer = function (entries, buffer, offset) { + var length = entries.length; + for (var idx = 0; idx < length; idx++) { + var entry = entries[idx]; + var entryOffset = padStart(String(entry.offset), 10, '0'); + offset += copyStringIntoBuffer(entryOffset, buffer, offset); + buffer[offset++] = CharCodes$1.Space; + var entryGen = padStart(String(entry.ref.generationNumber), 5, '0'); + offset += copyStringIntoBuffer(entryGen, buffer, offset); + buffer[offset++] = CharCodes$1.Space; + buffer[offset++] = entry.deleted ? CharCodes$1.f : CharCodes$1.n; + buffer[offset++] = CharCodes$1.Space; + buffer[offset++] = CharCodes$1.Newline; + } + return 20 * length; + }; + PDFCrossRefSection.prototype.append = function (currEntry) { + if (this.chunkLength === 0) { + this.subsections.push([currEntry]); + this.chunkIdx = 0; + this.chunkLength = 1; + return; + } + var chunk = this.subsections[this.chunkIdx]; + var prevEntry = chunk[this.chunkLength - 1]; + if (currEntry.ref.objectNumber - prevEntry.ref.objectNumber > 1) { + this.subsections.push([currEntry]); + this.chunkIdx += 1; + this.chunkLength = 1; + } + else { + chunk.push(currEntry); + this.chunkLength += 1; + } + }; + PDFCrossRefSection.create = function () { + return new PDFCrossRefSection({ + ref: PDFRef.of(0, 65535), + offset: 0, + deleted: true, + }); + }; + PDFCrossRefSection.createEmpty = function () { return new PDFCrossRefSection(); }; + return PDFCrossRefSection; +}()); + +var PDFTrailer = /** @class */ (function () { + function PDFTrailer(lastXRefOffset) { + this.lastXRefOffset = String(lastXRefOffset); + } + PDFTrailer.prototype.toString = function () { + return "startxref\n" + this.lastXRefOffset + "\n%%EOF"; + }; + PDFTrailer.prototype.sizeInBytes = function () { + return 16 + this.lastXRefOffset.length; + }; + PDFTrailer.prototype.copyBytesInto = function (buffer, offset) { + var initialOffset = offset; + buffer[offset++] = CharCodes$1.s; + buffer[offset++] = CharCodes$1.t; + buffer[offset++] = CharCodes$1.a; + buffer[offset++] = CharCodes$1.r; + buffer[offset++] = CharCodes$1.t; + buffer[offset++] = CharCodes$1.x; + buffer[offset++] = CharCodes$1.r; + buffer[offset++] = CharCodes$1.e; + buffer[offset++] = CharCodes$1.f; + buffer[offset++] = CharCodes$1.Newline; + offset += copyStringIntoBuffer(this.lastXRefOffset, buffer, offset); + buffer[offset++] = CharCodes$1.Newline; + buffer[offset++] = CharCodes$1.Percent; + buffer[offset++] = CharCodes$1.Percent; + buffer[offset++] = CharCodes$1.E; + buffer[offset++] = CharCodes$1.O; + buffer[offset++] = CharCodes$1.F; + return offset - initialOffset; + }; + PDFTrailer.forLastCrossRefSectionOffset = function (offset) { + return new PDFTrailer(offset); + }; + return PDFTrailer; +}()); + +var PDFTrailerDict = /** @class */ (function () { + function PDFTrailerDict(dict) { + this.dict = dict; + } + PDFTrailerDict.prototype.toString = function () { + return "trailer\n" + this.dict.toString(); + }; + PDFTrailerDict.prototype.sizeInBytes = function () { + return 8 + this.dict.sizeInBytes(); + }; + PDFTrailerDict.prototype.copyBytesInto = function (buffer, offset) { + var initialOffset = offset; + buffer[offset++] = CharCodes$1.t; + buffer[offset++] = CharCodes$1.r; + buffer[offset++] = CharCodes$1.a; + buffer[offset++] = CharCodes$1.i; + buffer[offset++] = CharCodes$1.l; + buffer[offset++] = CharCodes$1.e; + buffer[offset++] = CharCodes$1.r; + buffer[offset++] = CharCodes$1.Newline; + offset += this.dict.copyBytesInto(buffer, offset); + return offset - initialOffset; + }; + PDFTrailerDict.of = function (dict) { return new PDFTrailerDict(dict); }; + return PDFTrailerDict; +}()); + +var PDFObjectStream = /** @class */ (function (_super) { + __extends(PDFObjectStream, _super); + function PDFObjectStream(context, objects, encode) { + if (encode === void 0) { encode = true; } + var _this = _super.call(this, context.obj({}), encode) || this; + _this.objects = objects; + _this.offsets = _this.computeObjectOffsets(); + _this.offsetsString = _this.computeOffsetsString(); + _this.dict.set(PDFName.of('Type'), PDFName.of('ObjStm')); + _this.dict.set(PDFName.of('N'), PDFNumber.of(_this.objects.length)); + _this.dict.set(PDFName.of('First'), PDFNumber.of(_this.offsetsString.length)); + return _this; + } + PDFObjectStream.prototype.getObjectsCount = function () { + return this.objects.length; + }; + PDFObjectStream.prototype.clone = function (context) { + return PDFObjectStream.withContextAndObjects(context || this.dict.context, this.objects.slice(), this.encode); + }; + PDFObjectStream.prototype.getContentsString = function () { + var value = this.offsetsString; + for (var idx = 0, len = this.objects.length; idx < len; idx++) { + var _a = this.objects[idx], object = _a[1]; + value += object + "\n"; + } + return value; + }; + PDFObjectStream.prototype.getUnencodedContents = function () { + var buffer = new Uint8Array(this.getUnencodedContentsSize()); + var offset = copyStringIntoBuffer(this.offsetsString, buffer, 0); + for (var idx = 0, len = this.objects.length; idx < len; idx++) { + var _a = this.objects[idx], object = _a[1]; + offset += object.copyBytesInto(buffer, offset); + buffer[offset++] = CharCodes$1.Newline; + } + return buffer; + }; + PDFObjectStream.prototype.getUnencodedContentsSize = function () { + return (this.offsetsString.length + + last(this.offsets)[1] + + last(this.objects)[1].sizeInBytes() + + 1); + }; + PDFObjectStream.prototype.computeOffsetsString = function () { + var offsetsString = ''; + for (var idx = 0, len = this.offsets.length; idx < len; idx++) { + var _a = this.offsets[idx], objectNumber = _a[0], offset = _a[1]; + offsetsString += objectNumber + " " + offset + " "; + } + return offsetsString; + }; + PDFObjectStream.prototype.computeObjectOffsets = function () { + var offset = 0; + var offsets = new Array(this.objects.length); + for (var idx = 0, len = this.objects.length; idx < len; idx++) { + var _a = this.objects[idx], ref = _a[0], object = _a[1]; + offsets[idx] = [ref.objectNumber, offset]; + offset += object.sizeInBytes() + 1; // '\n' + } + return offsets; + }; + PDFObjectStream.withContextAndObjects = function (context, objects, encode) { + if (encode === void 0) { encode = true; } + return new PDFObjectStream(context, objects, encode); + }; + return PDFObjectStream; +}(PDFFlateStream)); + +var PDFWriter = /** @class */ (function () { + function PDFWriter(context, objectsPerTick) { + var _this = this; + this.parsedObjects = 0; + this.shouldWaitForTick = function (n) { + _this.parsedObjects += n; + return _this.parsedObjects % _this.objectsPerTick === 0; + }; + this.context = context; + this.objectsPerTick = objectsPerTick; + } + PDFWriter.prototype.serializeToBuffer = function () { + return __awaiter(this, void 0, void 0, function () { + var _a, size, header, indirectObjects, xref, trailerDict, trailer, offset, buffer, idx, len, _b, ref, object, objectNumber, generationNumber, n; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: return [4 /*yield*/, this.computeBufferSize()]; + case 1: + _a = _c.sent(), size = _a.size, header = _a.header, indirectObjects = _a.indirectObjects, xref = _a.xref, trailerDict = _a.trailerDict, trailer = _a.trailer; + offset = 0; + buffer = new Uint8Array(size); + offset += header.copyBytesInto(buffer, offset); + buffer[offset++] = CharCodes$1.Newline; + buffer[offset++] = CharCodes$1.Newline; + idx = 0, len = indirectObjects.length; + _c.label = 2; + case 2: + if (!(idx < len)) return [3 /*break*/, 5]; + _b = indirectObjects[idx], ref = _b[0], object = _b[1]; + objectNumber = String(ref.objectNumber); + offset += copyStringIntoBuffer(objectNumber, buffer, offset); + buffer[offset++] = CharCodes$1.Space; + generationNumber = String(ref.generationNumber); + offset += copyStringIntoBuffer(generationNumber, buffer, offset); + buffer[offset++] = CharCodes$1.Space; + buffer[offset++] = CharCodes$1.o; + buffer[offset++] = CharCodes$1.b; + buffer[offset++] = CharCodes$1.j; + buffer[offset++] = CharCodes$1.Newline; + offset += object.copyBytesInto(buffer, offset); + buffer[offset++] = CharCodes$1.Newline; + buffer[offset++] = CharCodes$1.e; + buffer[offset++] = CharCodes$1.n; + buffer[offset++] = CharCodes$1.d; + buffer[offset++] = CharCodes$1.o; + buffer[offset++] = CharCodes$1.b; + buffer[offset++] = CharCodes$1.j; + buffer[offset++] = CharCodes$1.Newline; + buffer[offset++] = CharCodes$1.Newline; + n = object instanceof PDFObjectStream ? object.getObjectsCount() : 1; + if (!this.shouldWaitForTick(n)) return [3 /*break*/, 4]; + return [4 /*yield*/, waitForTick()]; + case 3: + _c.sent(); + _c.label = 4; + case 4: + idx++; + return [3 /*break*/, 2]; + case 5: + if (xref) { + offset += xref.copyBytesInto(buffer, offset); + buffer[offset++] = CharCodes$1.Newline; + } + if (trailerDict) { + offset += trailerDict.copyBytesInto(buffer, offset); + buffer[offset++] = CharCodes$1.Newline; + buffer[offset++] = CharCodes$1.Newline; + } + offset += trailer.copyBytesInto(buffer, offset); + return [2 /*return*/, buffer]; + } + }); + }); + }; + PDFWriter.prototype.computeIndirectObjectSize = function (_a) { + var ref = _a[0], object = _a[1]; + var refSize = ref.sizeInBytes() + 3; // 'R' -> 'obj\n' + var objectSize = object.sizeInBytes() + 9; // '\nendobj\n\n' + return refSize + objectSize; + }; + PDFWriter.prototype.createTrailerDict = function () { + return this.context.obj({ + Size: this.context.largestObjectNumber + 1, + Root: this.context.trailerInfo.Root, + Encrypt: this.context.trailerInfo.Encrypt, + Info: this.context.trailerInfo.Info, + ID: this.context.trailerInfo.ID, + }); + }; + PDFWriter.prototype.computeBufferSize = function () { + return __awaiter(this, void 0, void 0, function () { + var header, size, xref, indirectObjects, idx, len, indirectObject, ref, xrefOffset, trailerDict, trailer; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + header = PDFHeader.forVersion(1, 7); + size = header.sizeInBytes() + 2; + xref = PDFCrossRefSection.create(); + indirectObjects = this.context.enumerateIndirectObjects(); + idx = 0, len = indirectObjects.length; + _a.label = 1; + case 1: + if (!(idx < len)) return [3 /*break*/, 4]; + indirectObject = indirectObjects[idx]; + ref = indirectObject[0]; + xref.addEntry(ref, size); + size += this.computeIndirectObjectSize(indirectObject); + if (!this.shouldWaitForTick(1)) return [3 /*break*/, 3]; + return [4 /*yield*/, waitForTick()]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + idx++; + return [3 /*break*/, 1]; + case 4: + xrefOffset = size; + size += xref.sizeInBytes() + 1; // '\n' + trailerDict = PDFTrailerDict.of(this.createTrailerDict()); + size += trailerDict.sizeInBytes() + 2; // '\n\n' + trailer = PDFTrailer.forLastCrossRefSectionOffset(xrefOffset); + size += trailer.sizeInBytes(); + return [2 /*return*/, { size: size, header: header, indirectObjects: indirectObjects, xref: xref, trailerDict: trailerDict, trailer: trailer }]; + } + }); + }); + }; + PDFWriter.forContext = function (context, objectsPerTick) { + return new PDFWriter(context, objectsPerTick); + }; + return PDFWriter; +}()); + +var PDFInvalidObject = /** @class */ (function (_super) { + __extends(PDFInvalidObject, _super); + function PDFInvalidObject(data) { + var _this = _super.call(this) || this; + _this.data = data; + return _this; + } + PDFInvalidObject.prototype.clone = function () { + return PDFInvalidObject.of(this.data.slice()); + }; + PDFInvalidObject.prototype.toString = function () { + return "PDFInvalidObject(" + this.data.length + " bytes)"; + }; + PDFInvalidObject.prototype.sizeInBytes = function () { + return this.data.length; + }; + PDFInvalidObject.prototype.copyBytesInto = function (buffer, offset) { + var length = this.data.length; + for (var idx = 0; idx < length; idx++) { + buffer[offset++] = this.data[idx]; + } + return length; + }; + PDFInvalidObject.of = function (data) { return new PDFInvalidObject(data); }; + return PDFInvalidObject; +}(PDFObject)); + +var EntryType; +(function (EntryType) { + EntryType[EntryType["Deleted"] = 0] = "Deleted"; + EntryType[EntryType["Uncompressed"] = 1] = "Uncompressed"; + EntryType[EntryType["Compressed"] = 2] = "Compressed"; +})(EntryType || (EntryType = {})); +/** + * Entries should be added using the [[addDeletedEntry]], + * [[addUncompressedEntry]], and [[addCompressedEntry]] methods + * **in order of ascending object number**. + */ +var PDFCrossRefStream = /** @class */ (function (_super) { + __extends(PDFCrossRefStream, _super); + function PDFCrossRefStream(dict, entries, encode) { + if (encode === void 0) { encode = true; } + var _this = _super.call(this, dict, encode) || this; + // Returns an array of integer pairs for each subsection of the cross ref + // section, where each integer pair represents: + // firstObjectNumber(OfSection), length(OfSection) + _this.computeIndex = function () { + var subsections = []; + var subsectionLength = 0; + for (var idx = 0, len = _this.entries.length; idx < len; idx++) { + var currEntry = _this.entries[idx]; + var prevEntry = _this.entries[idx - 1]; + if (idx === 0) { + subsections.push(currEntry.ref.objectNumber); + } + else if (currEntry.ref.objectNumber - prevEntry.ref.objectNumber > 1) { + subsections.push(subsectionLength); + subsections.push(currEntry.ref.objectNumber); + subsectionLength = 0; + } + subsectionLength += 1; + } + subsections.push(subsectionLength); + return subsections; + }; + _this.computeEntryTuples = function () { + var entryTuples = new Array(_this.entries.length); + for (var idx = 0, len = _this.entries.length; idx < len; idx++) { + var entry = _this.entries[idx]; + if (entry.type === EntryType.Deleted) { + var type = entry.type, nextFreeObjectNumber = entry.nextFreeObjectNumber, ref = entry.ref; + entryTuples[idx] = [type, nextFreeObjectNumber, ref.generationNumber]; + } + if (entry.type === EntryType.Uncompressed) { + var type = entry.type, offset = entry.offset, ref = entry.ref; + entryTuples[idx] = [type, offset, ref.generationNumber]; + } + if (entry.type === EntryType.Compressed) { + var type = entry.type, objectStreamRef = entry.objectStreamRef, index = entry.index; + entryTuples[idx] = [type, objectStreamRef.objectNumber, index]; + } + } + return entryTuples; + }; + _this.computeMaxEntryByteWidths = function () { + var entryTuples = _this.entryTuplesCache.access(); + var widths = [0, 0, 0]; + for (var idx = 0, len = entryTuples.length; idx < len; idx++) { + var _a = entryTuples[idx], first = _a[0], second = _a[1], third = _a[2]; + var firstSize = sizeInBytes(first); + var secondSize = sizeInBytes(second); + var thirdSize = sizeInBytes(third); + if (firstSize > widths[0]) + widths[0] = firstSize; + if (secondSize > widths[1]) + widths[1] = secondSize; + if (thirdSize > widths[2]) + widths[2] = thirdSize; + } + return widths; + }; + _this.entries = entries || []; + _this.entryTuplesCache = Cache.populatedBy(_this.computeEntryTuples); + _this.maxByteWidthsCache = Cache.populatedBy(_this.computeMaxEntryByteWidths); + _this.indexCache = Cache.populatedBy(_this.computeIndex); + dict.set(PDFName.of('Type'), PDFName.of('XRef')); + return _this; + } + PDFCrossRefStream.prototype.addDeletedEntry = function (ref, nextFreeObjectNumber) { + var type = EntryType.Deleted; + this.entries.push({ type: type, ref: ref, nextFreeObjectNumber: nextFreeObjectNumber }); + this.entryTuplesCache.invalidate(); + this.maxByteWidthsCache.invalidate(); + this.indexCache.invalidate(); + this.contentsCache.invalidate(); + }; + PDFCrossRefStream.prototype.addUncompressedEntry = function (ref, offset) { + var type = EntryType.Uncompressed; + this.entries.push({ type: type, ref: ref, offset: offset }); + this.entryTuplesCache.invalidate(); + this.maxByteWidthsCache.invalidate(); + this.indexCache.invalidate(); + this.contentsCache.invalidate(); + }; + PDFCrossRefStream.prototype.addCompressedEntry = function (ref, objectStreamRef, index) { + var type = EntryType.Compressed; + this.entries.push({ type: type, ref: ref, objectStreamRef: objectStreamRef, index: index }); + this.entryTuplesCache.invalidate(); + this.maxByteWidthsCache.invalidate(); + this.indexCache.invalidate(); + this.contentsCache.invalidate(); + }; + PDFCrossRefStream.prototype.clone = function (context) { + var _a = this, dict = _a.dict, entries = _a.entries, encode = _a.encode; + return PDFCrossRefStream.of(dict.clone(context), entries.slice(), encode); + }; + PDFCrossRefStream.prototype.getContentsString = function () { + var entryTuples = this.entryTuplesCache.access(); + var byteWidths = this.maxByteWidthsCache.access(); + var value = ''; + for (var entryIdx = 0, entriesLen = entryTuples.length; entryIdx < entriesLen; entryIdx++) { + var _a = entryTuples[entryIdx], first = _a[0], second = _a[1], third = _a[2]; + var firstBytes = reverseArray(bytesFor(first)); + var secondBytes = reverseArray(bytesFor(second)); + var thirdBytes = reverseArray(bytesFor(third)); + for (var idx = byteWidths[0] - 1; idx >= 0; idx--) { + value += (firstBytes[idx] || 0).toString(2); + } + for (var idx = byteWidths[1] - 1; idx >= 0; idx--) { + value += (secondBytes[idx] || 0).toString(2); + } + for (var idx = byteWidths[2] - 1; idx >= 0; idx--) { + value += (thirdBytes[idx] || 0).toString(2); + } + } + return value; + }; + PDFCrossRefStream.prototype.getUnencodedContents = function () { + var entryTuples = this.entryTuplesCache.access(); + var byteWidths = this.maxByteWidthsCache.access(); + var buffer = new Uint8Array(this.getUnencodedContentsSize()); + var offset = 0; + for (var entryIdx = 0, entriesLen = entryTuples.length; entryIdx < entriesLen; entryIdx++) { + var _a = entryTuples[entryIdx], first = _a[0], second = _a[1], third = _a[2]; + var firstBytes = reverseArray(bytesFor(first)); + var secondBytes = reverseArray(bytesFor(second)); + var thirdBytes = reverseArray(bytesFor(third)); + for (var idx = byteWidths[0] - 1; idx >= 0; idx--) { + buffer[offset++] = firstBytes[idx] || 0; + } + for (var idx = byteWidths[1] - 1; idx >= 0; idx--) { + buffer[offset++] = secondBytes[idx] || 0; + } + for (var idx = byteWidths[2] - 1; idx >= 0; idx--) { + buffer[offset++] = thirdBytes[idx] || 0; + } + } + return buffer; + }; + PDFCrossRefStream.prototype.getUnencodedContentsSize = function () { + var byteWidths = this.maxByteWidthsCache.access(); + var entryWidth = sum(byteWidths); + return entryWidth * this.entries.length; + }; + PDFCrossRefStream.prototype.updateDict = function () { + _super.prototype.updateDict.call(this); + var byteWidths = this.maxByteWidthsCache.access(); + var index = this.indexCache.access(); + var context = this.dict.context; + this.dict.set(PDFName.of('W'), context.obj(byteWidths)); + this.dict.set(PDFName.of('Index'), context.obj(index)); + }; + PDFCrossRefStream.create = function (dict, encode) { + if (encode === void 0) { encode = true; } + var stream = new PDFCrossRefStream(dict, [], encode); + stream.addDeletedEntry(PDFRef.of(0, 65535), 0); + return stream; + }; + PDFCrossRefStream.of = function (dict, entries, encode) { + if (encode === void 0) { encode = true; } + return new PDFCrossRefStream(dict, entries, encode); + }; + return PDFCrossRefStream; +}(PDFFlateStream)); + +var PDFStreamWriter = /** @class */ (function (_super) { + __extends(PDFStreamWriter, _super); + function PDFStreamWriter(context, objectsPerTick, encodeStreams, objectsPerStream) { + var _this = _super.call(this, context, objectsPerTick) || this; + _this.encodeStreams = encodeStreams; + _this.objectsPerStream = objectsPerStream; + return _this; + } + PDFStreamWriter.prototype.computeBufferSize = function () { + return __awaiter(this, void 0, void 0, function () { + var objectNumber, header, size, xrefStream, uncompressedObjects, compressedObjects, objectStreamRefs, indirectObjects, idx, len, indirectObject, ref, object, shouldNotCompress, chunk, objectStreamRef, idx, len, chunk, ref, objectStream, xrefStreamRef, xrefOffset, trailer; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + objectNumber = this.context.largestObjectNumber + 1; + header = PDFHeader.forVersion(1, 7); + size = header.sizeInBytes() + 2; + xrefStream = PDFCrossRefStream.create(this.createTrailerDict(), this.encodeStreams); + uncompressedObjects = []; + compressedObjects = []; + objectStreamRefs = []; + indirectObjects = this.context.enumerateIndirectObjects(); + idx = 0, len = indirectObjects.length; + _a.label = 1; + case 1: + if (!(idx < len)) return [3 /*break*/, 6]; + indirectObject = indirectObjects[idx]; + ref = indirectObject[0], object = indirectObject[1]; + shouldNotCompress = ref === this.context.trailerInfo.Encrypt || + object instanceof PDFStream || + object instanceof PDFInvalidObject || + ref.generationNumber !== 0; + if (!shouldNotCompress) return [3 /*break*/, 4]; + uncompressedObjects.push(indirectObject); + xrefStream.addUncompressedEntry(ref, size); + size += this.computeIndirectObjectSize(indirectObject); + if (!this.shouldWaitForTick(1)) return [3 /*break*/, 3]; + return [4 /*yield*/, waitForTick()]; + case 2: + _a.sent(); + _a.label = 3; + case 3: return [3 /*break*/, 5]; + case 4: + chunk = last(compressedObjects); + objectStreamRef = last(objectStreamRefs); + if (!chunk || chunk.length % this.objectsPerStream === 0) { + chunk = []; + compressedObjects.push(chunk); + objectStreamRef = PDFRef.of(objectNumber++); + objectStreamRefs.push(objectStreamRef); + } + xrefStream.addCompressedEntry(ref, objectStreamRef, chunk.length); + chunk.push(indirectObject); + _a.label = 5; + case 5: + idx++; + return [3 /*break*/, 1]; + case 6: + idx = 0, len = compressedObjects.length; + _a.label = 7; + case 7: + if (!(idx < len)) return [3 /*break*/, 10]; + chunk = compressedObjects[idx]; + ref = objectStreamRefs[idx]; + objectStream = PDFObjectStream.withContextAndObjects(this.context, chunk, this.encodeStreams); + xrefStream.addUncompressedEntry(ref, size); + size += this.computeIndirectObjectSize([ref, objectStream]); + uncompressedObjects.push([ref, objectStream]); + if (!this.shouldWaitForTick(chunk.length)) return [3 /*break*/, 9]; + return [4 /*yield*/, waitForTick()]; + case 8: + _a.sent(); + _a.label = 9; + case 9: + idx++; + return [3 /*break*/, 7]; + case 10: + xrefStreamRef = PDFRef.of(objectNumber++); + xrefStream.dict.set(PDFName.of('Size'), PDFNumber.of(objectNumber)); + xrefStream.addUncompressedEntry(xrefStreamRef, size); + xrefOffset = size; + size += this.computeIndirectObjectSize([xrefStreamRef, xrefStream]); + uncompressedObjects.push([xrefStreamRef, xrefStream]); + trailer = PDFTrailer.forLastCrossRefSectionOffset(xrefOffset); + size += trailer.sizeInBytes(); + return [2 /*return*/, { size: size, header: header, indirectObjects: uncompressedObjects, trailer: trailer }]; + } + }); + }); + }; + PDFStreamWriter.forContext = function (context, objectsPerTick, encodeStreams, objectsPerStream) { + if (encodeStreams === void 0) { encodeStreams = true; } + if (objectsPerStream === void 0) { objectsPerStream = 50; } + return new PDFStreamWriter(context, objectsPerTick, encodeStreams, objectsPerStream); + }; + return PDFStreamWriter; +}(PDFWriter)); + +var PDFHexString = /** @class */ (function (_super) { + __extends(PDFHexString, _super); + function PDFHexString(value) { + var _this = _super.call(this) || this; + _this.value = value; + return _this; + } + PDFHexString.prototype.asBytes = function () { + // Append a zero if the number of digits is odd. See PDF spec 7.3.4.3 + var hex = this.value + (this.value.length % 2 === 1 ? '0' : ''); + var hexLength = hex.length; + var bytes = new Uint8Array(hex.length / 2); + var hexOffset = 0; + var bytesOffset = 0; + // Interpret each pair of hex digits as a single byte + while (hexOffset < hexLength) { + var byte = parseInt(hex.substring(hexOffset, hexOffset + 2), 16); + bytes[bytesOffset] = byte; + hexOffset += 2; + bytesOffset += 1; + } + return bytes; + }; + PDFHexString.prototype.decodeText = function () { + var bytes = this.asBytes(); + if (hasUtf16BOM(bytes)) + return utf16Decode(bytes); + return pdfDocEncodingDecode(bytes); + }; + PDFHexString.prototype.decodeDate = function () { + var text = this.decodeText(); + var date = parseDate(text); + if (!date) + throw new InvalidPDFDateStringError(text); + return date; + }; + PDFHexString.prototype.asString = function () { + return this.value; + }; + PDFHexString.prototype.clone = function () { + return PDFHexString.of(this.value); + }; + PDFHexString.prototype.toString = function () { + return "<" + this.value + ">"; + }; + PDFHexString.prototype.sizeInBytes = function () { + return this.value.length + 2; + }; + PDFHexString.prototype.copyBytesInto = function (buffer, offset) { + buffer[offset++] = CharCodes$1.LessThan; + offset += copyStringIntoBuffer(this.value, buffer, offset); + buffer[offset++] = CharCodes$1.GreaterThan; + return this.value.length + 2; + }; + PDFHexString.of = function (value) { return new PDFHexString(value); }; + PDFHexString.fromText = function (value) { + var encoded = utf16Encode(value); + var hex = ''; + for (var idx = 0, len = encoded.length; idx < len; idx++) { + hex += toHexStringOfMinLength(encoded[idx], 4); + } + return new PDFHexString(hex); + }; + return PDFHexString; +}(PDFObject)); + +/** + * A note of thanks to the developers of https://github.com/foliojs/pdfkit, as + * this class borrows from: + * https://github.com/foliojs/pdfkit/blob/f91bdd61c164a72ea06be1a43dc0a412afc3925f/lib/font/afm.coffee + */ +var StandardFontEmbedder = /** @class */ (function () { + function StandardFontEmbedder(fontName, customName) { + // prettier-ignore + this.encoding = (fontName === FontNames.ZapfDingbats ? Encodings.ZapfDingbats + : fontName === FontNames.Symbol ? Encodings.Symbol + : Encodings.WinAnsi); + this.font = Font.load(fontName); + this.fontName = this.font.FontName; + this.customName = customName; + } + /** + * Encode the JavaScript string into this font. (JavaScript encodes strings in + * Unicode, but standard fonts use either WinAnsi, ZapfDingbats, or Symbol + * encodings) + */ + StandardFontEmbedder.prototype.encodeText = function (text) { + var glyphs = this.encodeTextAsGlyphs(text); + var hexCodes = new Array(glyphs.length); + for (var idx = 0, len = glyphs.length; idx < len; idx++) { + hexCodes[idx] = toHexString(glyphs[idx].code); + } + return PDFHexString.of(hexCodes.join('')); + }; + StandardFontEmbedder.prototype.widthOfTextAtSize = function (text, size) { + var glyphs = this.encodeTextAsGlyphs(text); + var totalWidth = 0; + for (var idx = 0, len = glyphs.length; idx < len; idx++) { + var left = glyphs[idx].name; + var right = (glyphs[idx + 1] || {}).name; + var kernAmount = this.font.getXAxisKerningForPair(left, right) || 0; + totalWidth += this.widthOfGlyph(left) + kernAmount; + } + var scale = size / 1000; + return totalWidth * scale; + }; + StandardFontEmbedder.prototype.heightOfFontAtSize = function (size, options) { + if (options === void 0) { options = {}; } + var _a = options.descender, descender = _a === void 0 ? true : _a; + var _b = this.font, Ascender = _b.Ascender, Descender = _b.Descender, FontBBox = _b.FontBBox; + var yTop = Ascender || FontBBox[3]; + var yBottom = Descender || FontBBox[1]; + var height = yTop - yBottom; + if (!descender) + height += Descender || 0; + return (height / 1000) * size; + }; + StandardFontEmbedder.prototype.sizeOfFontAtHeight = function (height) { + var _a = this.font, Ascender = _a.Ascender, Descender = _a.Descender, FontBBox = _a.FontBBox; + var yTop = Ascender || FontBBox[3]; + var yBottom = Descender || FontBBox[1]; + return (1000 * height) / (yTop - yBottom); + }; + StandardFontEmbedder.prototype.embedIntoContext = function (context, ref) { + var fontDict = context.obj({ + Type: 'Font', + Subtype: 'Type1', + BaseFont: this.customName || this.fontName, + Encoding: this.encoding === Encodings.WinAnsi ? 'WinAnsiEncoding' : undefined, + }); + if (ref) { + context.assign(ref, fontDict); + return ref; + } + else { + return context.register(fontDict); + } + }; + StandardFontEmbedder.prototype.widthOfGlyph = function (glyphName) { + // Default to 250 if font doesn't specify a width + return this.font.getWidthOfGlyph(glyphName) || 250; + }; + StandardFontEmbedder.prototype.encodeTextAsGlyphs = function (text) { + var codePoints = Array.from(text); + var glyphs = new Array(codePoints.length); + for (var idx = 0, len = codePoints.length; idx < len; idx++) { + var codePoint = toCodePoint(codePoints[idx]); + glyphs[idx] = this.encoding.encodeUnicodeCodePoint(codePoint); + } + return glyphs; + }; + StandardFontEmbedder.for = function (fontName, customName) { + return new StandardFontEmbedder(fontName, customName); + }; + return StandardFontEmbedder; +}()); + +/** `glyphs` should be an array of unique glyphs */ +var createCmap = function (glyphs, glyphId) { + var bfChars = new Array(glyphs.length); + for (var idx = 0, len = glyphs.length; idx < len; idx++) { + var glyph = glyphs[idx]; + var id = cmapHexFormat(cmapHexString(glyphId(glyph))); + var unicode = cmapHexFormat.apply(void 0, glyph.codePoints.map(cmapCodePointFormat)); + bfChars[idx] = [id, unicode]; + } + return fillCmapTemplate(bfChars); +}; +/* =============================== Templates ================================ */ +var fillCmapTemplate = function (bfChars) { return "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo <<\n /Registry (Adobe)\n /Ordering (UCS)\n /Supplement 0\n>> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000><ffff>\nendcodespacerange\n" + bfChars.length + " beginbfchar\n" + bfChars.map(function (_a) { + var glyphId = _a[0], codePoint = _a[1]; + return glyphId + " " + codePoint; +}).join('\n') + "\nendbfchar\nendcmap\nCMapName currentdict /CMap defineresource pop\nend\nend"; }; +/* =============================== Utilities ================================ */ +var cmapHexFormat = function () { + var values = []; + for (var _i = 0; _i < arguments.length; _i++) { + values[_i] = arguments[_i]; + } + return "<" + values.join('') + ">"; +}; +var cmapHexString = function (value) { return toHexStringOfMinLength(value, 4); }; +var cmapCodePointFormat = function (codePoint) { + if (isWithinBMP(codePoint)) + return cmapHexString(codePoint); + if (hasSurrogates(codePoint)) { + var hs = highSurrogate(codePoint); + var ls = lowSurrogate(codePoint); + return "" + cmapHexString(hs) + cmapHexString(ls); + } + var hex = toHexString(codePoint); + var msg = "0x" + hex + " is not a valid UTF-8 or UTF-16 codepoint."; + throw new Error(msg); +}; + +// prettier-ignore +var makeFontFlags = function (options) { + var flags = 0; + var flipBit = function (bit) { flags |= (1 << (bit - 1)); }; + if (options.fixedPitch) + flipBit(1); + if (options.serif) + flipBit(2); + if (options.symbolic) + flipBit(3); + if (options.script) + flipBit(4); + if (options.nonsymbolic) + flipBit(6); + if (options.italic) + flipBit(7); + if (options.allCap) + flipBit(17); + if (options.smallCap) + flipBit(18); + if (options.forceBold) + flipBit(19); + return flags; +}; +// From: https://github.com/foliojs/pdfkit/blob/83f5f7243172a017adcf6a7faa5547c55982c57b/lib/font/embedded.js#L123-L129 +var deriveFontFlags = function (font) { + var familyClass = font['OS/2'] ? font['OS/2'].sFamilyClass : 0; + var flags = makeFontFlags({ + fixedPitch: font.post.isFixedPitch, + serif: 1 <= familyClass && familyClass <= 7, + symbolic: true, + script: familyClass === 10, + italic: font.head.macStyle.italic, + }); + return flags; +}; + +var PDFString = /** @class */ (function (_super) { + __extends(PDFString, _super); + function PDFString(value) { + var _this = _super.call(this) || this; + _this.value = value; + return _this; + } + PDFString.prototype.asBytes = function () { + var bytes = []; + var octal = ''; + var escaped = false; + var pushByte = function (byte) { + if (byte !== undefined) + bytes.push(byte); + escaped = false; + }; + for (var idx = 0, len = this.value.length; idx < len; idx++) { + var char = this.value[idx]; + var byte = toCharCode(char); + var nextChar = this.value[idx + 1]; + if (!escaped) { + if (byte === CharCodes$1.BackSlash) + escaped = true; + else + pushByte(byte); + } + else { + if (byte === CharCodes$1.Newline) + pushByte(); + else if (byte === CharCodes$1.CarriageReturn) + pushByte(); + else if (byte === CharCodes$1.n) + pushByte(CharCodes$1.Newline); + else if (byte === CharCodes$1.r) + pushByte(CharCodes$1.CarriageReturn); + else if (byte === CharCodes$1.t) + pushByte(CharCodes$1.Tab); + else if (byte === CharCodes$1.b) + pushByte(CharCodes$1.Backspace); + else if (byte === CharCodes$1.f) + pushByte(CharCodes$1.FormFeed); + else if (byte === CharCodes$1.LeftParen) + pushByte(CharCodes$1.LeftParen); + else if (byte === CharCodes$1.RightParen) + pushByte(CharCodes$1.RightParen); + else if (byte === CharCodes$1.Backspace) + pushByte(CharCodes$1.BackSlash); + else if (byte >= CharCodes$1.Zero && byte <= CharCodes$1.Seven) { + octal += char; + if (octal.length === 3 || !(nextChar >= '0' && nextChar <= '7')) { + pushByte(parseInt(octal, 8)); + octal = ''; + } + } + else { + pushByte(byte); + } + } + } + return new Uint8Array(bytes); + }; + PDFString.prototype.decodeText = function () { + var bytes = this.asBytes(); + if (hasUtf16BOM(bytes)) + return utf16Decode(bytes); + return pdfDocEncodingDecode(bytes); + }; + PDFString.prototype.decodeDate = function () { + var text = this.decodeText(); + var date = parseDate(text); + if (!date) + throw new InvalidPDFDateStringError(text); + return date; + }; + PDFString.prototype.asString = function () { + return this.value; + }; + PDFString.prototype.clone = function () { + return PDFString.of(this.value); + }; + PDFString.prototype.toString = function () { + return "(" + this.value + ")"; + }; + PDFString.prototype.sizeInBytes = function () { + return this.value.length + 2; + }; + PDFString.prototype.copyBytesInto = function (buffer, offset) { + buffer[offset++] = CharCodes$1.LeftParen; + offset += copyStringIntoBuffer(this.value, buffer, offset); + buffer[offset++] = CharCodes$1.RightParen; + return this.value.length + 2; + }; + // The PDF spec allows newlines and parens to appear directly within a literal + // string. These character _may_ be escaped. But they do not _have_ to be. So + // for simplicity, we will not bother escaping them. + PDFString.of = function (value) { return new PDFString(value); }; + PDFString.fromDate = function (date) { + var year = padStart(String(date.getUTCFullYear()), 4, '0'); + var month = padStart(String(date.getUTCMonth() + 1), 2, '0'); + var day = padStart(String(date.getUTCDate()), 2, '0'); + var hours = padStart(String(date.getUTCHours()), 2, '0'); + var mins = padStart(String(date.getUTCMinutes()), 2, '0'); + var secs = padStart(String(date.getUTCSeconds()), 2, '0'); + return new PDFString("D:" + year + month + day + hours + mins + secs + "Z"); + }; + return PDFString; +}(PDFObject)); + +/** + * A note of thanks to the developers of https://github.com/foliojs/pdfkit, as + * this class borrows from: + * https://github.com/devongovett/pdfkit/blob/e71edab0dd4657b5a767804ba86c94c58d01fbca/lib/image/jpeg.coffee + */ +var CustomFontEmbedder = /** @class */ (function () { + function CustomFontEmbedder(font, fontData, customName, fontFeatures) { + var _this = this; + this.allGlyphsInFontSortedById = function () { + var glyphs = new Array(_this.font.characterSet.length); + for (var idx = 0, len = glyphs.length; idx < len; idx++) { + var codePoint = _this.font.characterSet[idx]; + glyphs[idx] = _this.font.glyphForCodePoint(codePoint); + } + return sortedUniq(glyphs.sort(byAscendingId), function (g) { return g.id; }); + }; + this.font = font; + this.scale = 1000 / this.font.unitsPerEm; + this.fontData = fontData; + this.fontName = this.font.postscriptName || 'Font'; + this.customName = customName; + this.fontFeatures = fontFeatures; + this.baseFontName = ''; + this.glyphCache = Cache.populatedBy(this.allGlyphsInFontSortedById); + } + CustomFontEmbedder.for = function (fontkit, fontData, customName, fontFeatures) { + return __awaiter(this, void 0, void 0, function () { + var font; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, fontkit.create(fontData)]; + case 1: + font = _a.sent(); + return [2 /*return*/, new CustomFontEmbedder(font, fontData, customName, fontFeatures)]; + } + }); + }); + }; + /** + * Encode the JavaScript string into this font. (JavaScript encodes strings in + * Unicode, but embedded fonts use their own custom encodings) + */ + CustomFontEmbedder.prototype.encodeText = function (text) { + var glyphs = this.font.layout(text, this.fontFeatures).glyphs; + var hexCodes = new Array(glyphs.length); + for (var idx = 0, len = glyphs.length; idx < len; idx++) { + hexCodes[idx] = toHexStringOfMinLength(glyphs[idx].id, 4); + } + return PDFHexString.of(hexCodes.join('')); + }; + // The advanceWidth takes into account kerning automatically, so we don't + // have to do that manually like we do for the standard fonts. + CustomFontEmbedder.prototype.widthOfTextAtSize = function (text, size) { + var glyphs = this.font.layout(text, this.fontFeatures).glyphs; + var totalWidth = 0; + for (var idx = 0, len = glyphs.length; idx < len; idx++) { + totalWidth += glyphs[idx].advanceWidth * this.scale; + } + var scale = size / 1000; + return totalWidth * scale; + }; + CustomFontEmbedder.prototype.heightOfFontAtSize = function (size, options) { + if (options === void 0) { options = {}; } + var _a = options.descender, descender = _a === void 0 ? true : _a; + var _b = this.font, ascent = _b.ascent, descent = _b.descent, bbox = _b.bbox; + var yTop = (ascent || bbox.maxY) * this.scale; + var yBottom = (descent || bbox.minY) * this.scale; + var height = yTop - yBottom; + if (!descender) + height -= Math.abs(descent) || 0; + return (height / 1000) * size; + }; + CustomFontEmbedder.prototype.sizeOfFontAtHeight = function (height) { + var _a = this.font, ascent = _a.ascent, descent = _a.descent, bbox = _a.bbox; + var yTop = (ascent || bbox.maxY) * this.scale; + var yBottom = (descent || bbox.minY) * this.scale; + return (1000 * height) / (yTop - yBottom); + }; + CustomFontEmbedder.prototype.embedIntoContext = function (context, ref) { + this.baseFontName = + this.customName || context.addRandomSuffix(this.fontName); + return this.embedFontDict(context, ref); + }; + CustomFontEmbedder.prototype.embedFontDict = function (context, ref) { + return __awaiter(this, void 0, void 0, function () { + var cidFontDictRef, unicodeCMapRef, fontDict; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.embedCIDFontDict(context)]; + case 1: + cidFontDictRef = _a.sent(); + unicodeCMapRef = this.embedUnicodeCmap(context); + fontDict = context.obj({ + Type: 'Font', + Subtype: 'Type0', + BaseFont: this.baseFontName, + Encoding: 'Identity-H', + DescendantFonts: [cidFontDictRef], + ToUnicode: unicodeCMapRef, + }); + if (ref) { + context.assign(ref, fontDict); + return [2 /*return*/, ref]; + } + else { + return [2 /*return*/, context.register(fontDict)]; + } + } + }); + }); + }; + CustomFontEmbedder.prototype.isCFF = function () { + return this.font.cff; + }; + CustomFontEmbedder.prototype.embedCIDFontDict = function (context) { + return __awaiter(this, void 0, void 0, function () { + var fontDescriptorRef, cidFontDict; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.embedFontDescriptor(context)]; + case 1: + fontDescriptorRef = _a.sent(); + cidFontDict = context.obj({ + Type: 'Font', + Subtype: this.isCFF() ? 'CIDFontType0' : 'CIDFontType2', + CIDToGIDMap: 'Identity', + BaseFont: this.baseFontName, + CIDSystemInfo: { + Registry: PDFString.of('Adobe'), + Ordering: PDFString.of('Identity'), + Supplement: 0, + }, + FontDescriptor: fontDescriptorRef, + W: this.computeWidths(), + }); + return [2 /*return*/, context.register(cidFontDict)]; + } + }); + }); + }; + CustomFontEmbedder.prototype.embedFontDescriptor = function (context) { + return __awaiter(this, void 0, void 0, function () { + var fontStreamRef, scale, _a, italicAngle, ascent, descent, capHeight, xHeight, _b, minX, minY, maxX, maxY, fontDescriptor; + var _c; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: return [4 /*yield*/, this.embedFontStream(context)]; + case 1: + fontStreamRef = _d.sent(); + scale = this.scale; + _a = this.font, italicAngle = _a.italicAngle, ascent = _a.ascent, descent = _a.descent, capHeight = _a.capHeight, xHeight = _a.xHeight; + _b = this.font.bbox, minX = _b.minX, minY = _b.minY, maxX = _b.maxX, maxY = _b.maxY; + fontDescriptor = context.obj((_c = { + Type: 'FontDescriptor', + FontName: this.baseFontName, + Flags: deriveFontFlags(this.font), + FontBBox: [minX * scale, minY * scale, maxX * scale, maxY * scale], + ItalicAngle: italicAngle, + Ascent: ascent * scale, + Descent: descent * scale, + CapHeight: (capHeight || ascent) * scale, + XHeight: (xHeight || 0) * scale, + // Not sure how to compute/find this, nor is anybody else really: + // https://stackoverflow.com/questions/35485179/stemv-value-of-the-truetype-font + StemV: 0 + }, + _c[this.isCFF() ? 'FontFile3' : 'FontFile2'] = fontStreamRef, + _c)); + return [2 /*return*/, context.register(fontDescriptor)]; + } + }); + }); + }; + CustomFontEmbedder.prototype.serializeFont = function () { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + return [2 /*return*/, this.fontData]; + }); + }); + }; + CustomFontEmbedder.prototype.embedFontStream = function (context) { + return __awaiter(this, void 0, void 0, function () { + var fontStream, _a, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = (_a = context).flateStream; + return [4 /*yield*/, this.serializeFont()]; + case 1: + fontStream = _b.apply(_a, [_c.sent(), { + Subtype: this.isCFF() ? 'CIDFontType0C' : undefined, + }]); + return [2 /*return*/, context.register(fontStream)]; + } + }); + }); + }; + CustomFontEmbedder.prototype.embedUnicodeCmap = function (context) { + var cmap = createCmap(this.glyphCache.access(), this.glyphId.bind(this)); + var cmapStream = context.flateStream(cmap); + return context.register(cmapStream); + }; + CustomFontEmbedder.prototype.glyphId = function (glyph) { + return glyph ? glyph.id : -1; + }; + CustomFontEmbedder.prototype.computeWidths = function () { + var glyphs = this.glyphCache.access(); + var widths = []; + var currSection = []; + for (var idx = 0, len = glyphs.length; idx < len; idx++) { + var currGlyph = glyphs[idx]; + var prevGlyph = glyphs[idx - 1]; + var currGlyphId = this.glyphId(currGlyph); + var prevGlyphId = this.glyphId(prevGlyph); + if (idx === 0) { + widths.push(currGlyphId); + } + else if (currGlyphId - prevGlyphId !== 1) { + widths.push(currSection); + widths.push(currGlyphId); + currSection = []; + } + currSection.push(currGlyph.advanceWidth * this.scale); + } + widths.push(currSection); + return widths; + }; + return CustomFontEmbedder; +}()); + +/** + * A note of thanks to the developers of https://github.com/foliojs/pdfkit, as + * this class borrows from: + * https://github.com/devongovett/pdfkit/blob/e71edab0dd4657b5a767804ba86c94c58d01fbca/lib/image/jpeg.coffee + */ +var CustomFontSubsetEmbedder = /** @class */ (function (_super) { + __extends(CustomFontSubsetEmbedder, _super); + function CustomFontSubsetEmbedder(font, fontData, customFontName, fontFeatures) { + var _this = _super.call(this, font, fontData, customFontName, fontFeatures) || this; + _this.subset = _this.font.createSubset(); + _this.glyphs = []; + _this.glyphCache = Cache.populatedBy(function () { return _this.glyphs; }); + _this.glyphIdMap = new Map(); + return _this; + } + CustomFontSubsetEmbedder.for = function (fontkit, fontData, customFontName, fontFeatures) { + return __awaiter(this, void 0, void 0, function () { + var font; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, fontkit.create(fontData)]; + case 1: + font = _a.sent(); + return [2 /*return*/, new CustomFontSubsetEmbedder(font, fontData, customFontName, fontFeatures)]; + } + }); + }); + }; + CustomFontSubsetEmbedder.prototype.encodeText = function (text) { + var glyphs = this.font.layout(text, this.fontFeatures).glyphs; + var hexCodes = new Array(glyphs.length); + for (var idx = 0, len = glyphs.length; idx < len; idx++) { + var glyph = glyphs[idx]; + var subsetGlyphId = this.subset.includeGlyph(glyph); + this.glyphs[subsetGlyphId - 1] = glyph; + this.glyphIdMap.set(glyph.id, subsetGlyphId); + hexCodes[idx] = toHexStringOfMinLength(subsetGlyphId, 4); + } + this.glyphCache.invalidate(); + return PDFHexString.of(hexCodes.join('')); + }; + CustomFontSubsetEmbedder.prototype.isCFF = function () { + return this.subset.cff; + }; + CustomFontSubsetEmbedder.prototype.glyphId = function (glyph) { + return glyph ? this.glyphIdMap.get(glyph.id) : -1; + }; + CustomFontSubsetEmbedder.prototype.serializeFont = function () { + var _this = this; + return new Promise(function (resolve, reject) { + var parts = []; + _this.subset + .encodeStream() + .on('data', function (bytes) { return parts.push(bytes); }) + .on('end', function () { return resolve(mergeUint8Arrays(parts)); }) + .on('error', function (err) { return reject(err); }); + }); + }; + return CustomFontSubsetEmbedder; +}(CustomFontEmbedder)); + +/** + * From the PDF-A3 specification, section **3.1. Requirements - General**. + * See: + * * https://www.pdfa.org/wp-content/uploads/2018/10/PDF20_AN002-AF.pdf + */ +var AFRelationship; +(function (AFRelationship) { + AFRelationship["Source"] = "Source"; + AFRelationship["Data"] = "Data"; + AFRelationship["Alternative"] = "Alternative"; + AFRelationship["Supplement"] = "Supplement"; + AFRelationship["EncryptedPayload"] = "EncryptedPayload"; + AFRelationship["FormData"] = "EncryptedPayload"; + AFRelationship["Schema"] = "Schema"; + AFRelationship["Unspecified"] = "Unspecified"; +})(AFRelationship || (AFRelationship = {})); +var FileEmbedder = /** @class */ (function () { + function FileEmbedder(fileData, fileName, options) { + if (options === void 0) { options = {}; } + this.fileData = fileData; + this.fileName = fileName; + this.options = options; + } + FileEmbedder.for = function (bytes, fileName, options) { + if (options === void 0) { options = {}; } + return new FileEmbedder(bytes, fileName, options); + }; + FileEmbedder.prototype.embedIntoContext = function (context, ref) { + return __awaiter(this, void 0, void 0, function () { + var _a, mimeType, description, creationDate, modificationDate, afRelationship, embeddedFileStream, embeddedFileStreamRef, fileSpecDict; + return __generator(this, function (_b) { + _a = this.options, mimeType = _a.mimeType, description = _a.description, creationDate = _a.creationDate, modificationDate = _a.modificationDate, afRelationship = _a.afRelationship; + embeddedFileStream = context.flateStream(this.fileData, { + Type: 'EmbeddedFile', + Subtype: mimeType !== null && mimeType !== void 0 ? mimeType : undefined, + Params: { + Size: this.fileData.length, + CreationDate: creationDate + ? PDFString.fromDate(creationDate) + : undefined, + ModDate: modificationDate + ? PDFString.fromDate(modificationDate) + : undefined, + }, + }); + embeddedFileStreamRef = context.register(embeddedFileStream); + fileSpecDict = context.obj({ + Type: 'Filespec', + F: PDFString.of(this.fileName), + UF: PDFHexString.fromText(this.fileName), + EF: { F: embeddedFileStreamRef }, + Desc: description ? PDFHexString.fromText(description) : undefined, + AFRelationship: afRelationship !== null && afRelationship !== void 0 ? afRelationship : undefined, + }); + if (ref) { + context.assign(ref, fileSpecDict); + return [2 /*return*/, ref]; + } + else { + return [2 /*return*/, context.register(fileSpecDict)]; + } + }); + }); + }; + return FileEmbedder; +}()); + +// prettier-ignore +var MARKERS = [ + 0xffc0, 0xffc1, 0xffc2, + 0xffc3, 0xffc5, 0xffc6, + 0xffc7, 0xffc8, 0xffc9, + 0xffca, 0xffcb, 0xffcc, + 0xffcd, 0xffce, 0xffcf, +]; +var ColorSpace; +(function (ColorSpace) { + ColorSpace["DeviceGray"] = "DeviceGray"; + ColorSpace["DeviceRGB"] = "DeviceRGB"; + ColorSpace["DeviceCMYK"] = "DeviceCMYK"; +})(ColorSpace || (ColorSpace = {})); +var ChannelToColorSpace = { + 1: ColorSpace.DeviceGray, + 3: ColorSpace.DeviceRGB, + 4: ColorSpace.DeviceCMYK, +}; +/** + * A note of thanks to the developers of https://github.com/foliojs/pdfkit, as + * this class borrows from: + * https://github.com/foliojs/pdfkit/blob/a6af76467ce06bd6a2af4aa7271ccac9ff152a7d/lib/image/jpeg.js + */ +var JpegEmbedder = /** @class */ (function () { + function JpegEmbedder(imageData, bitsPerComponent, width, height, colorSpace) { + this.imageData = imageData; + this.bitsPerComponent = bitsPerComponent; + this.width = width; + this.height = height; + this.colorSpace = colorSpace; + } + JpegEmbedder.for = function (imageData) { + return __awaiter(this, void 0, void 0, function () { + var dataView, soi, pos, marker, bitsPerComponent, height, width, channelByte, channelName, colorSpace; + return __generator(this, function (_a) { + dataView = new DataView(imageData.buffer); + soi = dataView.getUint16(0); + if (soi !== 0xffd8) + throw new Error('SOI not found in JPEG'); + pos = 2; + while (pos < dataView.byteLength) { + marker = dataView.getUint16(pos); + pos += 2; + if (MARKERS.includes(marker)) + break; + pos += dataView.getUint16(pos); + } + if (!MARKERS.includes(marker)) + throw new Error('Invalid JPEG'); + pos += 2; + bitsPerComponent = dataView.getUint8(pos++); + height = dataView.getUint16(pos); + pos += 2; + width = dataView.getUint16(pos); + pos += 2; + channelByte = dataView.getUint8(pos++); + channelName = ChannelToColorSpace[channelByte]; + if (!channelName) + throw new Error('Unknown JPEG channel.'); + colorSpace = channelName; + return [2 /*return*/, new JpegEmbedder(imageData, bitsPerComponent, width, height, colorSpace)]; + }); + }); + }; + JpegEmbedder.prototype.embedIntoContext = function (context, ref) { + return __awaiter(this, void 0, void 0, function () { + var xObject; + return __generator(this, function (_a) { + xObject = context.stream(this.imageData, { + Type: 'XObject', + Subtype: 'Image', + BitsPerComponent: this.bitsPerComponent, + Width: this.width, + Height: this.height, + ColorSpace: this.colorSpace, + Filter: 'DCTDecode', + // CMYK JPEG streams in PDF are typically stored complemented, + // with 1 as 'off' and 0 as 'on' (PDF 32000-1:2008, 8.6.4.4). + // + // Standalone CMYK JPEG (usually exported by Photoshop) are + // stored inverse, with 0 as 'off' and 1 as 'on', like RGB. + // + // Applying a swap here as a hedge that most bytes passing + // through this method will benefit from it. + Decode: this.colorSpace === ColorSpace.DeviceCMYK + ? [1, 0, 1, 0, 1, 0, 1, 0] + : undefined, + }); + if (ref) { + context.assign(ref, xObject); + return [2 /*return*/, ref]; + } + else { + return [2 /*return*/, context.register(xObject)]; + } + }); + }); + }; + return JpegEmbedder; +}()); + +var common$2 = createCommonjsModule(function (module, exports) { + + +var TYPED_OK = (typeof Uint8Array !== 'undefined') && + (typeof Uint16Array !== 'undefined') && + (typeof Int32Array !== 'undefined'); + +function _has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +exports.assign = function (obj /*from1, from2, from3, ...*/) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { continue; } + + if (typeof source !== 'object') { + throw new TypeError(source + 'must be non-object'); + } + + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + + return obj; +}; + + +// reduce buffer size, avoiding mem copy +exports.shrinkBuf = function (buf, size) { + if (buf.length === size) { return buf; } + if (buf.subarray) { return buf.subarray(0, size); } + buf.length = size; + return buf; +}; + + +var fnTyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + var i, l, len, pos, chunk, result; + + // calculate data length + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + + // join chunks + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + + return result; + } +}; + +var fnUntyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + return [].concat.apply([], chunks); + } +}; + + +// Enable/Disable typed arrays use, for testing +// +exports.setTyped = function (on) { + if (on) { + exports.Buf8 = Uint8Array; + exports.Buf16 = Uint16Array; + exports.Buf32 = Int32Array; + exports.assign(exports, fnTyped); + } else { + exports.Buf8 = Array; + exports.Buf16 = Array; + exports.Buf32 = Array; + exports.assign(exports, fnUntyped); + } +}; + +exports.setTyped(TYPED_OK); +}); + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +/* eslint-disable space-unary-ops */ + + + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED$4 = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY$2 = 0; +var Z_TEXT$2 = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN$4 = 2; + +/*============================================================================*/ + + +function zero$4(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK$2 = 0; +var STATIC_TREES$2 = 1; +var DYN_TREES$2 = 2; +/* The three kinds of block type */ + +var MIN_MATCH$4 = 3; +var MAX_MATCH$4 = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES$4 = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS$4 = 256; +/* number of literal bytes 0..255 */ + +var L_CODES$4 = LITERALS$4 + 1 + LENGTH_CODES$4; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES$4 = 30; +/* number of distance codes */ + +var BL_CODES$4 = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE$4 = 2 * L_CODES$4 + 1; +/* maximum heap size */ + +var MAX_BITS$4 = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size$2 = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS$2 = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK$2 = 256; +/* end of block literal code */ + +var REP_3_6$2 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10$2 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138$2 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +/* eslint-disable comma-spacing,array-bracket-spacing */ +var extra_lbits$2 = /* 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$2 = /* 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$2 = /* 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$2 = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +/* eslint-enable comma-spacing,array-bracket-spacing */ + +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN$2 = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 +var static_ltree$2 = new Array((L_CODES$4 + 2) * 2); +zero$4(static_ltree$2); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree$2 = new Array(D_CODES$4 * 2); +zero$4(static_dtree$2); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code$2 = new Array(DIST_CODE_LEN$2); +zero$4(_dist_code$2); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code$2 = new Array(MAX_MATCH$4 - MIN_MATCH$4 + 1); +zero$4(_length_code$2); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length$2 = new Array(LENGTH_CODES$4); +zero$4(base_length$2); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist$2 = new Array(D_CODES$4); +zero$4(base_dist$2); +/* First normalized distance for each code (0 = distance of 1) */ + + +function StaticTreeDesc$2(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +} + + +var static_l_desc$2; +var static_d_desc$2; +var static_bl_desc$2; + + +function TreeDesc$2(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +} + + + +function d_code$2(dist) { + return dist < 256 ? _dist_code$2[dist] : _dist_code$2[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short$2(s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits$2(s, value, length) { + if (s.bi_valid > (Buf_size$2 - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short$2(s, s.bi_buf); + s.bi_buf = value >> (Buf_size$2 - s.bi_valid); + s.bi_valid += length - Buf_size$2; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code$2(s, c, tree) { + send_bits$2(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse$2(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush$2(s) { + if (s.bi_valid === 16) { + put_short$2(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen$2(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS$4; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE$4; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes$2(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS$4 + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS$4; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, + // "inconsistent bit counts"); + //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); + + for (n = 0; n <= max_code; n++) { + var len = tree[n * 2 + 1]/*.Len*/; + if (len === 0) { continue; } + /* Now reverse the bits */ + tree[n * 2]/*.Code*/ = bi_reverse$2(next_code[len]++, len); + + //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", + // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); + } +} + + +/* =========================================================================== + * Initialize the various 'constant' tables. + */ +function tr_static_init$2() { + var n; /* iterates over tree elements */ + var bits; /* bit counter */ + var length; /* length value */ + var code; /* code value */ + var dist; /* distance index */ + var bl_count = new Array(MAX_BITS$4 + 1); + /* number of codes at each bit length for an optimal tree */ + + // do check in _tr_init() + //if (static_init_done) return; + + /* For some embedded targets, global variables are not initialized: */ +/*#ifdef NO_INIT_GLOBAL_POINTERS + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; +#endif*/ + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES$4 - 1; code++) { + base_length$2[code] = length; + for (n = 0; n < (1 << extra_lbits$2[code]); n++) { + _length_code$2[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code$2[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist$2[code] = dist; + for (n = 0; n < (1 << extra_dbits$2[code]); n++) { + _dist_code$2[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES$4; code++) { + base_dist$2[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits$2[code] - 7)); n++) { + _dist_code$2[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS$4; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree$2[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree$2[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree$2[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree$2[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes$2(static_ltree$2, L_CODES$4 + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES$4; n++) { + static_dtree$2[n * 2 + 1]/*.Len*/ = 5; + static_dtree$2[n * 2]/*.Code*/ = bi_reverse$2(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc$2 = new StaticTreeDesc$2(static_ltree$2, extra_lbits$2, LITERALS$4 + 1, L_CODES$4, MAX_BITS$4); + static_d_desc$2 = new StaticTreeDesc$2(static_dtree$2, extra_dbits$2, 0, D_CODES$4, MAX_BITS$4); + static_bl_desc$2 = new StaticTreeDesc$2(new Array(0), extra_blbits$2, 0, BL_CODES$4, MAX_BL_BITS$2); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block$2(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES$4; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES$4; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES$4; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK$2 * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup$2(s) +{ + if (s.bi_valid > 8) { + put_short$2(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block$2(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup$2(s); /* align on byte boundary */ + + if (header) { + put_short$2(s, len); + put_short$2(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + common$2.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller$2(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap$2(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller$2(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller$2(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block$2(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code$2(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code$2[lc]; + send_code$2(s, code + LITERALS$4 + 1, ltree); /* send the length code */ + extra = extra_lbits$2[code]; + if (extra !== 0) { + lc -= base_length$2[code]; + send_bits$2(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code$2(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code$2(s, code, dtree); /* send the distance code */ + extra = extra_dbits$2[code]; + if (extra !== 0) { + dist -= base_dist$2[code]; + send_bits$2(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code$2(s, END_BLOCK$2, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree$2(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE$4; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap$2(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap$2(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap$2(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen$2(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes$2(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree$2(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6$2 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10$2 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138$2 * 2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree$2(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code$2(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code$2(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code$2(s, REP_3_6$2, s.bl_tree); + send_bits$2(s, count - 3, 2); + + } else if (count <= 10) { + send_code$2(s, REPZ_3_10$2, s.bl_tree); + send_bits$2(s, count - 3, 3); + + } else { + send_code$2(s, REPZ_11_138$2, s.bl_tree); + send_bits$2(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree$2(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree$2(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree$2(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree$2(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES$4 - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order$2[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees$2(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits$2(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits$2(s, dcodes - 1, 5); + send_bits$2(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits$2(s, s.bl_tree[bl_order$2[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree$2(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree$2(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type$2(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY$2; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT$2; + } + for (n = 32; n < LITERALS$4; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT$2; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY$2; +} + + +var static_init_done$2 = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init$2(s) +{ + + if (!static_init_done$2) { + tr_static_init$2(); + static_init_done$2 = true; + } + + s.l_desc = new TreeDesc$2(s.dyn_ltree, static_l_desc$2); + s.d_desc = new TreeDesc$2(s.dyn_dtree, static_d_desc$2); + s.bl_desc = new TreeDesc$2(s.bl_tree, static_bl_desc$2); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block$2(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block$2(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits$2(s, (STORED_BLOCK$2 << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block$2(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align$2(s) { + send_bits$2(s, STATIC_TREES$2 << 1, 3); + send_code$2(s, END_BLOCK$2, static_ltree$2); + bi_flush$2(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block$2(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN$4) { + s.strm.data_type = detect_data_type$2(s); + } + + /* Construct the literal and distance trees */ + build_tree$2(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree$2(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree$2(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block$2(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED$4 || static_lenb === opt_lenb) { + + send_bits$2(s, (STATIC_TREES$2 << 1) + (last ? 1 : 0), 3); + compress_block$2(s, static_ltree$2, static_dtree$2); + + } else { + send_bits$2(s, (DYN_TREES$2 << 1) + (last ? 1 : 0), 3); + send_all_trees$2(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block$2(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block$2(s); + + if (last) { + bi_windup$2(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally$2(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code$2[lc] + LITERALS$4 + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code$2(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +var _tr_init_1$2 = _tr_init$2; +var _tr_stored_block_1$2 = _tr_stored_block$2; +var _tr_flush_block_1$2 = _tr_flush_block$2; +var _tr_tally_1$2 = _tr_tally$2; +var _tr_align_1$2 = _tr_align$2; + +var trees$2 = { + _tr_init: _tr_init_1$2, + _tr_stored_block: _tr_stored_block_1$2, + _tr_flush_block: _tr_flush_block_1$2, + _tr_tally: _tr_tally_1$2, + _tr_align: _tr_align_1$2 +}; + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It isn't worth it to make additional optimizations as in original. +// Small size is preferable. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function adler32$2(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + + +var adler32_1$2 = adler32$2; + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// Use ordinary array, since untyped makes no boost here +function makeTable$2() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable$2 = makeTable$2(); + + +function crc32$2(crc, buf, len, pos) { + var t = crcTable$2, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + + +var crc32_1$2 = crc32$2; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var messages$2 = { + 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) */ +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + + + + + + + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +var Z_NO_FLUSH$4 = 0; +var Z_PARTIAL_FLUSH$2 = 1; +//var Z_SYNC_FLUSH = 2; +var Z_FULL_FLUSH$2 = 3; +var Z_FINISH$6 = 4; +var Z_BLOCK$4 = 5; +//var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK$6 = 0; +var Z_STREAM_END$6 = 1; +//var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR$4 = -2; +var Z_DATA_ERROR$4 = -3; +//var Z_MEM_ERROR = -4; +var Z_BUF_ERROR$4 = -5; +//var Z_VERSION_ERROR = -6; + + +/* compression levels */ +//var Z_NO_COMPRESSION = 0; +//var Z_BEST_SPEED = 1; +//var Z_BEST_COMPRESSION = 9; +var Z_DEFAULT_COMPRESSION$4 = -1; + + +var Z_FILTERED$2 = 1; +var Z_HUFFMAN_ONLY$2 = 2; +var Z_RLE$2 = 3; +var Z_FIXED$5 = 4; +var Z_DEFAULT_STRATEGY$4 = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//var Z_BINARY = 0; +//var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN$5 = 2; + + +/* The deflate compression method */ +var Z_DEFLATED$6 = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL$2 = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS$4 = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL$2 = 8; + + +var LENGTH_CODES$5 = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS$5 = 256; +/* number of literal bytes 0..255 */ +var L_CODES$5 = LITERALS$5 + 1 + LENGTH_CODES$5; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES$5 = 30; +/* number of distance codes */ +var BL_CODES$5 = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE$5 = 2 * L_CODES$5 + 1; +/* maximum heap size */ +var MAX_BITS$5 = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH$5 = 3; +var MAX_MATCH$5 = 258; +var MIN_LOOKAHEAD$2 = (MAX_MATCH$5 + MIN_MATCH$5 + 1); + +var PRESET_DICT$2 = 0x20; + +var INIT_STATE$2 = 42; +var EXTRA_STATE$2 = 69; +var NAME_STATE$2 = 73; +var COMMENT_STATE$2 = 91; +var HCRC_STATE$2 = 103; +var BUSY_STATE$2 = 113; +var FINISH_STATE$2 = 666; + +var BS_NEED_MORE$2 = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE$2 = 2; /* block flush performed */ +var BS_FINISH_STARTED$2 = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE$2 = 4; /* finish done, accept no more input or output */ + +var OS_CODE$2 = 0x03; // Unix :) . Don't detect, use this default. + +function err$2(strm, errorCode) { + strm.msg = messages$2[errorCode]; + return errorCode; +} + +function rank$2(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero$5(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending$2(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + common$2.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$2(s, last) { + trees$2._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$2(s.strm); +} + + +function put_byte$2(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB$2(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf$2(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + common$2.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32_1$2(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32_1$2(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match$2(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD$2)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD$2) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH$5; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH$5 - (strend - scan); + scan = strend - MAX_MATCH$5; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window$2(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD$2)) { + + common$2.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf$2(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH$5) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$5 - 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$5) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD$2 && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored$2(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window$2(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH$4) { + return BS_NEED_MORE$2; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$2(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$2; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD$2)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$2(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$2; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH$6) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only$2(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED$2; + } + /***/ + return BS_FINISH_DONE$2; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$2(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$2; + } + /***/ + } + + return BS_NEED_MORE$2; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast$2(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD$2) { + fill_window$2(s); + if (s.lookahead < MIN_LOOKAHEAD$2 && flush === Z_NO_FLUSH$4) { + return BS_NEED_MORE$2; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH$5) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$5 - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD$2))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match$2(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH$5) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees$2._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$5); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH$5) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$5 - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees$2._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$2(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$2; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH$5 - 1)) ? s.strstart : MIN_MATCH$5 - 1); + if (flush === Z_FINISH$6) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only$2(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED$2; + } + /***/ + return BS_FINISH_DONE$2; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$2(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$2; + } + /***/ + } + return BS_BLOCK_DONE$2; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow$2(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD$2) { + fill_window$2(s); + if (s.lookahead < MIN_LOOKAHEAD$2 && flush === Z_NO_FLUSH$4) { + return BS_NEED_MORE$2; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH$5) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$5 - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH$5 - 1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD$2)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match$2(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED$2 || (s.match_length === MIN_MATCH$5 && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH$5 - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH$5 && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH$5; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees$2._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$5); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$5 - 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$5 - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$2(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$2; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees$2._tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only$2(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$2; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees$2._tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH$5 - 1 ? s.strstart : MIN_MATCH$5 - 1; + if (flush === Z_FINISH$6) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only$2(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED$2; + } + /***/ + return BS_FINISH_DONE$2; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$2(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$2; + } + /***/ + } + + return BS_BLOCK_DONE$2; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle$2(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH$5) { + fill_window$2(s); + if (s.lookahead <= MAX_MATCH$5 && flush === Z_NO_FLUSH$4) { + return BS_NEED_MORE$2; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH$5 && 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$5; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH$5 - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH$5) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees$2._tr_tally(s, 1, s.match_length - MIN_MATCH$5); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees$2._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$2(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$2; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH$6) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only$2(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED$2; + } + /***/ + return BS_FINISH_DONE$2; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$2(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$2; + } + /***/ + } + return BS_BLOCK_DONE$2; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff$2(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window$2(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH$4) { + return BS_NEED_MORE$2; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees$2._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$2(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$2; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH$6) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only$2(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED$2; + } + /***/ + return BS_FINISH_DONE$2; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only$2(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE$2; + } + /***/ + } + return BS_BLOCK_DONE$2; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +function Config$2(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$2; + +configuration_table$2 = [ + /* good lazy nice chain */ + new Config$2(0, 0, 0, 0, deflate_stored$2), /* 0 store only */ + new Config$2(4, 4, 8, 4, deflate_fast$2), /* 1 max speed, no lazy matches */ + new Config$2(4, 5, 16, 8, deflate_fast$2), /* 2 */ + new Config$2(4, 6, 32, 32, deflate_fast$2), /* 3 */ + + new Config$2(4, 4, 16, 16, deflate_slow$2), /* 4 lazy matches */ + new Config$2(8, 16, 32, 32, deflate_slow$2), /* 5 */ + new Config$2(8, 16, 128, 128, deflate_slow$2), /* 6 */ + new Config$2(8, 32, 128, 256, deflate_slow$2), /* 7 */ + new Config$2(32, 128, 258, 1024, deflate_slow$2), /* 8 */ + new Config$2(32, 258, 258, 4096, deflate_slow$2) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init$2(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero$5(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table$2[s.level].max_lazy; + s.good_match = configuration_table$2[s.level].good_length; + s.nice_match = configuration_table$2[s.level].nice_length; + s.max_chain_length = configuration_table$2[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$5 - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState$2() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED$6; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new common$2.Buf16(HEAP_SIZE$5 * 2); + this.dyn_dtree = new common$2.Buf16((2 * D_CODES$5 + 1) * 2); + this.bl_tree = new common$2.Buf16((2 * BL_CODES$5 + 1) * 2); + zero$5(this.dyn_ltree); + zero$5(this.dyn_dtree); + zero$5(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new common$2.Buf16(MAX_BITS$5 + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new common$2.Buf16(2 * L_CODES$5 + 1); /* heap used to build the Huffman trees */ + zero$5(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new common$2.Buf16(2 * L_CODES$5 + 1); //uch depth[2*L_CODES+1]; + zero$5(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep$2(strm) { + var s; + + if (!strm || !strm.state) { + return err$2(strm, Z_STREAM_ERROR$4); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN$5; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE$2 : BUSY_STATE$2); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH$4; + trees$2._tr_init(s); + return Z_OK$6; +} + + +function deflateReset$2(strm) { + var ret = deflateResetKeep$2(strm); + if (ret === Z_OK$6) { + lm_init$2(strm.state); + } + return ret; +} + + +function deflateSetHeader$2(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR$4; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR$4; } + strm.state.gzhead = head; + return Z_OK$6; +} + + +function deflateInit2$2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR$4; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION$4) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL$2 || method !== Z_DEFLATED$6 || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED$5) { + return err$2(strm, Z_STREAM_ERROR$4); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState$2(); + + 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$5 - 1) / MIN_MATCH$5); + + s.window = new common$2.Buf8(s.w_size * 2); + s.head = new common$2.Buf16(s.hash_size); + s.prev = new common$2.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new common$2.Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset$2(strm); +} + +function deflateInit$2(strm, level) { + return deflateInit2$2(strm, level, Z_DEFLATED$6, MAX_WBITS$4, DEF_MEM_LEVEL$2, Z_DEFAULT_STRATEGY$4); +} + + +function deflate$4(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK$4 || flush < 0) { + return strm ? err$2(strm, Z_STREAM_ERROR$4) : Z_STREAM_ERROR$4; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE$2 && flush !== Z_FINISH$6)) { + return err$2(strm, (strm.avail_out === 0) ? Z_BUF_ERROR$4 : Z_STREAM_ERROR$4); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE$2) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte$2(s, 31); + put_byte$2(s, 139); + put_byte$2(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte$2(s, 0); + put_byte$2(s, 0); + put_byte$2(s, 0); + put_byte$2(s, 0); + put_byte$2(s, 0); + put_byte$2(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY$2 || s.level < 2 ? + 4 : 0)); + put_byte$2(s, OS_CODE$2); + s.status = BUSY_STATE$2; + } + else { + put_byte$2(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$2(s, s.gzhead.time & 0xff); + put_byte$2(s, (s.gzhead.time >> 8) & 0xff); + put_byte$2(s, (s.gzhead.time >> 16) & 0xff); + put_byte$2(s, (s.gzhead.time >> 24) & 0xff); + put_byte$2(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY$2 || s.level < 2 ? + 4 : 0)); + put_byte$2(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte$2(s, s.gzhead.extra.length & 0xff); + put_byte$2(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32_1$2(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE$2; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED$6 + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY$2 || 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$2; } + header += 31 - (header % 31); + + s.status = BUSY_STATE$2; + putShortMSB$2(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB$2(s, strm.adler >>> 16); + putShortMSB$2(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE$2) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1$2(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending$2(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte$2(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1$2(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE$2; + } + } + else { + s.status = NAME_STATE$2; + } + } + if (s.status === NAME_STATE$2) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1$2(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending$2(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte$2(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1$2(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE$2; + } + } + else { + s.status = COMMENT_STATE$2; + } + } + if (s.status === COMMENT_STATE$2) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1$2(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending$2(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte$2(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1$2(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE$2; + } + } + else { + s.status = HCRC_STATE$2; + } + } + if (s.status === HCRC_STATE$2) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending$2(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte$2(s, strm.adler & 0xff); + put_byte$2(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE$2; + } + } + else { + s.status = BUSY_STATE$2; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending$2(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK$6; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank$2(flush) <= rank$2(old_flush) && + flush !== Z_FINISH$6) { + return err$2(strm, Z_BUF_ERROR$4); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE$2 && strm.avail_in !== 0) { + return err$2(strm, Z_BUF_ERROR$4); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH$4 && s.status !== FINISH_STATE$2)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY$2) ? deflate_huff$2(s, flush) : + (s.strategy === Z_RLE$2 ? deflate_rle$2(s, flush) : + configuration_table$2[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED$2 || bstate === BS_FINISH_DONE$2) { + s.status = FINISH_STATE$2; + } + if (bstate === BS_NEED_MORE$2 || bstate === BS_FINISH_STARTED$2) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK$6; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE$2) { + if (flush === Z_PARTIAL_FLUSH$2) { + trees$2._tr_align(s); + } + else if (flush !== Z_BLOCK$4) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees$2._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH$2) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero$5(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending$2(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK$6; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH$6) { return Z_OK$6; } + if (s.wrap <= 0) { return Z_STREAM_END$6; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte$2(s, strm.adler & 0xff); + put_byte$2(s, (strm.adler >> 8) & 0xff); + put_byte$2(s, (strm.adler >> 16) & 0xff); + put_byte$2(s, (strm.adler >> 24) & 0xff); + put_byte$2(s, strm.total_in & 0xff); + put_byte$2(s, (strm.total_in >> 8) & 0xff); + put_byte$2(s, (strm.total_in >> 16) & 0xff); + put_byte$2(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB$2(s, strm.adler >>> 16); + putShortMSB$2(s, strm.adler & 0xffff); + } + + flush_pending$2(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK$6 : Z_STREAM_END$6; +} + +function deflateEnd$2(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR$4; + } + + status = strm.state.status; + if (status !== INIT_STATE$2 && + status !== EXTRA_STATE$2 && + status !== NAME_STATE$2 && + status !== COMMENT_STATE$2 && + status !== HCRC_STATE$2 && + status !== BUSY_STATE$2 && + status !== FINISH_STATE$2 + ) { + return err$2(strm, Z_STREAM_ERROR$4); + } + + strm.state = null; + + return status === BUSY_STATE$2 ? err$2(strm, Z_DATA_ERROR$4) : Z_OK$6; +} + + +/* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ +function deflateSetDictionary$2(strm, dictionary) { + var dictLength = dictionary.length; + + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR$4; + } + + s = strm.state; + wrap = s.wrap; + + if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE$2) || s.lookahead) { + return Z_STREAM_ERROR$4; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32_1$2(strm.adler, dictionary, dictLength, 0); + } + + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero$5(s.head); // Fill with NIL (= 0); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + tmpDict = new common$2.Buf8(s.w_size); + common$2.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + /* insert dictionary into window and hash */ + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window$2(s); + while (s.lookahead >= MIN_MATCH$5) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH$5 - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$5 - 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$5 - 1; + fill_window$2(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$5 - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK$6; +} + + +var deflateInit_1$2 = deflateInit$2; +var deflateInit2_1$2 = deflateInit2$2; +var deflateReset_1$2 = deflateReset$2; +var deflateResetKeep_1$2 = deflateResetKeep$2; +var deflateSetHeader_1$2 = deflateSetHeader$2; +var deflate_2$4 = deflate$4; +var deflateEnd_1$2 = deflateEnd$2; +var deflateSetDictionary_1$2 = deflateSetDictionary$2; +var deflateInfo$2 = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ + +var deflate_1$4 = { + deflateInit: deflateInit_1$2, + deflateInit2: deflateInit2_1$2, + deflateReset: deflateReset_1$2, + deflateResetKeep: deflateResetKeep_1$2, + deflateSetHeader: deflateSetHeader_1$2, + deflate: deflate_2$4, + deflateEnd: deflateEnd_1$2, + deflateSetDictionary: deflateSetDictionary_1$2, + deflateInfo: deflateInfo$2 +}; + +// Quick check if we can use fast array to bin string conversion +// +// - apply(Array) can fail on Android 2.2 +// - apply(Uint8Array) can fail on iOS 5.1 Safari +// +var STR_APPLY_OK$2 = true; +var STR_APPLY_UIA_OK$2 = true; + +try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK$2 = false; } +try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK$2 = false; } + + +// Table with utf8 lengths (calculated by first byte of sequence) +// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, +// because max possible codepoint is 0x10ffff +var _utf8len$2 = new common$2.Buf8(256); +for (var q$2 = 0; q$2 < 256; q$2++) { + _utf8len$2[q$2] = (q$2 >= 252 ? 6 : q$2 >= 248 ? 5 : q$2 >= 240 ? 4 : q$2 >= 224 ? 3 : q$2 >= 192 ? 2 : 1); +} +_utf8len$2[254] = _utf8len$2[254] = 1; // Invalid sequence start + + +// convert string to array (typed, when possible) +var string2buf$2 = function (str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + + // count binary size + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + } + + // allocate buffer + buf = new common$2.Buf8(buf_len); + + // convert + for (i = 0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + if (c < 0x80) { + /* one byte */ + buf[i++] = c; + } else if (c < 0x800) { + /* two bytes */ + buf[i++] = 0xC0 | (c >>> 6); + buf[i++] = 0x80 | (c & 0x3f); + } else if (c < 0x10000) { + /* three bytes */ + buf[i++] = 0xE0 | (c >>> 12); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } else { + /* four bytes */ + buf[i++] = 0xf0 | (c >>> 18); + buf[i++] = 0x80 | (c >>> 12 & 0x3f); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } + } + + return buf; +}; + +// Helper (used in 2 places) +function buf2binstring$2(buf, len) { + // On Chrome, the arguments in a function call that are allowed is `65534`. + // If the length of the buffer is smaller than that, we can use this optimization, + // otherwise we will take a slower path. + if (len < 65534) { + if ((buf.subarray && STR_APPLY_UIA_OK$2) || (!buf.subarray && STR_APPLY_OK$2)) { + return String.fromCharCode.apply(null, common$2.shrinkBuf(buf, len)); + } + } + + var result = ''; + for (var i = 0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; +} + + +// Convert byte array to binary string +var buf2binstring_1$2 = function (buf) { + return buf2binstring$2(buf, buf.length); +}; + + +// Convert binary string (typed, when possible) +var binstring2buf$2 = function (str) { + var buf = new common$2.Buf8(str.length); + for (var i = 0, len = buf.length; i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; +}; + + +// convert array to string +var buf2string$2 = function (buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + + // Reserve max possible length (2 words per char) + // NB: by unknown reasons, Array is significantly faster for + // String.fromCharCode.apply than Uint16Array. + var utf16buf = new Array(len * 2); + + for (out = 0, i = 0; i < len;) { + c = buf[i++]; + // quick process ascii + if (c < 0x80) { utf16buf[out++] = c; continue; } + + c_len = _utf8len$2[c]; + // skip 5 & 6 byte codes + if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } + + // apply mask on first byte + c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; + // join the rest + while (c_len > 1 && i < len) { + c = (c << 6) | (buf[i++] & 0x3f); + c_len--; + } + + // terminated by end of string? + if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + + if (c < 0x10000) { + utf16buf[out++] = c; + } else { + c -= 0x10000; + utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); + utf16buf[out++] = 0xdc00 | (c & 0x3ff); + } + } + + return buf2binstring$2(utf16buf, out); +}; + + +// Calculate max possible position in utf8 buffer, +// that will not break sequence. If that's not possible +// - (very small limits) return max size as is. +// +// buf[] - utf8 bytes array +// max - length limit (mandatory); +var utf8border$2 = function (buf, max) { + var pos; + + max = max || buf.length; + if (max > buf.length) { max = buf.length; } + + // go back from last position, until start of sequence found + pos = max - 1; + while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } + + // Very small and broken sequence, + // return max, because we should return something anyway. + if (pos < 0) { return max; } + + // If we came to start of buffer - that means buffer is too small, + // return max too. + if (pos === 0) { return max; } + + return (pos + _utf8len$2[buf[pos]] > max) ? pos : max; +}; + +var strings$2 = { + string2buf: string2buf$2, + buf2binstring: buf2binstring_1$2, + binstring2buf: binstring2buf$2, + buf2string: buf2string$2, + utf8border: utf8border$2 +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function ZStream$2() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +var zstream$2 = ZStream$2; + +var toString$4 = Object.prototype.toString; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + +var Z_NO_FLUSH$5 = 0; +var Z_FINISH$7 = 4; + +var Z_OK$7 = 0; +var Z_STREAM_END$7 = 1; +var Z_SYNC_FLUSH$2 = 2; + +var Z_DEFAULT_COMPRESSION$5 = -1; + +var Z_DEFAULT_STRATEGY$5 = 0; + +var Z_DEFLATED$7 = 8; + +/* ===========================================================================*/ + + +/** + * class Deflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[deflate]], + * [[deflateRaw]] and [[gzip]]. + **/ + +/* internal + * Deflate.chunks -> Array + * + * Chunks of output data, if [[Deflate#onData]] not overridden. + **/ + +/** + * Deflate.result -> Uint8Array|Array + * + * Compressed result, generated by default [[Deflate#onData]] + * and [[Deflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Deflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Deflate.err -> Number + * + * Error code after deflate finished. 0 (Z_OK) on success. + * You will not need it in real life, because deflate errors + * are possible only on wrong options or bad `onData` / `onEnd` + * custom handlers. + **/ + +/** + * Deflate.msg -> String + * + * Error message, if [[Deflate.err]] != 0 + **/ + + +/** + * new Deflate(options) + * - options (Object): zlib deflate options. + * + * Creates new deflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `level` + * - `windowBits` + * - `memLevel` + * - `strategy` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw deflate + * - `gzip` (Boolean) - create gzip wrapper + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * - `header` (Object) - custom header for gzip + * - `text` (Boolean) - true if compressed data believed to be text + * - `time` (Number) - modification time, unix timestamp + * - `os` (Number) - operation system code + * - `extra` (Array) - array of bytes with extra data (max 65536) + * - `name` (String) - file name (binary string) + * - `comment` (String) - comment (binary string) + * - `hcrc` (Boolean) - true if header crc should be added + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var deflate = new pako.Deflate({ level: 3}); + * + * deflate.push(chunk1, false); + * deflate.push(chunk2, true); // true -> last chunk + * + * if (deflate.err) { throw new Error(deflate.err); } + * + * console.log(deflate.result); + * ``` + **/ +function Deflate$2(options) { + if (!(this instanceof Deflate$2)) return new Deflate$2(options); + + this.options = common$2.assign({ + level: Z_DEFAULT_COMPRESSION$5, + method: Z_DEFLATED$7, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY$5, + 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; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new zstream$2(); + this.strm.avail_out = 0; + + var status = deflate_1$4.deflateInit2( + this.strm, + opt.level, + opt.method, + opt.windowBits, + opt.memLevel, + opt.strategy + ); + + if (status !== Z_OK$7) { + throw new Error(messages$2[status]); + } + + if (opt.header) { + deflate_1$4.deflateSetHeader(this.strm, opt.header); + } + + if (opt.dictionary) { + var dict; + // Convert data if needed + if (typeof opt.dictionary === 'string') { + // If we need to compress text, change encoding to utf8. + dict = strings$2.string2buf(opt.dictionary); + } else if (toString$4.call(opt.dictionary) === '[object ArrayBuffer]') { + dict = new Uint8Array(opt.dictionary); + } else { + dict = opt.dictionary; + } + + status = deflate_1$4.deflateSetDictionary(this.strm, dict); + + if (status !== Z_OK$7) { + throw new Error(messages$2[status]); + } + + this._dict_set = true; + } +} + +/** + * Deflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be + * converted to utf8 byte sequence. + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with + * new compressed chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the compression context. + * + * On fail call [[Deflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * array format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Deflate$2.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$7 : Z_NO_FLUSH$5); + + // Convert data if needed + if (typeof data === 'string') { + // If we need to compress text, change encoding to utf8. + strm.input = strings$2.string2buf(data); + } else if (toString$4.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 common$2.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = deflate_1$4.deflate(strm, _mode); /* no bad return value */ + + if (status !== Z_STREAM_END$7 && status !== Z_OK$7) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH$7 || _mode === Z_SYNC_FLUSH$2))) { + if (this.options.to === 'string') { + this.onData(strings$2.buf2binstring(common$2.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(common$2.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END$7); + + // Finalize on the last chunk. + if (_mode === Z_FINISH$7) { + status = deflate_1$4.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK$7; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === Z_SYNC_FLUSH$2) { + this.onEnd(Z_OK$7); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Deflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Deflate$2.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Deflate#onEnd(status) -> Void + * - status (Number): deflate status. 0 (Z_OK) on success, + * other if not. + * + * Called once after you tell deflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Deflate$2.prototype.onEnd = function (status) { + // On success - join + if (status === Z_OK$7) { + if (this.options.to === 'string') { + this.result = this.chunks.join(''); + } else { + this.result = common$2.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * deflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * Compress `data` with deflate algorithm and `options`. + * + * Supported options are: + * + * - level + * - windowBits + * - memLevel + * - strategy + * - dictionary + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); + * + * console.log(pako.deflate(data)); + * ``` + **/ +function deflate$5(input, options) { + var deflator = new Deflate$2(options); + + deflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (deflator.err) { throw deflator.msg || messages$2[deflator.err]; } + + return deflator.result; +} + + +/** + * deflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function deflateRaw$2(input, options) { + options = options || {}; + options.raw = true; + return deflate$5(input, options); +} + + +/** + * gzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but create gzip wrapper instead of + * deflate one. + **/ +function gzip$2(input, options) { + options = options || {}; + options.gzip = true; + return deflate$5(input, options); +} + + +var Deflate_1$2 = Deflate$2; +var deflate_2$5 = deflate$5; +var deflateRaw_1$2 = deflateRaw$2; +var gzip_1$2 = gzip$2; + +var deflate_1$5 = { + Deflate: Deflate_1$2, + deflate: deflate_2$5, + deflateRaw: deflateRaw_1$2, + gzip: gzip_1$2 +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// See state defs from inflate.js +var BAD$4 = 30; /* got a data error -- remain here until reset */ +var TYPE$4 = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +var inffast$2 = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + 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; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD$4; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD$4; + break top; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD$4; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE$4; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD$4; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + + + +var MAXBITS$2 = 15; +var ENOUGH_LENS$4 = 852; +var ENOUGH_DISTS$4 = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES$4 = 0; +var LENS$4 = 1; +var DISTS$4 = 2; + +var lbase$2 = [ /* 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$2 = [ /* 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$2 = [ /* 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$2 = [ /* 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 +]; + +var inftrees$2 = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new common$2.Buf16(MAXBITS$2 + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new common$2.Buf16(MAXBITS$2 + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS$2; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS$2; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS$2; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES$4 || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS$2; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES$4) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS$4) { + base = lbase$2; + base_index -= 257; + extra = lext$2; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase$2; + extra = dext$2; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS$4 && used > ENOUGH_LENS$4) || + (type === DISTS$4 && used > ENOUGH_DISTS$4)) { + return 1; + } + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS$4 && used > ENOUGH_LENS$4) || + (type === DISTS$4 && used > ENOUGH_DISTS$4)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + + + + + + + +var CODES$5 = 0; +var LENS$5 = 1; +var DISTS$5 = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//var Z_NO_FLUSH = 0; +//var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +//var Z_FULL_FLUSH = 3; +var Z_FINISH$8 = 4; +var Z_BLOCK$5 = 5; +var Z_TREES$2 = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK$8 = 0; +var Z_STREAM_END$8 = 1; +var Z_NEED_DICT$2 = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR$5 = -2; +var Z_DATA_ERROR$5 = -3; +var Z_MEM_ERROR$2 = -4; +var Z_BUF_ERROR$5 = -5; +//var Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +var Z_DEFLATED$8 = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD$2 = 1; /* i: waiting for magic header */ +var FLAGS$2 = 2; /* i: waiting for method and flags (gzip) */ +var TIME$2 = 3; /* i: waiting for modification time (gzip) */ +var OS$2 = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN$2 = 5; /* i: waiting for extra length (gzip) */ +var EXTRA$2 = 6; /* i: waiting for extra bytes (gzip) */ +var NAME$2 = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT$2 = 8; /* i: waiting for end of comment (gzip) */ +var HCRC$2 = 9; /* i: waiting for header crc (gzip) */ +var DICTID$2 = 10; /* i: waiting for dictionary check value */ +var DICT$2 = 11; /* waiting for inflateSetDictionary() call */ +var TYPE$5 = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO$2 = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED$2 = 14; /* i: waiting for stored size (length and complement) */ +var COPY_$2 = 15; /* i/o: same as COPY below, but only first time in */ +var COPY$2 = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE$2 = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS$2 = 18; /* i: waiting for code length code lengths */ +var CODELENS$2 = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_$2 = 20; /* i: same as LEN below, but only first time in */ +var LEN$2 = 21; /* i: waiting for length/lit/eob code */ +var LENEXT$2 = 22; /* i: waiting for length extra bits */ +var DIST$2 = 23; /* i: waiting for distance code */ +var DISTEXT$2 = 24; /* i: waiting for distance extra bits */ +var MATCH$2 = 25; /* o: waiting for output space to copy string */ +var LIT$2 = 26; /* o: waiting for output space to write literal */ +var CHECK$2 = 27; /* i: waiting for 32-bit check value */ +var LENGTH$2 = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE$2 = 29; /* finished check, done -- remain here until reset */ +var BAD$5 = 30; /* got a data error -- remain here until reset */ +var MEM$2 = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC$2 = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS$5 = 852; +var ENOUGH_DISTS$5 = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS$5 = 15; +/* 32K LZ77 window */ +var DEF_WBITS$2 = MAX_WBITS$5; + + +function zswap32$2(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState$2() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new common$2.Buf16(320); /* temporary storage for code lengths */ + this.work = new common$2.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep$2(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR$5; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD$2; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new common$2.Buf32(ENOUGH_LENS$5); + state.distcode = state.distdyn = new common$2.Buf32(ENOUGH_DISTS$5); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK$8; +} + +function inflateReset$2(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR$5; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep$2(strm); + +} + +function inflateReset2$2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR$5; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR$5; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset$2(strm); +} + +function inflateInit2$2(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR$5; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState$2(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2$2(strm, windowBits); + if (ret !== Z_OK$8) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit$2(strm) { + return inflateInit2$2(strm, DEF_WBITS$2); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin$2 = true; + +var lenfix$2, distfix$2; // We have no pointers in JS, so keep tables separate + +function fixedtables$2(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin$2) { + var sym; + + lenfix$2 = new common$2.Buf32(512); + distfix$2 = new common$2.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inftrees$2(LENS$5, state.lens, 0, 288, lenfix$2, 0, state.work, { bits: 9 }); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inftrees$2(DISTS$5, state.lens, 0, 32, distfix$2, 0, state.work, { bits: 5 }); + + /* do this just once */ + virgin$2 = false; + } + + state.lencode = lenfix$2; + state.lenbits = 9; + state.distcode = distfix$2; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow$2(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new common$2.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + common$2.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + common$2.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + common$2.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$4(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new common$2.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR$5; + } + + state = strm.state; + if (state.mode === TYPE$5) { state.mode = TYPEDO$2; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK$8; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD$2: + if (state.wrap === 0) { + state.mode = TYPEDO$2; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32_1$2(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS$2; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD$5; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED$8) { + strm.msg = 'unknown compression method'; + state.mode = BAD$5; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD$5; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID$2 : TYPE$5; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS$2: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED$8) { + strm.msg = 'unknown compression method'; + state.mode = BAD$5; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD$5; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32_1$2(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME$2; + /* falls through */ + case TIME$2: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32_1$2(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS$2; + /* falls through */ + case OS$2: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32_1$2(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN$2; + /* falls through */ + case EXLEN$2: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32_1$2(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA$2; + /* falls through */ + case EXTRA$2: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more convenient processing later + state.head.extra = new Array(state.head.extra_len); + } + common$2.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32_1$2(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME$2; + /* falls through */ + case NAME$2: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32_1$2(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$2; + /* falls through */ + case COMMENT$2: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32_1$2(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$2; + /* falls through */ + case HCRC$2: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD$5; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE$5; + break; + case DICTID$2: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32$2(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT$2; + /* falls through */ + case DICT$2: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT$2; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE$5; + /* falls through */ + case TYPE$5: + if (flush === Z_BLOCK$5 || flush === Z_TREES$2) { break inf_leave; } + /* falls through */ + case TYPEDO$2: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK$2; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED$2; + break; + case 1: /* fixed block */ + fixedtables$2(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_$2; /* decode codes */ + if (flush === Z_TREES$2) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE$2; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD$5; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED$2: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD$5; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_$2; + if (flush === Z_TREES$2) { break inf_leave; } + /* falls through */ + case COPY_$2: + state.mode = COPY$2; + /* falls through */ + case COPY$2: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + common$2.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE$5; + break; + case TABLE$2: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD$5; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS$2; + /* falls through */ + case LENLENS$2: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { bits: state.lenbits }; + ret = inftrees$2(CODES$5, 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$5; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS$2; + /* falls through */ + case CODELENS$2: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD$5; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD$5; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD$5) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD$5; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { bits: state.lenbits }; + ret = inftrees$2(LENS$5, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD$5; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inftrees$2(DISTS$5, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD$5; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_$2; + if (flush === Z_TREES$2) { break inf_leave; } + /* falls through */ + case LEN_$2: + state.mode = LEN$2; + /* falls through */ + case LEN$2: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inffast$2(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE$5) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT$2; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE$5; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD$5; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT$2; + /* falls through */ + case LENEXT$2: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST$2; + /* falls through */ + case DIST$2: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD$5; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT$2; + /* falls through */ + case DISTEXT$2: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD$5; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH$2; + /* falls through */ + case MATCH$2: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD$5; + break; + } +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN$2; } + break; + case LIT$2: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN$2; + break; + case CHECK$2: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' instead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32_1$2(state.check, output, _out, put - _out) : adler32_1$2(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32$2(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD$5; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH$2; + /* falls through */ + case LENGTH$2: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD$5; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE$2; + /* falls through */ + case DONE$2: + ret = Z_STREAM_END$8; + break inf_leave; + case BAD$5: + ret = Z_DATA_ERROR$5; + break inf_leave; + case MEM$2: + return Z_MEM_ERROR$2; + case SYNC$2: + /* falls through */ + default: + return Z_STREAM_ERROR$5; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$5 && + (state.mode < CHECK$2 || flush !== Z_FINISH$8))) { + if (updatewindow$2(strm, strm.output, strm.next_out, _out - strm.avail_out)) ; + } + _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_1$2(state.check, output, _out, strm.next_out - _out) : adler32_1$2(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE$5 ? 128 : 0) + + (state.mode === LEN_$2 || state.mode === COPY_$2 ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH$8) && ret === Z_OK$8) { + ret = Z_BUF_ERROR$5; + } + return ret; +} + +function inflateEnd$2(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR$5; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK$8; +} + +function inflateGetHeader$2(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR$5; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$5; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK$8; +} + +function inflateSetDictionary$2(strm, dictionary) { + var dictLength = dictionary.length; + + var state; + var dictid; + var ret; + + /* check state */ + if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR$5; } + state = strm.state; + + if (state.wrap !== 0 && state.mode !== DICT$2) { + return Z_STREAM_ERROR$5; + } + + /* check for correct dictionary identifier */ + if (state.mode === DICT$2) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32_1$2(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR$5; + } + } + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow$2(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM$2; + return Z_MEM_ERROR$2; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK$8; +} + +var inflateReset_1$2 = inflateReset$2; +var inflateReset2_1$2 = inflateReset2$2; +var inflateResetKeep_1$2 = inflateResetKeep$2; +var inflateInit_1$2 = inflateInit$2; +var inflateInit2_1$2 = inflateInit2$2; +var inflate_2$4 = inflate$4; +var inflateEnd_1$2 = inflateEnd$2; +var inflateGetHeader_1$2 = inflateGetHeader$2; +var inflateSetDictionary_1$2 = inflateSetDictionary$2; +var inflateInfo$2 = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ + +var inflate_1$4 = { + inflateReset: inflateReset_1$2, + inflateReset2: inflateReset2_1$2, + inflateResetKeep: inflateResetKeep_1$2, + inflateInit: inflateInit_1$2, + inflateInit2: inflateInit2_1$2, + inflate: inflate_2$4, + inflateEnd: inflateEnd_1$2, + inflateGetHeader: inflateGetHeader_1$2, + inflateSetDictionary: inflateSetDictionary_1$2, + inflateInfo: inflateInfo$2 +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var constants$2 = { + + /* 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 +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function GZheader$2() { + /* true if compressed data believed to be text */ + this.text = 0; + /* modification time */ + this.time = 0; + /* extra flags (not used when writing a gzip file) */ + this.xflags = 0; + /* operating system */ + this.os = 0; + /* pointer to extra field or Z_NULL if none */ + this.extra = null; + /* extra field length (valid if extra != Z_NULL) */ + this.extra_len = 0; // Actually, we don't need it in JS, + // but leave for few code modifications + + // + // Setup limits is not necessary because in js we should not preallocate memory + // for inflate use constant limit in 65536 bytes + // + + /* space at extra (only when reading header) */ + // this.extra_max = 0; + /* pointer to zero-terminated file name or Z_NULL */ + this.name = ''; + /* space at name (only when reading header) */ + // this.name_max = 0; + /* pointer to zero-terminated comment or Z_NULL */ + this.comment = ''; + /* space at comment (only when reading header) */ + // this.comm_max = 0; + /* true if there was or will be a header crc */ + this.hcrc = 0; + /* true when done reading gzip header (not used when writing a gzip file) */ + this.done = false; +} + +var gzheader$2 = GZheader$2; + +var toString$5 = Object.prototype.toString; + +/** + * class Inflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[inflate]] + * and [[inflateRaw]]. + **/ + +/* internal + * inflate.chunks -> Array + * + * Chunks of output data, if [[Inflate#onData]] not overridden. + **/ + +/** + * Inflate.result -> Uint8Array|Array|String + * + * Uncompressed result, generated by default [[Inflate#onData]] + * and [[Inflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Inflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Inflate.err -> Number + * + * Error code after inflate finished. 0 (Z_OK) on success. + * Should be checked if broken data possible. + **/ + +/** + * Inflate.msg -> String + * + * Error message, if [[Inflate.err]] != 0 + **/ + + +/** + * new Inflate(options) + * - options (Object): zlib inflate options. + * + * Creates new inflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `windowBits` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw inflate + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * By default, when no options set, autodetect deflate/gzip data format via + * wrapper header. + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var inflate = new pako.Inflate({ level: 3}); + * + * inflate.push(chunk1, false); + * inflate.push(chunk2, true); // true -> last chunk + * + * if (inflate.err) { throw new Error(inflate.err); } + * + * console.log(inflate.result); + * ``` + **/ +function Inflate$2(options) { + if (!(this instanceof Inflate$2)) return new Inflate$2(options); + + this.options = common$2.assign({ + chunkSize: 16384, + windowBits: 0, + to: '' + }, options || {}); + + var opt = this.options; + + // Force window size for `raw` data, if not set directly, + // because we have no header for autodetect. + if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { opt.windowBits = -15; } + } + + // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate + if ((opt.windowBits >= 0) && (opt.windowBits < 16) && + !(options && options.windowBits)) { + opt.windowBits += 32; + } + + // Gzip header has no info about windows size, we can do autodetect only + // for deflate. So, if window size not set, force it to max when gzip possible + if ((opt.windowBits > 15) && (opt.windowBits < 48)) { + // bit 3 (16) -> gzipped data + // bit 4 (32) -> autodetect gzip/deflate + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new zstream$2(); + this.strm.avail_out = 0; + + var status = inflate_1$4.inflateInit2( + this.strm, + opt.windowBits + ); + + if (status !== constants$2.Z_OK) { + throw new Error(messages$2[status]); + } + + this.header = new gzheader$2(); + + inflate_1$4.inflateGetHeader(this.strm, this.header); + + // Setup dictionary + if (opt.dictionary) { + // Convert data if needed + if (typeof opt.dictionary === 'string') { + opt.dictionary = strings$2.string2buf(opt.dictionary); + } else if (toString$5.call(opt.dictionary) === '[object ArrayBuffer]') { + opt.dictionary = new Uint8Array(opt.dictionary); + } + if (opt.raw) { //In raw mode we need to set the dictionary early + status = inflate_1$4.inflateSetDictionary(this.strm, opt.dictionary); + if (status !== constants$2.Z_OK) { + throw new Error(messages$2[status]); + } + } + } +} + +/** + * Inflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with + * new output chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the decompression context. + * + * On fail call [[Inflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Inflate$2.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; + + // Flag to properly process Z_BUF_ERROR on testing inflate call + // when we check that all output data was flushed. + var allowBufError = false; + + if (this.ended) { return false; } + _mode = (mode === ~~mode) ? mode : ((mode === true) ? constants$2.Z_FINISH : constants$2.Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // Only binary strings can be decompressed on practice + strm.input = strings$2.binstring2buf(data); + } else if (toString$5.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 common$2.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + + status = inflate_1$4.inflate(strm, constants$2.Z_NO_FLUSH); /* no bad return value */ + + if (status === constants$2.Z_NEED_DICT && dictionary) { + status = inflate_1$4.inflateSetDictionary(this.strm, dictionary); + } + + if (status === constants$2.Z_BUF_ERROR && allowBufError === true) { + status = constants$2.Z_OK; + allowBufError = false; + } + + if (status !== constants$2.Z_STREAM_END && status !== constants$2.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + + if (strm.next_out) { + if (strm.avail_out === 0 || status === constants$2.Z_STREAM_END || (strm.avail_in === 0 && (_mode === constants$2.Z_FINISH || _mode === constants$2.Z_SYNC_FLUSH))) { + + if (this.options.to === 'string') { + + next_out_utf8 = strings$2.utf8border(strm.output, strm.next_out); + + tail = strm.next_out - next_out_utf8; + utf8str = strings$2.buf2string(strm.output, next_out_utf8); + + // move tail + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { common$2.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } + + this.onData(utf8str); + + } else { + this.onData(common$2.shrinkBuf(strm.output, strm.next_out)); + } + } + } + + // When no more input data, we should check that internal inflate buffers + // are flushed. The only way to do it when avail_out = 0 - run one more + // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. + // Here we set flag to process this error properly. + // + // NOTE. Deflate does not return error in this case and does not needs such + // logic. + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== constants$2.Z_STREAM_END); + + if (status === constants$2.Z_STREAM_END) { + _mode = constants$2.Z_FINISH; + } + + // Finalize on the last chunk. + if (_mode === constants$2.Z_FINISH) { + status = inflate_1$4.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === constants$2.Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === constants$2.Z_SYNC_FLUSH) { + this.onEnd(constants$2.Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Inflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Inflate$2.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Inflate#onEnd(status) -> Void + * - status (Number): inflate status. 0 (Z_OK) on success, + * other if not. + * + * Called either after you tell inflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Inflate$2.prototype.onEnd = function (status) { + // On success - join + if (status === constants$2.Z_OK) { + if (this.options.to === 'string') { + // Glue & convert here, until we teach pako to send + // utf8 aligned strings to onData + this.result = this.chunks.join(''); + } else { + this.result = common$2.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * inflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Decompress `data` with inflate/ungzip and `options`. Autodetect + * format via wrapper header by default. That's why we don't provide + * separate `ungzip` method. + * + * Supported options are: + * + * - windowBits + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) + * , output; + * + * try { + * output = pako.inflate(input); + * } catch (err) + * console.log(err); + * } + * ``` + **/ +function inflate$5(input, options) { + var inflator = new Inflate$2(options); + + inflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (inflator.err) { throw inflator.msg || messages$2[inflator.err]; } + + return inflator.result; +} + + +/** + * inflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * The same as [[inflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function inflateRaw$2(input, options) { + options = options || {}; + options.raw = true; + return inflate$5(input, options); +} + + +/** + * ungzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Just shortcut to [[inflate]], because it autodetects format + * by header.content. Done for convenience. + **/ + + +var Inflate_1$2 = Inflate$2; +var inflate_2$5 = inflate$5; +var inflateRaw_1$2 = inflateRaw$2; +var ungzip$2 = inflate$5; + +var inflate_1$5 = { + Inflate: Inflate_1$2, + inflate: inflate_2$5, + inflateRaw: inflateRaw_1$2, + ungzip: ungzip$2 +}; + +var assign$2 = common$2.assign; + + + + + +var pako$2 = {}; + +assign$2(pako$2, deflate_1$5, inflate_1$5, constants$2); + +var pako_1$2 = pako$2; + +var UPNG = {}; + + + +UPNG.toRGBA8 = function(out) +{ + var w = out.width, h = out.height; + if(out.tabs.acTL==null) return [UPNG.toRGBA8.decodeImage(out.data, w, h, out).buffer]; + + var frms = []; + if(out.frames[0].data==null) out.frames[0].data = out.data; + + var len = w*h*4, img = new Uint8Array(len), empty = new Uint8Array(len), prev=new Uint8Array(len); + for(var i=0; i<out.frames.length; i++) + { + var frm = out.frames[i]; + var fx=frm.rect.x, fy=frm.rect.y, fw = frm.rect.width, fh = frm.rect.height; + var fdata = UPNG.toRGBA8.decodeImage(frm.data, fw,fh, out); + + if(i!=0) for(var j=0; j<len; j++) prev[j]=img[j]; + + if (frm.blend==0) UPNG._copyTile(fdata, fw, fh, img, w, h, fx, fy, 0); + else if(frm.blend==1) UPNG._copyTile(fdata, fw, fh, img, w, h, fx, fy, 1); + + frms.push(img.buffer.slice(0)); + + if (frm.dispose==0) ; + else if(frm.dispose==1) UPNG._copyTile(empty, fw, fh, img, w, h, fx, fy, 0); + else if(frm.dispose==2) for(var j=0; j<len; j++) img[j]=prev[j]; + } + return frms; +}; +UPNG.toRGBA8.decodeImage = function(data, w, h, out) +{ + var area = w*h, bpp = UPNG.decode._getBPP(out); + var bpl = Math.ceil(w*bpp/8); // bytes per line + + var bf = new Uint8Array(area*4), bf32 = new Uint32Array(bf.buffer); + var ctype = out.ctype, depth = out.depth; + var rs = UPNG._bin.readUshort; + + if (ctype==6) { // RGB + alpha + var qarea = area<<2; + if(depth== 8) for(var i=0; i<qarea;i+=4) { bf[i] = data[i]; bf[i+1] = data[i+1]; bf[i+2] = data[i+2]; bf[i+3] = data[i+3]; } + if(depth==16) for(var i=0; i<qarea;i++ ) { bf[i] = data[i<<1]; } + } + else if(ctype==2) { // RGB + var ts=out.tabs["tRNS"]; + if(ts==null) { + if(depth== 8) for(var i=0; i<area; i++) { var ti=i*3; bf32[i] = (255<<24)|(data[ti+2]<<16)|(data[ti+1]<<8)|data[ti]; } + if(depth==16) for(var i=0; i<area; i++) { var ti=i*6; bf32[i] = (255<<24)|(data[ti+4]<<16)|(data[ti+2]<<8)|data[ti]; } + } + else { var tr=ts[0], tg=ts[1], tb=ts[2]; + if(depth== 8) for(var i=0; i<area; i++) { var qi=i<<2, ti=i*3; bf32[i] = (255<<24)|(data[ti+2]<<16)|(data[ti+1]<<8)|data[ti]; + if(data[ti] ==tr && data[ti+1] ==tg && data[ti+2] ==tb) bf[qi+3] = 0; } + if(depth==16) for(var i=0; i<area; i++) { var qi=i<<2, ti=i*6; bf32[i] = (255<<24)|(data[ti+4]<<16)|(data[ti+2]<<8)|data[ti]; + if(rs(data,ti)==tr && rs(data,ti+2)==tg && rs(data,ti+4)==tb) bf[qi+3] = 0; } + } + } + else if(ctype==3) { // palette + var p=out.tabs["PLTE"], ap=out.tabs["tRNS"], tl=ap?ap.length:0; + //console.log(p, ap); + if(depth==1) for(var y=0; y<h; y++) { var s0 = y*bpl, t0 = y*w; + for(var i=0; i<w; i++) { var qi=(t0+i)<<2, j=((data[s0+(i>>3)]>>(7-((i&7)<<0)))& 1), cj=3*j; bf[qi]=p[cj]; bf[qi+1]=p[cj+1]; bf[qi+2]=p[cj+2]; bf[qi+3]=(j<tl)?ap[j]:255; } + } + if(depth==2) for(var y=0; y<h; y++) { var s0 = y*bpl, t0 = y*w; + for(var i=0; i<w; i++) { var qi=(t0+i)<<2, j=((data[s0+(i>>2)]>>(6-((i&3)<<1)))& 3), cj=3*j; bf[qi]=p[cj]; bf[qi+1]=p[cj+1]; bf[qi+2]=p[cj+2]; bf[qi+3]=(j<tl)?ap[j]:255; } + } + if(depth==4) for(var y=0; y<h; y++) { var s0 = y*bpl, t0 = y*w; + for(var i=0; i<w; i++) { var qi=(t0+i)<<2, j=((data[s0+(i>>1)]>>(4-((i&1)<<2)))&15), cj=3*j; bf[qi]=p[cj]; bf[qi+1]=p[cj+1]; bf[qi+2]=p[cj+2]; bf[qi+3]=(j<tl)?ap[j]:255; } + } + if(depth==8) for(var i=0; i<area; i++ ) { var qi=i<<2, j=data[i] , cj=3*j; bf[qi]=p[cj]; bf[qi+1]=p[cj+1]; bf[qi+2]=p[cj+2]; bf[qi+3]=(j<tl)?ap[j]:255; } + } + else if(ctype==4) { // gray + alpha + if(depth== 8) for(var i=0; i<area; i++) { var qi=i<<2, di=i<<1, gr=data[di]; bf[qi]=gr; bf[qi+1]=gr; bf[qi+2]=gr; bf[qi+3]=data[di+1]; } + if(depth==16) for(var i=0; i<area; i++) { var qi=i<<2, di=i<<2, gr=data[di]; bf[qi]=gr; bf[qi+1]=gr; bf[qi+2]=gr; bf[qi+3]=data[di+2]; } + } + else if(ctype==0) { // gray + var tr = out.tabs["tRNS"] ? out.tabs["tRNS"] : -1; + for(var y=0; y<h; y++) { + var off = y*bpl, to = y*w; + if (depth== 1) for(var x=0; x<w; x++) { var gr=255*((data[off+(x>>>3)]>>>(7 -((x&7) )))& 1), al=(gr==tr*255)?0:255; bf32[to+x]=(al<<24)|(gr<<16)|(gr<<8)|gr; } + else if(depth== 2) for(var x=0; x<w; x++) { var gr= 85*((data[off+(x>>>2)]>>>(6 -((x&3)<<1)))& 3), al=(gr==tr* 85)?0:255; bf32[to+x]=(al<<24)|(gr<<16)|(gr<<8)|gr; } + else if(depth== 4) for(var x=0; x<w; x++) { var gr= 17*((data[off+(x>>>1)]>>>(4 -((x&1)<<2)))&15), al=(gr==tr* 17)?0:255; bf32[to+x]=(al<<24)|(gr<<16)|(gr<<8)|gr; } + else if(depth== 8) for(var x=0; x<w; x++) { var gr=data[off+ x], al=(gr ==tr)?0:255; bf32[to+x]=(al<<24)|(gr<<16)|(gr<<8)|gr; } + else if(depth==16) for(var x=0; x<w; x++) { var gr=data[off+(x<<1)], al=(rs(data,off+(x<<i))==tr)?0:255; bf32[to+x]=(al<<24)|(gr<<16)|(gr<<8)|gr; } + } + } + //console.log(Date.now()-time); + return bf; +}; + + + +UPNG.decode = function(buff) +{ + var data = new Uint8Array(buff), offset = 8, bin = UPNG._bin, rUs = bin.readUshort, rUi = bin.readUint; + var out = {tabs:{}, frames:[]}; + var dd = new Uint8Array(data.length), doff = 0; // put all IDAT data into it + var fd, foff = 0; // frames + + var mgck = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; + for(var i=0; i<8; i++) if(data[i]!=mgck[i]) throw "The input is not a PNG file!"; + + while(offset<data.length) + { + var len = bin.readUint(data, offset); offset += 4; + var type = bin.readASCII(data, offset, 4); offset += 4; + //console.log(type,len); + + if (type=="IHDR") { UPNG.decode._IHDR(data, offset, out); } + else if(type=="IDAT") { + for(var i=0; i<len; i++) dd[doff+i] = data[offset+i]; + doff += len; + } + else if(type=="acTL") { + out.tabs[type] = { num_frames:rUi(data, offset), num_plays:rUi(data, offset+4) }; + fd = new Uint8Array(data.length); + } + else if(type=="fcTL") { + if(foff!=0) { var fr = out.frames[out.frames.length-1]; + fr.data = UPNG.decode._decompress(out, fd.slice(0,foff), fr.rect.width, fr.rect.height); foff=0; + } + var rct = {x:rUi(data, offset+12),y:rUi(data, offset+16),width:rUi(data, offset+4),height:rUi(data, offset+8)}; + var del = rUs(data, offset+22); del = rUs(data, offset+20) / (del==0?100:del); + var frm = {rect:rct, delay:Math.round(del*1000), dispose:data[offset+24], blend:data[offset+25]}; + //console.log(frm); + out.frames.push(frm); + } + else if(type=="fdAT") { + for(var i=0; i<len-4; i++) fd[foff+i] = data[offset+i+4]; + foff += len-4; + } + else if(type=="pHYs") { + out.tabs[type] = [bin.readUint(data, offset), bin.readUint(data, offset+4), data[offset+8]]; + } + else if(type=="cHRM") { + out.tabs[type] = []; + for(var i=0; i<8; i++) out.tabs[type].push(bin.readUint(data, offset+i*4)); + } + else if(type=="tEXt") { + if(out.tabs[type]==null) out.tabs[type] = {}; + var nz = bin.nextZero(data, offset); + var keyw = bin.readASCII(data, offset, nz-offset); + var text = bin.readASCII(data, nz+1, offset+len-nz-1); + out.tabs[type][keyw] = text; + } + else if(type=="iTXt") { + if(out.tabs[type]==null) out.tabs[type] = {}; + var nz = 0, off = offset; + nz = bin.nextZero(data, off); + var keyw = bin.readASCII(data, off, nz-off); off = nz + 1; + off+=2; + nz = bin.nextZero(data, off); + var ltag = bin.readASCII(data, off, nz-off); off = nz + 1; + nz = bin.nextZero(data, off); + var tkeyw = bin.readUTF8(data, off, nz-off); off = nz + 1; + var text = bin.readUTF8(data, off, len-(off-offset)); + out.tabs[type][keyw] = text; + } + else if(type=="PLTE") { + out.tabs[type] = bin.readBytes(data, offset, len); + } + else if(type=="hIST") { + var pl = out.tabs["PLTE"].length/3; + out.tabs[type] = []; for(var i=0; i<pl; i++) out.tabs[type].push(rUs(data, offset+i*2)); + } + else if(type=="tRNS") { + if (out.ctype==3) out.tabs[type] = bin.readBytes(data, offset, len); + else if(out.ctype==0) out.tabs[type] = rUs(data, offset); + else if(out.ctype==2) out.tabs[type] = [ rUs(data,offset),rUs(data,offset+2),rUs(data,offset+4) ]; + //else console.log("tRNS for unsupported color type",out.ctype, len); + } + else if(type=="gAMA") out.tabs[type] = bin.readUint(data, offset)/100000; + else if(type=="sRGB") out.tabs[type] = data[offset]; + else if(type=="bKGD") + { + if (out.ctype==0 || out.ctype==4) out.tabs[type] = [rUs(data, offset)]; + else if(out.ctype==2 || out.ctype==6) out.tabs[type] = [rUs(data, offset), rUs(data, offset+2), rUs(data, offset+4)]; + else if(out.ctype==3) out.tabs[type] = data[offset]; + } + else if(type=="IEND") { + break; + } + //else { log("unknown chunk type", type, len); } + offset += len; + var crc = bin.readUint(data, offset); offset += 4; + } + if(foff!=0) { var fr = out.frames[out.frames.length-1]; + fr.data = UPNG.decode._decompress(out, fd.slice(0,foff), fr.rect.width, fr.rect.height); foff=0; + } + out.data = UPNG.decode._decompress(out, dd, out.width, out.height); + + delete out.compress; delete out.interlace; delete out.filter; + return out; +}; + +UPNG.decode._decompress = function(out, dd, w, h) { + var bpp = UPNG.decode._getBPP(out), bpl = Math.ceil(w*bpp/8), buff = new Uint8Array((bpl+1+out.interlace)*h); + dd = UPNG.decode._inflate(dd,buff); + if (out.interlace==0) dd = UPNG.decode._filterZero(dd, out, 0, w, h); + else if(out.interlace==1) dd = UPNG.decode._readInterlace(dd, out); + //console.log(Date.now()-time); + return dd; +}; + +UPNG.decode._inflate = function(data, buff) { var out=UPNG["inflateRaw"](new Uint8Array(data.buffer, 2,data.length-6),buff); return out; }; +UPNG.inflateRaw=function(){var H={};H.H={};H.H.N=function(N,W){var R=Uint8Array,i=0,m=0,J=0,h=0,Q=0,X=0,u=0,w=0,d=0,v,C; +if(N[0]==3&&N[1]==0)return W?W:new R(0);var V=H.H,n=V.b,A=V.e,l=V.R,M=V.n,I=V.A,e=V.Z,b=V.m,Z=W==null; +if(Z)W=new R(N.length>>>2<<3);while(i==0){i=n(N,d,1);m=n(N,d+1,2);d+=3;if(m==0){if((d&7)!=0)d+=8-(d&7); +var D=(d>>>3)+4,q=N[D-4]|N[D-3]<<8;if(Z)W=H.H.W(W,w+q);W.set(new R(N.buffer,N.byteOffset+D,q),w);d=D+q<<3; +w+=q;continue}if(Z)W=H.H.W(W,w+(1<<17));if(m==1){v=b.J;C=b.h;X=(1<<9)-1;u=(1<<5)-1;}if(m==2){J=A(N,d,5)+257; +h=A(N,d+5,5)+1;Q=A(N,d+10,4)+4;d+=14;var j=1;for(var c=0;c<38;c+=2){b.Q[c]=0;b.Q[c+1]=0;}for(var c=0; +c<Q;c++){var K=A(N,d+c*3,3);b.Q[(b.X[c]<<1)+1]=K;if(K>j)j=K;}d+=3*Q;M(b.Q,j);I(b.Q,j,b.u);v=b.w;C=b.d; +d=l(b.u,(1<<j)-1,J+h,N,d,b.v);var r=V.V(b.v,0,J,b.C);X=(1<<r)-1;var S=V.V(b.v,J,h,b.D);u=(1<<S)-1;M(b.C,r); +I(b.C,r,v);M(b.D,S);I(b.D,S,C);}while(!0){var T=v[e(N,d)&X];d+=T&15;var p=T>>>4;if(p>>>8==0){W[w++]=p;}else if(p==256){break}else {var z=w+p-254; +if(p>264){var _=b.q[p-257];z=w+(_>>>3)+A(N,d,_&7);d+=_&7;}var $=C[e(N,d)&u];d+=$&15;var s=$>>>4,Y=b.c[s],a=(Y>>>4)+n(N,d,Y&15); +d+=Y&15;while(w<z){W[w]=W[w++-a];W[w]=W[w++-a];W[w]=W[w++-a];W[w]=W[w++-a];}w=z;}}}return W.length==w?W:W.slice(0,w)}; +H.H.W=function(N,W){var R=N.length;if(W<=R)return N;var V=new Uint8Array(R<<1);V.set(N,0);return V}; +H.H.R=function(N,W,R,V,n,A){var l=H.H.e,M=H.H.Z,I=0;while(I<R){var e=N[M(V,n)&W];n+=e&15;var b=e>>>4; +if(b<=15){A[I]=b;I++;}else {var Z=0,m=0;if(b==16){m=3+l(V,n,2);n+=2;Z=A[I-1];}else if(b==17){m=3+l(V,n,3); +n+=3;}else if(b==18){m=11+l(V,n,7);n+=7;}var J=I+m;while(I<J){A[I]=Z;I++;}}}return n};H.H.V=function(N,W,R,V){var n=0,A=0,l=V.length>>>1; +while(A<R){var M=N[A+W];V[A<<1]=0;V[(A<<1)+1]=M;if(M>n)n=M;A++;}while(A<l){V[A<<1]=0;V[(A<<1)+1]=0;A++;}return n}; +H.H.n=function(N,W){var R=H.H.m,V=N.length,n,A,l,M,I,e=R.j;for(var M=0;M<=W;M++)e[M]=0;for(M=1;M<V;M+=2)e[N[M]]++; +var b=R.K;n=0;e[0]=0;for(A=1;A<=W;A++){n=n+e[A-1]<<1;b[A]=n;}for(l=0;l<V;l+=2){I=N[l+1];if(I!=0){N[l]=b[I]; +b[I]++;}}};H.H.A=function(N,W,R){var V=N.length,n=H.H.m,A=n.r;for(var l=0;l<V;l+=2)if(N[l+1]!=0){var M=l>>1,I=N[l+1],e=M<<4|I,b=W-I,Z=N[l]<<b,m=Z+(1<<b); +while(Z!=m){var J=A[Z]>>>15-W;R[J]=e;Z++;}}};H.H.l=function(N,W){var R=H.H.m.r,V=15-W;for(var n=0;n<N.length; +n+=2){var A=N[n]<<W-N[n+1];N[n]=R[A]>>>V;}};H.H.M=function(N,W,R){R=R<<(W&7);var V=W>>>3;N[V]|=R;N[V+1]|=R>>>8;}; +H.H.I=function(N,W,R){R=R<<(W&7);var V=W>>>3;N[V]|=R;N[V+1]|=R>>>8;N[V+2]|=R>>>16;};H.H.e=function(N,W,R){return (N[W>>>3]|N[(W>>>3)+1]<<8)>>>(W&7)&(1<<R)-1}; +H.H.b=function(N,W,R){return (N[W>>>3]|N[(W>>>3)+1]<<8|N[(W>>>3)+2]<<16)>>>(W&7)&(1<<R)-1};H.H.Z=function(N,W){return (N[W>>>3]|N[(W>>>3)+1]<<8|N[(W>>>3)+2]<<16)>>>(W&7)}; +H.H.i=function(N,W){return (N[W>>>3]|N[(W>>>3)+1]<<8|N[(W>>>3)+2]<<16|N[(W>>>3)+3]<<24)>>>(W&7)};H.H.m=function(){var N=Uint16Array,W=Uint32Array; +return {K:new N(16),j:new N(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[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,999,999,999],T:[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,0,0,0],q:new N(32),p:[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,65535,65535],z:[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,0,0],c:new W(32),J:new N(512),_:[],h:new N(32),$:[],w:new N(32768),C:[],v:[],d:new N(32768),D:[],u:new N(512),Q:[],r:new N(1<<15),s:new W(286),Y:new W(30),a:new W(19),t:new W(15e3),k:new N(1<<16),g:new N(1<<15)}}(); +(function(){var N=H.H.m,W=1<<15;for(var R=0;R<W;R++){var V=R;V=(V&2863311530)>>>1|(V&1431655765)<<1; +V=(V&3435973836)>>>2|(V&858993459)<<2;V=(V&4042322160)>>>4|(V&252645135)<<4;V=(V&4278255360)>>>8|(V&16711935)<<8; +N.r[R]=(V>>>16|V<<16)>>>17;}function n(A,l,M){while(l--!=0)A.push(0,M);}for(var R=0;R<32;R++){N.q[R]=N.S[R]<<3|N.T[R]; +N.c[R]=N.p[R]<<4|N.z[R];}n(N._,144,8);n(N._,255-143,9);n(N._,279-255,7);n(N._,287-279,8);H.H.n(N._,9); +H.H.A(N._,9,N.J);H.H.l(N._,9);n(N.$,32,5);H.H.n(N.$,5);H.H.A(N.$,5,N.h);H.H.l(N.$,5);n(N.Q,19,0);n(N.C,286,0); +n(N.D,30,0);n(N.v,320,0);}());return H.H.N}(); + + +UPNG.decode._readInterlace = function(data, out) +{ + var w = out.width, h = out.height; + var bpp = UPNG.decode._getBPP(out), cbpp = bpp>>3, bpl = Math.ceil(w*bpp/8); + var img = new Uint8Array( h * bpl ); + var di = 0; + + var starting_row = [ 0, 0, 4, 0, 2, 0, 1 ]; + var starting_col = [ 0, 4, 0, 2, 0, 1, 0 ]; + var row_increment = [ 8, 8, 8, 4, 4, 2, 2 ]; + var col_increment = [ 8, 8, 4, 4, 2, 2, 1 ]; + + var pass=0; + while(pass<7) + { + var ri = row_increment[pass], ci = col_increment[pass]; + var sw = 0, sh = 0; + var cr = starting_row[pass]; while(cr<h) { cr+=ri; sh++; } + var cc = starting_col[pass]; while(cc<w) { cc+=ci; sw++; } + var bpll = Math.ceil(sw*bpp/8); + UPNG.decode._filterZero(data, out, di, sw, sh); + + var y=0, row = starting_row[pass]; + while(row<h) + { + var col = starting_col[pass]; + var cdi = (di+y*bpll)<<3; + + while(col<w) + { + if(bpp==1) { + var val = data[cdi>>3]; val = (val>>(7-(cdi&7)))&1; + img[row*bpl + (col>>3)] |= (val << (7-((col&7)<<0))); + } + if(bpp==2) { + var val = data[cdi>>3]; val = (val>>(6-(cdi&7)))&3; + img[row*bpl + (col>>2)] |= (val << (6-((col&3)<<1))); + } + if(bpp==4) { + var val = data[cdi>>3]; val = (val>>(4-(cdi&7)))&15; + img[row*bpl + (col>>1)] |= (val << (4-((col&1)<<2))); + } + if(bpp>=8) { + var ii = row*bpl+col*cbpp; + for(var j=0; j<cbpp; j++) img[ii+j] = data[(cdi>>3)+j]; + } + cdi+=bpp; col+=ci; + } + y++; row += ri; + } + if(sw*sh!=0) di += sh * (1 + bpll); + pass = pass + 1; + } + return img; +}; + +UPNG.decode._getBPP = function(out) { + var noc = [1,null,3,1,2,null,4][out.ctype]; + return noc * out.depth; +}; + +UPNG.decode._filterZero = function(data, out, off, w, h) +{ + var bpp = UPNG.decode._getBPP(out), bpl = Math.ceil(w*bpp/8), paeth = UPNG.decode._paeth; + bpp = Math.ceil(bpp/8); + + var i=0, di=1, type=data[off], x=0; + + if(type>1) data[off]=[0,0,1][type-2]; + if(type==3) for(x=bpp; x<bpl; x++) data[x+1] = (data[x+1] + (data[x+1-bpp]>>>1) )&255; + + for(var y=0; y<h; y++) { + i = off+y*bpl; di = i+y+1; + type = data[di-1]; x=0; + + if (type==0) for(; x<bpl; x++) data[i+x] = data[di+x]; + else if(type==1) { for(; x<bpp; x++) data[i+x] = data[di+x]; + for(; x<bpl; x++) data[i+x] = (data[di+x] + data[i+x-bpp]); } + else if(type==2) { for(; x<bpl; x++) data[i+x] = (data[di+x] + data[i+x-bpl]); } + else if(type==3) { for(; x<bpp; x++) data[i+x] = (data[di+x] + ( data[i+x-bpl]>>>1)); + for(; x<bpl; x++) data[i+x] = (data[di+x] + ((data[i+x-bpl]+data[i+x-bpp])>>>1) ); } + else { for(; x<bpp; x++) data[i+x] = (data[di+x] + paeth(0, data[i+x-bpl], 0)); + for(; x<bpl; x++) data[i+x] = (data[di+x] + paeth(data[i+x-bpp], data[i+x-bpl], data[i+x-bpp-bpl]) ); } + } + return data; +}; + +UPNG.decode._paeth = function(a,b,c) +{ + var p = a+b-c, pa = (p-a), pb = (p-b), pc = (p-c); + if (pa*pa <= pb*pb && pa*pa <= pc*pc) return a; + else if (pb*pb <= pc*pc) return b; + return c; +}; + +UPNG.decode._IHDR = function(data, offset, out) +{ + var bin = UPNG._bin; + out.width = bin.readUint(data, offset); offset += 4; + out.height = bin.readUint(data, offset); offset += 4; + out.depth = data[offset]; offset++; + out.ctype = data[offset]; offset++; + out.compress = data[offset]; offset++; + out.filter = data[offset]; offset++; + out.interlace = data[offset]; offset++; +}; + +UPNG._bin = { + nextZero : function(data,p) { while(data[p]!=0) p++; return p; }, + readUshort : function(buff,p) { return (buff[p]<< 8) | buff[p+1]; }, + writeUshort: function(buff,p,n){ buff[p] = (n>>8)&255; buff[p+1] = n&255; }, + readUint : function(buff,p) { return (buff[p]*(256*256*256)) + ((buff[p+1]<<16) | (buff[p+2]<< 8) | buff[p+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&255; }, + readASCII : function(buff,p,l){ var s = ""; for(var i=0; i<l; i++) s += String.fromCharCode(buff[p+i]); return s; }, + writeASCII : function(data,p,s){ for(var i=0; i<s.length; i++) data[p+i] = s.charCodeAt(i); }, + readBytes : function(buff,p,l){ var arr = []; for(var i=0; i<l; i++) arr.push(buff[p+i]); return arr; }, + pad : function(n) { return n.length < 2 ? "0" + n : n; }, + readUTF8 : function(buff, p, l) { + var s = "", ns; + for(var i=0; i<l; i++) s += "%" + UPNG._bin.pad(buff[p+i].toString(16)); + try { ns = decodeURIComponent(s); } + catch(e) { return UPNG._bin.readASCII(buff, p, l); } + return ns; + } +}; +UPNG._copyTile = function(sb, sw, sh, tb, tw, th, xoff, yoff, mode) +{ + var w = Math.min(sw,tw), h = Math.min(sh,th); + var si=0, ti=0; + for(var y=0; y<h; y++) + for(var x=0; x<w; x++) + { + if(xoff>=0 && yoff>=0) { si = (y*sw+x)<<2; ti = (( yoff+y)*tw+xoff+x)<<2; } + else { si = ((-yoff+y)*sw-xoff+x)<<2; ti = (y*tw+x)<<2; } + + if (mode==0) { tb[ti] = sb[si]; tb[ti+1] = sb[si+1]; tb[ti+2] = sb[si+2]; tb[ti+3] = sb[si+3]; } + else if(mode==1) { + var fa = sb[si+3]*(1/255), fr=sb[si]*fa, fg=sb[si+1]*fa, fb=sb[si+2]*fa; + var ba = tb[ti+3]*(1/255), br=tb[ti]*ba, bg=tb[ti+1]*ba, bb=tb[ti+2]*ba; + + var ifa=1-fa, oa = fa+ba*ifa, ioa = (oa==0?0:1/oa); + tb[ti+3] = 255*oa; + tb[ti+0] = (fr+br*ifa)*ioa; + tb[ti+1] = (fg+bg*ifa)*ioa; + tb[ti+2] = (fb+bb*ifa)*ioa; + } + else if(mode==2){ // copy only differences, otherwise zero + var fa = sb[si+3], fr=sb[si], fg=sb[si+1], fb=sb[si+2]; + var ba = tb[ti+3], br=tb[ti], bg=tb[ti+1], bb=tb[ti+2]; + if(fa==ba && fr==br && fg==bg && fb==bb) { tb[ti]=0; tb[ti+1]=0; tb[ti+2]=0; tb[ti+3]=0; } + else { tb[ti]=fr; tb[ti+1]=fg; tb[ti+2]=fb; tb[ti+3]=fa; } + } + else if(mode==3){ // check if can be blended + var fa = sb[si+3], fr=sb[si], fg=sb[si+1], fb=sb[si+2]; + var ba = tb[ti+3], br=tb[ti], bg=tb[ti+1], bb=tb[ti+2]; + if(fa==ba && fr==br && fg==bg && fb==bb) continue; + //if(fa!=255 && ba!=0) return false; + if(fa<220 && ba>20) return false; + } + } + return true; +}; + + + + +UPNG.encode = function(bufs, w, h, ps, dels, tabs, forbidPlte) +{ + if(ps==null) ps=0; + if(forbidPlte==null) forbidPlte = false; + + var nimg = UPNG.encode.compress(bufs, w, h, ps, [false, false, false, 0, forbidPlte]); + UPNG.encode.compressPNG(nimg, -1); + + return UPNG.encode._main(nimg, w, h, dels, tabs); +}; + +UPNG.encodeLL = function(bufs, w, h, cc, ac, depth, dels, tabs) { + var nimg = { ctype: 0 + (cc==1 ? 0 : 2) + (ac==0 ? 0 : 4), depth: depth, frames: [] }; + var bipp = (cc+ac)*depth, bipl = bipp * w; + for(var i=0; i<bufs.length; i++) + nimg.frames.push({ rect:{x:0,y:0,width:w,height:h}, img:new Uint8Array(bufs[i]), blend:0, dispose:1, bpp:Math.ceil(bipp/8), bpl:Math.ceil(bipl/8) }); + + UPNG.encode.compressPNG(nimg, 0, true); + + var out = UPNG.encode._main(nimg, w, h, dels, tabs); + return out; +}; + +UPNG.encode._main = function(nimg, w, h, dels, tabs) { + if(tabs==null) tabs={}; + var crc = UPNG.crc.crc, wUi = UPNG._bin.writeUint, wUs = UPNG._bin.writeUshort, wAs = UPNG._bin.writeASCII; + var offset = 8, anim = nimg.frames.length>1, pltAlpha = false; + + var leng = 8 + (16+5+4) /*+ (9+4)*/ + (anim ? 20 : 0); + if(tabs["sRGB"]!=null) leng += 8+1+4; + if(tabs["pHYs"]!=null) leng += 8+9+4; + if(nimg.ctype==3) { + var dl = nimg.plte.length; + for(var i=0; i<dl; i++) if((nimg.plte[i]>>>24)!=255) pltAlpha = true; + leng += (8 + dl*3 + 4) + (pltAlpha ? (8 + dl*1 + 4) : 0); + } + for(var j=0; j<nimg.frames.length; j++) + { + var fr = nimg.frames[j]; + if(anim) leng += 38; + leng += fr.cimg.length + 12; + if(j!=0) leng+=4; + } + leng += 12; + + var data = new Uint8Array(leng); + var wr=[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; + for(var i=0; i<8; i++) data[i]=wr[i]; + + wUi(data,offset, 13); offset+=4; + wAs(data,offset,"IHDR"); offset+=4; + wUi(data,offset,w); offset+=4; + wUi(data,offset,h); offset+=4; + data[offset] = nimg.depth; offset++; // depth + data[offset] = nimg.ctype; offset++; // ctype + data[offset] = 0; offset++; // compress + data[offset] = 0; offset++; // filter + data[offset] = 0; offset++; // interlace + wUi(data,offset,crc(data,offset-17,17)); offset+=4; // crc + + // 13 bytes to say, that it is sRGB + if(tabs["sRGB"]!=null) { + wUi(data,offset, 1); offset+=4; + wAs(data,offset,"sRGB"); offset+=4; + data[offset] = tabs["sRGB"]; offset++; + wUi(data,offset,crc(data,offset-5,5)); offset+=4; // crc + } + if(tabs["pHYs"]!=null) { + wUi(data,offset, 9); offset+=4; + wAs(data,offset,"pHYs"); offset+=4; + wUi(data,offset, tabs["pHYs"][0]); offset+=4; + wUi(data,offset, tabs["pHYs"][1]); offset+=4; + data[offset]=tabs["pHYs"][2]; offset++; + wUi(data,offset,crc(data,offset-13,13)); offset+=4; // crc + } + + if(anim) { + wUi(data,offset, 8); offset+=4; + wAs(data,offset,"acTL"); offset+=4; + wUi(data,offset, nimg.frames.length); offset+=4; + wUi(data,offset, tabs["loop"]!=null?tabs["loop"]:0); offset+=4; + wUi(data,offset,crc(data,offset-12,12)); offset+=4; // crc + } + + if(nimg.ctype==3) { + var dl = nimg.plte.length; + wUi(data,offset, dl*3); offset+=4; + wAs(data,offset,"PLTE"); offset+=4; + for(var i=0; i<dl; i++){ + var ti=i*3, c=nimg.plte[i], r=(c)&255, g=(c>>>8)&255, b=(c>>>16)&255; + data[offset+ti+0]=r; data[offset+ti+1]=g; data[offset+ti+2]=b; + } + offset+=dl*3; + wUi(data,offset,crc(data,offset-dl*3-4,dl*3+4)); offset+=4; // crc + + if(pltAlpha) { + wUi(data,offset, dl); offset+=4; + wAs(data,offset,"tRNS"); offset+=4; + for(var i=0; i<dl; i++) data[offset+i]=(nimg.plte[i]>>>24)&255; + offset+=dl; + wUi(data,offset,crc(data,offset-dl-4,dl+4)); offset+=4; // crc + } + } + + var fi = 0; + for(var j=0; j<nimg.frames.length; j++) + { + var fr = nimg.frames[j]; + if(anim) { + wUi(data, offset, 26); offset+=4; + wAs(data, offset,"fcTL"); offset+=4; + wUi(data, offset, fi++); offset+=4; + wUi(data, offset, fr.rect.width ); offset+=4; + wUi(data, offset, fr.rect.height); offset+=4; + wUi(data, offset, fr.rect.x); offset+=4; + wUi(data, offset, fr.rect.y); offset+=4; + wUs(data, offset, dels[j]); offset+=2; + wUs(data, offset, 1000); offset+=2; + data[offset] = fr.dispose; offset++; // dispose + data[offset] = fr.blend ; offset++; // blend + wUi(data,offset,crc(data,offset-30,30)); offset+=4; // crc + } + + var imgd = fr.cimg, dl = imgd.length; + wUi(data,offset, dl+(j==0?0:4)); offset+=4; + var ioff = offset; + wAs(data,offset,(j==0)?"IDAT":"fdAT"); offset+=4; + if(j!=0) { wUi(data, offset, fi++); offset+=4; } + data.set(imgd,offset); + offset += dl; + wUi(data,offset,crc(data,ioff,offset-ioff)); offset+=4; // crc + } + + wUi(data,offset, 0); offset+=4; + wAs(data,offset,"IEND"); offset+=4; + wUi(data,offset,crc(data,offset-4,4)); offset+=4; // crc + + return data.buffer; +}; + +UPNG.encode.compressPNG = function(out, filter, levelZero) { + for(var i=0; i<out.frames.length; i++) { + var frm = out.frames[i], nw=frm.rect.width, nh=frm.rect.height; + var fdata = new Uint8Array(nh*frm.bpl+nh); + frm.cimg = UPNG.encode._filterZero(frm.img,nh,frm.bpp,frm.bpl,fdata, filter, levelZero); + } +}; + + + +UPNG.encode.compress = function(bufs, w, h, ps, prms) // prms: onlyBlend, minBits, forbidPlte +{ + //var time = Date.now(); + var onlyBlend = prms[0], evenCrd = prms[1], forbidPrev = prms[2], minBits = prms[3], forbidPlte = prms[4]; + + var ctype = 6, depth = 8, alphaAnd=255; + + for(var j=0; j<bufs.length; j++) { // when not quantized, other frames can contain colors, that are not in an initial frame + var img = new Uint8Array(bufs[j]), ilen = img.length; + for(var i=0; i<ilen; i+=4) alphaAnd &= img[i+3]; + } + var gotAlpha = (alphaAnd!=255); + + //console.log("alpha check", Date.now()-time); time = Date.now(); + + //var brute = gotAlpha && forGIF; // brute : frames can only be copied, not "blended" + var frms = UPNG.encode.framize(bufs, w, h, onlyBlend, evenCrd, forbidPrev); + //console.log("framize", Date.now()-time); time = Date.now(); + + var cmap={}, plte=[], inds=[]; + + if(ps!=0) { + var nbufs = []; for(var i=0; i<frms.length; i++) nbufs.push(frms[i].img.buffer); + + var abuf = UPNG.encode.concatRGBA(nbufs), qres = UPNG.quantize(abuf, ps); + var cof = 0, bb = new Uint8Array(qres.abuf); + for(var i=0; i<frms.length; i++) { var ti=frms[i].img, bln=ti.length; inds.push(new Uint8Array(qres.inds.buffer, cof>>2, bln>>2)); + for(var j=0; j<bln; j+=4) { ti[j]=bb[cof+j]; ti[j+1]=bb[cof+j+1]; ti[j+2]=bb[cof+j+2]; ti[j+3]=bb[cof+j+3]; } cof+=bln; } + + for(var i=0; i<qres.plte.length; i++) plte.push(qres.plte[i].est.rgba); + //console.log("quantize", Date.now()-time); time = Date.now(); + } + else { + // what if ps==0, but there are <=256 colors? we still need to detect, if the palette could be used + for(var j=0; j<frms.length; j++) { // when not quantized, other frames can contain colors, that are not in an initial frame + var frm = frms[j], img32 = new Uint32Array(frm.img.buffer), nw=frm.rect.width, ilen = img32.length; + var ind = new Uint8Array(ilen); inds.push(ind); + for(var i=0; i<ilen; i++) { + var c = img32[i]; + if (i!=0 && c==img32[i- 1]) ind[i]=ind[i-1]; + else if(i>nw && c==img32[i-nw]) ind[i]=ind[i-nw]; + else { + var cmc = cmap[c]; + if(cmc==null) { cmap[c]=cmc=plte.length; plte.push(c); if(plte.length>=300) break; } + ind[i]=cmc; + } + } + } + //console.log("make palette", Date.now()-time); time = Date.now(); + } + + var cc=plte.length; //console.log("colors:",cc); + if(cc<=256 && forbidPlte==false) { + if(cc<= 2) depth=1; else if(cc<= 4) depth=2; else if(cc<=16) depth=4; else depth=8; + depth = Math.max(depth, minBits); + } + + for(var j=0; j<frms.length; j++) + { + var frm = frms[j], nx=frm.rect.x, ny=frm.rect.y, nw=frm.rect.width, nh=frm.rect.height; + var cimg = frm.img, cimg32 = new Uint32Array(cimg.buffer); + var bpl = 4*nw, bpp=4; + if(cc<=256 && forbidPlte==false) { + bpl = Math.ceil(depth*nw/8); + var nimg = new Uint8Array(bpl*nh); + var inj = inds[j]; + for(var y=0; y<nh; y++) { var i=y*bpl, ii=y*nw; + if (depth==8) for(var x=0; x<nw; x++) nimg[i+(x) ] = (inj[ii+x] ); + else if(depth==4) for(var x=0; x<nw; x++) nimg[i+(x>>1)] |= (inj[ii+x]<<(4-(x&1)*4)); + else if(depth==2) for(var x=0; x<nw; x++) nimg[i+(x>>2)] |= (inj[ii+x]<<(6-(x&3)*2)); + else if(depth==1) for(var x=0; x<nw; x++) nimg[i+(x>>3)] |= (inj[ii+x]<<(7-(x&7)*1)); + } + cimg=nimg; ctype=3; bpp=1; + } + else if(gotAlpha==false && frms.length==1) { // some next "reduced" frames may contain alpha for blending + var nimg = new Uint8Array(nw*nh*3), area=nw*nh; + for(var i=0; i<area; i++) { var ti=i*3, qi=i*4; nimg[ti]=cimg[qi]; nimg[ti+1]=cimg[qi+1]; nimg[ti+2]=cimg[qi+2]; } + cimg=nimg; ctype=2; bpp=3; bpl=3*nw; + } + frm.img=cimg; frm.bpl=bpl; frm.bpp=bpp; + } + //console.log("colors => palette indices", Date.now()-time); time = Date.now(); + + return {ctype:ctype, depth:depth, plte:plte, frames:frms }; +}; +UPNG.encode.framize = function(bufs,w,h,alwaysBlend,evenCrd,forbidPrev) { + /* DISPOSE + - 0 : no change + - 1 : clear to transparent + - 2 : retstore to content before rendering (previous frame disposed) + BLEND + - 0 : replace + - 1 : blend + */ + var frms = []; + for(var j=0; j<bufs.length; j++) { + var cimg = new Uint8Array(bufs[j]), cimg32 = new Uint32Array(cimg.buffer); + var nimg; + + var nx=0, ny=0, nw=w, nh=h, blend=alwaysBlend?1:0; + if(j!=0) { + var tlim = (forbidPrev || alwaysBlend || j==1 || frms[j-2].dispose!=0)?1:2, tstp = 0, tarea = 1e9; + for(var it=0; it<tlim; it++) + { + var pimg = new Uint8Array(bufs[j-1-it]), p32 = new Uint32Array(bufs[j-1-it]); + var mix=w,miy=h,max=-1,may=-1; + for(var y=0; y<h; y++) for(var x=0; x<w; x++) { + var i = y*w+x; + if(cimg32[i]!=p32[i]) { + if(x<mix) mix=x; if(x>max) max=x; + if(y<miy) miy=y; if(y>may) may=y; + } + } + if(max==-1) mix=miy=max=may=0; + if(evenCrd) { if((mix&1)==1)mix--; if((miy&1)==1)miy--; } + var sarea = (max-mix+1)*(may-miy+1); + if(sarea<tarea) { + tarea = sarea; tstp = it; + nx = mix; ny = miy; nw = max-mix+1; nh = may-miy+1; + } + } + + // alwaysBlend: pokud zjistím, že blendit nelze, nastavím předchozímu snímku dispose=1. Zajistím, aby obsahoval můj obdélník. + var pimg = new Uint8Array(bufs[j-1-tstp]); + if(tstp==1) frms[j-1].dispose = 2; + + nimg = new Uint8Array(nw*nh*4); + UPNG._copyTile(pimg,w,h, nimg,nw,nh, -nx,-ny, 0); + + blend = UPNG._copyTile(cimg,w,h, nimg,nw,nh, -nx,-ny, 3) ? 1 : 0; + if(blend==1) UPNG.encode._prepareDiff(cimg,w,h,nimg,{x:nx,y:ny,width:nw,height:nh}); + else UPNG._copyTile(cimg,w,h, nimg,nw,nh, -nx,-ny, 0); + //UPNG._copyTile(cimg,w,h, nimg,nw,nh, -nx,-ny, blend==1?2:0); + } + else nimg = cimg.slice(0); // img may be rewritten further ... don't rewrite input + + frms.push({rect:{x:nx,y:ny,width:nw,height:nh}, img:nimg, blend:blend, dispose:0}); + } + + + if(alwaysBlend) for(var j=0; j<frms.length; j++) { + var frm = frms[j]; if(frm.blend==1) continue; + var r0 = frm.rect, r1 = frms[j-1].rect; + var miX = Math.min(r0.x, r1.x), miY = Math.min(r0.y, r1.y); + var maX = Math.max(r0.x+r0.width, r1.x+r1.width), maY = Math.max(r0.y+r0.height, r1.y+r1.height); + var r = {x:miX, y:miY, width:maX-miX, height:maY-miY}; + + frms[j-1].dispose = 1; + if(j-1!=0) + UPNG.encode._updateFrame(bufs, w,h,frms, j-1,r, evenCrd); + UPNG.encode._updateFrame(bufs, w,h,frms, j ,r, evenCrd); + } + var area = 0; + if(bufs.length!=1) for(var i=0; i<frms.length; i++) { + var frm = frms[i]; + area += frm.rect.width*frm.rect.height; + //if(i==0 || frm.blend!=1) continue; + //var ob = new Uint8Array( + //console.log(frm.blend, frm.dispose, frm.rect); + } + //if(area!=0) console.log(area); + return frms; +}; +UPNG.encode._updateFrame = function(bufs, w,h, frms, i, r, evenCrd) { + var U8 = Uint8Array, U32 = Uint32Array; + var pimg = new U8(bufs[i-1]), pimg32 = new U32(bufs[i-1]), nimg = i+1<bufs.length ? new U8(bufs[i+1]):null; + var cimg = new U8(bufs[i]), cimg32 = new U32(cimg.buffer); + + var mix=w,miy=h,max=-1,may=-1; + for(var y=0; y<r.height; y++) for(var x=0; x<r.width; x++) { + var cx = r.x+x, cy = r.y+y; + var j = cy*w+cx, cc = cimg32[j]; + // no need to draw transparency, or to dispose it. Or, if writing the same color and the next one does not need transparency. + if(cc==0 || (frms[i-1].dispose==0 && pimg32[j]==cc && (nimg==null || nimg[j*4+3]!=0))/**/) ; + else { + if(cx<mix) mix=cx; if(cx>max) max=cx; + if(cy<miy) miy=cy; if(cy>may) may=cy; + } + } + if(max==-1) mix=miy=max=may=0; + if(evenCrd) { if((mix&1)==1)mix--; if((miy&1)==1)miy--; } + r = {x:mix, y:miy, width:max-mix+1, height:may-miy+1}; + + var fr = frms[i]; fr.rect = r; fr.blend = 1; fr.img = new Uint8Array(r.width*r.height*4); + if(frms[i-1].dispose==0) { + UPNG._copyTile(pimg,w,h, fr.img,r.width,r.height, -r.x,-r.y, 0); + UPNG.encode._prepareDiff(cimg,w,h,fr.img,r); + //UPNG._copyTile(cimg,w,h, fr.img,r.width,r.height, -r.x,-r.y, 2); + } + else + UPNG._copyTile(cimg,w,h, fr.img,r.width,r.height, -r.x,-r.y, 0); +}; +UPNG.encode._prepareDiff = function(cimg, w,h, nimg, rec) { + UPNG._copyTile(cimg,w,h, nimg,rec.width,rec.height, -rec.x,-rec.y, 2); + /* + var n32 = new Uint32Array(nimg.buffer); + var og = new Uint8Array(rec.width*rec.height*4), o32 = new Uint32Array(og.buffer); + UPNG._copyTile(cimg,w,h, og,rec.width,rec.height, -rec.x,-rec.y, 0); + for(var i=4; i<nimg.length; i+=4) { + if(nimg[i-1]!=0 && nimg[i+3]==0 && o32[i>>>2]==o32[(i>>>2)-1]) { + n32[i>>>2]=o32[i>>>2]; + //var j = i, c=p32[(i>>>2)-1]; + //while(p32[j>>>2]==c) { n32[j>>>2]=c; j+=4; } + } + } + for(var i=nimg.length-8; i>0; i-=4) { + if(nimg[i+7]!=0 && nimg[i+3]==0 && o32[i>>>2]==o32[(i>>>2)+1]) { + n32[i>>>2]=o32[i>>>2]; + //var j = i, c=p32[(i>>>2)-1]; + //while(p32[j>>>2]==c) { n32[j>>>2]=c; j+=4; } + } + }*/ +}; + +UPNG.encode._filterZero = function(img,h,bpp,bpl,data, filter, levelZero) +{ + var fls = [], ftry=[0,1,2,3,4]; + if (filter!=-1) ftry=[filter]; + else if(h*bpl>500000 || bpp==1) ftry=[0]; + var opts; if(levelZero) opts={level:0}; + + var CMPR = (levelZero && UZIP!=null) ? UZIP : pako_1$2; + + for(var i=0; i<ftry.length; i++) { + for(var y=0; y<h; y++) UPNG.encode._filterLine(data, img, y, bpl, bpp, ftry[i]); + //var nimg = new Uint8Array(data.length); + //var sz = UZIP.F.deflate(data, nimg); fls.push(nimg.slice(0,sz)); + //var dfl = pako["deflate"](data), dl=dfl.length-4; + //var crc = (dfl[dl+3]<<24)|(dfl[dl+2]<<16)|(dfl[dl+1]<<8)|(dfl[dl+0]<<0); + //console.log(crc, UZIP.adler(data,2,data.length-6)); + fls.push(CMPR["deflate"](data,opts)); + } + var ti, tsize=1e9; + for(var i=0; i<fls.length; i++) if(fls[i].length<tsize) { ti=i; tsize=fls[i].length; } + return fls[ti]; +}; +UPNG.encode._filterLine = function(data, img, y, bpl, bpp, type) +{ + var i = y*bpl, di = i+y, paeth = UPNG.decode._paeth; + data[di]=type; di++; + + if(type==0) { + if(bpl<500) for(var x=0; x<bpl; x++) data[di+x] = img[i+x]; + else data.set(new Uint8Array(img.buffer,i,bpl),di); + } + else if(type==1) { + for(var x= 0; x<bpp; x++) data[di+x] = img[i+x]; + for(var x=bpp; x<bpl; x++) data[di+x] = (img[i+x]-img[i+x-bpp]+256)&255; + } + else if(y==0) { + for(var x= 0; x<bpp; x++) data[di+x] = img[i+x]; + + if(type==2) for(var x=bpp; x<bpl; x++) data[di+x] = img[i+x]; + if(type==3) for(var x=bpp; x<bpl; x++) data[di+x] = (img[i+x] - (img[i+x-bpp]>>1) +256)&255; + if(type==4) for(var x=bpp; x<bpl; x++) data[di+x] = (img[i+x] - paeth(img[i+x-bpp], 0, 0) +256)&255; + } + else { + if(type==2) { for(var x= 0; x<bpl; x++) data[di+x] = (img[i+x]+256 - img[i+x-bpl])&255; } + if(type==3) { for(var x= 0; x<bpp; x++) data[di+x] = (img[i+x]+256 - (img[i+x-bpl]>>1))&255; + for(var x=bpp; x<bpl; x++) data[di+x] = (img[i+x]+256 - ((img[i+x-bpl]+img[i+x-bpp])>>1))&255; } + if(type==4) { for(var x= 0; x<bpp; x++) data[di+x] = (img[i+x]+256 - paeth(0, img[i+x-bpl], 0))&255; + for(var x=bpp; x<bpl; x++) data[di+x] = (img[i+x]+256 - paeth(img[i+x-bpp], img[i+x-bpl], img[i+x-bpp-bpl]))&255; } + } +}; + +UPNG.crc = { + table : ( function() { + var tab = new Uint32Array(256); + for (var n=0; n<256; n++) { + var c = n; + for (var k=0; k<8; k++) { + if (c & 1) c = 0xedb88320 ^ (c >>> 1); + else c = c >>> 1; + } + tab[n] = c; } + return tab; })(), + update : function(c, buf, off, len) { + for (var i=0; i<len; i++) c = UPNG.crc.table[(c ^ buf[off+i]) & 0xff] ^ (c >>> 8); + return c; + }, + crc : function(b,o,l) { return UPNG.crc.update(0xffffffff,b,o,l) ^ 0xffffffff; } +}; + + +UPNG.quantize = function(abuf, ps) +{ + var oimg = new Uint8Array(abuf), nimg = oimg.slice(0), nimg32 = new Uint32Array(nimg.buffer); + + var KD = UPNG.quantize.getKDtree(nimg, ps); + var root = KD[0], leafs = KD[1]; + + var planeDst = UPNG.quantize.planeDst; + var sb = oimg, tb = nimg32, len=sb.length; + + var inds = new Uint8Array(oimg.length>>2); + for(var i=0; i<len; i+=4) { + var r=sb[i]*(1/255), g=sb[i+1]*(1/255), b=sb[i+2]*(1/255), a=sb[i+3]*(1/255); + + // exact, but too slow :( + var nd = UPNG.quantize.getNearest(root, r, g, b, a); + //var nd = root; + //while(nd.left) nd = (planeDst(nd.est,r,g,b,a)<=0) ? nd.left : nd.right; + + inds[i>>2] = nd.ind; + tb[i>>2] = nd.est.rgba; + } + return { abuf:nimg.buffer, inds:inds, plte:leafs }; +}; + +UPNG.quantize.getKDtree = function(nimg, ps, err) { + if(err==null) err = 0.0001; + var nimg32 = new Uint32Array(nimg.buffer); + + var root = {i0:0, i1:nimg.length, bst:null, est:null, tdst:0, left:null, right:null }; // basic statistic, extra statistic + root.bst = UPNG.quantize.stats( nimg,root.i0, root.i1 ); root.est = UPNG.quantize.estats( root.bst ); + var leafs = [root]; + + while(leafs.length<ps) + { + var maxL = 0, mi=0; + for(var i=0; i<leafs.length; i++) if(leafs[i].est.L > maxL) { maxL=leafs[i].est.L; mi=i; } + if(maxL<err) break; + var node = leafs[mi]; + + var s0 = UPNG.quantize.splitPixels(nimg,nimg32, node.i0, node.i1, node.est.e, node.est.eMq255); + var s0wrong = (node.i0>=s0 || node.i1<=s0); + //console.log(maxL, leafs.length, mi); + if(s0wrong) { node.est.L=0; continue; } + + + var ln = {i0:node.i0, i1:s0, bst:null, est:null, tdst:0, left:null, right:null }; ln.bst = UPNG.quantize.stats( nimg, ln.i0, ln.i1 ); + ln.est = UPNG.quantize.estats( ln.bst ); + var rn = {i0:s0, i1:node.i1, bst:null, est:null, tdst:0, left:null, right:null }; rn.bst = {R:[], m:[], N:node.bst.N-ln.bst.N}; + for(var i=0; i<16; i++) rn.bst.R[i] = node.bst.R[i]-ln.bst.R[i]; + for(var i=0; i< 4; i++) rn.bst.m[i] = node.bst.m[i]-ln.bst.m[i]; + rn.est = UPNG.quantize.estats( rn.bst ); + + node.left = ln; node.right = rn; + leafs[mi]=ln; leafs.push(rn); + } + leafs.sort(function(a,b) { return b.bst.N-a.bst.N; }); + for(var i=0; i<leafs.length; i++) leafs[i].ind=i; + return [root, leafs]; +}; + +UPNG.quantize.getNearest = function(nd, r,g,b,a) +{ + if(nd.left==null) { nd.tdst = UPNG.quantize.dist(nd.est.q,r,g,b,a); return nd; } + var planeDst = UPNG.quantize.planeDst(nd.est,r,g,b,a); + + var node0 = nd.left, node1 = nd.right; + if(planeDst>0) { node0=nd.right; node1=nd.left; } + + var ln = UPNG.quantize.getNearest(node0, r,g,b,a); + if(ln.tdst<=planeDst*planeDst) return ln; + var rn = UPNG.quantize.getNearest(node1, r,g,b,a); + return rn.tdst<ln.tdst ? rn : ln; +}; +UPNG.quantize.planeDst = function(est, r,g,b,a) { var e = est.e; return e[0]*r + e[1]*g + e[2]*b + e[3]*a - est.eMq; }; +UPNG.quantize.dist = function(q, r,g,b,a) { var d0=r-q[0], d1=g-q[1], d2=b-q[2], d3=a-q[3]; return d0*d0+d1*d1+d2*d2+d3*d3; }; + +UPNG.quantize.splitPixels = function(nimg, nimg32, i0, i1, e, eMq) +{ + var vecDot = UPNG.quantize.vecDot; + i1-=4; + while(i0<i1) + { + while(vecDot(nimg, i0, e)<=eMq) i0+=4; + while(vecDot(nimg, i1, e)> eMq) i1-=4; + if(i0>=i1) break; + + var t = nimg32[i0>>2]; nimg32[i0>>2] = nimg32[i1>>2]; nimg32[i1>>2]=t; + + i0+=4; i1-=4; + } + while(vecDot(nimg, i0, e)>eMq) i0-=4; + return i0+4; +}; +UPNG.quantize.vecDot = function(nimg, i, e) +{ + return nimg[i]*e[0] + nimg[i+1]*e[1] + nimg[i+2]*e[2] + nimg[i+3]*e[3]; +}; +UPNG.quantize.stats = function(nimg, i0, i1){ + var R = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; + var m = [0,0,0,0]; + var N = (i1-i0)>>2; + for(var i=i0; i<i1; i+=4) + { + var r = nimg[i]*(1/255), g = nimg[i+1]*(1/255), b = nimg[i+2]*(1/255), a = nimg[i+3]*(1/255); + //var r = nimg[i], g = nimg[i+1], b = nimg[i+2], a = nimg[i+3]; + m[0]+=r; m[1]+=g; m[2]+=b; m[3]+=a; + + R[ 0] += r*r; R[ 1] += r*g; R[ 2] += r*b; R[ 3] += r*a; + R[ 5] += g*g; R[ 6] += g*b; R[ 7] += g*a; + R[10] += b*b; R[11] += b*a; + R[15] += a*a; + } + R[4]=R[1]; R[8]=R[2]; R[9]=R[6]; R[12]=R[3]; R[13]=R[7]; R[14]=R[11]; + + return {R:R, m:m, N:N}; +}; +UPNG.quantize.estats = function(stats){ + var R = stats.R, m = stats.m, N = stats.N; + + // when all samples are equal, but N is large (millions), the Rj can be non-zero ( 0.0003.... - precission error) + var m0 = m[0], m1 = m[1], m2 = m[2], m3 = m[3], iN = (N==0 ? 0 : 1/N); + var Rj = [ + R[ 0] - m0*m0*iN, R[ 1] - m0*m1*iN, R[ 2] - m0*m2*iN, R[ 3] - m0*m3*iN, + R[ 4] - m1*m0*iN, R[ 5] - m1*m1*iN, R[ 6] - m1*m2*iN, R[ 7] - m1*m3*iN, + R[ 8] - m2*m0*iN, R[ 9] - m2*m1*iN, R[10] - m2*m2*iN, R[11] - m2*m3*iN, + R[12] - m3*m0*iN, R[13] - m3*m1*iN, R[14] - m3*m2*iN, R[15] - m3*m3*iN + ]; + + var A = Rj, M = UPNG.M4; + var b = [0.5,0.5,0.5,0.5], mi = 0, tmi = 0; + + if(N!=0) + for(var i=0; i<10; i++) { + b = M.multVec(A, b); tmi = Math.sqrt(M.dot(b,b)); b = M.sml(1/tmi, b); + if(Math.abs(tmi-mi)<1e-9) break; mi = tmi; + } + //b = [0,0,1,0]; mi=N; + var q = [m0*iN, m1*iN, m2*iN, m3*iN]; + var eMq255 = M.dot(M.sml(255,q),b); + + return { Cov:Rj, q:q, e:b, L:mi, eMq255:eMq255, eMq : M.dot(b,q), + rgba: (((Math.round(255*q[3])<<24) | (Math.round(255*q[2])<<16) | (Math.round(255*q[1])<<8) | (Math.round(255*q[0])<<0))>>>0) }; +}; +UPNG.M4 = { + multVec : function(m,v) { + return [ + m[ 0]*v[0] + m[ 1]*v[1] + m[ 2]*v[2] + m[ 3]*v[3], + m[ 4]*v[0] + m[ 5]*v[1] + m[ 6]*v[2] + m[ 7]*v[3], + m[ 8]*v[0] + m[ 9]*v[1] + m[10]*v[2] + m[11]*v[3], + m[12]*v[0] + m[13]*v[1] + m[14]*v[2] + m[15]*v[3] + ]; + }, + dot : function(x,y) { return x[0]*y[0]+x[1]*y[1]+x[2]*y[2]+x[3]*y[3]; }, + sml : function(a,y) { return [a*y[0],a*y[1],a*y[2],a*y[3]]; } +}; + +UPNG.encode.concatRGBA = function(bufs) { + var tlen = 0; + for(var i=0; i<bufs.length; i++) tlen += bufs[i].byteLength; + var nimg = new Uint8Array(tlen), noff=0; + for(var i=0; i<bufs.length; i++) { + var img = new Uint8Array(bufs[i]), il = img.length; + for(var j=0; j<il; j+=4) { + var r=img[j], g=img[j+1], b=img[j+2], a = img[j+3]; + if(a==0) r=g=b=0; + nimg[noff+j]=r; nimg[noff+j+1]=g; nimg[noff+j+2]=b; nimg[noff+j+3]=a; } + noff += il; + } + return nimg.buffer; +}; + +var getImageType = function (ctype) { + if (ctype === 0) + return PngType.Greyscale; + if (ctype === 2) + return PngType.Truecolour; + if (ctype === 3) + return PngType.IndexedColour; + if (ctype === 4) + return PngType.GreyscaleWithAlpha; + if (ctype === 6) + return PngType.TruecolourWithAlpha; + throw new Error("Unknown color type: " + ctype); +}; +var splitAlphaChannel = function (rgbaChannel) { + var pixelCount = Math.floor(rgbaChannel.length / 4); + var rgbChannel = new Uint8Array(pixelCount * 3); + var alphaChannel = new Uint8Array(pixelCount * 1); + var rgbaOffset = 0; + var rgbOffset = 0; + var alphaOffset = 0; + while (rgbaOffset < rgbaChannel.length) { + rgbChannel[rgbOffset++] = rgbaChannel[rgbaOffset++]; + rgbChannel[rgbOffset++] = rgbaChannel[rgbaOffset++]; + rgbChannel[rgbOffset++] = rgbaChannel[rgbaOffset++]; + alphaChannel[alphaOffset++] = rgbaChannel[rgbaOffset++]; + } + return { rgbChannel: rgbChannel, alphaChannel: alphaChannel }; +}; +var PngType; +(function (PngType) { + PngType["Greyscale"] = "Greyscale"; + PngType["Truecolour"] = "Truecolour"; + PngType["IndexedColour"] = "IndexedColour"; + PngType["GreyscaleWithAlpha"] = "GreyscaleWithAlpha"; + PngType["TruecolourWithAlpha"] = "TruecolourWithAlpha"; +})(PngType || (PngType = {})); +var PNG = /** @class */ (function () { + function PNG(pngData) { + var upng = UPNG.decode(pngData); + var frames = UPNG.toRGBA8(upng); + if (frames.length > 1) + throw new Error("Animated PNGs are not supported"); + var frame = new Uint8Array(frames[0]); + var _a = splitAlphaChannel(frame), rgbChannel = _a.rgbChannel, alphaChannel = _a.alphaChannel; + this.rgbChannel = rgbChannel; + var hasAlphaValues = alphaChannel.some(function (a) { return a < 255; }); + if (hasAlphaValues) + this.alphaChannel = alphaChannel; + this.type = getImageType(upng.ctype); + this.width = upng.width; + this.height = upng.height; + this.bitsPerComponent = 8; + } + PNG.load = function (pngData) { return new PNG(pngData); }; + return PNG; +}()); + +/** + * A note of thanks to the developers of https://github.com/foliojs/pdfkit, as + * this class borrows from: + * https://github.com/devongovett/pdfkit/blob/e71edab0dd4657b5a767804ba86c94c58d01fbca/lib/image/png.coffee + */ +var PngEmbedder = /** @class */ (function () { + function PngEmbedder(png) { + this.image = png; + this.bitsPerComponent = png.bitsPerComponent; + this.width = png.width; + this.height = png.height; + this.colorSpace = 'DeviceRGB'; + } + PngEmbedder.for = function (imageData) { + return __awaiter(this, void 0, void 0, function () { + var png; + return __generator(this, function (_a) { + png = PNG.load(imageData); + return [2 /*return*/, new PngEmbedder(png)]; + }); + }); + }; + PngEmbedder.prototype.embedIntoContext = function (context, ref) { + return __awaiter(this, void 0, void 0, function () { + var SMask, xObject; + return __generator(this, function (_a) { + SMask = this.embedAlphaChannel(context); + xObject = context.flateStream(this.image.rgbChannel, { + Type: 'XObject', + Subtype: 'Image', + BitsPerComponent: this.image.bitsPerComponent, + Width: this.image.width, + Height: this.image.height, + ColorSpace: this.colorSpace, + SMask: SMask, + }); + if (ref) { + context.assign(ref, xObject); + return [2 /*return*/, ref]; + } + else { + return [2 /*return*/, context.register(xObject)]; + } + }); + }); + }; + PngEmbedder.prototype.embedAlphaChannel = function (context) { + if (!this.image.alphaChannel) + return undefined; + var xObject = context.flateStream(this.image.alphaChannel, { + Type: 'XObject', + Subtype: 'Image', + Height: this.image.height, + Width: this.image.width, + BitsPerComponent: this.image.bitsPerComponent, + ColorSpace: 'DeviceGray', + Decode: [0, 1], + }); + return context.register(xObject); + }; + return PngEmbedder; +}()); + +/* + * Copyright 2012 Mozilla Foundation + * + * The Stream class contained in this file is a TypeScript port of the + * JavaScript Stream class in Mozilla's pdf.js project, made available + * under the Apache 2.0 open source license. + */ +var Stream = /** @class */ (function () { + function Stream(buffer, start, length) { + this.bytes = buffer; + this.start = start || 0; + this.pos = this.start; + this.end = !!start && !!length ? start + length : this.bytes.length; + } + Object.defineProperty(Stream.prototype, "length", { + get: function () { + return this.end - this.start; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Stream.prototype, "isEmpty", { + get: function () { + return this.length === 0; + }, + enumerable: false, + configurable: true + }); + Stream.prototype.getByte = function () { + if (this.pos >= this.end) { + return -1; + } + return this.bytes[this.pos++]; + }; + Stream.prototype.getUint16 = function () { + var b0 = this.getByte(); + var b1 = this.getByte(); + if (b0 === -1 || b1 === -1) { + return -1; + } + return (b0 << 8) + b1; + }; + Stream.prototype.getInt32 = function () { + var b0 = this.getByte(); + var b1 = this.getByte(); + var b2 = this.getByte(); + var b3 = this.getByte(); + return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3; + }; + // Returns subarray of original buffer, should only be read. + Stream.prototype.getBytes = function (length, forceClamped) { + if (forceClamped === void 0) { forceClamped = false; } + var bytes = this.bytes; + var pos = this.pos; + var strEnd = this.end; + if (!length) { + var subarray = bytes.subarray(pos, strEnd); + // `this.bytes` is always a `Uint8Array` here. + return forceClamped ? new Uint8ClampedArray(subarray) : subarray; + } + else { + var end = pos + length; + if (end > strEnd) { + end = strEnd; + } + this.pos = end; + var subarray = bytes.subarray(pos, end); + // `this.bytes` is always a `Uint8Array` here. + return forceClamped ? new Uint8ClampedArray(subarray) : subarray; + } + }; + Stream.prototype.peekByte = function () { + var peekedByte = this.getByte(); + this.pos--; + return peekedByte; + }; + Stream.prototype.peekBytes = function (length, forceClamped) { + if (forceClamped === void 0) { forceClamped = false; } + var bytes = this.getBytes(length, forceClamped); + this.pos -= bytes.length; + return bytes; + }; + Stream.prototype.skip = function (n) { + if (!n) { + n = 1; + } + this.pos += n; + }; + Stream.prototype.reset = function () { + this.pos = this.start; + }; + Stream.prototype.moveStart = function () { + this.start = this.pos; + }; + Stream.prototype.makeSubStream = function (start, length) { + return new Stream(this.bytes, start, length); + }; + Stream.prototype.decode = function () { + return this.bytes; + }; + return Stream; +}()); + +/* + * Copyright 2012 Mozilla Foundation + * + * The DecodeStream class contained in this file is a TypeScript port of the + * JavaScript DecodeStream class in Mozilla's pdf.js project, made available + * under the Apache 2.0 open source license. + */ +// Lots of DecodeStreams are created whose buffers are never used. For these +// we share a single empty buffer. This is (a) space-efficient and (b) avoids +// having special cases that would be required if we used |null| for an empty +// buffer. +var emptyBuffer = new Uint8Array(0); +/** + * Super class for the decoding streams + */ +var DecodeStream = /** @class */ (function () { + function DecodeStream(maybeMinBufferLength) { + this.pos = 0; + this.bufferLength = 0; + this.eof = false; + this.buffer = emptyBuffer; + this.minBufferLength = 512; + if (maybeMinBufferLength) { + // Compute the first power of two that is as big as maybeMinBufferLength. + while (this.minBufferLength < maybeMinBufferLength) { + this.minBufferLength *= 2; + } + } + } + Object.defineProperty(DecodeStream.prototype, "isEmpty", { + get: function () { + while (!this.eof && this.bufferLength === 0) { + this.readBlock(); + } + return this.bufferLength === 0; + }, + enumerable: false, + configurable: true + }); + DecodeStream.prototype.getByte = function () { + var pos = this.pos; + while (this.bufferLength <= pos) { + if (this.eof) { + return -1; + } + this.readBlock(); + } + return this.buffer[this.pos++]; + }; + DecodeStream.prototype.getUint16 = function () { + var b0 = this.getByte(); + var b1 = this.getByte(); + if (b0 === -1 || b1 === -1) { + return -1; + } + return (b0 << 8) + b1; + }; + DecodeStream.prototype.getInt32 = function () { + var b0 = this.getByte(); + var b1 = this.getByte(); + var b2 = this.getByte(); + var b3 = this.getByte(); + return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3; + }; + DecodeStream.prototype.getBytes = function (length, forceClamped) { + if (forceClamped === void 0) { forceClamped = false; } + var end; + var pos = this.pos; + if (length) { + this.ensureBuffer(pos + length); + end = pos + length; + while (!this.eof && this.bufferLength < end) { + this.readBlock(); + } + var bufEnd = this.bufferLength; + if (end > bufEnd) { + end = bufEnd; + } + } + else { + while (!this.eof) { + this.readBlock(); + } + end = this.bufferLength; + } + this.pos = end; + var subarray = this.buffer.subarray(pos, end); + // `this.buffer` is either a `Uint8Array` or `Uint8ClampedArray` here. + return forceClamped && !(subarray instanceof Uint8ClampedArray) + ? new Uint8ClampedArray(subarray) + : subarray; + }; + DecodeStream.prototype.peekByte = function () { + var peekedByte = this.getByte(); + this.pos--; + return peekedByte; + }; + DecodeStream.prototype.peekBytes = function (length, forceClamped) { + if (forceClamped === void 0) { forceClamped = false; } + var bytes = this.getBytes(length, forceClamped); + this.pos -= bytes.length; + return bytes; + }; + DecodeStream.prototype.skip = function (n) { + if (!n) { + n = 1; + } + this.pos += n; + }; + DecodeStream.prototype.reset = function () { + this.pos = 0; + }; + DecodeStream.prototype.makeSubStream = function (start, length /* dict */) { + var end = start + length; + while (this.bufferLength <= end && !this.eof) { + this.readBlock(); + } + return new Stream(this.buffer, start, length /* dict */); + }; + DecodeStream.prototype.decode = function () { + while (!this.eof) + this.readBlock(); + return this.buffer.subarray(0, this.bufferLength); + }; + DecodeStream.prototype.readBlock = function () { + throw new MethodNotImplementedError(this.constructor.name, 'readBlock'); + }; + DecodeStream.prototype.ensureBuffer = function (requested) { + var buffer = this.buffer; + if (requested <= buffer.byteLength) { + return buffer; + } + var size = this.minBufferLength; + while (size < requested) { + size *= 2; + } + var buffer2 = new Uint8Array(size); + buffer2.set(buffer); + return (this.buffer = buffer2); + }; + return DecodeStream; +}()); + +/* + * Copyright 2012 Mozilla Foundation + * + * The Ascii85Stream class contained in this file is a TypeScript port of the + * JavaScript Ascii85Stream class in Mozilla's pdf.js project, made available + * under the Apache 2.0 open source license. + */ +var isSpace = function (ch) { + return ch === 0x20 || ch === 0x09 || ch === 0x0d || ch === 0x0a; +}; +var Ascii85Stream = /** @class */ (function (_super) { + __extends(Ascii85Stream, _super); + function Ascii85Stream(stream, maybeLength) { + var _this = _super.call(this, maybeLength) || this; + _this.stream = stream; + _this.input = new Uint8Array(5); + // Most streams increase in size when decoded, but Ascii85 streams + // typically shrink by ~20%. + if (maybeLength) { + maybeLength = 0.8 * maybeLength; + } + return _this; + } + Ascii85Stream.prototype.readBlock = function () { + var TILDA_CHAR = 0x7e; // '~' + var Z_LOWER_CHAR = 0x7a; // 'z' + var EOF = -1; + var stream = this.stream; + var c = stream.getByte(); + while (isSpace(c)) { + c = stream.getByte(); + } + if (c === EOF || c === TILDA_CHAR) { + this.eof = true; + return; + } + var bufferLength = this.bufferLength; + var buffer; + var i; + // special code for z + if (c === Z_LOWER_CHAR) { + buffer = this.ensureBuffer(bufferLength + 4); + for (i = 0; i < 4; ++i) { + buffer[bufferLength + i] = 0; + } + this.bufferLength += 4; + } + else { + var input = this.input; + input[0] = c; + for (i = 1; i < 5; ++i) { + c = stream.getByte(); + while (isSpace(c)) { + c = stream.getByte(); + } + input[i] = c; + if (c === EOF || c === TILDA_CHAR) { + break; + } + } + buffer = this.ensureBuffer(bufferLength + i - 1); + this.bufferLength += i - 1; + // partial ending; + if (i < 5) { + for (; i < 5; ++i) { + input[i] = 0x21 + 84; + } + this.eof = true; + } + var t = 0; + for (i = 0; i < 5; ++i) { + t = t * 85 + (input[i] - 0x21); + } + for (i = 3; i >= 0; --i) { + buffer[bufferLength + i] = t & 0xff; + t >>= 8; + } + } + }; + return Ascii85Stream; +}(DecodeStream)); + +/* + * Copyright 2012 Mozilla Foundation + * + * The AsciiHexStream class contained in this file is a TypeScript port of the + * JavaScript AsciiHexStream class in Mozilla's pdf.js project, made available + * under the Apache 2.0 open source license. + */ +var AsciiHexStream = /** @class */ (function (_super) { + __extends(AsciiHexStream, _super); + function AsciiHexStream(stream, maybeLength) { + var _this = _super.call(this, maybeLength) || this; + _this.stream = stream; + _this.firstDigit = -1; + // Most streams increase in size when decoded, but AsciiHex streams shrink + // by 50%. + if (maybeLength) { + maybeLength = 0.5 * maybeLength; + } + return _this; + } + AsciiHexStream.prototype.readBlock = function () { + var UPSTREAM_BLOCK_SIZE = 8000; + var bytes = this.stream.getBytes(UPSTREAM_BLOCK_SIZE); + if (!bytes.length) { + this.eof = true; + return; + } + var maxDecodeLength = (bytes.length + 1) >> 1; + var buffer = this.ensureBuffer(this.bufferLength + maxDecodeLength); + var bufferLength = this.bufferLength; + var firstDigit = this.firstDigit; + for (var i = 0, ii = bytes.length; i < ii; i++) { + var ch = bytes[i]; + var digit = void 0; + if (ch >= 0x30 && ch <= 0x39) { + // '0'-'9' + digit = ch & 0x0f; + } + else if ((ch >= 0x41 && ch <= 0x46) || (ch >= 0x61 && ch <= 0x66)) { + // 'A'-'Z', 'a'-'z' + digit = (ch & 0x0f) + 9; + } + else if (ch === 0x3e) { + // '>' + this.eof = true; + break; + } + else { + // probably whitespace + continue; // ignoring + } + if (firstDigit < 0) { + firstDigit = digit; + } + else { + buffer[bufferLength++] = (firstDigit << 4) | digit; + firstDigit = -1; + } + } + if (firstDigit >= 0 && this.eof) { + // incomplete byte + buffer[bufferLength++] = firstDigit << 4; + firstDigit = -1; + } + this.firstDigit = firstDigit; + this.bufferLength = bufferLength; + }; + return AsciiHexStream; +}(DecodeStream)); + +/* + * Copyright 1996-2003 Glyph & Cog, LLC + * + * The flate stream implementation contained in this file is a JavaScript port + * of XPDF's implementation, made available under the Apache 2.0 open source + * license. + */ +// prettier-ignore +var codeLenCodeMap = new Int32Array([ + 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 +]); +// prettier-ignore +var lengthDecode = new Int32Array([ + 0x00003, 0x00004, 0x00005, 0x00006, 0x00007, 0x00008, 0x00009, 0x0000a, + 0x1000b, 0x1000d, 0x1000f, 0x10011, 0x20013, 0x20017, 0x2001b, 0x2001f, + 0x30023, 0x3002b, 0x30033, 0x3003b, 0x40043, 0x40053, 0x40063, 0x40073, + 0x50083, 0x500a3, 0x500c3, 0x500e3, 0x00102, 0x00102, 0x00102 +]); +// prettier-ignore +var distDecode = new Int32Array([ + 0x00001, 0x00002, 0x00003, 0x00004, 0x10005, 0x10007, 0x20009, 0x2000d, + 0x30011, 0x30019, 0x40021, 0x40031, 0x50041, 0x50061, 0x60081, 0x600c1, + 0x70101, 0x70181, 0x80201, 0x80301, 0x90401, 0x90601, 0xa0801, 0xa0c01, + 0xb1001, 0xb1801, 0xc2001, 0xc3001, 0xd4001, 0xd6001 +]); +// prettier-ignore +var fixedLitCodeTab = [new Int32Array([ + 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c0, + 0x70108, 0x80060, 0x80020, 0x900a0, 0x80000, 0x80080, 0x80040, 0x900e0, + 0x70104, 0x80058, 0x80018, 0x90090, 0x70114, 0x80078, 0x80038, 0x900d0, + 0x7010c, 0x80068, 0x80028, 0x900b0, 0x80008, 0x80088, 0x80048, 0x900f0, + 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c8, + 0x7010a, 0x80064, 0x80024, 0x900a8, 0x80004, 0x80084, 0x80044, 0x900e8, + 0x70106, 0x8005c, 0x8001c, 0x90098, 0x70116, 0x8007c, 0x8003c, 0x900d8, + 0x7010e, 0x8006c, 0x8002c, 0x900b8, 0x8000c, 0x8008c, 0x8004c, 0x900f8, + 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c4, + 0x70109, 0x80062, 0x80022, 0x900a4, 0x80002, 0x80082, 0x80042, 0x900e4, + 0x70105, 0x8005a, 0x8001a, 0x90094, 0x70115, 0x8007a, 0x8003a, 0x900d4, + 0x7010d, 0x8006a, 0x8002a, 0x900b4, 0x8000a, 0x8008a, 0x8004a, 0x900f4, + 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cc, + 0x7010b, 0x80066, 0x80026, 0x900ac, 0x80006, 0x80086, 0x80046, 0x900ec, + 0x70107, 0x8005e, 0x8001e, 0x9009c, 0x70117, 0x8007e, 0x8003e, 0x900dc, + 0x7010f, 0x8006e, 0x8002e, 0x900bc, 0x8000e, 0x8008e, 0x8004e, 0x900fc, + 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c2, + 0x70108, 0x80061, 0x80021, 0x900a2, 0x80001, 0x80081, 0x80041, 0x900e2, + 0x70104, 0x80059, 0x80019, 0x90092, 0x70114, 0x80079, 0x80039, 0x900d2, + 0x7010c, 0x80069, 0x80029, 0x900b2, 0x80009, 0x80089, 0x80049, 0x900f2, + 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900ca, + 0x7010a, 0x80065, 0x80025, 0x900aa, 0x80005, 0x80085, 0x80045, 0x900ea, + 0x70106, 0x8005d, 0x8001d, 0x9009a, 0x70116, 0x8007d, 0x8003d, 0x900da, + 0x7010e, 0x8006d, 0x8002d, 0x900ba, 0x8000d, 0x8008d, 0x8004d, 0x900fa, + 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c6, + 0x70109, 0x80063, 0x80023, 0x900a6, 0x80003, 0x80083, 0x80043, 0x900e6, + 0x70105, 0x8005b, 0x8001b, 0x90096, 0x70115, 0x8007b, 0x8003b, 0x900d6, + 0x7010d, 0x8006b, 0x8002b, 0x900b6, 0x8000b, 0x8008b, 0x8004b, 0x900f6, + 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900ce, + 0x7010b, 0x80067, 0x80027, 0x900ae, 0x80007, 0x80087, 0x80047, 0x900ee, + 0x70107, 0x8005f, 0x8001f, 0x9009e, 0x70117, 0x8007f, 0x8003f, 0x900de, + 0x7010f, 0x8006f, 0x8002f, 0x900be, 0x8000f, 0x8008f, 0x8004f, 0x900fe, + 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c1, + 0x70108, 0x80060, 0x80020, 0x900a1, 0x80000, 0x80080, 0x80040, 0x900e1, + 0x70104, 0x80058, 0x80018, 0x90091, 0x70114, 0x80078, 0x80038, 0x900d1, + 0x7010c, 0x80068, 0x80028, 0x900b1, 0x80008, 0x80088, 0x80048, 0x900f1, + 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c9, + 0x7010a, 0x80064, 0x80024, 0x900a9, 0x80004, 0x80084, 0x80044, 0x900e9, + 0x70106, 0x8005c, 0x8001c, 0x90099, 0x70116, 0x8007c, 0x8003c, 0x900d9, + 0x7010e, 0x8006c, 0x8002c, 0x900b9, 0x8000c, 0x8008c, 0x8004c, 0x900f9, + 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c5, + 0x70109, 0x80062, 0x80022, 0x900a5, 0x80002, 0x80082, 0x80042, 0x900e5, + 0x70105, 0x8005a, 0x8001a, 0x90095, 0x70115, 0x8007a, 0x8003a, 0x900d5, + 0x7010d, 0x8006a, 0x8002a, 0x900b5, 0x8000a, 0x8008a, 0x8004a, 0x900f5, + 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cd, + 0x7010b, 0x80066, 0x80026, 0x900ad, 0x80006, 0x80086, 0x80046, 0x900ed, + 0x70107, 0x8005e, 0x8001e, 0x9009d, 0x70117, 0x8007e, 0x8003e, 0x900dd, + 0x7010f, 0x8006e, 0x8002e, 0x900bd, 0x8000e, 0x8008e, 0x8004e, 0x900fd, + 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c3, + 0x70108, 0x80061, 0x80021, 0x900a3, 0x80001, 0x80081, 0x80041, 0x900e3, + 0x70104, 0x80059, 0x80019, 0x90093, 0x70114, 0x80079, 0x80039, 0x900d3, + 0x7010c, 0x80069, 0x80029, 0x900b3, 0x80009, 0x80089, 0x80049, 0x900f3, + 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900cb, + 0x7010a, 0x80065, 0x80025, 0x900ab, 0x80005, 0x80085, 0x80045, 0x900eb, + 0x70106, 0x8005d, 0x8001d, 0x9009b, 0x70116, 0x8007d, 0x8003d, 0x900db, + 0x7010e, 0x8006d, 0x8002d, 0x900bb, 0x8000d, 0x8008d, 0x8004d, 0x900fb, + 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c7, + 0x70109, 0x80063, 0x80023, 0x900a7, 0x80003, 0x80083, 0x80043, 0x900e7, + 0x70105, 0x8005b, 0x8001b, 0x90097, 0x70115, 0x8007b, 0x8003b, 0x900d7, + 0x7010d, 0x8006b, 0x8002b, 0x900b7, 0x8000b, 0x8008b, 0x8004b, 0x900f7, + 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900cf, + 0x7010b, 0x80067, 0x80027, 0x900af, 0x80007, 0x80087, 0x80047, 0x900ef, + 0x70107, 0x8005f, 0x8001f, 0x9009f, 0x70117, 0x8007f, 0x8003f, 0x900df, + 0x7010f, 0x8006f, 0x8002f, 0x900bf, 0x8000f, 0x8008f, 0x8004f, 0x900ff + ]), 9]; +// prettier-ignore +var fixedDistCodeTab = [new Int32Array([ + 0x50000, 0x50010, 0x50008, 0x50018, 0x50004, 0x50014, 0x5000c, 0x5001c, + 0x50002, 0x50012, 0x5000a, 0x5001a, 0x50006, 0x50016, 0x5000e, 0x00000, + 0x50001, 0x50011, 0x50009, 0x50019, 0x50005, 0x50015, 0x5000d, 0x5001d, + 0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000 + ]), 5]; +var FlateStream = /** @class */ (function (_super) { + __extends(FlateStream, _super); + function FlateStream(stream, maybeLength) { + var _this = _super.call(this, maybeLength) || this; + _this.stream = stream; + var cmf = stream.getByte(); + var flg = stream.getByte(); + if (cmf === -1 || flg === -1) { + throw new Error("Invalid header in flate stream: " + cmf + ", " + flg); + } + if ((cmf & 0x0f) !== 0x08) { + throw new Error("Unknown compression method in flate stream: " + cmf + ", " + flg); + } + if (((cmf << 8) + flg) % 31 !== 0) { + throw new Error("Bad FCHECK in flate stream: " + cmf + ", " + flg); + } + if (flg & 0x20) { + throw new Error("FDICT bit set in flate stream: " + cmf + ", " + flg); + } + _this.codeSize = 0; + _this.codeBuf = 0; + return _this; + } + FlateStream.prototype.readBlock = function () { + var buffer; + var len; + var str = this.stream; + // read block header + var hdr = this.getBits(3); + if (hdr & 1) { + this.eof = true; + } + hdr >>= 1; + if (hdr === 0) { + // uncompressed block + var b = void 0; + if ((b = str.getByte()) === -1) { + throw new Error('Bad block header in flate stream'); + } + var blockLen = b; + if ((b = str.getByte()) === -1) { + throw new Error('Bad block header in flate stream'); + } + blockLen |= b << 8; + if ((b = str.getByte()) === -1) { + throw new Error('Bad block header in flate stream'); + } + var check = b; + if ((b = str.getByte()) === -1) { + throw new Error('Bad block header in flate stream'); + } + check |= b << 8; + if (check !== (~blockLen & 0xffff) && (blockLen !== 0 || check !== 0)) { + // Ignoring error for bad "empty" block (see issue 1277) + throw new Error('Bad uncompressed block length in flate stream'); + } + this.codeBuf = 0; + this.codeSize = 0; + var bufferLength = this.bufferLength; + buffer = this.ensureBuffer(bufferLength + blockLen); + var end = bufferLength + blockLen; + this.bufferLength = end; + if (blockLen === 0) { + if (str.peekByte() === -1) { + this.eof = true; + } + } + else { + for (var n = bufferLength; n < end; ++n) { + if ((b = str.getByte()) === -1) { + this.eof = true; + break; + } + buffer[n] = b; + } + } + return; + } + var litCodeTable; + var distCodeTable; + if (hdr === 1) { + // compressed block, fixed codes + litCodeTable = fixedLitCodeTab; + distCodeTable = fixedDistCodeTab; + } + else if (hdr === 2) { + // compressed block, dynamic codes + var numLitCodes = this.getBits(5) + 257; + var numDistCodes = this.getBits(5) + 1; + var numCodeLenCodes = this.getBits(4) + 4; + // build the code lengths code table + var codeLenCodeLengths = new Uint8Array(codeLenCodeMap.length); + var i = void 0; + for (i = 0; i < numCodeLenCodes; ++i) { + codeLenCodeLengths[codeLenCodeMap[i]] = this.getBits(3); + } + var codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths); + // build the literal and distance code tables + len = 0; + i = 0; + var codes = numLitCodes + numDistCodes; + var codeLengths = new Uint8Array(codes); + var bitsLength = void 0; + var bitsOffset = void 0; + var what = void 0; + while (i < codes) { + var code = this.getCode(codeLenCodeTab); + if (code === 16) { + bitsLength = 2; + bitsOffset = 3; + what = len; + } + else if (code === 17) { + bitsLength = 3; + bitsOffset = 3; + what = len = 0; + } + else if (code === 18) { + bitsLength = 7; + bitsOffset = 11; + what = len = 0; + } + else { + codeLengths[i++] = len = code; + continue; + } + var repeatLength = this.getBits(bitsLength) + bitsOffset; + while (repeatLength-- > 0) { + codeLengths[i++] = what; + } + } + litCodeTable = this.generateHuffmanTable(codeLengths.subarray(0, numLitCodes)); + distCodeTable = this.generateHuffmanTable(codeLengths.subarray(numLitCodes, codes)); + } + else { + throw new Error('Unknown block type in flate stream'); + } + buffer = this.buffer; + var limit = buffer ? buffer.length : 0; + var pos = this.bufferLength; + while (true) { + var code1 = this.getCode(litCodeTable); + if (code1 < 256) { + if (pos + 1 >= limit) { + buffer = this.ensureBuffer(pos + 1); + limit = buffer.length; + } + buffer[pos++] = code1; + continue; + } + if (code1 === 256) { + this.bufferLength = pos; + return; + } + code1 -= 257; + code1 = lengthDecode[code1]; + var code2 = code1 >> 16; + if (code2 > 0) { + code2 = this.getBits(code2); + } + len = (code1 & 0xffff) + code2; + code1 = this.getCode(distCodeTable); + code1 = distDecode[code1]; + code2 = code1 >> 16; + if (code2 > 0) { + code2 = this.getBits(code2); + } + var dist = (code1 & 0xffff) + code2; + if (pos + len >= limit) { + buffer = this.ensureBuffer(pos + len); + limit = buffer.length; + } + for (var k = 0; k < len; ++k, ++pos) { + buffer[pos] = buffer[pos - dist]; + } + } + }; + FlateStream.prototype.getBits = function (bits) { + var str = this.stream; + var codeSize = this.codeSize; + var codeBuf = this.codeBuf; + var b; + while (codeSize < bits) { + if ((b = str.getByte()) === -1) { + throw new Error('Bad encoding in flate stream'); + } + codeBuf |= b << codeSize; + codeSize += 8; + } + b = codeBuf & ((1 << bits) - 1); + this.codeBuf = codeBuf >> bits; + this.codeSize = codeSize -= bits; + return b; + }; + FlateStream.prototype.getCode = function (table) { + var str = this.stream; + var codes = table[0]; + var maxLen = table[1]; + var codeSize = this.codeSize; + var codeBuf = this.codeBuf; + var b; + while (codeSize < maxLen) { + if ((b = str.getByte()) === -1) { + // premature end of stream. code might however still be valid. + // codeSize < codeLen check below guards against incomplete codeVal. + break; + } + codeBuf |= b << codeSize; + codeSize += 8; + } + var code = codes[codeBuf & ((1 << maxLen) - 1)]; + if (typeof codes === 'number') { + console.log('FLATE:', code); + } + var codeLen = code >> 16; + var codeVal = code & 0xffff; + if (codeLen < 1 || codeSize < codeLen) { + throw new Error('Bad encoding in flate stream'); + } + this.codeBuf = codeBuf >> codeLen; + this.codeSize = codeSize - codeLen; + return codeVal; + }; + FlateStream.prototype.generateHuffmanTable = function (lengths) { + var n = lengths.length; + // find max code length + var maxLen = 0; + var i; + for (i = 0; i < n; ++i) { + if (lengths[i] > maxLen) { + maxLen = lengths[i]; + } + } + // build the table + var size = 1 << maxLen; + var codes = new Int32Array(size); + for (var len = 1, code = 0, skip = 2; len <= maxLen; ++len, code <<= 1, skip <<= 1) { + for (var val = 0; val < n; ++val) { + if (lengths[val] === len) { + // bit-reverse the code + var code2 = 0; + var t = code; + for (i = 0; i < len; ++i) { + code2 = (code2 << 1) | (t & 1); + t >>= 1; + } + // fill the table entries + for (i = code2; i < size; i += skip) { + codes[i] = (len << 16) | val; + } + ++code; + } + } + } + return [codes, maxLen]; + }; + return FlateStream; +}(DecodeStream)); + +/* + * Copyright 2012 Mozilla Foundation + * + * The LZWStream class contained in this file is a TypeScript port of the + * JavaScript LZWStream class in Mozilla's pdf.js project, made available + * under the Apache 2.0 open source license. + */ +var LZWStream = /** @class */ (function (_super) { + __extends(LZWStream, _super); + function LZWStream(stream, maybeLength, earlyChange) { + var _this = _super.call(this, maybeLength) || this; + _this.stream = stream; + _this.cachedData = 0; + _this.bitsCached = 0; + var maxLzwDictionarySize = 4096; + var lzwState = { + earlyChange: earlyChange, + codeLength: 9, + nextCode: 258, + dictionaryValues: new Uint8Array(maxLzwDictionarySize), + dictionaryLengths: new Uint16Array(maxLzwDictionarySize), + dictionaryPrevCodes: new Uint16Array(maxLzwDictionarySize), + currentSequence: new Uint8Array(maxLzwDictionarySize), + currentSequenceLength: 0, + }; + for (var i = 0; i < 256; ++i) { + lzwState.dictionaryValues[i] = i; + lzwState.dictionaryLengths[i] = 1; + } + _this.lzwState = lzwState; + return _this; + } + LZWStream.prototype.readBlock = function () { + var blockSize = 512; + var estimatedDecodedSize = blockSize * 2; + var decodedSizeDelta = blockSize; + var i; + var j; + var q; + var lzwState = this.lzwState; + if (!lzwState) { + return; // eof was found + } + var earlyChange = lzwState.earlyChange; + var nextCode = lzwState.nextCode; + var dictionaryValues = lzwState.dictionaryValues; + var dictionaryLengths = lzwState.dictionaryLengths; + var dictionaryPrevCodes = lzwState.dictionaryPrevCodes; + var codeLength = lzwState.codeLength; + var prevCode = lzwState.prevCode; + var currentSequence = lzwState.currentSequence; + var currentSequenceLength = lzwState.currentSequenceLength; + var decodedLength = 0; + var currentBufferLength = this.bufferLength; + var buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize); + for (i = 0; i < blockSize; i++) { + var code = this.readBits(codeLength); + var hasPrev = currentSequenceLength > 0; + if (!code || code < 256) { + currentSequence[0] = code; + currentSequenceLength = 1; + } + else if (code >= 258) { + if (code < nextCode) { + currentSequenceLength = dictionaryLengths[code]; + for (j = currentSequenceLength - 1, q = code; j >= 0; j--) { + currentSequence[j] = dictionaryValues[q]; + q = dictionaryPrevCodes[q]; + } + } + else { + currentSequence[currentSequenceLength++] = currentSequence[0]; + } + } + else if (code === 256) { + codeLength = 9; + nextCode = 258; + currentSequenceLength = 0; + continue; + } + else { + this.eof = true; + delete this.lzwState; + break; + } + if (hasPrev) { + dictionaryPrevCodes[nextCode] = prevCode; + dictionaryLengths[nextCode] = dictionaryLengths[prevCode] + 1; + dictionaryValues[nextCode] = currentSequence[0]; + nextCode++; + codeLength = + (nextCode + earlyChange) & (nextCode + earlyChange - 1) + ? codeLength + : Math.min(Math.log(nextCode + earlyChange) / 0.6931471805599453 + 1, 12) | 0; + } + prevCode = code; + decodedLength += currentSequenceLength; + if (estimatedDecodedSize < decodedLength) { + do { + estimatedDecodedSize += decodedSizeDelta; + } while (estimatedDecodedSize < decodedLength); + buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize); + } + for (j = 0; j < currentSequenceLength; j++) { + buffer[currentBufferLength++] = currentSequence[j]; + } + } + lzwState.nextCode = nextCode; + lzwState.codeLength = codeLength; + lzwState.prevCode = prevCode; + lzwState.currentSequenceLength = currentSequenceLength; + this.bufferLength = currentBufferLength; + }; + LZWStream.prototype.readBits = function (n) { + var bitsCached = this.bitsCached; + var cachedData = this.cachedData; + while (bitsCached < n) { + var c = this.stream.getByte(); + if (c === -1) { + this.eof = true; + return null; + } + cachedData = (cachedData << 8) | c; + bitsCached += 8; + } + this.bitsCached = bitsCached -= n; + this.cachedData = cachedData; + return (cachedData >>> bitsCached) & ((1 << n) - 1); + }; + return LZWStream; +}(DecodeStream)); + +/* + * Copyright 2012 Mozilla Foundation + * + * The RunLengthStream class contained in this file is a TypeScript port of the + * JavaScript RunLengthStream class in Mozilla's pdf.js project, made available + * under the Apache 2.0 open source license. + */ +var RunLengthStream = /** @class */ (function (_super) { + __extends(RunLengthStream, _super); + function RunLengthStream(stream, maybeLength) { + var _this = _super.call(this, maybeLength) || this; + _this.stream = stream; + return _this; + } + RunLengthStream.prototype.readBlock = function () { + // The repeatHeader has following format. The first byte defines type of run + // and amount of bytes to repeat/copy: n = 0 through 127 - copy next n bytes + // (in addition to the second byte from the header), n = 129 through 255 - + // duplicate the second byte from the header (257 - n) times, n = 128 - end. + var repeatHeader = this.stream.getBytes(2); + if (!repeatHeader || repeatHeader.length < 2 || repeatHeader[0] === 128) { + this.eof = true; + return; + } + var buffer; + var bufferLength = this.bufferLength; + var n = repeatHeader[0]; + if (n < 128) { + // copy n bytes + buffer = this.ensureBuffer(bufferLength + n + 1); + buffer[bufferLength++] = repeatHeader[1]; + if (n > 0) { + var source = this.stream.getBytes(n); + buffer.set(source, bufferLength); + bufferLength += n; + } + } + else { + n = 257 - n; + var b = repeatHeader[1]; + buffer = this.ensureBuffer(bufferLength + n + 1); + for (var i = 0; i < n; i++) { + buffer[bufferLength++] = b; + } + } + this.bufferLength = bufferLength; + }; + return RunLengthStream; +}(DecodeStream)); + +var decodeStream = function (stream, encoding, params) { + if (encoding === PDFName.of('FlateDecode')) { + return new FlateStream(stream); + } + if (encoding === PDFName.of('LZWDecode')) { + var earlyChange = 1; + if (params instanceof PDFDict) { + var EarlyChange = params.lookup(PDFName.of('EarlyChange')); + if (EarlyChange instanceof PDFNumber) { + earlyChange = EarlyChange.asNumber(); + } + } + return new LZWStream(stream, undefined, earlyChange); + } + if (encoding === PDFName.of('ASCII85Decode')) { + return new Ascii85Stream(stream); + } + if (encoding === PDFName.of('ASCIIHexDecode')) { + return new AsciiHexStream(stream); + } + if (encoding === PDFName.of('RunLengthDecode')) { + return new RunLengthStream(stream); + } + throw new UnsupportedEncodingError(encoding.asString()); +}; +var decodePDFRawStream = function (_a) { + var dict = _a.dict, contents = _a.contents; + var stream = new Stream(contents); + var Filter = dict.lookup(PDFName.of('Filter')); + var DecodeParms = dict.lookup(PDFName.of('DecodeParms')); + if (Filter instanceof PDFName) { + stream = decodeStream(stream, Filter, DecodeParms); + } + else if (Filter instanceof PDFArray) { + for (var idx = 0, len = Filter.size(); idx < len; idx++) { + stream = decodeStream(stream, Filter.lookup(idx, PDFName), DecodeParms && DecodeParms.lookupMaybe(idx, PDFDict)); + } + } + else if (!!Filter) { + throw new UnexpectedObjectTypeError([PDFName, PDFArray], Filter); + } + return stream; +}; + +var fullPageBoundingBox = function (page) { + var mediaBox = page.MediaBox(); + var width = mediaBox.lookup(2, PDFNumber).asNumber() - + mediaBox.lookup(0, PDFNumber).asNumber(); + var height = mediaBox.lookup(3, PDFNumber).asNumber() - + mediaBox.lookup(1, PDFNumber).asNumber(); + return { left: 0, bottom: 0, right: width, top: height }; +}; +// Returns the identity matrix, modified to position the content of the given +// bounding box at (0, 0). +var boundingBoxAdjustedMatrix = function (bb) { return [1, 0, 0, 1, -bb.left, -bb.bottom]; }; +var PDFPageEmbedder = /** @class */ (function () { + function PDFPageEmbedder(page, boundingBox, transformationMatrix) { + this.page = page; + var bb = boundingBox !== null && boundingBox !== void 0 ? boundingBox : fullPageBoundingBox(page); + this.width = bb.right - bb.left; + this.height = bb.top - bb.bottom; + this.boundingBox = bb; + this.transformationMatrix = transformationMatrix !== null && transformationMatrix !== void 0 ? transformationMatrix : boundingBoxAdjustedMatrix(bb); + } + PDFPageEmbedder.for = function (page, boundingBox, transformationMatrix) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + return [2 /*return*/, new PDFPageEmbedder(page, boundingBox, transformationMatrix)]; + }); + }); + }; + PDFPageEmbedder.prototype.embedIntoContext = function (context, ref) { + return __awaiter(this, void 0, void 0, function () { + var _a, Contents, Resources, decodedContents, _b, left, bottom, right, top, xObject; + return __generator(this, function (_c) { + _a = this.page.normalizedEntries(), Contents = _a.Contents, Resources = _a.Resources; + if (!Contents) + throw new MissingPageContentsEmbeddingError(); + decodedContents = this.decodeContents(Contents); + _b = this.boundingBox, left = _b.left, bottom = _b.bottom, right = _b.right, top = _b.top; + xObject = context.flateStream(decodedContents, { + Type: 'XObject', + Subtype: 'Form', + FormType: 1, + BBox: [left, bottom, right, top], + Matrix: this.transformationMatrix, + Resources: Resources, + }); + if (ref) { + context.assign(ref, xObject); + return [2 /*return*/, ref]; + } + else { + return [2 /*return*/, context.register(xObject)]; + } + }); + }); + }; + // `contents` is an array of streams which are merged to include them in the XObject. + // This methods extracts each stream and joins them with a newline character. + PDFPageEmbedder.prototype.decodeContents = function (contents) { + var newline = Uint8Array.of(CharCodes$1.Newline); + var decodedContents = []; + for (var idx = 0, len = contents.size(); idx < len; idx++) { + var stream = contents.lookup(idx, PDFStream); + var content = void 0; + if (stream instanceof PDFRawStream) { + content = decodePDFRawStream(stream).decode(); + } + else if (stream instanceof PDFContentStream) { + content = stream.getUnencodedContents(); + } + else { + throw new UnrecognizedStreamTypeError(stream); + } + decodedContents.push(content, newline); + } + return mergeIntoTypedArray.apply(void 0, decodedContents); + }; + return PDFPageEmbedder; +}()); + +var asEnum = function (rawValue, enumType) { + if (rawValue === undefined) + return undefined; + return enumType[rawValue]; +}; +var NonFullScreenPageMode; +(function (NonFullScreenPageMode) { + /** + * After exiting FullScreen mode, neither the document outline nor thumbnail + * images should be visible. + */ + NonFullScreenPageMode["UseNone"] = "UseNone"; + /** After exiting FullScreen mode, the document outline should be visible. */ + NonFullScreenPageMode["UseOutlines"] = "UseOutlines"; + /** After exiting FullScreen mode, thumbnail images should be visible. */ + NonFullScreenPageMode["UseThumbs"] = "UseThumbs"; + /** + * After exiting FullScreen mode, the optional content group panel should be + * visible. + */ + NonFullScreenPageMode["UseOC"] = "UseOC"; +})(NonFullScreenPageMode || (NonFullScreenPageMode = {})); +var ReadingDirection; +(function (ReadingDirection) { + /** The predominant reading order is Left to Right. */ + ReadingDirection["L2R"] = "L2R"; + /** + * The predominant reading order is Right to left (including vertical writing + * systems, such as Chinese, Japanese and Korean). + */ + ReadingDirection["R2L"] = "R2L"; +})(ReadingDirection || (ReadingDirection = {})); +var PrintScaling; +(function (PrintScaling) { + /** No page scaling. */ + PrintScaling["None"] = "None"; + /* Use the PDF reader's default print scaling. */ + PrintScaling["AppDefault"] = "AppDefault"; +})(PrintScaling || (PrintScaling = {})); +var Duplex; +(function (Duplex) { + /** The PDF reader should print single-sided. */ + Duplex["Simplex"] = "Simplex"; + /** + * The PDF reader should print double sided and flip on the short edge of the + * sheet. + */ + Duplex["DuplexFlipShortEdge"] = "DuplexFlipShortEdge"; + /** + * The PDF reader should print double sided and flip on the long edge of the + * sheet. + */ + Duplex["DuplexFlipLongEdge"] = "DuplexFlipLongEdge"; +})(Duplex || (Duplex = {})); +var ViewerPreferences = /** @class */ (function () { + /** @ignore */ + function ViewerPreferences(dict) { + this.dict = dict; + } + ViewerPreferences.prototype.lookupBool = function (key) { + var returnObj = this.dict.lookup(PDFName.of(key)); + if (returnObj instanceof PDFBool) + return returnObj; + return undefined; + }; + ViewerPreferences.prototype.lookupName = function (key) { + var returnObj = this.dict.lookup(PDFName.of(key)); + if (returnObj instanceof PDFName) + return returnObj; + return undefined; + }; + /** @ignore */ + ViewerPreferences.prototype.HideToolbar = function () { + return this.lookupBool('HideToolbar'); + }; + /** @ignore */ + ViewerPreferences.prototype.HideMenubar = function () { + return this.lookupBool('HideMenubar'); + }; + /** @ignore */ + ViewerPreferences.prototype.HideWindowUI = function () { + return this.lookupBool('HideWindowUI'); + }; + /** @ignore */ + ViewerPreferences.prototype.FitWindow = function () { + return this.lookupBool('FitWindow'); + }; + /** @ignore */ + ViewerPreferences.prototype.CenterWindow = function () { + return this.lookupBool('CenterWindow'); + }; + /** @ignore */ + ViewerPreferences.prototype.DisplayDocTitle = function () { + return this.lookupBool('DisplayDocTitle'); + }; + /** @ignore */ + ViewerPreferences.prototype.NonFullScreenPageMode = function () { + return this.lookupName('NonFullScreenPageMode'); + }; + /** @ignore */ + ViewerPreferences.prototype.Direction = function () { + return this.lookupName('Direction'); + }; + /** @ignore */ + ViewerPreferences.prototype.PrintScaling = function () { + return this.lookupName('PrintScaling'); + }; + /** @ignore */ + ViewerPreferences.prototype.Duplex = function () { + return this.lookupName('Duplex'); + }; + /** @ignore */ + ViewerPreferences.prototype.PickTrayByPDFSize = function () { + return this.lookupBool('PickTrayByPDFSize'); + }; + /** @ignore */ + ViewerPreferences.prototype.PrintPageRange = function () { + var PrintPageRange = this.dict.lookup(PDFName.of('PrintPageRange')); + if (PrintPageRange instanceof PDFArray) + return PrintPageRange; + return undefined; + }; + /** @ignore */ + ViewerPreferences.prototype.NumCopies = function () { + var NumCopies = this.dict.lookup(PDFName.of('NumCopies')); + if (NumCopies instanceof PDFNumber) + return NumCopies; + return undefined; + }; + /** + * Returns `true` if PDF readers should hide the toolbar menus when displaying + * this document. + * @returns Whether or not toolbars should be hidden. + */ + ViewerPreferences.prototype.getHideToolbar = function () { + var _a, _b; + return (_b = (_a = this.HideToolbar()) === null || _a === void 0 ? void 0 : _a.asBoolean()) !== null && _b !== void 0 ? _b : false; + }; + /** + * Returns `true` if PDF readers should hide the menu bar when displaying this + * document. + * @returns Whether or not the menu bar should be hidden. + */ + ViewerPreferences.prototype.getHideMenubar = function () { + var _a, _b; + return (_b = (_a = this.HideMenubar()) === null || _a === void 0 ? void 0 : _a.asBoolean()) !== null && _b !== void 0 ? _b : false; + }; + /** + * Returns `true` if PDF readers should hide the user interface elements in + * the document's window (such as scroll bars and navigation controls), + * leaving only the document's contents displayed. + * @returns Whether or not user interface elements should be hidden. + */ + ViewerPreferences.prototype.getHideWindowUI = function () { + var _a, _b; + return (_b = (_a = this.HideWindowUI()) === null || _a === void 0 ? void 0 : _a.asBoolean()) !== null && _b !== void 0 ? _b : false; + }; + /** + * Returns `true` if PDF readers should resize the document's window to fit + * the size of the first displayed page. + * @returns Whether or not the window should be resized to fit. + */ + ViewerPreferences.prototype.getFitWindow = function () { + var _a, _b; + return (_b = (_a = this.FitWindow()) === null || _a === void 0 ? void 0 : _a.asBoolean()) !== null && _b !== void 0 ? _b : false; + }; + /** + * Returns `true` if PDF readers should position the document's window in the + * center of the screen. + * @returns Whether or not to center the document window. + */ + ViewerPreferences.prototype.getCenterWindow = function () { + var _a, _b; + return (_b = (_a = this.CenterWindow()) === null || _a === void 0 ? void 0 : _a.asBoolean()) !== null && _b !== void 0 ? _b : false; + }; + /** + * Returns `true` if the window's title bar should display the document + * `Title`, taken from the document metadata (see [[PDFDocument.getTitle]]). + * Returns `false` if the title bar should instead display the filename of the + * PDF file. + * @returns Whether to display the document title. + */ + ViewerPreferences.prototype.getDisplayDocTitle = function () { + var _a, _b; + return (_b = (_a = this.DisplayDocTitle()) === null || _a === void 0 ? void 0 : _a.asBoolean()) !== null && _b !== void 0 ? _b : false; + }; + /** + * Returns the page mode, which tells the PDF reader how to display the + * document after exiting full-screen mode. + * @returns The page mode after exiting full-screen mode. + */ + ViewerPreferences.prototype.getNonFullScreenPageMode = function () { + var _a, _b; + var mode = (_a = this.NonFullScreenPageMode()) === null || _a === void 0 ? void 0 : _a.decodeText(); + return (_b = asEnum(mode, NonFullScreenPageMode)) !== null && _b !== void 0 ? _b : NonFullScreenPageMode.UseNone; + }; + /** + * Returns the predominant reading order for text. + * @returns The text reading order. + */ + ViewerPreferences.prototype.getReadingDirection = function () { + var _a, _b; + var direction = (_a = this.Direction()) === null || _a === void 0 ? void 0 : _a.decodeText(); + return (_b = asEnum(direction, ReadingDirection)) !== null && _b !== void 0 ? _b : ReadingDirection.L2R; + }; + /** + * Returns the page scaling option that the PDF reader should select when the + * print dialog is displayed. + * @returns The page scaling option. + */ + ViewerPreferences.prototype.getPrintScaling = function () { + var _a, _b; + var scaling = (_a = this.PrintScaling()) === null || _a === void 0 ? void 0 : _a.decodeText(); + return (_b = asEnum(scaling, PrintScaling)) !== null && _b !== void 0 ? _b : PrintScaling.AppDefault; + }; + /** + * Returns the paper handling option that should be used when printing the + * file from the print dialog. + * @returns The paper handling option. + */ + ViewerPreferences.prototype.getDuplex = function () { + var _a; + var duplex = (_a = this.Duplex()) === null || _a === void 0 ? void 0 : _a.decodeText(); + return asEnum(duplex, Duplex); + }; + /** + * Returns `true` if the PDF page size should be used to select the input + * paper tray. + * @returns Whether or not the PDF page size should be used to select the + * input paper tray. + */ + ViewerPreferences.prototype.getPickTrayByPDFSize = function () { + var _a; + return (_a = this.PickTrayByPDFSize()) === null || _a === void 0 ? void 0 : _a.asBoolean(); + }; + /** + * Returns an array of page number ranges, which are the values used to + * initialize the print dialog box when the file is printed. Each range + * specifies the first (`start`) and last (`end`) pages in a sub-range of + * pages to be printed. The first page of the PDF file is denoted by 0. + * For example: + * ```js + * const viewerPrefs = pdfDoc.catalog.getOrCreateViewerPreferences() + * const includesPage3 = viewerPrefs + * .getPrintRanges() + * .some(pr => pr.start =< 2 && pr.end >= 2) + * if (includesPage3) console.log('printRange includes page 3') + * ``` + * @returns An array of objects, each with the properties `start` and `end`, + * denoting page indices. If not, specified an empty array is + * returned. + */ + ViewerPreferences.prototype.getPrintPageRange = function () { + var rng = this.PrintPageRange(); + if (!rng) + return []; + var pageRanges = []; + for (var i = 0; i < rng.size(); i += 2) { + // Despite the spec clearly stating that "The first page of the PDF file + // shall be donoted by 1", several test PDFs (spec 1.7) created in + // Acrobat XI 11.0 and also read with Reader DC 2020.013 indicate this is + // actually a 0 based index. + var start = rng.lookup(i, PDFNumber).asNumber(); + var end = rng.lookup(i + 1, PDFNumber).asNumber(); + pageRanges.push({ start: start, end: end }); + } + return pageRanges; + }; + /** + * Returns the number of copies to be printed when the print dialog is opened + * for this document. + * @returns The default number of copies to be printed. + */ + ViewerPreferences.prototype.getNumCopies = function () { + var _a, _b; + return (_b = (_a = this.NumCopies()) === null || _a === void 0 ? void 0 : _a.asNumber()) !== null && _b !== void 0 ? _b : 1; + }; + /** + * Choose whether the PDF reader's toolbars should be hidden while the + * document is active. + * @param hideToolbar `true` if the toolbar should be hidden. + */ + ViewerPreferences.prototype.setHideToolbar = function (hideToolbar) { + var HideToolbar = this.dict.context.obj(hideToolbar); + this.dict.set(PDFName.of('HideToolbar'), HideToolbar); + }; + /** + * Choose whether the PDF reader's menu bar should be hidden while the + * document is active. + * @param hideMenubar `true` if the menu bar should be hidden. + */ + ViewerPreferences.prototype.setHideMenubar = function (hideMenubar) { + var HideMenubar = this.dict.context.obj(hideMenubar); + this.dict.set(PDFName.of('HideMenubar'), HideMenubar); + }; + /** + * Choose whether the PDF reader should hide user interface elements in the + * document's window (such as scroll bars and navigation controls), leaving + * only the document's contents displayed. + * @param hideWindowUI `true` if the user interface elements should be hidden. + */ + ViewerPreferences.prototype.setHideWindowUI = function (hideWindowUI) { + var HideWindowUI = this.dict.context.obj(hideWindowUI); + this.dict.set(PDFName.of('HideWindowUI'), HideWindowUI); + }; + /** + * Choose whether the PDF reader should resize the document's window to fit + * the size of the first displayed page. + * @param fitWindow `true` if the window should be resized. + */ + ViewerPreferences.prototype.setFitWindow = function (fitWindow) { + var FitWindow = this.dict.context.obj(fitWindow); + this.dict.set(PDFName.of('FitWindow'), FitWindow); + }; + /** + * Choose whether the PDF reader should position the document's window in the + * center of the screen. + * @param centerWindow `true` if the window should be centered. + */ + ViewerPreferences.prototype.setCenterWindow = function (centerWindow) { + var CenterWindow = this.dict.context.obj(centerWindow); + this.dict.set(PDFName.of('CenterWindow'), CenterWindow); + }; + /** + * Choose whether the window's title bar should display the document `Title` + * taken from the document metadata (see [[PDFDocument.setTitle]]). If + * `false`, the title bar should instead display the PDF filename. + * @param displayTitle `true` if the document title should be displayed. + */ + ViewerPreferences.prototype.setDisplayDocTitle = function (displayTitle) { + var DisplayDocTitle = this.dict.context.obj(displayTitle); + this.dict.set(PDFName.of('DisplayDocTitle'), DisplayDocTitle); + }; + /** + * Choose how the PDF reader should display the document upon exiting + * full-screen mode. This entry is meaningful only if the value of the + * `PageMode` entry in the document's [[PDFCatalog]] is `FullScreen`. + * + * For example: + * ```js + * import { PDFDocument, NonFullScreenPageMode, PDFName } from 'pdf-lib' + * + * const pdfDoc = await PDFDocument.create() + * + * // Set the PageMode + * pdfDoc.catalog.set(PDFName.of('PageMode'),PDFName.of('FullScreen')) + * + * // Set what happens when full-screen is closed + * const viewerPrefs = pdfDoc.catalog.getOrCreateViewerPreferences() + * viewerPrefs.setNonFullScreenPageMode(NonFullScreenPageMode.UseOutlines) + * ``` + * + * @param nonFullScreenPageMode How the document should be displayed upon + * exiting full screen mode. + */ + ViewerPreferences.prototype.setNonFullScreenPageMode = function (nonFullScreenPageMode) { + assertIsOneOf(nonFullScreenPageMode, 'nonFullScreenPageMode', NonFullScreenPageMode); + var mode = PDFName.of(nonFullScreenPageMode); + this.dict.set(PDFName.of('NonFullScreenPageMode'), mode); + }; + /** + * Choose the predominant reading order for text. + * + * This entry has no direct effect on the document's contents or page + * numbering, but may be used to determine the relative positioning of pages + * when displayed side by side or printed n-up. + * + * For example: + * ```js + * import { PDFDocument, ReadingDirection } from 'pdf-lib' + * + * const pdfDoc = await PDFDocument.create() + * const viewerPrefs = pdfDoc.catalog.getOrCreateViewerPreferences() + * viewerPrefs.setReadingDirection(ReadingDirection.R2L) + * ``` + * + * @param readingDirection The reading order for text. + */ + ViewerPreferences.prototype.setReadingDirection = function (readingDirection) { + assertIsOneOf(readingDirection, 'readingDirection', ReadingDirection); + var direction = PDFName.of(readingDirection); + this.dict.set(PDFName.of('Direction'), direction); + }; + /** + * Choose the page scaling option that should be selected when a print dialog + * is displayed for this document. + * + * For example: + * ```js + * import { PDFDocument, PrintScaling } from 'pdf-lib' + * + * const pdfDoc = await PDFDocument.create() + * const viewerPrefs = pdfDoc.catalog.getOrCreateViewerPreferences() + * viewerPrefs.setPrintScaling(PrintScaling.None) + * ``` + * + * @param printScaling The print scaling option. + */ + ViewerPreferences.prototype.setPrintScaling = function (printScaling) { + assertIsOneOf(printScaling, 'printScaling', PrintScaling); + var scaling = PDFName.of(printScaling); + this.dict.set(PDFName.of('PrintScaling'), scaling); + }; + /** + * Choose the paper handling option that should be selected by default in the + * print dialog. + * + * For example: + * ```js + * import { PDFDocument, Duplex } from 'pdf-lib' + * + * const pdfDoc = await PDFDocument.create() + * const viewerPrefs = pdfDoc.catalog.getOrCreateViewerPreferences() + * viewerPrefs.setDuplex(Duplex.DuplexFlipShortEdge) + * ``` + * + * @param duplex The double or single sided printing option. + */ + ViewerPreferences.prototype.setDuplex = function (duplex) { + assertIsOneOf(duplex, 'duplex', Duplex); + var dup = PDFName.of(duplex); + this.dict.set(PDFName.of('Duplex'), dup); + }; + /** + * Choose whether the PDF document's page size should be used to select the + * input paper tray when printing. This setting influences only the preset + * values used to populate the print dialog presented by a PDF reader. + * + * If PickTrayByPDFSize is true, the check box in the print dialog associated + * with input paper tray should be checked. This setting has no effect on + * operating systems that do not provide the ability to pick the input tray + * by size. + * + * @param pickTrayByPDFSize `true` if the document's page size should be used + * to select the input paper tray. + */ + ViewerPreferences.prototype.setPickTrayByPDFSize = function (pickTrayByPDFSize) { + var PickTrayByPDFSize = this.dict.context.obj(pickTrayByPDFSize); + this.dict.set(PDFName.of('PickTrayByPDFSize'), PickTrayByPDFSize); + }; + /** + * Choose the page numbers used to initialize the print dialog box when the + * file is printed. The first page of the PDF file is denoted by 0. + * + * For example: + * ```js + * import { PDFDocument } from 'pdf-lib' + * + * const pdfDoc = await PDFDocument.create() + * const viewerPrefs = pdfDoc.catalog.getOrCreateViewerPreferences() + * + * // We can set the default print range to only the first page + * viewerPrefs.setPrintPageRange({ start: 0, end: 0 }) + * + * // Or we can supply noncontiguous ranges (e.g. pages 1, 3, and 5-7) + * viewerPrefs.setPrintPageRange([ + * { start: 0, end: 0 }, + * { start: 2, end: 2 }, + * { start: 4, end: 6 }, + * ]) + * ``` + * + * @param printPageRange An object or array of objects, each with the + * properties `start` and `end`, denoting a range of + * page indices. + */ + ViewerPreferences.prototype.setPrintPageRange = function (printPageRange) { + if (!Array.isArray(printPageRange)) + printPageRange = [printPageRange]; + var flatRange = []; + for (var idx = 0, len = printPageRange.length; idx < len; idx++) { + flatRange.push(printPageRange[idx].start); + flatRange.push(printPageRange[idx].end); + } + assertEachIs(flatRange, 'printPageRange', ['number']); + var pageRanges = this.dict.context.obj(flatRange); + this.dict.set(PDFName.of('PrintPageRange'), pageRanges); + }; + /** + * Choose the default number of copies to be printed when the print dialog is + * opened for this file. + * @param numCopies The default number of copies. + */ + ViewerPreferences.prototype.setNumCopies = function (numCopies) { + assertRange(numCopies, 'numCopies', 1, Number.MAX_VALUE); + assertInteger(numCopies, 'numCopies'); + var NumCopies = this.dict.context.obj(numCopies); + this.dict.set(PDFName.of('NumCopies'), NumCopies); + }; + /** @ignore */ + ViewerPreferences.fromDict = function (dict) { + return new ViewerPreferences(dict); + }; + /** @ignore */ + ViewerPreferences.create = function (context) { + var dict = context.obj({}); + return new ViewerPreferences(dict); + }; + return ViewerPreferences; +}()); + +// Examples: +// `/Helv 12 Tf` -> ['Helv', '12'] +// `/HeBo 8.00 Tf` -> ['HeBo', '8.00'] +// `/HeBo Tf` -> ['HeBo', undefined] +var tfRegex = /\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+Tf/; +var PDFAcroField = /** @class */ (function () { + function PDFAcroField(dict, ref) { + this.dict = dict; + this.ref = ref; + } + PDFAcroField.prototype.T = function () { + return this.dict.lookupMaybe(PDFName.of('T'), PDFString, PDFHexString); + }; + PDFAcroField.prototype.Ff = function () { + var numberOrRef = this.getInheritableAttribute(PDFName.of('Ff')); + return this.dict.context.lookupMaybe(numberOrRef, PDFNumber); + }; + PDFAcroField.prototype.V = function () { + var valueOrRef = this.getInheritableAttribute(PDFName.of('V')); + return this.dict.context.lookup(valueOrRef); + }; + PDFAcroField.prototype.Kids = function () { + return this.dict.lookupMaybe(PDFName.of('Kids'), PDFArray); + }; + // Parent(): PDFDict | undefined { + // return this.dict.lookupMaybe(PDFName.of('Parent'), PDFDict); + // } + PDFAcroField.prototype.DA = function () { + var da = this.dict.lookup(PDFName.of('DA')); + if (da instanceof PDFString || da instanceof PDFHexString) + return da; + return undefined; + }; + PDFAcroField.prototype.setKids = function (kids) { + this.dict.set(PDFName.of('Kids'), this.dict.context.obj(kids)); + }; + PDFAcroField.prototype.getParent = function () { + // const parent = this.Parent(); + // if (!parent) return undefined; + // return new PDFAcroField(parent); + var parentRef = this.dict.get(PDFName.of('Parent')); + if (parentRef instanceof PDFRef) { + var parent_1 = this.dict.lookup(PDFName.of('Parent'), PDFDict); + return new PDFAcroField(parent_1, parentRef); + } + return undefined; + }; + PDFAcroField.prototype.setParent = function (parent) { + if (!parent) + this.dict.delete(PDFName.of('Parent')); + else + this.dict.set(PDFName.of('Parent'), parent); + }; + PDFAcroField.prototype.getFullyQualifiedName = function () { + var parent = this.getParent(); + if (!parent) + return this.getPartialName(); + return parent.getFullyQualifiedName() + "." + this.getPartialName(); + }; + PDFAcroField.prototype.getPartialName = function () { + var _a; + return (_a = this.T()) === null || _a === void 0 ? void 0 : _a.decodeText(); + }; + PDFAcroField.prototype.setPartialName = function (partialName) { + if (!partialName) + this.dict.delete(PDFName.of('T')); + else + this.dict.set(PDFName.of('T'), PDFHexString.fromText(partialName)); + }; + PDFAcroField.prototype.setDefaultAppearance = function (appearance) { + this.dict.set(PDFName.of('DA'), PDFString.of(appearance)); + }; + PDFAcroField.prototype.getDefaultAppearance = function () { + var DA = this.DA(); + if (DA instanceof PDFHexString) { + return DA.decodeText(); + } + return DA === null || DA === void 0 ? void 0 : DA.asString(); + }; + PDFAcroField.prototype.setFontSize = function (fontSize) { + var _a; + var name = (_a = this.getFullyQualifiedName()) !== null && _a !== void 0 ? _a : ''; + var da = this.getDefaultAppearance(); + if (!da) + throw new MissingDAEntryError(name); + var daMatch = findLastMatch(da, tfRegex); + if (!daMatch.match) + throw new MissingTfOperatorError(name); + var daStart = da.slice(0, daMatch.pos - daMatch.match[0].length); + var daEnd = daMatch.pos <= da.length ? da.slice(daMatch.pos) : ''; + var fontName = daMatch.match[1]; + var modifiedDa = daStart + " /" + fontName + " " + fontSize + " Tf " + daEnd; + this.setDefaultAppearance(modifiedDa); + }; + PDFAcroField.prototype.getFlags = function () { + var _a, _b; + return (_b = (_a = this.Ff()) === null || _a === void 0 ? void 0 : _a.asNumber()) !== null && _b !== void 0 ? _b : 0; + }; + PDFAcroField.prototype.setFlags = function (flags) { + this.dict.set(PDFName.of('Ff'), PDFNumber.of(flags)); + }; + PDFAcroField.prototype.hasFlag = function (flag) { + var flags = this.getFlags(); + return (flags & flag) !== 0; + }; + PDFAcroField.prototype.setFlag = function (flag) { + var flags = this.getFlags(); + this.setFlags(flags | flag); + }; + PDFAcroField.prototype.clearFlag = function (flag) { + var flags = this.getFlags(); + this.setFlags(flags & ~flag); + }; + PDFAcroField.prototype.setFlagTo = function (flag, enable) { + if (enable) + this.setFlag(flag); + else + this.clearFlag(flag); + }; + PDFAcroField.prototype.getInheritableAttribute = function (name) { + var attribute; + this.ascend(function (node) { + if (!attribute) + attribute = node.dict.get(name); + }); + return attribute; + }; + PDFAcroField.prototype.ascend = function (visitor) { + visitor(this); + var parent = this.getParent(); + if (parent) + parent.ascend(visitor); + }; + return PDFAcroField; +}()); + +// TODO: Also handle the `/S` and `/D` entries +var BorderStyle = /** @class */ (function () { + function BorderStyle(dict) { + this.dict = dict; + } + BorderStyle.prototype.W = function () { + var W = this.dict.lookup(PDFName.of('W')); + if (W instanceof PDFNumber) + return W; + return undefined; + }; + BorderStyle.prototype.getWidth = function () { + var _a, _b; + return (_b = (_a = this.W()) === null || _a === void 0 ? void 0 : _a.asNumber()) !== null && _b !== void 0 ? _b : 1; + }; + BorderStyle.prototype.setWidth = function (width) { + var W = this.dict.context.obj(width); + this.dict.set(PDFName.of('W'), W); + }; + BorderStyle.fromDict = function (dict) { return new BorderStyle(dict); }; + return BorderStyle; +}()); + +var PDFAnnotation = /** @class */ (function () { + function PDFAnnotation(dict) { + this.dict = dict; + } + // This is technically required by the PDF spec + PDFAnnotation.prototype.Rect = function () { + return this.dict.lookup(PDFName.of('Rect'), PDFArray); + }; + PDFAnnotation.prototype.AP = function () { + return this.dict.lookupMaybe(PDFName.of('AP'), PDFDict); + }; + PDFAnnotation.prototype.F = function () { + var numberOrRef = this.dict.lookup(PDFName.of('F')); + return this.dict.context.lookupMaybe(numberOrRef, PDFNumber); + }; + PDFAnnotation.prototype.getRectangle = function () { + var _a; + var Rect = this.Rect(); + return (_a = Rect === null || Rect === void 0 ? void 0 : Rect.asRectangle()) !== null && _a !== void 0 ? _a : { x: 0, y: 0, width: 0, height: 0 }; + }; + PDFAnnotation.prototype.setRectangle = function (rect) { + var x = rect.x, y = rect.y, width = rect.width, height = rect.height; + var Rect = this.dict.context.obj([x, y, x + width, y + height]); + this.dict.set(PDFName.of('Rect'), Rect); + }; + PDFAnnotation.prototype.getAppearanceState = function () { + var AS = this.dict.lookup(PDFName.of('AS')); + if (AS instanceof PDFName) + return AS; + return undefined; + }; + PDFAnnotation.prototype.setAppearanceState = function (state) { + this.dict.set(PDFName.of('AS'), state); + }; + PDFAnnotation.prototype.setAppearances = function (appearances) { + this.dict.set(PDFName.of('AP'), appearances); + }; + PDFAnnotation.prototype.ensureAP = function () { + var AP = this.AP(); + if (!AP) { + AP = this.dict.context.obj({}); + this.dict.set(PDFName.of('AP'), AP); + } + return AP; + }; + PDFAnnotation.prototype.getNormalAppearance = function () { + var AP = this.ensureAP(); + var N = AP.get(PDFName.of('N')); + if (N instanceof PDFRef || N instanceof PDFDict) + return N; + throw new Error("Unexpected N type: " + (N === null || N === void 0 ? void 0 : N.constructor.name)); + }; + /** @param appearance A PDFDict or PDFStream (direct or ref) */ + PDFAnnotation.prototype.setNormalAppearance = function (appearance) { + var AP = this.ensureAP(); + AP.set(PDFName.of('N'), appearance); + }; + /** @param appearance A PDFDict or PDFStream (direct or ref) */ + PDFAnnotation.prototype.setRolloverAppearance = function (appearance) { + var AP = this.ensureAP(); + AP.set(PDFName.of('R'), appearance); + }; + /** @param appearance A PDFDict or PDFStream (direct or ref) */ + PDFAnnotation.prototype.setDownAppearance = function (appearance) { + var AP = this.ensureAP(); + AP.set(PDFName.of('D'), appearance); + }; + PDFAnnotation.prototype.removeRolloverAppearance = function () { + var AP = this.AP(); + AP === null || AP === void 0 ? void 0 : AP.delete(PDFName.of('R')); + }; + PDFAnnotation.prototype.removeDownAppearance = function () { + var AP = this.AP(); + AP === null || AP === void 0 ? void 0 : AP.delete(PDFName.of('D')); + }; + PDFAnnotation.prototype.getAppearances = function () { + var AP = this.AP(); + if (!AP) + return undefined; + var N = AP.lookup(PDFName.of('N'), PDFDict, PDFStream); + var R = AP.lookupMaybe(PDFName.of('R'), PDFDict, PDFStream); + var D = AP.lookupMaybe(PDFName.of('D'), PDFDict, PDFStream); + return { normal: N, rollover: R, down: D }; + }; + PDFAnnotation.prototype.getFlags = function () { + var _a, _b; + return (_b = (_a = this.F()) === null || _a === void 0 ? void 0 : _a.asNumber()) !== null && _b !== void 0 ? _b : 0; + }; + PDFAnnotation.prototype.setFlags = function (flags) { + this.dict.set(PDFName.of('F'), PDFNumber.of(flags)); + }; + PDFAnnotation.prototype.hasFlag = function (flag) { + var flags = this.getFlags(); + return (flags & flag) !== 0; + }; + PDFAnnotation.prototype.setFlag = function (flag) { + var flags = this.getFlags(); + this.setFlags(flags | flag); + }; + PDFAnnotation.prototype.clearFlag = function (flag) { + var flags = this.getFlags(); + this.setFlags(flags & ~flag); + }; + PDFAnnotation.prototype.setFlagTo = function (flag, enable) { + if (enable) + this.setFlag(flag); + else + this.clearFlag(flag); + }; + PDFAnnotation.fromDict = function (dict) { return new PDFAnnotation(dict); }; + return PDFAnnotation; +}()); + +var AppearanceCharacteristics = /** @class */ (function () { + function AppearanceCharacteristics(dict) { + this.dict = dict; + } + AppearanceCharacteristics.prototype.R = function () { + var R = this.dict.lookup(PDFName.of('R')); + if (R instanceof PDFNumber) + return R; + return undefined; + }; + AppearanceCharacteristics.prototype.BC = function () { + var BC = this.dict.lookup(PDFName.of('BC')); + if (BC instanceof PDFArray) + return BC; + return undefined; + }; + AppearanceCharacteristics.prototype.BG = function () { + var BG = this.dict.lookup(PDFName.of('BG')); + if (BG instanceof PDFArray) + return BG; + return undefined; + }; + AppearanceCharacteristics.prototype.CA = function () { + var CA = this.dict.lookup(PDFName.of('CA')); + if (CA instanceof PDFHexString || CA instanceof PDFString) + return CA; + return undefined; + }; + AppearanceCharacteristics.prototype.RC = function () { + var RC = this.dict.lookup(PDFName.of('RC')); + if (RC instanceof PDFHexString || RC instanceof PDFString) + return RC; + return undefined; + }; + AppearanceCharacteristics.prototype.AC = function () { + var AC = this.dict.lookup(PDFName.of('AC')); + if (AC instanceof PDFHexString || AC instanceof PDFString) + return AC; + return undefined; + }; + AppearanceCharacteristics.prototype.getRotation = function () { + var _a; + return (_a = this.R()) === null || _a === void 0 ? void 0 : _a.asNumber(); + }; + AppearanceCharacteristics.prototype.getBorderColor = function () { + var BC = this.BC(); + if (!BC) + return undefined; + var components = []; + for (var idx = 0, len = BC === null || BC === void 0 ? void 0 : BC.size(); idx < len; idx++) { + var component = BC.get(idx); + if (component instanceof PDFNumber) + components.push(component.asNumber()); + } + return components; + }; + AppearanceCharacteristics.prototype.getBackgroundColor = function () { + var BG = this.BG(); + if (!BG) + return undefined; + var components = []; + for (var idx = 0, len = BG === null || BG === void 0 ? void 0 : BG.size(); idx < len; idx++) { + var component = BG.get(idx); + if (component instanceof PDFNumber) + components.push(component.asNumber()); + } + return components; + }; + AppearanceCharacteristics.prototype.getCaptions = function () { + var CA = this.CA(); + var RC = this.RC(); + var AC = this.AC(); + return { + normal: CA === null || CA === void 0 ? void 0 : CA.decodeText(), + rollover: RC === null || RC === void 0 ? void 0 : RC.decodeText(), + down: AC === null || AC === void 0 ? void 0 : AC.decodeText(), + }; + }; + AppearanceCharacteristics.prototype.setRotation = function (rotation) { + var R = this.dict.context.obj(rotation); + this.dict.set(PDFName.of('R'), R); + }; + AppearanceCharacteristics.prototype.setBorderColor = function (color) { + var BC = this.dict.context.obj(color); + this.dict.set(PDFName.of('BC'), BC); + }; + AppearanceCharacteristics.prototype.setBackgroundColor = function (color) { + var BG = this.dict.context.obj(color); + this.dict.set(PDFName.of('BG'), BG); + }; + AppearanceCharacteristics.prototype.setCaptions = function (captions) { + var CA = PDFHexString.fromText(captions.normal); + this.dict.set(PDFName.of('CA'), CA); + if (captions.rollover) { + var RC = PDFHexString.fromText(captions.rollover); + this.dict.set(PDFName.of('RC'), RC); + } + else { + this.dict.delete(PDFName.of('RC')); + } + if (captions.down) { + var AC = PDFHexString.fromText(captions.down); + this.dict.set(PDFName.of('AC'), AC); + } + else { + this.dict.delete(PDFName.of('AC')); + } + }; + AppearanceCharacteristics.fromDict = function (dict) { + return new AppearanceCharacteristics(dict); + }; + return AppearanceCharacteristics; +}()); + +var PDFWidgetAnnotation = /** @class */ (function (_super) { + __extends(PDFWidgetAnnotation, _super); + function PDFWidgetAnnotation() { + return _super !== null && _super.apply(this, arguments) || this; + } + PDFWidgetAnnotation.prototype.MK = function () { + var MK = this.dict.lookup(PDFName.of('MK')); + if (MK instanceof PDFDict) + return MK; + return undefined; + }; + PDFWidgetAnnotation.prototype.BS = function () { + var BS = this.dict.lookup(PDFName.of('BS')); + if (BS instanceof PDFDict) + return BS; + return undefined; + }; + PDFWidgetAnnotation.prototype.DA = function () { + var da = this.dict.lookup(PDFName.of('DA')); + if (da instanceof PDFString || da instanceof PDFHexString) + return da; + return undefined; + }; + PDFWidgetAnnotation.prototype.P = function () { + var P = this.dict.get(PDFName.of('P')); + if (P instanceof PDFRef) + return P; + return undefined; + }; + PDFWidgetAnnotation.prototype.setP = function (page) { + this.dict.set(PDFName.of('P'), page); + }; + PDFWidgetAnnotation.prototype.setDefaultAppearance = function (appearance) { + this.dict.set(PDFName.of('DA'), PDFString.of(appearance)); + }; + PDFWidgetAnnotation.prototype.getDefaultAppearance = function () { + var DA = this.DA(); + if (DA instanceof PDFHexString) { + return DA.decodeText(); + } + return DA === null || DA === void 0 ? void 0 : DA.asString(); + }; + PDFWidgetAnnotation.prototype.getAppearanceCharacteristics = function () { + var MK = this.MK(); + if (MK) + return AppearanceCharacteristics.fromDict(MK); + return undefined; + }; + PDFWidgetAnnotation.prototype.getOrCreateAppearanceCharacteristics = function () { + var MK = this.MK(); + if (MK) + return AppearanceCharacteristics.fromDict(MK); + var ac = AppearanceCharacteristics.fromDict(this.dict.context.obj({})); + this.dict.set(PDFName.of('MK'), ac.dict); + return ac; + }; + PDFWidgetAnnotation.prototype.getBorderStyle = function () { + var BS = this.BS(); + if (BS) + return BorderStyle.fromDict(BS); + return undefined; + }; + PDFWidgetAnnotation.prototype.getOrCreateBorderStyle = function () { + var BS = this.BS(); + if (BS) + return BorderStyle.fromDict(BS); + var bs = BorderStyle.fromDict(this.dict.context.obj({})); + this.dict.set(PDFName.of('BS'), bs.dict); + return bs; + }; + PDFWidgetAnnotation.prototype.getOnValue = function () { + var _a; + var normal = (_a = this.getAppearances()) === null || _a === void 0 ? void 0 : _a.normal; + if (normal instanceof PDFDict) { + var keys = normal.keys(); + for (var idx = 0, len = keys.length; idx < len; idx++) { + var key = keys[idx]; + if (key !== PDFName.of('Off')) + return key; + } + } + return undefined; + }; + PDFWidgetAnnotation.fromDict = function (dict) { + return new PDFWidgetAnnotation(dict); + }; + PDFWidgetAnnotation.create = function (context, parent) { + var dict = context.obj({ + Type: 'Annot', + Subtype: 'Widget', + Rect: [0, 0, 0, 0], + Parent: parent, + }); + return new PDFWidgetAnnotation(dict); + }; + return PDFWidgetAnnotation; +}(PDFAnnotation)); + +var PDFAcroTerminal = /** @class */ (function (_super) { + __extends(PDFAcroTerminal, _super); + function PDFAcroTerminal() { + return _super !== null && _super.apply(this, arguments) || this; + } + PDFAcroTerminal.prototype.FT = function () { + var nameOrRef = this.getInheritableAttribute(PDFName.of('FT')); + return this.dict.context.lookup(nameOrRef, PDFName); + }; + PDFAcroTerminal.prototype.getWidgets = function () { + var kidDicts = this.Kids(); + // This field is itself a widget + if (!kidDicts) + return [PDFWidgetAnnotation.fromDict(this.dict)]; + // This field's kids are its widgets + var widgets = new Array(kidDicts.size()); + for (var idx = 0, len = kidDicts.size(); idx < len; idx++) { + var dict = kidDicts.lookup(idx, PDFDict); + widgets[idx] = PDFWidgetAnnotation.fromDict(dict); + } + return widgets; + }; + PDFAcroTerminal.prototype.addWidget = function (ref) { + var Kids = this.normalizedEntries().Kids; + Kids.push(ref); + }; + PDFAcroTerminal.prototype.removeWidget = function (idx) { + var kidDicts = this.Kids(); + if (!kidDicts) { + // This field is itself a widget + if (idx !== 0) + throw new IndexOutOfBoundsError(idx, 0, 0); + this.setKids([]); + } + else { + // This field's kids are its widgets + if (idx < 0 || idx > kidDicts.size()) { + throw new IndexOutOfBoundsError(idx, 0, kidDicts.size()); + } + kidDicts.remove(idx); + } + }; + PDFAcroTerminal.prototype.normalizedEntries = function () { + var Kids = this.Kids(); + // If this field is itself a widget (because it was only rendered once in + // the document, so the field and widget properties were merged) then we + // add itself to the `Kids` array. The alternative would be to try + // splitting apart the widget properties and creating a separate object + // for them. + if (!Kids) { + Kids = this.dict.context.obj([this.ref]); + this.dict.set(PDFName.of('Kids'), Kids); + } + return { Kids: Kids }; + }; + PDFAcroTerminal.fromDict = function (dict, ref) { + return new PDFAcroTerminal(dict, ref); + }; + return PDFAcroTerminal; +}(PDFAcroField)); + +var PDFAcroButton = /** @class */ (function (_super) { + __extends(PDFAcroButton, _super); + function PDFAcroButton() { + return _super !== null && _super.apply(this, arguments) || this; + } + PDFAcroButton.prototype.Opt = function () { + return this.dict.lookupMaybe(PDFName.of('Opt'), PDFString, PDFHexString, PDFArray); + }; + PDFAcroButton.prototype.setOpt = function (opt) { + this.dict.set(PDFName.of('Opt'), this.dict.context.obj(opt)); + }; + PDFAcroButton.prototype.getExportValues = function () { + var opt = this.Opt(); + if (!opt) + return undefined; + if (opt instanceof PDFString || opt instanceof PDFHexString) { + return [opt]; + } + var values = []; + for (var idx = 0, len = opt.size(); idx < len; idx++) { + var value = opt.lookup(idx); + if (value instanceof PDFString || value instanceof PDFHexString) { + values.push(value); + } + } + return values; + }; + PDFAcroButton.prototype.removeExportValue = function (idx) { + var opt = this.Opt(); + if (!opt) + return; + if (opt instanceof PDFString || opt instanceof PDFHexString) { + if (idx !== 0) + throw new IndexOutOfBoundsError(idx, 0, 0); + this.setOpt([]); + } + else { + if (idx < 0 || idx > opt.size()) { + throw new IndexOutOfBoundsError(idx, 0, opt.size()); + } + opt.remove(idx); + } + }; + // Enforce use use of /Opt even if it isn't strictly necessary + PDFAcroButton.prototype.normalizeExportValues = function () { + var _a, _b, _c, _d; + var exportValues = (_a = this.getExportValues()) !== null && _a !== void 0 ? _a : []; + var Opt = []; + var widgets = this.getWidgets(); + for (var idx = 0, len = widgets.length; idx < len; idx++) { + var widget = widgets[idx]; + var exportVal = (_b = exportValues[idx]) !== null && _b !== void 0 ? _b : PDFHexString.fromText((_d = (_c = widget.getOnValue()) === null || _c === void 0 ? void 0 : _c.decodeText()) !== null && _d !== void 0 ? _d : ''); + Opt.push(exportVal); + } + this.setOpt(Opt); + }; + /** + * Reuses existing opt if one exists with the same value (assuming + * `useExistingIdx` is `true`). Returns index of existing (or new) opt. + */ + PDFAcroButton.prototype.addOpt = function (opt, useExistingOptIdx) { + var _a; + this.normalizeExportValues(); + var optText = opt.decodeText(); + var existingIdx; + if (useExistingOptIdx) { + var exportValues = (_a = this.getExportValues()) !== null && _a !== void 0 ? _a : []; + for (var idx = 0, len = exportValues.length; idx < len; idx++) { + var exportVal = exportValues[idx]; + if (exportVal.decodeText() === optText) + existingIdx = idx; + } + } + var Opt = this.Opt(); + Opt.push(opt); + return existingIdx !== null && existingIdx !== void 0 ? existingIdx : Opt.size() - 1; + }; + PDFAcroButton.prototype.addWidgetWithOpt = function (widget, opt, useExistingOptIdx) { + var optIdx = this.addOpt(opt, useExistingOptIdx); + var apStateValue = PDFName.of(String(optIdx)); + this.addWidget(widget); + return apStateValue; + }; + return PDFAcroButton; +}(PDFAcroTerminal)); + +var PDFAcroCheckBox = /** @class */ (function (_super) { + __extends(PDFAcroCheckBox, _super); + function PDFAcroCheckBox() { + return _super !== null && _super.apply(this, arguments) || this; + } + PDFAcroCheckBox.prototype.setValue = function (value) { + var _a; + var onValue = (_a = this.getOnValue()) !== null && _a !== void 0 ? _a : PDFName.of('Yes'); + if (value !== onValue && value !== PDFName.of('Off')) { + throw new InvalidAcroFieldValueError(); + } + this.dict.set(PDFName.of('V'), value); + var widgets = this.getWidgets(); + for (var idx = 0, len = widgets.length; idx < len; idx++) { + var widget = widgets[idx]; + var state = widget.getOnValue() === value ? value : PDFName.of('Off'); + widget.setAppearanceState(state); + } + }; + PDFAcroCheckBox.prototype.getValue = function () { + var v = this.V(); + if (v instanceof PDFName) + return v; + return PDFName.of('Off'); + }; + PDFAcroCheckBox.prototype.getOnValue = function () { + var widget = this.getWidgets()[0]; + return widget === null || widget === void 0 ? void 0 : widget.getOnValue(); + }; + PDFAcroCheckBox.fromDict = function (dict, ref) { + return new PDFAcroCheckBox(dict, ref); + }; + PDFAcroCheckBox.create = function (context) { + var dict = context.obj({ + FT: 'Btn', + Kids: [], + }); + var ref = context.register(dict); + return new PDFAcroCheckBox(dict, ref); + }; + return PDFAcroCheckBox; +}(PDFAcroButton)); + +var flag = function (bitIndex) { return 1 << bitIndex; }; +/** From PDF spec table 221 */ +var AcroFieldFlags; +(function (AcroFieldFlags) { + /** + * If set, the user may not change the value of the field. Any associated + * widget annotations will not interact with the user; that is, they will not + * respond to mouse clicks or change their appearance in response to mouse + * motions. This flag is useful for fields whose values are computed or + * imported from a database. + */ + AcroFieldFlags[AcroFieldFlags["ReadOnly"] = flag(1 - 1)] = "ReadOnly"; + /** + * If set, the field shall have a value at the time it is exported by a + * submit-form action (see 12.7.5.2, "Submit-Form Action"). + */ + AcroFieldFlags[AcroFieldFlags["Required"] = flag(2 - 1)] = "Required"; + /** + * If set, the field shall not be exported by a submit-form action + * (see 12.7.5.2, "Submit-Form Action"). + */ + AcroFieldFlags[AcroFieldFlags["NoExport"] = flag(3 - 1)] = "NoExport"; +})(AcroFieldFlags || (AcroFieldFlags = {})); +/** From PDF spec table 226 */ +var AcroButtonFlags; +(function (AcroButtonFlags) { + /** + * (Radio buttons only) If set, exactly one radio button shall be selected at + * all times; selecting the currently selected button has no effect. If clear, + * clicking the selected button deselects it, leaving no button selected. + */ + AcroButtonFlags[AcroButtonFlags["NoToggleToOff"] = flag(15 - 1)] = "NoToggleToOff"; + /** + * If set, the field is a set of radio buttons; if clear, the field is a check + * box. This flag may be set only if the Pushbutton flag is clear. + */ + AcroButtonFlags[AcroButtonFlags["Radio"] = flag(16 - 1)] = "Radio"; + /** + * If set, the field is a pushbutton that does not retain a permanent value. + */ + AcroButtonFlags[AcroButtonFlags["PushButton"] = flag(17 - 1)] = "PushButton"; + /** + * If set, a group of radio buttons within a radio button field that use the + * same value for the on state will turn on and off in unison; that is if one + * is checked, they are all checked. If clear, the buttons are mutually + * exclusive (the same behavior as HTML radio buttons). + */ + AcroButtonFlags[AcroButtonFlags["RadiosInUnison"] = flag(26 - 1)] = "RadiosInUnison"; +})(AcroButtonFlags || (AcroButtonFlags = {})); +/** From PDF spec table 228 */ +var AcroTextFlags; +(function (AcroTextFlags) { + /** + * If set, the field may contain multiple lines of text; if clear, the field's + * text shall be restricted to a single line. + */ + AcroTextFlags[AcroTextFlags["Multiline"] = flag(13 - 1)] = "Multiline"; + /** + * If set, the field is intended for entering a secure password that should + * not be echoed visibly to the screen. Characters typed from the keyboard + * shall instead be echoed in some unreadable form, such as asterisks or + * bullet characters. + * > NOTE To protect password confidentiality, readers should never store + * > the value of the text field in the PDF file if this flag is set. + */ + AcroTextFlags[AcroTextFlags["Password"] = flag(14 - 1)] = "Password"; + /** + * If set, the text entered in the field represents the pathname of a file + * whose contents shall be submitted as the value of the field. + */ + AcroTextFlags[AcroTextFlags["FileSelect"] = flag(21 - 1)] = "FileSelect"; + /** + * If set, text entered in the field shall not be spell-checked. + */ + AcroTextFlags[AcroTextFlags["DoNotSpellCheck"] = flag(23 - 1)] = "DoNotSpellCheck"; + /** + * If set, the field shall not scroll (horizontally for single-line fields, + * vertically for multiple-line fields) to accommodate more text than fits + * within its annotation rectangle. Once the field is full, no further text + * shall be accepted for interactive form filling; for non-interactive form + * filling, the filler should take care not to add more character than will + * visibly fit in the defined area. + */ + AcroTextFlags[AcroTextFlags["DoNotScroll"] = flag(24 - 1)] = "DoNotScroll"; + /** + * May be set only if the MaxLen entry is present in the text field dictionary + * (see Table 229) and if the Multiline, Password, and FileSelect flags are + * clear. If set, the field shall be automatically divided into as many + * equally spaced positions, or combs, as the value of MaxLen, and the text + * is laid out into those combs. + */ + AcroTextFlags[AcroTextFlags["Comb"] = flag(25 - 1)] = "Comb"; + /** + * If set, the value of this field shall be a rich text string + * (see 12.7.3.4, "Rich Text Strings"). If the field has a value, the RV + * entry of the field dictionary (Table 222) shall specify the rich text + * string. + */ + AcroTextFlags[AcroTextFlags["RichText"] = flag(26 - 1)] = "RichText"; +})(AcroTextFlags || (AcroTextFlags = {})); +/** From PDF spec table 230 */ +var AcroChoiceFlags; +(function (AcroChoiceFlags) { + /** + * If set, the field is a combo box; if clear, the field is a list box. + */ + AcroChoiceFlags[AcroChoiceFlags["Combo"] = flag(18 - 1)] = "Combo"; + /** + * If set, the combo box shall include an editable text box as well as a + * drop-down list; if clear, it shall include only a drop-down list. This + * flag shall be used only if the Combo flag is set. + */ + AcroChoiceFlags[AcroChoiceFlags["Edit"] = flag(19 - 1)] = "Edit"; + /** + * If set, the field's option items shall be sorted alphabetically. This flag + * is intended for use by writers, not by readers. Conforming readers shall + * display the options in the order in which they occur in the Opt array + * (see Table 231). + */ + AcroChoiceFlags[AcroChoiceFlags["Sort"] = flag(20 - 1)] = "Sort"; + /** + * If set, more than one of the field's option items may be selected + * simultaneously; if clear, at most one item shall be selected. + */ + AcroChoiceFlags[AcroChoiceFlags["MultiSelect"] = flag(22 - 1)] = "MultiSelect"; + /** + * If set, text entered in the field shall not be spell-checked. This flag + * shall not be used unless the Combo and Edit flags are both set. + */ + AcroChoiceFlags[AcroChoiceFlags["DoNotSpellCheck"] = flag(23 - 1)] = "DoNotSpellCheck"; + /** + * If set, the new value shall be committed as soon as a selection is made + * (commonly with the pointing device). In this case, supplying a value for + * a field involves three actions: selecting the field for fill-in, + * selecting a choice for the fill-in value, and leaving that field, which + * finalizes or "commits" the data choice and triggers any actions associated + * with the entry or changing of this data. If this flag is on, then + * processing does not wait for leaving the field action to occur, but + * immediately proceeds to the third step. + * + * This option enables applications to perform an action once a selection is + * made, without requiring the user to exit the field. If clear, the new + * value is not committed until the user exits the field. + */ + AcroChoiceFlags[AcroChoiceFlags["CommitOnSelChange"] = flag(27 - 1)] = "CommitOnSelChange"; +})(AcroChoiceFlags || (AcroChoiceFlags = {})); + +var PDFAcroChoice = /** @class */ (function (_super) { + __extends(PDFAcroChoice, _super); + function PDFAcroChoice() { + return _super !== null && _super.apply(this, arguments) || this; + } + PDFAcroChoice.prototype.setValues = function (values) { + if (this.hasFlag(AcroChoiceFlags.Combo) && + !this.hasFlag(AcroChoiceFlags.Edit) && + !this.valuesAreValid(values)) { + throw new InvalidAcroFieldValueError(); + } + if (values.length === 0) { + this.dict.delete(PDFName.of('V')); + } + if (values.length === 1) { + this.dict.set(PDFName.of('V'), values[0]); + } + if (values.length > 1) { + if (!this.hasFlag(AcroChoiceFlags.MultiSelect)) { + throw new MultiSelectValueError(); + } + this.dict.set(PDFName.of('V'), this.dict.context.obj(values)); + } + this.updateSelectedIndices(values); + }; + PDFAcroChoice.prototype.valuesAreValid = function (values) { + var options = this.getOptions(); + var _loop_1 = function (idx, len) { + var val = values[idx].decodeText(); + if (!options.find(function (o) { return val === (o.display || o.value).decodeText(); })) { + return { value: false }; + } + }; + for (var idx = 0, len = values.length; idx < len; idx++) { + var state_1 = _loop_1(idx); + if (typeof state_1 === "object") + return state_1.value; + } + return true; + }; + PDFAcroChoice.prototype.updateSelectedIndices = function (values) { + if (values.length > 1) { + var indices = new Array(values.length); + var options = this.getOptions(); + var _loop_2 = function (idx, len) { + var val = values[idx].decodeText(); + indices[idx] = options.findIndex(function (o) { return val === (o.display || o.value).decodeText(); }); + }; + for (var idx = 0, len = values.length; idx < len; idx++) { + _loop_2(idx, len); + } + this.dict.set(PDFName.of('I'), this.dict.context.obj(indices.sort())); + } + else { + this.dict.delete(PDFName.of('I')); + } + }; + PDFAcroChoice.prototype.getValues = function () { + var v = this.V(); + if (v instanceof PDFString || v instanceof PDFHexString) + return [v]; + if (v instanceof PDFArray) { + var values = []; + for (var idx = 0, len = v.size(); idx < len; idx++) { + var value = v.lookup(idx); + if (value instanceof PDFString || value instanceof PDFHexString) { + values.push(value); + } + } + return values; + } + return []; + }; + PDFAcroChoice.prototype.Opt = function () { + return this.dict.lookupMaybe(PDFName.of('Opt'), PDFString, PDFHexString, PDFArray); + }; + PDFAcroChoice.prototype.setOptions = function (options) { + var newOpt = new Array(options.length); + for (var idx = 0, len = options.length; idx < len; idx++) { + var _a = options[idx], value = _a.value, display = _a.display; + newOpt[idx] = this.dict.context.obj([value, display || value]); + } + this.dict.set(PDFName.of('Opt'), this.dict.context.obj(newOpt)); + }; + PDFAcroChoice.prototype.getOptions = function () { + var Opt = this.Opt(); + // Not supposed to happen - Opt _should_ always be `PDFArray | undefined` + if (Opt instanceof PDFString || Opt instanceof PDFHexString) { + return [{ value: Opt, display: Opt }]; + } + if (Opt instanceof PDFArray) { + var res = []; + for (var idx = 0, len = Opt.size(); idx < len; idx++) { + var item = Opt.lookup(idx); + // If `item` is a string, use that as both the export and text value + if (item instanceof PDFString || item instanceof PDFHexString) { + res.push({ value: item, display: item }); + } + // If `item` is an array of one, treat it the same as just a string, + // if it's an array of two then `item[0]` is the export value and + // `item[1]` is the text value + if (item instanceof PDFArray) { + if (item.size() > 0) { + var first = item.lookup(0, PDFString, PDFHexString); + var second = item.lookupMaybe(1, PDFString, PDFHexString); + res.push({ value: first, display: second || first }); + } + } + } + return res; + } + return []; + }; + return PDFAcroChoice; +}(PDFAcroTerminal)); + +var PDFAcroComboBox = /** @class */ (function (_super) { + __extends(PDFAcroComboBox, _super); + function PDFAcroComboBox() { + return _super !== null && _super.apply(this, arguments) || this; + } + PDFAcroComboBox.fromDict = function (dict, ref) { + return new PDFAcroComboBox(dict, ref); + }; + PDFAcroComboBox.create = function (context) { + var dict = context.obj({ + FT: 'Ch', + Ff: AcroChoiceFlags.Combo, + Kids: [], + }); + var ref = context.register(dict); + return new PDFAcroComboBox(dict, ref); + }; + return PDFAcroComboBox; +}(PDFAcroChoice)); + +var PDFAcroNonTerminal = /** @class */ (function (_super) { + __extends(PDFAcroNonTerminal, _super); + function PDFAcroNonTerminal() { + return _super !== null && _super.apply(this, arguments) || this; + } + PDFAcroNonTerminal.prototype.addField = function (field) { + var Kids = this.normalizedEntries().Kids; + Kids === null || Kids === void 0 ? void 0 : Kids.push(field); + }; + PDFAcroNonTerminal.prototype.normalizedEntries = function () { + var Kids = this.Kids(); + if (!Kids) { + Kids = this.dict.context.obj([]); + this.dict.set(PDFName.of('Kids'), Kids); + } + return { Kids: Kids }; + }; + PDFAcroNonTerminal.fromDict = function (dict, ref) { + return new PDFAcroNonTerminal(dict, ref); + }; + PDFAcroNonTerminal.create = function (context) { + var dict = context.obj({}); + var ref = context.register(dict); + return new PDFAcroNonTerminal(dict, ref); + }; + return PDFAcroNonTerminal; +}(PDFAcroField)); + +var PDFAcroSignature = /** @class */ (function (_super) { + __extends(PDFAcroSignature, _super); + function PDFAcroSignature() { + return _super !== null && _super.apply(this, arguments) || this; + } + PDFAcroSignature.fromDict = function (dict, ref) { + return new PDFAcroSignature(dict, ref); + }; + return PDFAcroSignature; +}(PDFAcroTerminal)); + +var PDFAcroText = /** @class */ (function (_super) { + __extends(PDFAcroText, _super); + function PDFAcroText() { + return _super !== null && _super.apply(this, arguments) || this; + } + PDFAcroText.prototype.MaxLen = function () { + var maxLen = this.dict.lookup(PDFName.of('MaxLen')); + if (maxLen instanceof PDFNumber) + return maxLen; + return undefined; + }; + PDFAcroText.prototype.Q = function () { + var q = this.dict.lookup(PDFName.of('Q')); + if (q instanceof PDFNumber) + return q; + return undefined; + }; + PDFAcroText.prototype.setMaxLength = function (maxLength) { + this.dict.set(PDFName.of('MaxLen'), PDFNumber.of(maxLength)); + }; + PDFAcroText.prototype.removeMaxLength = function () { + this.dict.delete(PDFName.of('MaxLen')); + }; + PDFAcroText.prototype.getMaxLength = function () { + var _a; + return (_a = this.MaxLen()) === null || _a === void 0 ? void 0 : _a.asNumber(); + }; + PDFAcroText.prototype.setQuadding = function (quadding) { + this.dict.set(PDFName.of('Q'), PDFNumber.of(quadding)); + }; + PDFAcroText.prototype.getQuadding = function () { + var _a; + return (_a = this.Q()) === null || _a === void 0 ? void 0 : _a.asNumber(); + }; + PDFAcroText.prototype.setValue = function (value) { + this.dict.set(PDFName.of('V'), value); + // const widgets = this.getWidgets(); + // for (let idx = 0, len = widgets.length; idx < len; idx++) { + // const widget = widgets[idx]; + // const state = widget.getOnValue() === value ? value : PDFName.of('Off'); + // widget.setAppearanceState(state); + // } + }; + PDFAcroText.prototype.removeValue = function () { + this.dict.delete(PDFName.of('V')); + }; + PDFAcroText.prototype.getValue = function () { + var v = this.V(); + if (v instanceof PDFString || v instanceof PDFHexString) + return v; + return undefined; + }; + PDFAcroText.fromDict = function (dict, ref) { return new PDFAcroText(dict, ref); }; + PDFAcroText.create = function (context) { + var dict = context.obj({ + FT: 'Tx', + Kids: [], + }); + var ref = context.register(dict); + return new PDFAcroText(dict, ref); + }; + return PDFAcroText; +}(PDFAcroTerminal)); + +var PDFAcroPushButton = /** @class */ (function (_super) { + __extends(PDFAcroPushButton, _super); + function PDFAcroPushButton() { + return _super !== null && _super.apply(this, arguments) || this; + } + PDFAcroPushButton.fromDict = function (dict, ref) { + return new PDFAcroPushButton(dict, ref); + }; + PDFAcroPushButton.create = function (context) { + var dict = context.obj({ + FT: 'Btn', + Ff: AcroButtonFlags.PushButton, + Kids: [], + }); + var ref = context.register(dict); + return new PDFAcroPushButton(dict, ref); + }; + return PDFAcroPushButton; +}(PDFAcroButton)); + +var PDFAcroRadioButton = /** @class */ (function (_super) { + __extends(PDFAcroRadioButton, _super); + function PDFAcroRadioButton() { + return _super !== null && _super.apply(this, arguments) || this; + } + PDFAcroRadioButton.prototype.setValue = function (value) { + var onValues = this.getOnValues(); + if (!onValues.includes(value) && value !== PDFName.of('Off')) { + throw new InvalidAcroFieldValueError(); + } + this.dict.set(PDFName.of('V'), value); + var widgets = this.getWidgets(); + for (var idx = 0, len = widgets.length; idx < len; idx++) { + var widget = widgets[idx]; + var state = widget.getOnValue() === value ? value : PDFName.of('Off'); + widget.setAppearanceState(state); + } + }; + PDFAcroRadioButton.prototype.getValue = function () { + var v = this.V(); + if (v instanceof PDFName) + return v; + return PDFName.of('Off'); + }; + PDFAcroRadioButton.prototype.getOnValues = function () { + var widgets = this.getWidgets(); + var onValues = []; + for (var idx = 0, len = widgets.length; idx < len; idx++) { + var onValue = widgets[idx].getOnValue(); + if (onValue) + onValues.push(onValue); + } + return onValues; + }; + PDFAcroRadioButton.fromDict = function (dict, ref) { + return new PDFAcroRadioButton(dict, ref); + }; + PDFAcroRadioButton.create = function (context) { + var dict = context.obj({ + FT: 'Btn', + Ff: AcroButtonFlags.Radio, + Kids: [], + }); + var ref = context.register(dict); + return new PDFAcroRadioButton(dict, ref); + }; + return PDFAcroRadioButton; +}(PDFAcroButton)); + +var PDFAcroListBox = /** @class */ (function (_super) { + __extends(PDFAcroListBox, _super); + function PDFAcroListBox() { + return _super !== null && _super.apply(this, arguments) || this; + } + PDFAcroListBox.fromDict = function (dict, ref) { + return new PDFAcroListBox(dict, ref); + }; + PDFAcroListBox.create = function (context) { + var dict = context.obj({ + FT: 'Ch', + Kids: [], + }); + var ref = context.register(dict); + return new PDFAcroListBox(dict, ref); + }; + return PDFAcroListBox; +}(PDFAcroChoice)); + +var createPDFAcroFields = function (kidDicts) { + if (!kidDicts) + return []; + var kids = []; + for (var idx = 0, len = kidDicts.size(); idx < len; idx++) { + var ref = kidDicts.get(idx); + var dict = kidDicts.lookup(idx); + // if (dict instanceof PDFDict) kids.push(PDFAcroField.fromDict(dict)); + if (ref instanceof PDFRef && dict instanceof PDFDict) { + kids.push([createPDFAcroField(dict, ref), ref]); + } + } + return kids; +}; +var createPDFAcroField = function (dict, ref) { + var isNonTerminal = isNonTerminalAcroField(dict); + if (isNonTerminal) + return PDFAcroNonTerminal.fromDict(dict, ref); + return createPDFAcroTerminal(dict, ref); +}; +// TODO: Maybe just check if the dict is *not* a widget? That might be better. +// According to the PDF spec: +// +// > A field's children in the hierarchy may also include widget annotations +// > that define its appearance on the page. A field that has children that +// > are fields is called a non-terminal field. A field that does not have +// > children that are fields is called a terminal field. +// +// The spec is not entirely clear about how to determine whether a given +// dictionary represents an acrofield or a widget annotation. So we will assume +// that a dictionary is an acrofield if it is a member of the `/Kids` array +// and it contains a `/T` entry (widgets do not have `/T` entries). This isn't +// a bullet proof solution, because the `/T` entry is technically defined as +// optional for acrofields by the PDF spec. But in practice all acrofields seem +// to have a `/T` entry defined. +var isNonTerminalAcroField = function (dict) { + var kids = dict.lookup(PDFName.of('Kids')); + if (kids instanceof PDFArray) { + for (var idx = 0, len = kids.size(); idx < len; idx++) { + var kid = kids.lookup(idx); + var kidIsField = kid instanceof PDFDict && kid.has(PDFName.of('T')); + if (kidIsField) + return true; + } + } + return false; +}; +var createPDFAcroTerminal = function (dict, ref) { + var ftNameOrRef = getInheritableAttribute(dict, PDFName.of('FT')); + var type = dict.context.lookup(ftNameOrRef, PDFName); + if (type === PDFName.of('Btn')) + return createPDFAcroButton(dict, ref); + if (type === PDFName.of('Ch')) + return createPDFAcroChoice(dict, ref); + if (type === PDFName.of('Tx')) + return PDFAcroText.fromDict(dict, ref); + if (type === PDFName.of('Sig')) + return PDFAcroSignature.fromDict(dict, ref); + // We should never reach this line. But there are a lot of weird PDFs out + // there. So, just to be safe, we'll try to handle things gracefully instead + // of throwing an error. + return PDFAcroTerminal.fromDict(dict, ref); +}; +var createPDFAcroButton = function (dict, ref) { + var _a; + var ffNumberOrRef = getInheritableAttribute(dict, PDFName.of('Ff')); + var ffNumber = dict.context.lookupMaybe(ffNumberOrRef, PDFNumber); + var flags = (_a = ffNumber === null || ffNumber === void 0 ? void 0 : ffNumber.asNumber()) !== null && _a !== void 0 ? _a : 0; + if (flagIsSet(flags, AcroButtonFlags.PushButton)) { + return PDFAcroPushButton.fromDict(dict, ref); + } + else if (flagIsSet(flags, AcroButtonFlags.Radio)) { + return PDFAcroRadioButton.fromDict(dict, ref); + } + else { + return PDFAcroCheckBox.fromDict(dict, ref); + } +}; +var createPDFAcroChoice = function (dict, ref) { + var _a; + var ffNumberOrRef = getInheritableAttribute(dict, PDFName.of('Ff')); + var ffNumber = dict.context.lookupMaybe(ffNumberOrRef, PDFNumber); + var flags = (_a = ffNumber === null || ffNumber === void 0 ? void 0 : ffNumber.asNumber()) !== null && _a !== void 0 ? _a : 0; + if (flagIsSet(flags, AcroChoiceFlags.Combo)) { + return PDFAcroComboBox.fromDict(dict, ref); + } + else { + return PDFAcroListBox.fromDict(dict, ref); + } +}; +var flagIsSet = function (flags, flag) { + return (flags & flag) !== 0; +}; +var getInheritableAttribute = function (startNode, name) { + var attribute; + ascend(startNode, function (node) { + if (!attribute) + attribute = node.get(name); + }); + return attribute; +}; +var ascend = function (startNode, visitor) { + visitor(startNode); + var Parent = startNode.lookupMaybe(PDFName.of('Parent'), PDFDict); + if (Parent) + ascend(Parent, visitor); +}; + +var PDFAcroForm = /** @class */ (function () { + function PDFAcroForm(dict) { + this.dict = dict; + } + PDFAcroForm.prototype.Fields = function () { + var fields = this.dict.lookup(PDFName.of('Fields')); + if (fields instanceof PDFArray) + return fields; + return undefined; + }; + PDFAcroForm.prototype.getFields = function () { + var Fields = this.normalizedEntries().Fields; + var fields = new Array(Fields.size()); + for (var idx = 0, len = Fields.size(); idx < len; idx++) { + var ref = Fields.get(idx); + var dict = Fields.lookup(idx, PDFDict); + fields[idx] = [createPDFAcroField(dict, ref), ref]; + } + return fields; + }; + PDFAcroForm.prototype.getAllFields = function () { + var allFields = []; + var pushFields = function (fields) { + if (!fields) + return; + for (var idx = 0, len = fields.length; idx < len; idx++) { + var field = fields[idx]; + allFields.push(field); + var fieldModel = field[0]; + if (fieldModel instanceof PDFAcroNonTerminal) { + pushFields(createPDFAcroFields(fieldModel.Kids())); + } + } + }; + pushFields(this.getFields()); + return allFields; + }; + PDFAcroForm.prototype.addField = function (field) { + var Fields = this.normalizedEntries().Fields; + Fields === null || Fields === void 0 ? void 0 : Fields.push(field); + }; + PDFAcroForm.prototype.removeField = function (field) { + var parent = field.getParent(); + var fields = parent === undefined ? this.normalizedEntries().Fields : parent.Kids(); + var index = fields === null || fields === void 0 ? void 0 : fields.indexOf(field.ref); + if (fields === undefined || index === undefined) { + throw new Error("Tried to remove inexistent field " + field.getFullyQualifiedName()); + } + fields.remove(index); + if (parent !== undefined && fields.size() === 0) { + this.removeField(parent); + } + }; + PDFAcroForm.prototype.normalizedEntries = function () { + var Fields = this.Fields(); + if (!Fields) { + Fields = this.dict.context.obj([]); + this.dict.set(PDFName.of('Fields'), Fields); + } + return { Fields: Fields }; + }; + PDFAcroForm.fromDict = function (dict) { return new PDFAcroForm(dict); }; + PDFAcroForm.create = function (context) { + var dict = context.obj({ Fields: [] }); + return new PDFAcroForm(dict); + }; + return PDFAcroForm; +}()); + +var PDFCatalog = /** @class */ (function (_super) { + __extends(PDFCatalog, _super); + function PDFCatalog() { + return _super !== null && _super.apply(this, arguments) || this; + } + PDFCatalog.prototype.Pages = function () { + return this.lookup(PDFName.of('Pages'), PDFDict); + }; + PDFCatalog.prototype.AcroForm = function () { + return this.lookupMaybe(PDFName.of('AcroForm'), PDFDict); + }; + PDFCatalog.prototype.getAcroForm = function () { + var dict = this.AcroForm(); + if (!dict) + return undefined; + return PDFAcroForm.fromDict(dict); + }; + PDFCatalog.prototype.getOrCreateAcroForm = function () { + var acroForm = this.getAcroForm(); + if (!acroForm) { + acroForm = PDFAcroForm.create(this.context); + var acroFormRef = this.context.register(acroForm.dict); + this.set(PDFName.of('AcroForm'), acroFormRef); + } + return acroForm; + }; + PDFCatalog.prototype.ViewerPreferences = function () { + return this.lookupMaybe(PDFName.of('ViewerPreferences'), PDFDict); + }; + PDFCatalog.prototype.getViewerPreferences = function () { + var dict = this.ViewerPreferences(); + if (!dict) + return undefined; + return ViewerPreferences.fromDict(dict); + }; + PDFCatalog.prototype.getOrCreateViewerPreferences = function () { + var viewerPrefs = this.getViewerPreferences(); + if (!viewerPrefs) { + viewerPrefs = ViewerPreferences.create(this.context); + var viewerPrefsRef = this.context.register(viewerPrefs.dict); + this.set(PDFName.of('ViewerPreferences'), viewerPrefsRef); + } + return viewerPrefs; + }; + /** + * Inserts the given ref as a leaf node of this catalog's page tree at the + * specified index (zero-based). Also increments the `Count` of each node in + * the page tree hierarchy to accomodate the new page. + * + * Returns the ref of the PDFPageTree node into which `leafRef` was inserted. + */ + PDFCatalog.prototype.insertLeafNode = function (leafRef, index) { + var pagesRef = this.get(PDFName.of('Pages')); + var maybeParentRef = this.Pages().insertLeafNode(leafRef, index); + return maybeParentRef || pagesRef; + }; + PDFCatalog.prototype.removeLeafNode = function (index) { + this.Pages().removeLeafNode(index); + }; + PDFCatalog.withContextAndPages = function (context, pages) { + var dict = new Map(); + dict.set(PDFName.of('Type'), PDFName.of('Catalog')); + dict.set(PDFName.of('Pages'), pages); + return new PDFCatalog(dict, context); + }; + PDFCatalog.fromMapWithContext = function (map, context) { + return new PDFCatalog(map, context); + }; + return PDFCatalog; +}(PDFDict)); + +var PDFPageTree = /** @class */ (function (_super) { + __extends(PDFPageTree, _super); + function PDFPageTree() { + return _super !== null && _super.apply(this, arguments) || this; + } + PDFPageTree.prototype.Parent = function () { + return this.lookup(PDFName.of('Parent')); + }; + PDFPageTree.prototype.Kids = function () { + return this.lookup(PDFName.of('Kids'), PDFArray); + }; + PDFPageTree.prototype.Count = function () { + return this.lookup(PDFName.of('Count'), PDFNumber); + }; + PDFPageTree.prototype.pushTreeNode = function (treeRef) { + var Kids = this.Kids(); + Kids.push(treeRef); + }; + PDFPageTree.prototype.pushLeafNode = function (leafRef) { + var Kids = this.Kids(); + this.insertLeafKid(Kids.size(), leafRef); + }; + /** + * Inserts the given ref as a leaf node of this page tree at the specified + * index (zero-based). Also increments the `Count` of each page tree in the + * hierarchy to accomodate the new page. + * + * Returns the ref of the PDFPageTree node into which `leafRef` was inserted, + * or `undefined` if it was inserted into the root node (the PDFPageTree upon + * which the method was first called). + */ + PDFPageTree.prototype.insertLeafNode = function (leafRef, targetIndex) { + var Kids = this.Kids(); + var Count = this.Count().asNumber(); + if (targetIndex > Count) { + throw new InvalidTargetIndexError(targetIndex, Count); + } + var leafsRemainingUntilTarget = targetIndex; + for (var idx = 0, len = Kids.size(); idx < len; idx++) { + if (leafsRemainingUntilTarget === 0) { + // Insert page and return + this.insertLeafKid(idx, leafRef); + return undefined; + } + var kidRef = Kids.get(idx); + var kid = this.context.lookup(kidRef); + if (kid instanceof PDFPageTree) { + if (kid.Count().asNumber() > leafsRemainingUntilTarget) { + // Dig in + return (kid.insertLeafNode(leafRef, leafsRemainingUntilTarget) || kidRef); + } + else { + // Move on + leafsRemainingUntilTarget -= kid.Count().asNumber(); + } + } + if (kid instanceof PDFPageLeaf) { + // Move on + leafsRemainingUntilTarget -= 1; + } + } + if (leafsRemainingUntilTarget === 0) { + // Insert page at the end and return + this.insertLeafKid(Kids.size(), leafRef); + return undefined; + } + // Should never get here if `targetIndex` is valid + throw new CorruptPageTreeError(targetIndex, 'insertLeafNode'); + }; + /** + * Removes the leaf node at the specified index (zero-based) from this page + * tree. Also decrements the `Count` of each page tree in the hierarchy to + * account for the removed page. + * + * If `prune` is true, then intermediate tree nodes will be removed from the + * tree if they contain 0 children after the leaf node is removed. + */ + PDFPageTree.prototype.removeLeafNode = function (targetIndex, prune) { + if (prune === void 0) { prune = true; } + var Kids = this.Kids(); + var Count = this.Count().asNumber(); + if (targetIndex >= Count) { + throw new InvalidTargetIndexError(targetIndex, Count); + } + var leafsRemainingUntilTarget = targetIndex; + for (var idx = 0, len = Kids.size(); idx < len; idx++) { + var kidRef = Kids.get(idx); + var kid = this.context.lookup(kidRef); + if (kid instanceof PDFPageTree) { + if (kid.Count().asNumber() > leafsRemainingUntilTarget) { + // Dig in + kid.removeLeafNode(leafsRemainingUntilTarget, prune); + if (prune && kid.Kids().size() === 0) + Kids.remove(idx); + return; + } + else { + // Move on + leafsRemainingUntilTarget -= kid.Count().asNumber(); + } + } + if (kid instanceof PDFPageLeaf) { + if (leafsRemainingUntilTarget === 0) { + // Remove page and return + this.removeKid(idx); + return; + } + else { + // Move on + leafsRemainingUntilTarget -= 1; + } + } + } + // Should never get here if `targetIndex` is valid + throw new CorruptPageTreeError(targetIndex, 'removeLeafNode'); + }; + PDFPageTree.prototype.ascend = function (visitor) { + visitor(this); + var Parent = this.Parent(); + if (Parent) + Parent.ascend(visitor); + }; + /** Performs a Post-Order traversal of this page tree */ + PDFPageTree.prototype.traverse = function (visitor) { + var Kids = this.Kids(); + for (var idx = 0, len = Kids.size(); idx < len; idx++) { + var kidRef = Kids.get(idx); + var kid = this.context.lookup(kidRef); + if (kid instanceof PDFPageTree) + kid.traverse(visitor); + visitor(kid, kidRef); + } + }; + PDFPageTree.prototype.insertLeafKid = function (kidIdx, leafRef) { + var Kids = this.Kids(); + this.ascend(function (node) { + var newCount = node.Count().asNumber() + 1; + node.set(PDFName.of('Count'), PDFNumber.of(newCount)); + }); + Kids.insert(kidIdx, leafRef); + }; + PDFPageTree.prototype.removeKid = function (kidIdx) { + var Kids = this.Kids(); + var kid = Kids.lookup(kidIdx); + if (kid instanceof PDFPageLeaf) { + this.ascend(function (node) { + var newCount = node.Count().asNumber() - 1; + node.set(PDFName.of('Count'), PDFNumber.of(newCount)); + }); + } + Kids.remove(kidIdx); + }; + PDFPageTree.withContext = function (context, parent) { + var dict = new Map(); + dict.set(PDFName.of('Type'), PDFName.of('Pages')); + dict.set(PDFName.of('Kids'), context.obj([])); + dict.set(PDFName.of('Count'), context.obj(0)); + if (parent) + dict.set(PDFName.of('Parent'), parent); + return new PDFPageTree(dict, context); + }; + PDFPageTree.fromMapWithContext = function (map, context) { + return new PDFPageTree(map, context); + }; + return PDFPageTree; +}(PDFDict)); + +var IsDigit = new Uint8Array(256); +IsDigit[CharCodes$1.Zero] = 1; +IsDigit[CharCodes$1.One] = 1; +IsDigit[CharCodes$1.Two] = 1; +IsDigit[CharCodes$1.Three] = 1; +IsDigit[CharCodes$1.Four] = 1; +IsDigit[CharCodes$1.Five] = 1; +IsDigit[CharCodes$1.Six] = 1; +IsDigit[CharCodes$1.Seven] = 1; +IsDigit[CharCodes$1.Eight] = 1; +IsDigit[CharCodes$1.Nine] = 1; +var IsNumericPrefix = new Uint8Array(256); +IsNumericPrefix[CharCodes$1.Period] = 1; +IsNumericPrefix[CharCodes$1.Plus] = 1; +IsNumericPrefix[CharCodes$1.Minus] = 1; +var IsNumeric = new Uint8Array(256); +for (var idx$2 = 0, len$1 = 256; idx$2 < len$1; idx$2++) { + IsNumeric[idx$2] = IsDigit[idx$2] || IsNumericPrefix[idx$2] ? 1 : 0; +} + +var Newline = CharCodes$1.Newline, CarriageReturn = CharCodes$1.CarriageReturn; +// TODO: Throw error if eof is reached before finishing object parse... +var BaseParser = /** @class */ (function () { + function BaseParser(bytes, capNumbers) { + if (capNumbers === void 0) { capNumbers = false; } + this.bytes = bytes; + this.capNumbers = capNumbers; + } + BaseParser.prototype.parseRawInt = function () { + var value = ''; + while (!this.bytes.done()) { + var byte = this.bytes.peek(); + if (!IsDigit[byte]) + break; + value += charFromCode(this.bytes.next()); + } + var numberValue = Number(value); + if (!value || !isFinite(numberValue)) { + throw new NumberParsingError(this.bytes.position(), value); + } + return numberValue; + }; + // TODO: Maybe handle exponential format? + // TODO: Compare performance of string concatenation to charFromCode(...bytes) + BaseParser.prototype.parseRawNumber = function () { + var value = ''; + // Parse integer-part, the leading (+ | - | . | 0-9) + while (!this.bytes.done()) { + var byte = this.bytes.peek(); + if (!IsNumeric[byte]) + break; + value += charFromCode(this.bytes.next()); + if (byte === CharCodes$1.Period) + break; + } + // Parse decimal-part, the trailing (0-9) + while (!this.bytes.done()) { + var byte = this.bytes.peek(); + if (!IsDigit[byte]) + break; + value += charFromCode(this.bytes.next()); + } + var numberValue = Number(value); + if (!value || !isFinite(numberValue)) { + throw new NumberParsingError(this.bytes.position(), value); + } + if (numberValue > Number.MAX_SAFE_INTEGER) { + if (this.capNumbers) { + var msg = "Parsed number that is too large for some PDF readers: " + value + ", using Number.MAX_SAFE_INTEGER instead."; + console.warn(msg); + return Number.MAX_SAFE_INTEGER; + } + else { + var msg = "Parsed number that is too large for some PDF readers: " + value + ", not capping."; + console.warn(msg); + } + } + return numberValue; + }; + BaseParser.prototype.skipWhitespace = function () { + while (!this.bytes.done() && IsWhitespace[this.bytes.peek()]) { + this.bytes.next(); + } + }; + BaseParser.prototype.skipLine = function () { + while (!this.bytes.done()) { + var byte = this.bytes.peek(); + if (byte === Newline || byte === CarriageReturn) + return; + this.bytes.next(); + } + }; + BaseParser.prototype.skipComment = function () { + if (this.bytes.peek() !== CharCodes$1.Percent) + return false; + while (!this.bytes.done()) { + var byte = this.bytes.peek(); + if (byte === Newline || byte === CarriageReturn) + return true; + this.bytes.next(); + } + return true; + }; + BaseParser.prototype.skipWhitespaceAndComments = function () { + this.skipWhitespace(); + while (this.skipComment()) + this.skipWhitespace(); + }; + BaseParser.prototype.matchKeyword = function (keyword) { + var initialOffset = this.bytes.offset(); + for (var idx = 0, len = keyword.length; idx < len; idx++) { + if (this.bytes.done() || this.bytes.next() !== keyword[idx]) { + this.bytes.moveTo(initialOffset); + return false; + } + } + return true; + }; + return BaseParser; +}()); + +// TODO: See how line/col tracking affects performance +var ByteStream = /** @class */ (function () { + function ByteStream(bytes) { + this.idx = 0; + this.line = 0; + this.column = 0; + this.bytes = bytes; + this.length = this.bytes.length; + } + ByteStream.prototype.moveTo = function (offset) { + this.idx = offset; + }; + ByteStream.prototype.next = function () { + var byte = this.bytes[this.idx++]; + if (byte === CharCodes$1.Newline) { + this.line += 1; + this.column = 0; + } + else { + this.column += 1; + } + return byte; + }; + ByteStream.prototype.assertNext = function (expected) { + if (this.peek() !== expected) { + throw new NextByteAssertionError(this.position(), expected, this.peek()); + } + return this.next(); + }; + ByteStream.prototype.peek = function () { + return this.bytes[this.idx]; + }; + ByteStream.prototype.peekAhead = function (steps) { + return this.bytes[this.idx + steps]; + }; + ByteStream.prototype.peekAt = function (offset) { + return this.bytes[offset]; + }; + ByteStream.prototype.done = function () { + return this.idx >= this.length; + }; + ByteStream.prototype.offset = function () { + return this.idx; + }; + ByteStream.prototype.slice = function (start, end) { + return this.bytes.slice(start, end); + }; + ByteStream.prototype.position = function () { + return { line: this.line, column: this.column, offset: this.idx }; + }; + ByteStream.of = function (bytes) { return new ByteStream(bytes); }; + ByteStream.fromPDFRawStream = function (rawStream) { + return ByteStream.of(decodePDFRawStream(rawStream).decode()); + }; + return ByteStream; +}()); + +var Space = CharCodes$1.Space, CarriageReturn$1 = CharCodes$1.CarriageReturn, Newline$1 = CharCodes$1.Newline; +var stream = [ + CharCodes$1.s, + CharCodes$1.t, + CharCodes$1.r, + CharCodes$1.e, + CharCodes$1.a, + CharCodes$1.m, +]; +var endstream = [ + CharCodes$1.e, + CharCodes$1.n, + CharCodes$1.d, + CharCodes$1.s, + CharCodes$1.t, + CharCodes$1.r, + CharCodes$1.e, + CharCodes$1.a, + CharCodes$1.m, +]; +var Keywords = { + header: [ + CharCodes$1.Percent, + CharCodes$1.P, + CharCodes$1.D, + CharCodes$1.F, + CharCodes$1.Dash, + ], + eof: [ + CharCodes$1.Percent, + CharCodes$1.Percent, + CharCodes$1.E, + CharCodes$1.O, + CharCodes$1.F, + ], + obj: [CharCodes$1.o, CharCodes$1.b, CharCodes$1.j], + endobj: [ + CharCodes$1.e, + CharCodes$1.n, + CharCodes$1.d, + CharCodes$1.o, + CharCodes$1.b, + CharCodes$1.j, + ], + xref: [CharCodes$1.x, CharCodes$1.r, CharCodes$1.e, CharCodes$1.f], + trailer: [ + CharCodes$1.t, + CharCodes$1.r, + CharCodes$1.a, + CharCodes$1.i, + CharCodes$1.l, + CharCodes$1.e, + CharCodes$1.r, + ], + startxref: [ + CharCodes$1.s, + CharCodes$1.t, + CharCodes$1.a, + CharCodes$1.r, + CharCodes$1.t, + CharCodes$1.x, + CharCodes$1.r, + CharCodes$1.e, + CharCodes$1.f, + ], + true: [CharCodes$1.t, CharCodes$1.r, CharCodes$1.u, CharCodes$1.e], + false: [CharCodes$1.f, CharCodes$1.a, CharCodes$1.l, CharCodes$1.s, CharCodes$1.e], + null: [CharCodes$1.n, CharCodes$1.u, CharCodes$1.l, CharCodes$1.l], + stream: stream, + streamEOF1: __spreadArrays(stream, [Space, CarriageReturn$1, Newline$1]), + streamEOF2: __spreadArrays(stream, [CarriageReturn$1, Newline$1]), + streamEOF3: __spreadArrays(stream, [CarriageReturn$1]), + streamEOF4: __spreadArrays(stream, [Newline$1]), + endstream: endstream, + EOF1endstream: __spreadArrays([CarriageReturn$1, Newline$1], endstream), + EOF2endstream: __spreadArrays([CarriageReturn$1], endstream), + EOF3endstream: __spreadArrays([Newline$1], endstream), +}; + +// TODO: Throw error if eof is reached before finishing object parse... +var PDFObjectParser = /** @class */ (function (_super) { + __extends(PDFObjectParser, _super); + function PDFObjectParser(byteStream, context, capNumbers) { + if (capNumbers === void 0) { capNumbers = false; } + var _this = _super.call(this, byteStream, capNumbers) || this; + _this.context = context; + return _this; + } + // TODO: Is it possible to reduce duplicate parsing for ref lookaheads? + PDFObjectParser.prototype.parseObject = function () { + this.skipWhitespaceAndComments(); + if (this.matchKeyword(Keywords.true)) + return PDFBool.True; + if (this.matchKeyword(Keywords.false)) + return PDFBool.False; + if (this.matchKeyword(Keywords.null)) + return PDFNull$1; + var byte = this.bytes.peek(); + if (byte === CharCodes$1.LessThan && + this.bytes.peekAhead(1) === CharCodes$1.LessThan) { + return this.parseDictOrStream(); + } + if (byte === CharCodes$1.LessThan) + return this.parseHexString(); + if (byte === CharCodes$1.LeftParen) + return this.parseString(); + if (byte === CharCodes$1.ForwardSlash) + return this.parseName(); + if (byte === CharCodes$1.LeftSquareBracket) + return this.parseArray(); + if (IsNumeric[byte]) + return this.parseNumberOrRef(); + throw new PDFObjectParsingError(this.bytes.position(), byte); + }; + PDFObjectParser.prototype.parseNumberOrRef = function () { + var firstNum = this.parseRawNumber(); + this.skipWhitespaceAndComments(); + var lookaheadStart = this.bytes.offset(); + if (IsDigit[this.bytes.peek()]) { + var secondNum = this.parseRawNumber(); + this.skipWhitespaceAndComments(); + if (this.bytes.peek() === CharCodes$1.R) { + this.bytes.assertNext(CharCodes$1.R); + return PDFRef.of(firstNum, secondNum); + } + } + this.bytes.moveTo(lookaheadStart); + return PDFNumber.of(firstNum); + }; + // TODO: Maybe update PDFHexString.of() logic to remove whitespace and validate input? + PDFObjectParser.prototype.parseHexString = function () { + var value = ''; + this.bytes.assertNext(CharCodes$1.LessThan); + while (!this.bytes.done() && this.bytes.peek() !== CharCodes$1.GreaterThan) { + value += charFromCode(this.bytes.next()); + } + this.bytes.assertNext(CharCodes$1.GreaterThan); + return PDFHexString.of(value); + }; + PDFObjectParser.prototype.parseString = function () { + var nestingLvl = 0; + var isEscaped = false; + var value = ''; + while (!this.bytes.done()) { + var byte = this.bytes.next(); + value += charFromCode(byte); + // Check for unescaped parenthesis + if (!isEscaped) { + if (byte === CharCodes$1.LeftParen) + nestingLvl += 1; + if (byte === CharCodes$1.RightParen) + nestingLvl -= 1; + } + // Track whether current character is being escaped or not + if (byte === CharCodes$1.BackSlash) { + isEscaped = !isEscaped; + } + else if (isEscaped) { + isEscaped = false; + } + // Once (if) the unescaped parenthesis balance out, return their contents + if (nestingLvl === 0) { + // Remove the outer parens so they aren't part of the contents + return PDFString.of(value.substring(1, value.length - 1)); + } + } + throw new UnbalancedParenthesisError(this.bytes.position()); + }; + // TODO: Compare performance of string concatenation to charFromCode(...bytes) + // TODO: Maybe preallocate small Uint8Array if can use charFromCode? + PDFObjectParser.prototype.parseName = function () { + this.bytes.assertNext(CharCodes$1.ForwardSlash); + var name = ''; + while (!this.bytes.done()) { + var byte = this.bytes.peek(); + if (IsWhitespace[byte] || IsDelimiter[byte]) + break; + name += charFromCode(byte); + this.bytes.next(); + } + return PDFName.of(name); + }; + PDFObjectParser.prototype.parseArray = function () { + this.bytes.assertNext(CharCodes$1.LeftSquareBracket); + this.skipWhitespaceAndComments(); + var pdfArray = PDFArray.withContext(this.context); + while (this.bytes.peek() !== CharCodes$1.RightSquareBracket) { + var element = this.parseObject(); + pdfArray.push(element); + this.skipWhitespaceAndComments(); + } + this.bytes.assertNext(CharCodes$1.RightSquareBracket); + return pdfArray; + }; + PDFObjectParser.prototype.parseDict = function () { + this.bytes.assertNext(CharCodes$1.LessThan); + this.bytes.assertNext(CharCodes$1.LessThan); + this.skipWhitespaceAndComments(); + var dict = new Map(); + while (!this.bytes.done() && + this.bytes.peek() !== CharCodes$1.GreaterThan && + this.bytes.peekAhead(1) !== CharCodes$1.GreaterThan) { + var key = this.parseName(); + var value = this.parseObject(); + dict.set(key, value); + this.skipWhitespaceAndComments(); + } + this.skipWhitespaceAndComments(); + this.bytes.assertNext(CharCodes$1.GreaterThan); + this.bytes.assertNext(CharCodes$1.GreaterThan); + var Type = dict.get(PDFName.of('Type')); + if (Type === PDFName.of('Catalog')) { + return PDFCatalog.fromMapWithContext(dict, this.context); + } + else if (Type === PDFName.of('Pages')) { + return PDFPageTree.fromMapWithContext(dict, this.context); + } + else if (Type === PDFName.of('Page')) { + return PDFPageLeaf.fromMapWithContext(dict, this.context); + } + else { + return PDFDict.fromMapWithContext(dict, this.context); + } + }; + PDFObjectParser.prototype.parseDictOrStream = function () { + var startPos = this.bytes.position(); + var dict = this.parseDict(); + this.skipWhitespaceAndComments(); + if (!this.matchKeyword(Keywords.streamEOF1) && + !this.matchKeyword(Keywords.streamEOF2) && + !this.matchKeyword(Keywords.streamEOF3) && + !this.matchKeyword(Keywords.streamEOF4) && + !this.matchKeyword(Keywords.stream)) { + return dict; + } + var start = this.bytes.offset(); + var end; + var Length = dict.get(PDFName.of('Length')); + if (Length instanceof PDFNumber) { + end = start + Length.asNumber(); + this.bytes.moveTo(end); + this.skipWhitespaceAndComments(); + if (!this.matchKeyword(Keywords.endstream)) { + this.bytes.moveTo(start); + end = this.findEndOfStreamFallback(startPos); + } + } + else { + end = this.findEndOfStreamFallback(startPos); + } + var contents = this.bytes.slice(start, end); + return PDFRawStream.of(dict, contents); + }; + PDFObjectParser.prototype.findEndOfStreamFallback = function (startPos) { + // Move to end of stream, while handling nested streams + var nestingLvl = 1; + var end = this.bytes.offset(); + while (!this.bytes.done()) { + end = this.bytes.offset(); + if (this.matchKeyword(Keywords.stream)) { + nestingLvl += 1; + } + else if (this.matchKeyword(Keywords.EOF1endstream) || + this.matchKeyword(Keywords.EOF2endstream) || + this.matchKeyword(Keywords.EOF3endstream) || + this.matchKeyword(Keywords.endstream)) { + nestingLvl -= 1; + } + else { + this.bytes.next(); + } + if (nestingLvl === 0) + break; + } + if (nestingLvl !== 0) + throw new PDFStreamParsingError(startPos); + return end; + }; + PDFObjectParser.forBytes = function (bytes, context, capNumbers) { return new PDFObjectParser(ByteStream.of(bytes), context, capNumbers); }; + PDFObjectParser.forByteStream = function (byteStream, context, capNumbers) { + if (capNumbers === void 0) { capNumbers = false; } + return new PDFObjectParser(byteStream, context, capNumbers); + }; + return PDFObjectParser; +}(BaseParser)); + +var PDFObjectStreamParser = /** @class */ (function (_super) { + __extends(PDFObjectStreamParser, _super); + function PDFObjectStreamParser(rawStream, shouldWaitForTick) { + var _this = _super.call(this, ByteStream.fromPDFRawStream(rawStream), rawStream.dict.context) || this; + var dict = rawStream.dict; + _this.alreadyParsed = false; + _this.shouldWaitForTick = shouldWaitForTick || (function () { return false; }); + _this.firstOffset = dict.lookup(PDFName.of('First'), PDFNumber).asNumber(); + _this.objectCount = dict.lookup(PDFName.of('N'), PDFNumber).asNumber(); + return _this; + } + PDFObjectStreamParser.prototype.parseIntoContext = function () { + return __awaiter(this, void 0, void 0, function () { + var offsetsAndObjectNumbers, idx, len, _a, objectNumber, offset, object, ref; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (this.alreadyParsed) { + throw new ReparseError('PDFObjectStreamParser', 'parseIntoContext'); + } + this.alreadyParsed = true; + offsetsAndObjectNumbers = this.parseOffsetsAndObjectNumbers(); + idx = 0, len = offsetsAndObjectNumbers.length; + _b.label = 1; + case 1: + if (!(idx < len)) return [3 /*break*/, 4]; + _a = offsetsAndObjectNumbers[idx], objectNumber = _a.objectNumber, offset = _a.offset; + this.bytes.moveTo(this.firstOffset + offset); + object = this.parseObject(); + ref = PDFRef.of(objectNumber, 0); + this.context.assign(ref, object); + if (!this.shouldWaitForTick()) return [3 /*break*/, 3]; + return [4 /*yield*/, waitForTick()]; + case 2: + _b.sent(); + _b.label = 3; + case 3: + idx++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + }); + }; + PDFObjectStreamParser.prototype.parseOffsetsAndObjectNumbers = function () { + var offsetsAndObjectNumbers = []; + for (var idx = 0, len = this.objectCount; idx < len; idx++) { + this.skipWhitespaceAndComments(); + var objectNumber = this.parseRawInt(); + this.skipWhitespaceAndComments(); + var offset = this.parseRawInt(); + offsetsAndObjectNumbers.push({ objectNumber: objectNumber, offset: offset }); + } + return offsetsAndObjectNumbers; + }; + PDFObjectStreamParser.forStream = function (rawStream, shouldWaitForTick) { return new PDFObjectStreamParser(rawStream, shouldWaitForTick); }; + return PDFObjectStreamParser; +}(PDFObjectParser)); + +var PDFXRefStreamParser = /** @class */ (function () { + function PDFXRefStreamParser(rawStream) { + this.alreadyParsed = false; + this.dict = rawStream.dict; + this.bytes = ByteStream.fromPDFRawStream(rawStream); + this.context = this.dict.context; + var Size = this.dict.lookup(PDFName.of('Size'), PDFNumber); + var Index = this.dict.lookup(PDFName.of('Index')); + if (Index instanceof PDFArray) { + this.subsections = []; + for (var idx = 0, len = Index.size(); idx < len; idx += 2) { + var firstObjectNumber = Index.lookup(idx + 0, PDFNumber).asNumber(); + var length_1 = Index.lookup(idx + 1, PDFNumber).asNumber(); + this.subsections.push({ firstObjectNumber: firstObjectNumber, length: length_1 }); + } + } + else { + this.subsections = [{ firstObjectNumber: 0, length: Size.asNumber() }]; + } + var W = this.dict.lookup(PDFName.of('W'), PDFArray); + this.byteWidths = [-1, -1, -1]; + for (var idx = 0, len = W.size(); idx < len; idx++) { + this.byteWidths[idx] = W.lookup(idx, PDFNumber).asNumber(); + } + } + PDFXRefStreamParser.prototype.parseIntoContext = function () { + if (this.alreadyParsed) { + throw new ReparseError('PDFXRefStreamParser', 'parseIntoContext'); + } + this.alreadyParsed = true; + this.context.trailerInfo = { + Root: this.dict.get(PDFName.of('Root')), + Encrypt: this.dict.get(PDFName.of('Encrypt')), + Info: this.dict.get(PDFName.of('Info')), + ID: this.dict.get(PDFName.of('ID')), + }; + var entries = this.parseEntries(); + // for (let idx = 0, len = entries.length; idx < len; idx++) { + // const entry = entries[idx]; + // if (entry.deleted) this.context.delete(entry.ref); + // } + return entries; + }; + PDFXRefStreamParser.prototype.parseEntries = function () { + var entries = []; + var _a = this.byteWidths, typeFieldWidth = _a[0], offsetFieldWidth = _a[1], genFieldWidth = _a[2]; + for (var subsectionIdx = 0, subsectionLen = this.subsections.length; subsectionIdx < subsectionLen; subsectionIdx++) { + var _b = this.subsections[subsectionIdx], firstObjectNumber = _b.firstObjectNumber, length_2 = _b.length; + for (var objIdx = 0; objIdx < length_2; objIdx++) { + var type = 0; + for (var idx = 0, len = typeFieldWidth; idx < len; idx++) { + type = (type << 8) | this.bytes.next(); + } + var offset = 0; + for (var idx = 0, len = offsetFieldWidth; idx < len; idx++) { + offset = (offset << 8) | this.bytes.next(); + } + var generationNumber = 0; + for (var idx = 0, len = genFieldWidth; idx < len; idx++) { + generationNumber = (generationNumber << 8) | this.bytes.next(); + } + // When the `type` field is absent, it defaults to 1 + if (typeFieldWidth === 0) + type = 1; + var objectNumber = firstObjectNumber + objIdx; + var entry = { + ref: PDFRef.of(objectNumber, generationNumber), + offset: offset, + deleted: type === 0, + inObjectStream: type === 2, + }; + entries.push(entry); + } + } + return entries; + }; + PDFXRefStreamParser.forStream = function (rawStream) { + return new PDFXRefStreamParser(rawStream); + }; + return PDFXRefStreamParser; +}()); + +var PDFParser = /** @class */ (function (_super) { + __extends(PDFParser, _super); + function PDFParser(pdfBytes, objectsPerTick, throwOnInvalidObject, capNumbers) { + if (objectsPerTick === void 0) { objectsPerTick = Infinity; } + if (throwOnInvalidObject === void 0) { throwOnInvalidObject = false; } + if (capNumbers === void 0) { capNumbers = false; } + var _this = _super.call(this, ByteStream.of(pdfBytes), PDFContext.create(), capNumbers) || this; + _this.alreadyParsed = false; + _this.parsedObjects = 0; + _this.shouldWaitForTick = function () { + _this.parsedObjects += 1; + return _this.parsedObjects % _this.objectsPerTick === 0; + }; + _this.objectsPerTick = objectsPerTick; + _this.throwOnInvalidObject = throwOnInvalidObject; + return _this; + } + PDFParser.prototype.parseDocument = function () { + return __awaiter(this, void 0, void 0, function () { + var prevOffset, offset; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (this.alreadyParsed) { + throw new ReparseError('PDFParser', 'parseDocument'); + } + this.alreadyParsed = true; + this.context.header = this.parseHeader(); + _a.label = 1; + case 1: + if (!!this.bytes.done()) return [3 /*break*/, 3]; + return [4 /*yield*/, this.parseDocumentSection()]; + case 2: + _a.sent(); + offset = this.bytes.offset(); + if (offset === prevOffset) { + throw new StalledParserError(this.bytes.position()); + } + prevOffset = offset; + return [3 /*break*/, 1]; + case 3: + this.maybeRecoverRoot(); + if (this.context.lookup(PDFRef.of(0))) { + console.warn('Removing parsed object: 0 0 R'); + this.context.delete(PDFRef.of(0)); + } + return [2 /*return*/, this.context]; + } + }); + }); + }; + PDFParser.prototype.maybeRecoverRoot = function () { + var isValidCatalog = function (obj) { + return obj instanceof PDFDict && + obj.lookup(PDFName.of('Type')) === PDFName.of('Catalog'); + }; + var catalog = this.context.lookup(this.context.trailerInfo.Root); + if (!isValidCatalog(catalog)) { + var indirectObjects = this.context.enumerateIndirectObjects(); + for (var idx = 0, len = indirectObjects.length; idx < len; idx++) { + var _a = indirectObjects[idx], ref = _a[0], object = _a[1]; + if (isValidCatalog(object)) { + this.context.trailerInfo.Root = ref; + } + } + } + }; + PDFParser.prototype.parseHeader = function () { + while (!this.bytes.done()) { + if (this.matchKeyword(Keywords.header)) { + var major = this.parseRawInt(); + this.bytes.assertNext(CharCodes$1.Period); + var minor = this.parseRawInt(); + var header = PDFHeader.forVersion(major, minor); + this.skipBinaryHeaderComment(); + return header; + } + this.bytes.next(); + } + throw new MissingPDFHeaderError(this.bytes.position()); + }; + PDFParser.prototype.parseIndirectObjectHeader = function () { + this.skipWhitespaceAndComments(); + var objectNumber = this.parseRawInt(); + this.skipWhitespaceAndComments(); + var generationNumber = this.parseRawInt(); + this.skipWhitespaceAndComments(); + if (!this.matchKeyword(Keywords.obj)) { + throw new MissingKeywordError(this.bytes.position(), Keywords.obj); + } + return PDFRef.of(objectNumber, generationNumber); + }; + PDFParser.prototype.matchIndirectObjectHeader = function () { + var initialOffset = this.bytes.offset(); + try { + this.parseIndirectObjectHeader(); + return true; + } + catch (e) { + this.bytes.moveTo(initialOffset); + return false; + } + }; + PDFParser.prototype.parseIndirectObject = function () { + return __awaiter(this, void 0, void 0, function () { + var ref, object; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + ref = this.parseIndirectObjectHeader(); + this.skipWhitespaceAndComments(); + object = this.parseObject(); + this.skipWhitespaceAndComments(); + // if (!this.matchKeyword(Keywords.endobj)) { + // throw new MissingKeywordError(this.bytes.position(), Keywords.endobj); + // } + // TODO: Log a warning if this fails... + this.matchKeyword(Keywords.endobj); + if (!(object instanceof PDFRawStream && + object.dict.lookup(PDFName.of('Type')) === PDFName.of('ObjStm'))) return [3 /*break*/, 2]; + return [4 /*yield*/, PDFObjectStreamParser.forStream(object, this.shouldWaitForTick).parseIntoContext()]; + case 1: + _a.sent(); + return [3 /*break*/, 3]; + case 2: + if (object instanceof PDFRawStream && + object.dict.lookup(PDFName.of('Type')) === PDFName.of('XRef')) { + PDFXRefStreamParser.forStream(object).parseIntoContext(); + } + else { + this.context.assign(ref, object); + } + _a.label = 3; + case 3: return [2 /*return*/, ref]; + } + }); + }); + }; + // TODO: Improve and clean this up + PDFParser.prototype.tryToParseInvalidIndirectObject = function () { + var startPos = this.bytes.position(); + var msg = "Trying to parse invalid object: " + JSON.stringify(startPos) + ")"; + if (this.throwOnInvalidObject) + throw new Error(msg); + console.warn(msg); + var ref = this.parseIndirectObjectHeader(); + console.warn("Invalid object ref: " + ref); + this.skipWhitespaceAndComments(); + var start = this.bytes.offset(); + var failed = true; + while (!this.bytes.done()) { + if (this.matchKeyword(Keywords.endobj)) { + failed = false; + } + if (!failed) + break; + this.bytes.next(); + } + if (failed) + throw new PDFInvalidObjectParsingError(startPos); + var end = this.bytes.offset() - Keywords.endobj.length; + var object = PDFInvalidObject.of(this.bytes.slice(start, end)); + this.context.assign(ref, object); + return ref; + }; + PDFParser.prototype.parseIndirectObjects = function () { + return __awaiter(this, void 0, void 0, function () { + var initialOffset, e_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + this.skipWhitespaceAndComments(); + _a.label = 1; + case 1: + if (!(!this.bytes.done() && IsDigit[this.bytes.peek()])) return [3 /*break*/, 8]; + initialOffset = this.bytes.offset(); + _a.label = 2; + case 2: + _a.trys.push([2, 4, , 5]); + return [4 /*yield*/, this.parseIndirectObject()]; + case 3: + _a.sent(); + return [3 /*break*/, 5]; + case 4: + e_1 = _a.sent(); + // TODO: Add tracing/logging mechanism to track when this happens! + this.bytes.moveTo(initialOffset); + this.tryToParseInvalidIndirectObject(); + return [3 /*break*/, 5]; + case 5: + this.skipWhitespaceAndComments(); + // TODO: Can this be done only when needed, to avoid harming performance? + this.skipJibberish(); + if (!this.shouldWaitForTick()) return [3 /*break*/, 7]; + return [4 /*yield*/, waitForTick()]; + case 6: + _a.sent(); + _a.label = 7; + case 7: return [3 /*break*/, 1]; + case 8: return [2 /*return*/]; + } + }); + }); + }; + PDFParser.prototype.maybeParseCrossRefSection = function () { + this.skipWhitespaceAndComments(); + if (!this.matchKeyword(Keywords.xref)) + return; + this.skipWhitespaceAndComments(); + var objectNumber = -1; + var xref = PDFCrossRefSection.createEmpty(); + while (!this.bytes.done() && IsDigit[this.bytes.peek()]) { + var firstInt = this.parseRawInt(); + this.skipWhitespaceAndComments(); + var secondInt = this.parseRawInt(); + this.skipWhitespaceAndComments(); + var byte = this.bytes.peek(); + if (byte === CharCodes$1.n || byte === CharCodes$1.f) { + var ref = PDFRef.of(objectNumber, secondInt); + if (this.bytes.next() === CharCodes$1.n) { + xref.addEntry(ref, firstInt); + } + else { + // this.context.delete(ref); + xref.addDeletedEntry(ref, firstInt); + } + objectNumber += 1; + } + else { + objectNumber = firstInt; + } + this.skipWhitespaceAndComments(); + } + return xref; + }; + PDFParser.prototype.maybeParseTrailerDict = function () { + this.skipWhitespaceAndComments(); + if (!this.matchKeyword(Keywords.trailer)) + return; + this.skipWhitespaceAndComments(); + var dict = this.parseDict(); + var context = this.context; + context.trailerInfo = { + Root: dict.get(PDFName.of('Root')) || context.trailerInfo.Root, + Encrypt: dict.get(PDFName.of('Encrypt')) || context.trailerInfo.Encrypt, + Info: dict.get(PDFName.of('Info')) || context.trailerInfo.Info, + ID: dict.get(PDFName.of('ID')) || context.trailerInfo.ID, + }; + }; + PDFParser.prototype.maybeParseTrailer = function () { + this.skipWhitespaceAndComments(); + if (!this.matchKeyword(Keywords.startxref)) + return; + this.skipWhitespaceAndComments(); + var offset = this.parseRawInt(); + this.skipWhitespace(); + this.matchKeyword(Keywords.eof); + this.skipWhitespaceAndComments(); + this.matchKeyword(Keywords.eof); + this.skipWhitespaceAndComments(); + return PDFTrailer.forLastCrossRefSectionOffset(offset); + }; + PDFParser.prototype.parseDocumentSection = function () { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.parseIndirectObjects()]; + case 1: + _a.sent(); + this.maybeParseCrossRefSection(); + this.maybeParseTrailerDict(); + this.maybeParseTrailer(); + // TODO: Can this be done only when needed, to avoid harming performance? + this.skipJibberish(); + return [2 /*return*/]; + } + }); + }); + }; + /** + * This operation is not necessary for valid PDF files. But some invalid PDFs + * contain jibberish in between indirect objects. This method is designed to + * skip past that jibberish, should it exist, until it reaches the next + * indirect object header, an xref table section, or the file trailer. + */ + PDFParser.prototype.skipJibberish = function () { + this.skipWhitespaceAndComments(); + while (!this.bytes.done()) { + var initialOffset = this.bytes.offset(); + var byte = this.bytes.peek(); + var isAlphaNumeric = byte >= CharCodes$1.Space && byte <= CharCodes$1.Tilde; + if (isAlphaNumeric) { + if (this.matchKeyword(Keywords.xref) || + this.matchKeyword(Keywords.trailer) || + this.matchKeyword(Keywords.startxref) || + this.matchIndirectObjectHeader()) { + this.bytes.moveTo(initialOffset); + break; + } + } + this.bytes.next(); + } + }; + /** + * Skips the binary comment following a PDF header. The specification + * defines this binary comment (section 7.5.2 File Header) as a sequence of 4 + * or more bytes that are 128 or greater, and which are preceded by a "%". + * + * This would imply that to strip out this binary comment, we could check for + * a sequence of bytes starting with "%", and remove all subsequent bytes that + * are 128 or greater. This works for many documents that properly comply with + * the spec. But in the wild, there are PDFs that omit the leading "%", and + * include bytes that are less than 128 (e.g. 0 or 1). So in order to parse + * these headers correctly, we just throw out all bytes leading up to the + * first indirect object header. + */ + PDFParser.prototype.skipBinaryHeaderComment = function () { + this.skipWhitespaceAndComments(); + try { + var initialOffset = this.bytes.offset(); + this.parseIndirectObjectHeader(); + this.bytes.moveTo(initialOffset); + } + catch (e) { + this.bytes.next(); + this.skipWhitespaceAndComments(); + } + }; + PDFParser.forBytesWithOptions = function (pdfBytes, objectsPerTick, throwOnInvalidObject, capNumbers) { + return new PDFParser(pdfBytes, objectsPerTick, throwOnInvalidObject, capNumbers); + }; + return PDFParser; +}(PDFObjectParser)); + +var flag$1 = function (bitIndex) { return 1 << bitIndex; }; +/** From PDF spec table 165 */ +var AnnotationFlags; +(function (AnnotationFlags) { + /** + * If set, do not display the annotation if it does not belong to one of the + * standard annotation types and no annotation handler is available. If clear, + * display such an unknown annotation using an appearance stream specified by + * its appearance dictionary, if any. + */ + AnnotationFlags[AnnotationFlags["Invisible"] = flag$1(1 - 1)] = "Invisible"; + /** + * If set, do not display or print the annotation or allow it to interact with + * the user, regardless of its annotation type or whether an annotation + * handler is available. + * + * In cases where screen space is limited, the ability to hide and show + * annotations selectively can be used in combination with appearance streams + * to display auxiliary pop-up information similar in function to online help + * systems. + */ + AnnotationFlags[AnnotationFlags["Hidden"] = flag$1(2 - 1)] = "Hidden"; + /** + * If set, print the annotation when the page is printed. If clear, never + * print the annotation, regardless of whether it is displayed on the screen. + * + * This can be useful for annotations representing interactive pushbuttons, + * which would serve no meaningful purpose on the printed page. + */ + AnnotationFlags[AnnotationFlags["Print"] = flag$1(3 - 1)] = "Print"; + /** + * If set, do not scale the annotation’s appearance to match the magnification + * of the page. The location of the annotation on the page (defined by the + * upper-left corner of its annotation rectangle) shall remain fixed, + * regardless of the page magnification. + */ + AnnotationFlags[AnnotationFlags["NoZoom"] = flag$1(4 - 1)] = "NoZoom"; + /** + * If set, do not rotate the annotation’s appearance to match the rotation of + * the page. The upper-left corner of the annotation rectangle shall remain in + * a fixed location on the page, regardless of the page rotation. + */ + AnnotationFlags[AnnotationFlags["NoRotate"] = flag$1(5 - 1)] = "NoRotate"; + /** + * If set, do not display the annotation on the screen or allow it to interact + * with the user. The annotation may be printed (depending on the setting of + * the Print flag) but should be considered hidden for purposes of on-screen + * display and user interaction. + */ + AnnotationFlags[AnnotationFlags["NoView"] = flag$1(6 - 1)] = "NoView"; + /** + * If set, do not allow the annotation to interact with the user. The + * annotation may be displayed or printed (depending on the settings of the + * NoView and Print flags) but should not respond to mouse clicks or change + * its appearance in response to mouse motions. + * + * This flag shall be ignored for widget annotations; its function is + * subsumed by the ReadOnly flag of the associated form field. + */ + AnnotationFlags[AnnotationFlags["ReadOnly"] = flag$1(7 - 1)] = "ReadOnly"; + /** + * If set, do not allow the annotation to be deleted or its properties + * (including position and size) to be modified by the user. However, this + * flag does not restrict changes to the annotation’s contents, such as the + * value of a form field. + */ + AnnotationFlags[AnnotationFlags["Locked"] = flag$1(8 - 1)] = "Locked"; + /** + * If set, invert the interpretation of the NoView flag for certain events. + * + * A typical use is to have an annotation that appears only when a mouse + * cursor is held over it. + */ + AnnotationFlags[AnnotationFlags["ToggleNoView"] = flag$1(9 - 1)] = "ToggleNoView"; + /** + * If set, do not allow the contents of the annotation to be modified by the + * user. This flag does not restrict deletion of the annotation or changes to + * other annotation properties, such as position and size. + */ + AnnotationFlags[AnnotationFlags["LockedContents"] = flag$1(10 - 1)] = "LockedContents"; +})(AnnotationFlags || (AnnotationFlags = {})); + +var asPDFName = function (name) { + return name instanceof PDFName ? name : PDFName.of(name); +}; +var asPDFNumber = function (num) { + return num instanceof PDFNumber ? num : PDFNumber.of(num); +}; +var asNumber = function (num) { + return num instanceof PDFNumber ? num.asNumber() : num; +}; + +var RotationTypes; +(function (RotationTypes) { + RotationTypes["Degrees"] = "degrees"; + RotationTypes["Radians"] = "radians"; +})(RotationTypes || (RotationTypes = {})); +var radians = function (radianAngle) { + assertIs(radianAngle, 'radianAngle', ['number']); + return { type: RotationTypes.Radians, angle: radianAngle }; +}; +var degrees = function (degreeAngle) { + assertIs(degreeAngle, 'degreeAngle', ['number']); + return { type: RotationTypes.Degrees, angle: degreeAngle }; +}; +var Radians = RotationTypes.Radians, Degrees = RotationTypes.Degrees; +var degreesToRadians = function (degree) { return (degree * Math.PI) / 180; }; +var radiansToDegrees = function (radian) { return (radian * 180) / Math.PI; }; +// prettier-ignore +var toRadians = function (rotation) { + return rotation.type === Radians ? rotation.angle + : rotation.type === Degrees ? degreesToRadians(rotation.angle) + : error("Invalid rotation: " + JSON.stringify(rotation)); +}; +// prettier-ignore +var toDegrees = function (rotation) { + return rotation.type === Radians ? radiansToDegrees(rotation.angle) + : rotation.type === Degrees ? rotation.angle + : error("Invalid rotation: " + JSON.stringify(rotation)); +}; +var reduceRotation = function (degreeAngle) { + if (degreeAngle === void 0) { degreeAngle = 0; } + var quadrants = (degreeAngle / 90) % 4; + if (quadrants === 0) + return 0; + if (quadrants === 1) + return 90; + if (quadrants === 2) + return 180; + if (quadrants === 3) + return 270; + return 0; // `degreeAngle` is not a multiple of 90 +}; +var adjustDimsForRotation = function (dims, degreeAngle) { + if (degreeAngle === void 0) { degreeAngle = 0; } + var rotation = reduceRotation(degreeAngle); + return rotation === 90 || rotation === 270 + ? { width: dims.height, height: dims.width } + : { width: dims.width, height: dims.height }; +}; +var rotateRectangle = function (rectangle, borderWidth, degreeAngle) { + if (borderWidth === void 0) { borderWidth = 0; } + if (degreeAngle === void 0) { degreeAngle = 0; } + var x = rectangle.x, y = rectangle.y, w = rectangle.width, h = rectangle.height; + var r = reduceRotation(degreeAngle); + var b = borderWidth / 2; + // prettier-ignore + if (r === 0) + return { x: x - b, y: y - b, width: w, height: h }; + else if (r === 90) + return { x: x - h + b, y: y - b, width: h, height: w }; + else if (r === 180) + return { x: x - w + b, y: y - h + b, width: w, height: h }; + else if (r === 270) + return { x: x - b, y: y - w + b, width: h, height: w }; + else + return { x: x - b, y: y - b, width: w, height: h }; +}; + +/* ==================== Clipping Path Operators ==================== */ +var clip = function () { return PDFOperator.of(Ops.ClipNonZero); }; +var clipEvenOdd = function () { return PDFOperator.of(Ops.ClipEvenOdd); }; +/* ==================== Graphics State Operators ==================== */ +var cos = Math.cos, sin = Math.sin, tan = Math.tan; +var concatTransformationMatrix = function (a, b, c, d, e, f) { + return PDFOperator.of(Ops.ConcatTransformationMatrix, [ + asPDFNumber(a), + asPDFNumber(b), + asPDFNumber(c), + asPDFNumber(d), + asPDFNumber(e), + asPDFNumber(f), + ]); +}; +var translate = function (xPos, yPos) { + return concatTransformationMatrix(1, 0, 0, 1, xPos, yPos); +}; +var scale = function (xPos, yPos) { + return concatTransformationMatrix(xPos, 0, 0, yPos, 0, 0); +}; +var rotateRadians = function (angle) { + return concatTransformationMatrix(cos(asNumber(angle)), sin(asNumber(angle)), -sin(asNumber(angle)), cos(asNumber(angle)), 0, 0); +}; +var rotateDegrees = function (angle) { + return rotateRadians(degreesToRadians(asNumber(angle))); +}; +var skewRadians = function (xSkewAngle, ySkewAngle) { + return concatTransformationMatrix(1, tan(asNumber(xSkewAngle)), tan(asNumber(ySkewAngle)), 1, 0, 0); +}; +var skewDegrees = function (xSkewAngle, ySkewAngle) { + return skewRadians(degreesToRadians(asNumber(xSkewAngle)), degreesToRadians(asNumber(ySkewAngle))); +}; +var setDashPattern = function (dashArray, dashPhase) { + return PDFOperator.of(Ops.SetLineDashPattern, [ + "[" + dashArray.map(asPDFNumber).join(' ') + "]", + asPDFNumber(dashPhase), + ]); +}; +var restoreDashPattern = function () { return setDashPattern([], 0); }; +var LineCapStyle; +(function (LineCapStyle) { + LineCapStyle[LineCapStyle["Butt"] = 0] = "Butt"; + LineCapStyle[LineCapStyle["Round"] = 1] = "Round"; + LineCapStyle[LineCapStyle["Projecting"] = 2] = "Projecting"; +})(LineCapStyle || (LineCapStyle = {})); +var setLineCap = function (style) { + return PDFOperator.of(Ops.SetLineCapStyle, [asPDFNumber(style)]); +}; +var LineJoinStyle; +(function (LineJoinStyle) { + LineJoinStyle[LineJoinStyle["Miter"] = 0] = "Miter"; + LineJoinStyle[LineJoinStyle["Round"] = 1] = "Round"; + LineJoinStyle[LineJoinStyle["Bevel"] = 2] = "Bevel"; +})(LineJoinStyle || (LineJoinStyle = {})); +var setLineJoin = function (style) { + return PDFOperator.of(Ops.SetLineJoinStyle, [asPDFNumber(style)]); +}; +var setGraphicsState = function (state) { + return PDFOperator.of(Ops.SetGraphicsStateParams, [asPDFName(state)]); +}; +var pushGraphicsState = function () { return PDFOperator.of(Ops.PushGraphicsState); }; +var popGraphicsState = function () { return PDFOperator.of(Ops.PopGraphicsState); }; +var setLineWidth = function (width) { + return PDFOperator.of(Ops.SetLineWidth, [asPDFNumber(width)]); +}; +/* ==================== Path Construction Operators ==================== */ +var appendBezierCurve = function (x1, y1, x2, y2, x3, y3) { + return PDFOperator.of(Ops.AppendBezierCurve, [ + asPDFNumber(x1), + asPDFNumber(y1), + asPDFNumber(x2), + asPDFNumber(y2), + asPDFNumber(x3), + asPDFNumber(y3), + ]); +}; +var appendQuadraticCurve = function (x1, y1, x2, y2) { + return PDFOperator.of(Ops.CurveToReplicateInitialPoint, [ + asPDFNumber(x1), + asPDFNumber(y1), + asPDFNumber(x2), + asPDFNumber(y2), + ]); +}; +var closePath = function () { return PDFOperator.of(Ops.ClosePath); }; +var moveTo = function (xPos, yPos) { + return PDFOperator.of(Ops.MoveTo, [asPDFNumber(xPos), asPDFNumber(yPos)]); +}; +var lineTo = function (xPos, yPos) { + return PDFOperator.of(Ops.LineTo, [asPDFNumber(xPos), asPDFNumber(yPos)]); +}; +/** + * @param xPos x coordinate for the lower left corner of the rectangle + * @param yPos y coordinate for the lower left corner of the rectangle + * @param width width of the rectangle + * @param height height of the rectangle + */ +var rectangle = function (xPos, yPos, width, height) { + return PDFOperator.of(Ops.AppendRectangle, [ + asPDFNumber(xPos), + asPDFNumber(yPos), + asPDFNumber(width), + asPDFNumber(height), + ]); +}; +/** + * @param xPos x coordinate for the lower left corner of the square + * @param yPos y coordinate for the lower left corner of the square + * @param size width and height of the square + */ +var square = function (xPos, yPos, size) { + return rectangle(xPos, yPos, size, size); +}; +/* ==================== Path Painting Operators ==================== */ +var stroke = function () { return PDFOperator.of(Ops.StrokePath); }; +var fill = function () { return PDFOperator.of(Ops.FillNonZero); }; +var fillAndStroke = function () { return PDFOperator.of(Ops.FillNonZeroAndStroke); }; +var endPath = function () { return PDFOperator.of(Ops.EndPath); }; +/* ==================== Text Positioning Operators ==================== */ +var nextLine = function () { return PDFOperator.of(Ops.NextLine); }; +var moveText = function (x, y) { + return PDFOperator.of(Ops.MoveText, [asPDFNumber(x), asPDFNumber(y)]); +}; +/* ==================== Text Showing Operators ==================== */ +var showText = function (text) { + return PDFOperator.of(Ops.ShowText, [text]); +}; +/* ==================== Text State Operators ==================== */ +var beginText = function () { return PDFOperator.of(Ops.BeginText); }; +var endText = function () { return PDFOperator.of(Ops.EndText); }; +var setFontAndSize = function (name, size) { return PDFOperator.of(Ops.SetFontAndSize, [asPDFName(name), asPDFNumber(size)]); }; +var setCharacterSpacing = function (spacing) { + return PDFOperator.of(Ops.SetCharacterSpacing, [asPDFNumber(spacing)]); +}; +var setWordSpacing = function (spacing) { + return PDFOperator.of(Ops.SetWordSpacing, [asPDFNumber(spacing)]); +}; +/** @param squeeze horizontal character spacing */ +var setCharacterSqueeze = function (squeeze) { + return PDFOperator.of(Ops.SetTextHorizontalScaling, [asPDFNumber(squeeze)]); +}; +var setLineHeight = function (lineHeight) { + return PDFOperator.of(Ops.SetTextLineHeight, [asPDFNumber(lineHeight)]); +}; +var setTextRise = function (rise) { + return PDFOperator.of(Ops.SetTextRise, [asPDFNumber(rise)]); +}; +var TextRenderingMode; +(function (TextRenderingMode) { + TextRenderingMode[TextRenderingMode["Fill"] = 0] = "Fill"; + TextRenderingMode[TextRenderingMode["Outline"] = 1] = "Outline"; + TextRenderingMode[TextRenderingMode["FillAndOutline"] = 2] = "FillAndOutline"; + TextRenderingMode[TextRenderingMode["Invisible"] = 3] = "Invisible"; + TextRenderingMode[TextRenderingMode["FillAndClip"] = 4] = "FillAndClip"; + TextRenderingMode[TextRenderingMode["OutlineAndClip"] = 5] = "OutlineAndClip"; + TextRenderingMode[TextRenderingMode["FillAndOutlineAndClip"] = 6] = "FillAndOutlineAndClip"; + TextRenderingMode[TextRenderingMode["Clip"] = 7] = "Clip"; +})(TextRenderingMode || (TextRenderingMode = {})); +var setTextRenderingMode = function (mode) { + return PDFOperator.of(Ops.SetTextRenderingMode, [asPDFNumber(mode)]); +}; +var setTextMatrix = function (a, b, c, d, e, f) { + return PDFOperator.of(Ops.SetTextMatrix, [ + asPDFNumber(a), + asPDFNumber(b), + asPDFNumber(c), + asPDFNumber(d), + asPDFNumber(e), + asPDFNumber(f), + ]); +}; +var rotateAndSkewTextRadiansAndTranslate = function (rotationAngle, xSkewAngle, ySkewAngle, x, y) { + return setTextMatrix(cos(asNumber(rotationAngle)), sin(asNumber(rotationAngle)) + tan(asNumber(xSkewAngle)), -sin(asNumber(rotationAngle)) + tan(asNumber(ySkewAngle)), cos(asNumber(rotationAngle)), x, y); +}; +var rotateAndSkewTextDegreesAndTranslate = function (rotationAngle, xSkewAngle, ySkewAngle, x, y) { + return rotateAndSkewTextRadiansAndTranslate(degreesToRadians(asNumber(rotationAngle)), degreesToRadians(asNumber(xSkewAngle)), degreesToRadians(asNumber(ySkewAngle)), x, y); +}; +/* ==================== XObject Operator ==================== */ +var drawObject = function (name) { + return PDFOperator.of(Ops.DrawObject, [asPDFName(name)]); +}; +/* ==================== Color Operators ==================== */ +var setFillingGrayscaleColor = function (gray) { + return PDFOperator.of(Ops.NonStrokingColorGray, [asPDFNumber(gray)]); +}; +var setStrokingGrayscaleColor = function (gray) { + return PDFOperator.of(Ops.StrokingColorGray, [asPDFNumber(gray)]); +}; +var setFillingRgbColor = function (red, green, blue) { + return PDFOperator.of(Ops.NonStrokingColorRgb, [ + asPDFNumber(red), + asPDFNumber(green), + asPDFNumber(blue), + ]); +}; +var setStrokingRgbColor = function (red, green, blue) { + return PDFOperator.of(Ops.StrokingColorRgb, [ + asPDFNumber(red), + asPDFNumber(green), + asPDFNumber(blue), + ]); +}; +var setFillingCmykColor = function (cyan, magenta, yellow, key) { + return PDFOperator.of(Ops.NonStrokingColorCmyk, [ + asPDFNumber(cyan), + asPDFNumber(magenta), + asPDFNumber(yellow), + asPDFNumber(key), + ]); +}; +var setStrokingCmykColor = function (cyan, magenta, yellow, key) { + return PDFOperator.of(Ops.StrokingColorCmyk, [ + asPDFNumber(cyan), + asPDFNumber(magenta), + asPDFNumber(yellow), + asPDFNumber(key), + ]); +}; +/* ==================== Marked Content Operators ==================== */ +var beginMarkedContent = function (tag) { + return PDFOperator.of(Ops.BeginMarkedContent, [asPDFName(tag)]); +}; +var endMarkedContent = function () { return PDFOperator.of(Ops.EndMarkedContent); }; + +var ColorTypes; +(function (ColorTypes) { + ColorTypes["Grayscale"] = "Grayscale"; + ColorTypes["RGB"] = "RGB"; + ColorTypes["CMYK"] = "CMYK"; +})(ColorTypes || (ColorTypes = {})); +var grayscale = function (gray) { + assertRange(gray, 'gray', 0.0, 1.0); + return { type: ColorTypes.Grayscale, gray: gray }; +}; +var rgb = function (red, green, blue) { + assertRange(red, 'red', 0, 1); + assertRange(green, 'green', 0, 1); + assertRange(blue, 'blue', 0, 1); + return { type: ColorTypes.RGB, red: red, green: green, blue: blue }; +}; +var cmyk = function (cyan, magenta, yellow, key) { + assertRange(cyan, 'cyan', 0, 1); + assertRange(magenta, 'magenta', 0, 1); + assertRange(yellow, 'yellow', 0, 1); + assertRange(key, 'key', 0, 1); + return { type: ColorTypes.CMYK, cyan: cyan, magenta: magenta, yellow: yellow, key: key }; +}; +var Grayscale = ColorTypes.Grayscale, RGB = ColorTypes.RGB, CMYK = ColorTypes.CMYK; +// prettier-ignore +var setFillingColor = function (color) { + return color.type === Grayscale ? setFillingGrayscaleColor(color.gray) + : color.type === RGB ? setFillingRgbColor(color.red, color.green, color.blue) + : color.type === CMYK ? setFillingCmykColor(color.cyan, color.magenta, color.yellow, color.key) + : error("Invalid color: " + JSON.stringify(color)); +}; +// prettier-ignore +var setStrokingColor = function (color) { + return color.type === Grayscale ? setStrokingGrayscaleColor(color.gray) + : color.type === RGB ? setStrokingRgbColor(color.red, color.green, color.blue) + : color.type === CMYK ? setStrokingCmykColor(color.cyan, color.magenta, color.yellow, color.key) + : error("Invalid color: " + JSON.stringify(color)); +}; +// prettier-ignore +var componentsToColor = function (comps, scale) { + if (scale === void 0) { scale = 1; } + return ((comps === null || comps === void 0 ? void 0 : comps.length) === 1 ? grayscale(comps[0] * scale) + : (comps === null || comps === void 0 ? void 0 : comps.length) === 3 ? rgb(comps[0] * scale, comps[1] * scale, comps[2] * scale) + : (comps === null || comps === void 0 ? void 0 : comps.length) === 4 ? cmyk(comps[0] * scale, comps[1] * scale, comps[2] * scale, comps[3] * scale) + : undefined); +}; +// prettier-ignore +var colorToComponents = function (color) { + return color.type === Grayscale ? [color.gray] + : color.type === RGB ? [color.red, color.green, color.blue] + : color.type === CMYK ? [color.cyan, color.magenta, color.yellow, color.key] + : error("Invalid color: " + JSON.stringify(color)); +}; + +// Originated from pdfkit Copyright (c) 2014 Devon Govett +var cx = 0; +var cy = 0; +var px = 0; +var py = 0; +var sx = 0; +var sy = 0; +var parameters = new Map([ + ['A', 7], + ['a', 7], + ['C', 6], + ['c', 6], + ['H', 1], + ['h', 1], + ['L', 2], + ['l', 2], + ['M', 2], + ['m', 2], + ['Q', 4], + ['q', 4], + ['S', 4], + ['s', 4], + ['T', 2], + ['t', 2], + ['V', 1], + ['v', 1], + ['Z', 0], + ['z', 0], +]); +var parse = function (path) { + var cmd; + var ret = []; + var args = []; + var curArg = ''; + var foundDecimal = false; + var params = 0; + for (var _i = 0, path_1 = path; _i < path_1.length; _i++) { + var c = path_1[_i]; + if (parameters.has(c)) { + params = parameters.get(c); + if (cmd) { + // save existing command + if (curArg.length > 0) { + args[args.length] = +curArg; + } + ret[ret.length] = { cmd: cmd, args: args }; + args = []; + curArg = ''; + foundDecimal = false; + } + cmd = c; + } + else if ([' ', ','].includes(c) || + (c === '-' && curArg.length > 0 && curArg[curArg.length - 1] !== 'e') || + (c === '.' && foundDecimal)) { + if (curArg.length === 0) { + continue; + } + if (args.length === params) { + // handle reused commands + ret[ret.length] = { cmd: cmd, args: args }; + args = [+curArg]; + // handle assumed commands + if (cmd === 'M') { + cmd = 'L'; + } + if (cmd === 'm') { + cmd = 'l'; + } + } + else { + args[args.length] = +curArg; + } + foundDecimal = c === '.'; + // fix for negative numbers or repeated decimals with no delimeter between commands + curArg = ['-', '.'].includes(c) ? c : ''; + } + else { + curArg += c; + if (c === '.') { + foundDecimal = true; + } + } + } + // add the last command + if (curArg.length > 0) { + if (args.length === params) { + // handle reused commands + ret[ret.length] = { cmd: cmd, args: args }; + args = [+curArg]; + // handle assumed commands + if (cmd === 'M') { + cmd = 'L'; + } + if (cmd === 'm') { + cmd = 'l'; + } + } + else { + args[args.length] = +curArg; + } + } + ret[ret.length] = { cmd: cmd, args: args }; + return ret; +}; +var apply = function (commands) { + // current point, control point, and subpath starting point + cx = cy = px = py = sx = sy = 0; + // run the commands + var cmds = []; + for (var i = 0; i < commands.length; i++) { + var c = commands[i]; + if (c.cmd && typeof runners[c.cmd] === 'function') { + var cmd = runners[c.cmd](c.args); + if (Array.isArray(cmd)) { + cmds = cmds.concat(cmd); + } + else { + cmds.push(cmd); + } + } + } + return cmds; +}; +var runners = { + M: function (a) { + cx = a[0]; + cy = a[1]; + px = py = null; + sx = cx; + sy = cy; + return moveTo(cx, cy); + }, + m: function (a) { + cx += a[0]; + cy += a[1]; + px = py = null; + sx = cx; + sy = cy; + return moveTo(cx, cy); + }, + C: function (a) { + cx = a[4]; + cy = a[5]; + px = a[2]; + py = a[3]; + return appendBezierCurve(a[0], a[1], a[2], a[3], a[4], a[5]); + }, + c: function (a) { + var cmd = appendBezierCurve(a[0] + cx, a[1] + cy, a[2] + cx, a[3] + cy, a[4] + cx, a[5] + cy); + px = cx + a[2]; + py = cy + a[3]; + cx += a[4]; + cy += a[5]; + return cmd; + }, + S: function (a) { + if (px === null || py === null) { + px = cx; + py = cy; + } + var cmd = appendBezierCurve(cx - (px - cx), cy - (py - cy), a[0], a[1], a[2], a[3]); + px = a[0]; + py = a[1]; + cx = a[2]; + cy = a[3]; + return cmd; + }, + s: function (a) { + if (px === null || py === null) { + px = cx; + py = cy; + } + var cmd = appendBezierCurve(cx - (px - cx), cy - (py - cy), cx + a[0], cy + a[1], cx + a[2], cy + a[3]); + px = cx + a[0]; + py = cy + a[1]; + cx += a[2]; + cy += a[3]; + return cmd; + }, + Q: function (a) { + px = a[0]; + py = a[1]; + cx = a[2]; + cy = a[3]; + return appendQuadraticCurve(a[0], a[1], cx, cy); + }, + q: function (a) { + var cmd = appendQuadraticCurve(a[0] + cx, a[1] + cy, a[2] + cx, a[3] + cy); + px = cx + a[0]; + py = cy + a[1]; + cx += a[2]; + cy += a[3]; + return cmd; + }, + T: function (a) { + if (px === null || py === null) { + px = cx; + py = cy; + } + else { + px = cx - (px - cx); + py = cy - (py - cy); + } + var cmd = appendQuadraticCurve(px, py, a[0], a[1]); + px = cx - (px - cx); + py = cy - (py - cy); + cx = a[0]; + cy = a[1]; + return cmd; + }, + t: function (a) { + if (px === null || py === null) { + px = cx; + py = cy; + } + else { + px = cx - (px - cx); + py = cy - (py - cy); + } + var cmd = appendQuadraticCurve(px, py, cx + a[0], cy + a[1]); + cx += a[0]; + cy += a[1]; + return cmd; + }, + A: function (a) { + var cmds = solveArc(cx, cy, a); + cx = a[5]; + cy = a[6]; + return cmds; + }, + a: function (a) { + a[5] += cx; + a[6] += cy; + var cmds = solveArc(cx, cy, a); + cx = a[5]; + cy = a[6]; + return cmds; + }, + L: function (a) { + cx = a[0]; + cy = a[1]; + px = py = null; + return lineTo(cx, cy); + }, + l: function (a) { + cx += a[0]; + cy += a[1]; + px = py = null; + return lineTo(cx, cy); + }, + H: function (a) { + cx = a[0]; + px = py = null; + return lineTo(cx, cy); + }, + h: function (a) { + cx += a[0]; + px = py = null; + return lineTo(cx, cy); + }, + V: function (a) { + cy = a[0]; + px = py = null; + return lineTo(cx, cy); + }, + v: function (a) { + cy += a[0]; + px = py = null; + return lineTo(cx, cy); + }, + Z: function () { + var cmd = closePath(); + cx = sx; + cy = sy; + return cmd; + }, + z: function () { + var cmd = closePath(); + cx = sx; + cy = sy; + return cmd; + }, +}; +var solveArc = function (x, y, coords) { + var rx = coords[0], ry = coords[1], rot = coords[2], large = coords[3], sweep = coords[4], ex = coords[5], ey = coords[6]; + var segs = arcToSegments(ex, ey, rx, ry, large, sweep, rot, x, y); + var cmds = []; + for (var _i = 0, segs_1 = segs; _i < segs_1.length; _i++) { + var seg = segs_1[_i]; + var bez = segmentToBezier.apply(void 0, seg); + cmds.push(appendBezierCurve.apply(void 0, bez)); + } + return cmds; +}; +// from Inkscape svgtopdf, thanks! +var arcToSegments = function (x, y, rx, ry, large, sweep, rotateX, ox, oy) { + var th = rotateX * (Math.PI / 180); + var sinTh = Math.sin(th); + var cosTh = Math.cos(th); + rx = Math.abs(rx); + ry = Math.abs(ry); + px = cosTh * (ox - x) * 0.5 + sinTh * (oy - y) * 0.5; + py = cosTh * (oy - y) * 0.5 - sinTh * (ox - x) * 0.5; + var pl = (px * px) / (rx * rx) + (py * py) / (ry * ry); + if (pl > 1) { + pl = Math.sqrt(pl); + rx *= pl; + ry *= pl; + } + var a00 = cosTh / rx; + var a01 = sinTh / rx; + var a10 = -sinTh / ry; + var a11 = cosTh / ry; + var x0 = a00 * ox + a01 * oy; + var y0 = a10 * ox + a11 * oy; + var x1 = a00 * x + a01 * y; + var y1 = a10 * x + a11 * y; + var d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0); + var sfactorSq = 1 / d - 0.25; + if (sfactorSq < 0) { + sfactorSq = 0; + } + var sfactor = Math.sqrt(sfactorSq); + if (sweep === large) { + sfactor = -sfactor; + } + var xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0); + var yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0); + var th0 = Math.atan2(y0 - yc, x0 - xc); + var th1 = Math.atan2(y1 - yc, x1 - xc); + var thArc = th1 - th0; + if (thArc < 0 && sweep === 1) { + thArc += 2 * Math.PI; + } + else if (thArc > 0 && sweep === 0) { + thArc -= 2 * Math.PI; + } + var segments = Math.ceil(Math.abs(thArc / (Math.PI * 0.5 + 0.001))); + var result = []; + for (var i = 0; i < segments; i++) { + var th2 = th0 + (i * thArc) / segments; + var th3 = th0 + ((i + 1) * thArc) / segments; + result[i] = [xc, yc, th2, th3, rx, ry, sinTh, cosTh]; + } + return result; +}; +var segmentToBezier = function (cx1, cy1, th0, th1, rx, ry, sinTh, cosTh) { + var a00 = cosTh * rx; + var a01 = -sinTh * ry; + var a10 = sinTh * rx; + var a11 = cosTh * ry; + var thHalf = 0.5 * (th1 - th0); + var t = ((8 / 3) * Math.sin(thHalf * 0.5) * Math.sin(thHalf * 0.5)) / + Math.sin(thHalf); + var x1 = cx1 + Math.cos(th0) - t * Math.sin(th0); + var y1 = cy1 + Math.sin(th0) + t * Math.cos(th0); + var x3 = cx1 + Math.cos(th1); + var y3 = cy1 + Math.sin(th1); + var x2 = x3 + t * Math.sin(th1); + var y2 = y3 - t * Math.cos(th1); + var result = [ + a00 * x1 + a01 * y1, + a10 * x1 + a11 * y1, + a00 * x2 + a01 * y2, + a10 * x2 + a11 * y2, + a00 * x3 + a01 * y3, + a10 * x3 + a11 * y3, + ]; + return result; +}; +var svgPathToOperators = function (path) { return apply(parse(path)); }; + +var drawText = function (line, options) { + return [ + pushGraphicsState(), + options.graphicsState && setGraphicsState(options.graphicsState), + beginText(), + setFillingColor(options.color), + setFontAndSize(options.font, options.size), + rotateAndSkewTextRadiansAndTranslate(toRadians(options.rotate), toRadians(options.xSkew), toRadians(options.ySkew), options.x, options.y), + showText(line), + endText(), + popGraphicsState(), + ].filter(Boolean); +}; +var drawLinesOfText = function (lines, options) { + var operators = [ + pushGraphicsState(), + options.graphicsState && setGraphicsState(options.graphicsState), + beginText(), + setFillingColor(options.color), + setFontAndSize(options.font, options.size), + setLineHeight(options.lineHeight), + rotateAndSkewTextRadiansAndTranslate(toRadians(options.rotate), toRadians(options.xSkew), toRadians(options.ySkew), options.x, options.y), + ].filter(Boolean); + for (var idx = 0, len = lines.length; idx < len; idx++) { + operators.push(showText(lines[idx]), nextLine()); + } + operators.push(endText(), popGraphicsState()); + return operators; +}; +var drawImage = function (name, options) { + return [ + pushGraphicsState(), + options.graphicsState && setGraphicsState(options.graphicsState), + translate(options.x, options.y), + rotateRadians(toRadians(options.rotate)), + scale(options.width, options.height), + skewRadians(toRadians(options.xSkew), toRadians(options.ySkew)), + drawObject(name), + popGraphicsState(), + ].filter(Boolean); +}; +var drawPage = function (name, options) { + return [ + pushGraphicsState(), + options.graphicsState && setGraphicsState(options.graphicsState), + translate(options.x, options.y), + rotateRadians(toRadians(options.rotate)), + scale(options.xScale, options.yScale), + skewRadians(toRadians(options.xSkew), toRadians(options.ySkew)), + drawObject(name), + popGraphicsState(), + ].filter(Boolean); +}; +var drawLine = function (options) { + var _a, _b; + return [ + pushGraphicsState(), + options.graphicsState && setGraphicsState(options.graphicsState), + options.color && setStrokingColor(options.color), + setLineWidth(options.thickness), + setDashPattern((_a = options.dashArray) !== null && _a !== void 0 ? _a : [], (_b = options.dashPhase) !== null && _b !== void 0 ? _b : 0), + moveTo(options.start.x, options.start.y), + options.lineCap && setLineCap(options.lineCap), + moveTo(options.start.x, options.start.y), + lineTo(options.end.x, options.end.y), + stroke(), + popGraphicsState(), + ].filter(Boolean); +}; +var drawRectangle = function (options) { + var _a, _b; + return [ + pushGraphicsState(), + options.graphicsState && setGraphicsState(options.graphicsState), + options.color && setFillingColor(options.color), + options.borderColor && setStrokingColor(options.borderColor), + setLineWidth(options.borderWidth), + options.borderLineCap && setLineCap(options.borderLineCap), + setDashPattern((_a = options.borderDashArray) !== null && _a !== void 0 ? _a : [], (_b = options.borderDashPhase) !== null && _b !== void 0 ? _b : 0), + translate(options.x, options.y), + rotateRadians(toRadians(options.rotate)), + skewRadians(toRadians(options.xSkew), toRadians(options.ySkew)), + moveTo(0, 0), + lineTo(0, options.height), + lineTo(options.width, options.height), + lineTo(options.width, 0), + closePath(), + // prettier-ignore + options.color && options.borderWidth ? fillAndStroke() + : options.color ? fill() + : options.borderColor ? stroke() + : closePath(), + popGraphicsState(), + ].filter(Boolean); +}; +var KAPPA = 4.0 * ((Math.sqrt(2) - 1.0) / 3.0); +/** @deprecated */ +var drawEllipsePath = function (config) { + var x = asNumber(config.x); + var y = asNumber(config.y); + var xScale = asNumber(config.xScale); + var yScale = asNumber(config.yScale); + x -= xScale; + y -= yScale; + var ox = xScale * KAPPA; + var oy = yScale * KAPPA; + var xe = x + xScale * 2; + var ye = y + yScale * 2; + var xm = x + xScale; + var ym = y + yScale; + return [ + pushGraphicsState(), + moveTo(x, ym), + appendBezierCurve(x, ym - oy, xm - ox, y, xm, y), + appendBezierCurve(xm + ox, y, xe, ym - oy, xe, ym), + appendBezierCurve(xe, ym + oy, xm + ox, ye, xm, ye), + appendBezierCurve(xm - ox, ye, x, ym + oy, x, ym), + popGraphicsState(), + ]; +}; +var drawEllipseCurves = function (config) { + var centerX = asNumber(config.x); + var centerY = asNumber(config.y); + var xScale = asNumber(config.xScale); + var yScale = asNumber(config.yScale); + var x = -xScale; + var y = -yScale; + var ox = xScale * KAPPA; + var oy = yScale * KAPPA; + var xe = x + xScale * 2; + var ye = y + yScale * 2; + var xm = x + xScale; + var ym = y + yScale; + return [ + translate(centerX, centerY), + rotateRadians(toRadians(config.rotate)), + moveTo(x, ym), + appendBezierCurve(x, ym - oy, xm - ox, y, xm, y), + appendBezierCurve(xm + ox, y, xe, ym - oy, xe, ym), + appendBezierCurve(xe, ym + oy, xm + ox, ye, xm, ye), + appendBezierCurve(xm - ox, ye, x, ym + oy, x, ym), + ]; +}; +var drawEllipse = function (options) { + var _a, _b, _c; + return __spreadArrays([ + pushGraphicsState(), + options.graphicsState && setGraphicsState(options.graphicsState), + options.color && setFillingColor(options.color), + options.borderColor && setStrokingColor(options.borderColor), + setLineWidth(options.borderWidth), + options.borderLineCap && setLineCap(options.borderLineCap), + setDashPattern((_a = options.borderDashArray) !== null && _a !== void 0 ? _a : [], (_b = options.borderDashPhase) !== null && _b !== void 0 ? _b : 0) + ], (options.rotate === undefined + ? drawEllipsePath({ + x: options.x, + y: options.y, + xScale: options.xScale, + yScale: options.yScale, + }) + : drawEllipseCurves({ + x: options.x, + y: options.y, + xScale: options.xScale, + yScale: options.yScale, + rotate: (_c = options.rotate) !== null && _c !== void 0 ? _c : degrees(0), + })), [ + // prettier-ignore + options.color && options.borderWidth ? fillAndStroke() + : options.color ? fill() + : options.borderColor ? stroke() + : closePath(), + popGraphicsState(), + ]).filter(Boolean); +}; +var drawSvgPath = function (path, options) { + var _a, _b, _c; + return __spreadArrays([ + pushGraphicsState(), + options.graphicsState && setGraphicsState(options.graphicsState), + translate(options.x, options.y), + rotateRadians(toRadians((_a = options.rotate) !== null && _a !== void 0 ? _a : degrees(0))), + // SVG path Y axis is opposite pdf-lib's + options.scale ? scale(options.scale, -options.scale) : scale(1, -1), + options.color && setFillingColor(options.color), + options.borderColor && setStrokingColor(options.borderColor), + options.borderWidth && setLineWidth(options.borderWidth), + options.borderLineCap && setLineCap(options.borderLineCap), + setDashPattern((_b = options.borderDashArray) !== null && _b !== void 0 ? _b : [], (_c = options.borderDashPhase) !== null && _c !== void 0 ? _c : 0) + ], svgPathToOperators(path), [ + // prettier-ignore + options.color && options.borderWidth ? fillAndStroke() + : options.color ? fill() + : options.borderColor ? stroke() + : closePath(), + popGraphicsState(), + ]).filter(Boolean); +}; +var drawCheckMark = function (options) { + var size = asNumber(options.size); + /*********************** Define Check Mark Points ***************************/ + // A check mark is defined by three points in some coordinate space. Here, we + // define these points in a unit coordinate system, where the range of the x + // and y axis are both [-1, 1]. + // + // Note that we do not hard code `p1y` in case we wish to change the + // size/shape of the check mark in the future. We want the check mark to + // always form a right angle. This means that the dot product between (p1-p2) + // and (p3-p2) should be zero: + // + // (p1x-p2x) * (p3x-p2x) + (p1y-p2y) * (p3y-p2y) = 0 + // + // We can now rejigger this equation to solve for `p1y`: + // + // (p1y-p2y) * (p3y-p2y) = -((p1x-p2x) * (p3x-p2x)) + // (p1y-p2y) = -((p1x-p2x) * (p3x-p2x)) / (p3y-p2y) + // p1y = -((p1x-p2x) * (p3x-p2x)) / (p3y-p2y) + p2y + // + // Thanks to my friend Joel Walker (https://github.com/JWalker1995) for + // devising the above equation and unit coordinate system approach! + // (x, y) coords of the check mark's bottommost point + var p2x = -1 + 0.75; + var p2y = -1 + 0.51; + // (x, y) coords of the check mark's topmost point + var p3y = 1 - 0.525; + var p3x = 1 - 0.31; + // (x, y) coords of the check mark's center (vertically) point + var p1x = -1 + 0.325; + var p1y = -((p1x - p2x) * (p3x - p2x)) / (p3y - p2y) + p2y; + /****************************************************************************/ + return [ + pushGraphicsState(), + options.color && setStrokingColor(options.color), + setLineWidth(options.thickness), + translate(options.x, options.y), + moveTo(p1x * size, p1y * size), + lineTo(p2x * size, p2y * size), + lineTo(p3x * size, p3y * size), + stroke(), + popGraphicsState(), + ].filter(Boolean); +}; +// prettier-ignore +var rotateInPlace = function (options) { + return options.rotation === 0 ? [ + translate(0, 0), + rotateDegrees(0) + ] + : options.rotation === 90 ? [ + translate(options.width, 0), + rotateDegrees(90) + ] + : options.rotation === 180 ? [ + translate(options.width, options.height), + rotateDegrees(180) + ] + : options.rotation === 270 ? [ + translate(0, options.height), + rotateDegrees(270) + ] + : []; +}; // Invalid rotation - noop +var drawCheckBox = function (options) { + var outline = drawRectangle({ + x: options.x, + y: options.y, + width: options.width, + height: options.height, + borderWidth: options.borderWidth, + color: options.color, + borderColor: options.borderColor, + rotate: degrees(0), + xSkew: degrees(0), + ySkew: degrees(0), + }); + if (!options.filled) + return outline; + var width = asNumber(options.width); + var height = asNumber(options.height); + var checkMarkSize = Math.min(width, height) / 2; + var checkMark = drawCheckMark({ + x: width / 2, + y: height / 2, + size: checkMarkSize, + thickness: options.thickness, + color: options.markColor, + }); + return __spreadArrays([pushGraphicsState()], outline, checkMark, [popGraphicsState()]); +}; +var drawRadioButton = function (options) { + var width = asNumber(options.width); + var height = asNumber(options.height); + var outlineScale = Math.min(width, height) / 2; + var outline = drawEllipse({ + x: options.x, + y: options.y, + xScale: outlineScale, + yScale: outlineScale, + color: options.color, + borderColor: options.borderColor, + borderWidth: options.borderWidth, + }); + if (!options.filled) + return outline; + var dot = drawEllipse({ + x: options.x, + y: options.y, + xScale: outlineScale * 0.45, + yScale: outlineScale * 0.45, + color: options.dotColor, + borderColor: undefined, + borderWidth: 0, + }); + return __spreadArrays([pushGraphicsState()], outline, dot, [popGraphicsState()]); +}; +var drawButton = function (options) { + var x = asNumber(options.x); + var y = asNumber(options.y); + var width = asNumber(options.width); + var height = asNumber(options.height); + var background = drawRectangle({ + x: x, + y: y, + width: width, + height: height, + borderWidth: options.borderWidth, + color: options.color, + borderColor: options.borderColor, + rotate: degrees(0), + xSkew: degrees(0), + ySkew: degrees(0), + }); + var lines = drawTextLines(options.textLines, { + color: options.textColor, + font: options.font, + size: options.fontSize, + rotate: degrees(0), + xSkew: degrees(0), + ySkew: degrees(0), + }); + return __spreadArrays([pushGraphicsState()], background, lines, [popGraphicsState()]); +}; +var drawTextLines = function (lines, options) { + var operators = [ + beginText(), + setFillingColor(options.color), + setFontAndSize(options.font, options.size), + ]; + for (var idx = 0, len = lines.length; idx < len; idx++) { + var _a = lines[idx], encoded = _a.encoded, x = _a.x, y = _a.y; + operators.push(rotateAndSkewTextRadiansAndTranslate(toRadians(options.rotate), toRadians(options.xSkew), toRadians(options.ySkew), x, y), showText(encoded)); + } + operators.push(endText()); + return operators; +}; +var drawTextField = function (options) { + var x = asNumber(options.x); + var y = asNumber(options.y); + var width = asNumber(options.width); + var height = asNumber(options.height); + var borderWidth = asNumber(options.borderWidth); + var padding = asNumber(options.padding); + var clipX = x + borderWidth / 2 + padding; + var clipY = y + borderWidth / 2 + padding; + var clipWidth = width - (borderWidth / 2 + padding) * 2; + var clipHeight = height - (borderWidth / 2 + padding) * 2; + var clippingArea = [ + moveTo(clipX, clipY), + lineTo(clipX, clipY + clipHeight), + lineTo(clipX + clipWidth, clipY + clipHeight), + lineTo(clipX + clipWidth, clipY), + closePath(), + clip(), + endPath(), + ]; + var background = drawRectangle({ + x: x, + y: y, + width: width, + height: height, + borderWidth: options.borderWidth, + color: options.color, + borderColor: options.borderColor, + rotate: degrees(0), + xSkew: degrees(0), + ySkew: degrees(0), + }); + var lines = drawTextLines(options.textLines, { + color: options.textColor, + font: options.font, + size: options.fontSize, + rotate: degrees(0), + xSkew: degrees(0), + ySkew: degrees(0), + }); + var markedContent = __spreadArrays([ + beginMarkedContent('Tx'), + pushGraphicsState() + ], lines, [ + popGraphicsState(), + endMarkedContent(), + ]); + return __spreadArrays([ + pushGraphicsState() + ], background, clippingArea, markedContent, [ + popGraphicsState(), + ]); +}; +var drawOptionList = function (options) { + var x = asNumber(options.x); + var y = asNumber(options.y); + var width = asNumber(options.width); + var height = asNumber(options.height); + var lineHeight = asNumber(options.lineHeight); + var borderWidth = asNumber(options.borderWidth); + var padding = asNumber(options.padding); + var clipX = x + borderWidth / 2 + padding; + var clipY = y + borderWidth / 2 + padding; + var clipWidth = width - (borderWidth / 2 + padding) * 2; + var clipHeight = height - (borderWidth / 2 + padding) * 2; + var clippingArea = [ + moveTo(clipX, clipY), + lineTo(clipX, clipY + clipHeight), + lineTo(clipX + clipWidth, clipY + clipHeight), + lineTo(clipX + clipWidth, clipY), + closePath(), + clip(), + endPath(), + ]; + var background = drawRectangle({ + x: x, + y: y, + width: width, + height: height, + borderWidth: options.borderWidth, + color: options.color, + borderColor: options.borderColor, + rotate: degrees(0), + xSkew: degrees(0), + ySkew: degrees(0), + }); + var highlights = []; + for (var idx = 0, len = options.selectedLines.length; idx < len; idx++) { + var line = options.textLines[options.selectedLines[idx]]; + highlights.push.apply(highlights, drawRectangle({ + x: line.x - padding, + y: line.y - (lineHeight - line.height) / 2, + width: width - borderWidth, + height: line.height + (lineHeight - line.height) / 2, + borderWidth: 0, + color: options.selectedColor, + borderColor: undefined, + rotate: degrees(0), + xSkew: degrees(0), + ySkew: degrees(0), + })); + } + var lines = drawTextLines(options.textLines, { + color: options.textColor, + font: options.font, + size: options.fontSize, + rotate: degrees(0), + xSkew: degrees(0), + ySkew: degrees(0), + }); + var markedContent = __spreadArrays([ + beginMarkedContent('Tx'), + pushGraphicsState() + ], lines, [ + popGraphicsState(), + endMarkedContent(), + ]); + return __spreadArrays([ + pushGraphicsState() + ], background, highlights, clippingArea, markedContent, [ + popGraphicsState(), + ]); +}; + +// tslint:disable: max-classes-per-file +// TODO: Include link to documentation with example +var EncryptedPDFError = /** @class */ (function (_super) { + __extends(EncryptedPDFError, _super); + function EncryptedPDFError() { + var _this = this; + var msg = 'Input document to `PDFDocument.load` is encrypted. You can use `PDFDocument.load(..., { ignoreEncryption: true })` if you wish to load the document anyways.'; + _this = _super.call(this, msg) || this; + return _this; + } + return EncryptedPDFError; +}(Error)); +// TODO: Include link to documentation with example +var FontkitNotRegisteredError = /** @class */ (function (_super) { + __extends(FontkitNotRegisteredError, _super); + function FontkitNotRegisteredError() { + var _this = this; + var msg = 'Input to `PDFDocument.embedFont` was a custom font, but no `fontkit` instance was found. You must register a `fontkit` instance with `PDFDocument.registerFontkit(...)` before embedding custom fonts.'; + _this = _super.call(this, msg) || this; + return _this; + } + return FontkitNotRegisteredError; +}(Error)); +// TODO: Include link to documentation with example +var ForeignPageError = /** @class */ (function (_super) { + __extends(ForeignPageError, _super); + function ForeignPageError() { + var _this = this; + var msg = 'A `page` passed to `PDFDocument.addPage` or `PDFDocument.insertPage` was from a different (foreign) PDF document. If you want to copy pages from one PDFDocument to another, you must use `PDFDocument.copyPages(...)` to copy the pages before adding or inserting them.'; + _this = _super.call(this, msg) || this; + return _this; + } + return ForeignPageError; +}(Error)); +// TODO: Include link to documentation with example +var RemovePageFromEmptyDocumentError = /** @class */ (function (_super) { + __extends(RemovePageFromEmptyDocumentError, _super); + function RemovePageFromEmptyDocumentError() { + var _this = this; + var msg = 'PDFDocument has no pages so `PDFDocument.removePage` cannot be called'; + _this = _super.call(this, msg) || this; + return _this; + } + return RemovePageFromEmptyDocumentError; +}(Error)); +var NoSuchFieldError = /** @class */ (function (_super) { + __extends(NoSuchFieldError, _super); + function NoSuchFieldError(name) { + var _this = this; + var msg = "PDFDocument has no form field with the name \"" + name + "\""; + _this = _super.call(this, msg) || this; + return _this; + } + return NoSuchFieldError; +}(Error)); +var UnexpectedFieldTypeError = /** @class */ (function (_super) { + __extends(UnexpectedFieldTypeError, _super); + function UnexpectedFieldTypeError(name, expected, actual) { + var _a, _b; + var _this = this; + var expectedType = expected === null || expected === void 0 ? void 0 : expected.name; + var actualType = (_b = (_a = actual === null || actual === void 0 ? void 0 : actual.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : actual; + var msg = "Expected field \"" + name + "\" to be of type " + expectedType + ", " + + ("but it is actually of type " + actualType); + _this = _super.call(this, msg) || this; + return _this; + } + return UnexpectedFieldTypeError; +}(Error)); +var MissingOnValueCheckError = /** @class */ (function (_super) { + __extends(MissingOnValueCheckError, _super); + function MissingOnValueCheckError(onValue) { + var _this = this; + var msg = "Failed to select check box due to missing onValue: \"" + onValue + "\""; + _this = _super.call(this, msg) || this; + return _this; + } + return MissingOnValueCheckError; +}(Error)); +var FieldAlreadyExistsError = /** @class */ (function (_super) { + __extends(FieldAlreadyExistsError, _super); + function FieldAlreadyExistsError(name) { + var _this = this; + var msg = "A field already exists with the specified name: \"" + name + "\""; + _this = _super.call(this, msg) || this; + return _this; + } + return FieldAlreadyExistsError; +}(Error)); +var InvalidFieldNamePartError = /** @class */ (function (_super) { + __extends(InvalidFieldNamePartError, _super); + function InvalidFieldNamePartError(namePart) { + var _this = this; + var msg = "Field name contains invalid component: \"" + namePart + "\""; + _this = _super.call(this, msg) || this; + return _this; + } + return InvalidFieldNamePartError; +}(Error)); +var FieldExistsAsNonTerminalError = /** @class */ (function (_super) { + __extends(FieldExistsAsNonTerminalError, _super); + function FieldExistsAsNonTerminalError(name) { + var _this = this; + var msg = "A non-terminal field already exists with the specified name: \"" + name + "\""; + _this = _super.call(this, msg) || this; + return _this; + } + return FieldExistsAsNonTerminalError; +}(Error)); +var RichTextFieldReadError = /** @class */ (function (_super) { + __extends(RichTextFieldReadError, _super); + function RichTextFieldReadError(fieldName) { + var _this = this; + var msg = "Reading rich text fields is not supported: Attempted to read rich text field: " + fieldName; + _this = _super.call(this, msg) || this; + return _this; + } + return RichTextFieldReadError; +}(Error)); +var CombedTextLayoutError = /** @class */ (function (_super) { + __extends(CombedTextLayoutError, _super); + function CombedTextLayoutError(lineLength, cellCount) { + var _this = this; + var msg = "Failed to layout combed text as lineLength=" + lineLength + " is greater than cellCount=" + cellCount; + _this = _super.call(this, msg) || this; + return _this; + } + return CombedTextLayoutError; +}(Error)); +var ExceededMaxLengthError = /** @class */ (function (_super) { + __extends(ExceededMaxLengthError, _super); + function ExceededMaxLengthError(textLength, maxLength, name) { + var _this = this; + var msg = "Attempted to set text with length=" + textLength + " for TextField with maxLength=" + maxLength + " and name=" + name; + _this = _super.call(this, msg) || this; + return _this; + } + return ExceededMaxLengthError; +}(Error)); +var InvalidMaxLengthError = /** @class */ (function (_super) { + __extends(InvalidMaxLengthError, _super); + function InvalidMaxLengthError(textLength, maxLength, name) { + var _this = this; + var msg = "Attempted to set maxLength=" + maxLength + ", which is less than " + textLength + ", the length of this field's current value (name=" + name + ")"; + _this = _super.call(this, msg) || this; + return _this; + } + return InvalidMaxLengthError; +}(Error)); + +var TextAlignment; +(function (TextAlignment) { + TextAlignment[TextAlignment["Left"] = 0] = "Left"; + TextAlignment[TextAlignment["Center"] = 1] = "Center"; + TextAlignment[TextAlignment["Right"] = 2] = "Right"; +})(TextAlignment || (TextAlignment = {})); + +var MIN_FONT_SIZE = 4; +var MAX_FONT_SIZE = 500; +var computeFontSize = function (lines, font, bounds, multiline) { + if (multiline === void 0) { multiline = false; } + var fontSize = MIN_FONT_SIZE; + while (fontSize < MAX_FONT_SIZE) { + var linesUsed = 0; + for (var lineIdx = 0, lineLen = lines.length; lineIdx < lineLen; lineIdx++) { + linesUsed += 1; + var line = lines[lineIdx]; + var words = line.split(' '); + // Layout the words using the current `fontSize`, line wrapping + // whenever we reach the end of the current line. + var spaceInLineRemaining = bounds.width; + for (var idx = 0, len = words.length; idx < len; idx++) { + var isLastWord = idx === len - 1; + var word = isLastWord ? words[idx] : words[idx] + ' '; + var widthOfWord = font.widthOfTextAtSize(word, fontSize); + spaceInLineRemaining -= widthOfWord; + if (spaceInLineRemaining <= 0) { + linesUsed += 1; + spaceInLineRemaining = bounds.width - widthOfWord; + } + } + } + // Return if we exceeded the allowed width + if (!multiline && linesUsed > lines.length) + return fontSize - 1; + var height = font.heightAtSize(fontSize); + var lineHeight = height + height * 0.2; + var totalHeight = lineHeight * linesUsed; + // Return if we exceeded the allowed height + if (totalHeight > Math.abs(bounds.height)) + return fontSize - 1; + fontSize += 1; + } + return fontSize; +}; +var computeCombedFontSize = function (line, font, bounds, cellCount) { + var cellWidth = bounds.width / cellCount; + var cellHeight = bounds.height; + var fontSize = MIN_FONT_SIZE; + var chars = charSplit(line); + while (fontSize < MAX_FONT_SIZE) { + for (var idx = 0, len = chars.length; idx < len; idx++) { + var c = chars[idx]; + var tooLong = font.widthOfTextAtSize(c, fontSize) > cellWidth * 0.75; + if (tooLong) + return fontSize - 1; + } + var height = font.heightAtSize(fontSize, { descender: false }); + if (height > cellHeight) + return fontSize - 1; + fontSize += 1; + } + return fontSize; +}; +var lastIndexOfWhitespace = function (line) { + for (var idx = line.length; idx > 0; idx--) { + if (/\s/.test(line[idx])) + return idx; + } + return undefined; +}; +var splitOutLines = function (input, maxWidth, font, fontSize) { + var _a; + var lastWhitespaceIdx = input.length; + while (lastWhitespaceIdx > 0) { + var line = input.substring(0, lastWhitespaceIdx); + var encoded = font.encodeText(line); + var width = font.widthOfTextAtSize(line, fontSize); + if (width < maxWidth) { + var remainder = input.substring(lastWhitespaceIdx) || undefined; + return { line: line, encoded: encoded, width: width, remainder: remainder }; + } + lastWhitespaceIdx = (_a = lastIndexOfWhitespace(line)) !== null && _a !== void 0 ? _a : 0; + } + // We were unable to split the input enough to get a chunk that would fit + // within the specified `maxWidth` so we'll just return everything + return { + line: input, + encoded: font.encodeText(input), + width: font.widthOfTextAtSize(input, fontSize), + remainder: undefined, + }; +}; +var layoutMultilineText = function (text, _a) { + var alignment = _a.alignment, fontSize = _a.fontSize, font = _a.font, bounds = _a.bounds; + var lines = lineSplit(cleanText(text)); + if (fontSize === undefined || fontSize === 0) { + fontSize = computeFontSize(lines, font, bounds, true); + } + var height = font.heightAtSize(fontSize); + var lineHeight = height + height * 0.2; + var textLines = []; + var minX = bounds.x; + var minY = bounds.y; + var maxX = bounds.x + bounds.width; + var maxY = bounds.y + bounds.height; + var y = bounds.y + bounds.height; + for (var idx = 0, len = lines.length; idx < len; idx++) { + var prevRemainder = lines[idx]; + while (prevRemainder !== undefined) { + var _b = splitOutLines(prevRemainder, bounds.width, font, fontSize), line = _b.line, encoded = _b.encoded, width = _b.width, remainder = _b.remainder; + // prettier-ignore + var x = (alignment === TextAlignment.Left ? bounds.x + : alignment === TextAlignment.Center ? bounds.x + (bounds.width / 2) - (width / 2) + : alignment === TextAlignment.Right ? bounds.x + bounds.width - width + : bounds.x); + y -= lineHeight; + if (x < minX) + minX = x; + if (y < minY) + minY = y; + if (x + width > maxX) + maxX = x + width; + if (y + height > maxY) + maxY = y + height; + textLines.push({ text: line, encoded: encoded, width: width, height: height, x: x, y: y }); + // Only trim lines that we had to split ourselves. So we won't trim lines + // that the user provided themselves with whitespace. + prevRemainder = remainder === null || remainder === void 0 ? void 0 : remainder.trim(); + } + } + return { + fontSize: fontSize, + lineHeight: lineHeight, + lines: textLines, + bounds: { + x: minX, + y: minY, + width: maxX - minX, + height: maxY - minY, + }, + }; +}; +var layoutCombedText = function (text, _a) { + var fontSize = _a.fontSize, font = _a.font, bounds = _a.bounds, cellCount = _a.cellCount; + var line = mergeLines(cleanText(text)); + if (line.length > cellCount) { + throw new CombedTextLayoutError(line.length, cellCount); + } + if (fontSize === undefined || fontSize === 0) { + fontSize = computeCombedFontSize(line, font, bounds, cellCount); + } + var cellWidth = bounds.width / cellCount; + var height = font.heightAtSize(fontSize, { descender: false }); + var y = bounds.y + (bounds.height / 2 - height / 2); + var cells = []; + var minX = bounds.x; + var minY = bounds.y; + var maxX = bounds.x + bounds.width; + var maxY = bounds.y + bounds.height; + var cellOffset = 0; + var charOffset = 0; + while (cellOffset < cellCount) { + var _b = charAtIndex(line, charOffset), char = _b[0], charLength = _b[1]; + var encoded = font.encodeText(char); + var width = font.widthOfTextAtSize(char, fontSize); + var cellCenter = bounds.x + (cellWidth * cellOffset + cellWidth / 2); + var x = cellCenter - width / 2; + if (x < minX) + minX = x; + if (y < minY) + minY = y; + if (x + width > maxX) + maxX = x + width; + if (y + height > maxY) + maxY = y + height; + cells.push({ text: line, encoded: encoded, width: width, height: height, x: x, y: y }); + cellOffset += 1; + charOffset += charLength; + } + return { + fontSize: fontSize, + cells: cells, + bounds: { + x: minX, + y: minY, + width: maxX - minX, + height: maxY - minY, + }, + }; +}; +var layoutSinglelineText = function (text, _a) { + var alignment = _a.alignment, fontSize = _a.fontSize, font = _a.font, bounds = _a.bounds; + var line = mergeLines(cleanText(text)); + if (fontSize === undefined || fontSize === 0) { + fontSize = computeFontSize([line], font, bounds); + } + var encoded = font.encodeText(line); + var width = font.widthOfTextAtSize(line, fontSize); + var height = font.heightAtSize(fontSize, { descender: false }); + // prettier-ignore + var x = (alignment === TextAlignment.Left ? bounds.x + : alignment === TextAlignment.Center ? bounds.x + (bounds.width / 2) - (width / 2) + : alignment === TextAlignment.Right ? bounds.x + bounds.width - width + : bounds.x); + var y = bounds.y + (bounds.height / 2 - height / 2); + return { + fontSize: fontSize, + line: { text: line, encoded: encoded, width: width, height: height, x: x, y: y }, + bounds: { x: x, y: y, width: width, height: height }, + }; +}; + +/********************* Appearance Provider Functions **************************/ +var normalizeAppearance = function (appearance) { + if ('normal' in appearance) + return appearance; + return { normal: appearance }; +}; +// Examples: +// `/Helv 12 Tf` -> ['/Helv 12 Tf', 'Helv', '12'] +// `/HeBo 8.00 Tf` -> ['/HeBo 8 Tf', 'HeBo', '8.00'] +var tfRegex$1 = /\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/; +var getDefaultFontSize = function (field) { + var _a, _b; + var da = (_a = field.getDefaultAppearance()) !== null && _a !== void 0 ? _a : ''; + var daMatch = (_b = findLastMatch(da, tfRegex$1).match) !== null && _b !== void 0 ? _b : []; + var defaultFontSize = Number(daMatch[2]); + return isFinite(defaultFontSize) ? defaultFontSize : undefined; +}; +// Examples: +// `0.3 g` -> ['0.3', 'g'] +// `0.3 1 .3 rg` -> ['0.3', '1', '.3', 'rg'] +// `0.3 1 .3 0 k` -> ['0.3', '1', '.3', '0', 'k'] +var colorRegex = /(\d*\.\d+|\d+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+(g|rg|k)/; +var getDefaultColor = function (field) { + var _a; + var da = (_a = field.getDefaultAppearance()) !== null && _a !== void 0 ? _a : ''; + var daMatch = findLastMatch(da, colorRegex).match; + var _b = daMatch !== null && daMatch !== void 0 ? daMatch : [], c1 = _b[1], c2 = _b[2], c3 = _b[3], c4 = _b[4], colorSpace = _b[5]; + if (colorSpace === 'g' && c1) { + return grayscale(Number(c1)); + } + if (colorSpace === 'rg' && c1 && c2 && c3) { + return rgb(Number(c1), Number(c2), Number(c3)); + } + if (colorSpace === 'k' && c1 && c2 && c3 && c4) { + return cmyk(Number(c1), Number(c2), Number(c3), Number(c4)); + } + return undefined; +}; +var updateDefaultAppearance = function (field, color, font, fontSize) { + var _a; + if (fontSize === void 0) { fontSize = 0; } + var da = [ + setFillingColor(color).toString(), + setFontAndSize((_a = font === null || font === void 0 ? void 0 : font.name) !== null && _a !== void 0 ? _a : 'dummy__noop', fontSize).toString(), + ].join('\n'); + field.setDefaultAppearance(da); +}; +var defaultCheckBoxAppearanceProvider = function (checkBox, widget) { + var _a, _b, _c; + // The `/DA` entry can be at the widget or field level - so we handle both + var widgetColor = getDefaultColor(widget); + var fieldColor = getDefaultColor(checkBox.acroField); + var rectangle = widget.getRectangle(); + var ap = widget.getAppearanceCharacteristics(); + var bs = widget.getBorderStyle(); + var borderWidth = (_a = bs === null || bs === void 0 ? void 0 : bs.getWidth()) !== null && _a !== void 0 ? _a : 0; + var rotation = reduceRotation(ap === null || ap === void 0 ? void 0 : ap.getRotation()); + var _d = adjustDimsForRotation(rectangle, rotation), width = _d.width, height = _d.height; + var rotate = rotateInPlace(__assign(__assign({}, rectangle), { rotation: rotation })); + var black = rgb(0, 0, 0); + var borderColor = (_b = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBorderColor())) !== null && _b !== void 0 ? _b : black; + var normalBackgroundColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBackgroundColor()); + var downBackgroundColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBackgroundColor(), 0.8); + // Update color + var textColor = (_c = widgetColor !== null && widgetColor !== void 0 ? widgetColor : fieldColor) !== null && _c !== void 0 ? _c : black; + if (widgetColor) { + updateDefaultAppearance(widget, textColor); + } + else { + updateDefaultAppearance(checkBox.acroField, textColor); + } + var options = { + x: 0 + borderWidth / 2, + y: 0 + borderWidth / 2, + width: width - borderWidth, + height: height - borderWidth, + thickness: 1.5, + borderWidth: borderWidth, + borderColor: borderColor, + markColor: textColor, + }; + return { + normal: { + on: __spreadArrays(rotate, drawCheckBox(__assign(__assign({}, options), { color: normalBackgroundColor, filled: true }))), + off: __spreadArrays(rotate, drawCheckBox(__assign(__assign({}, options), { color: normalBackgroundColor, filled: false }))), + }, + down: { + on: __spreadArrays(rotate, drawCheckBox(__assign(__assign({}, options), { color: downBackgroundColor, filled: true }))), + off: __spreadArrays(rotate, drawCheckBox(__assign(__assign({}, options), { color: downBackgroundColor, filled: false }))), + }, + }; +}; +var defaultRadioGroupAppearanceProvider = function (radioGroup, widget) { + var _a, _b, _c; + // The `/DA` entry can be at the widget or field level - so we handle both + var widgetColor = getDefaultColor(widget); + var fieldColor = getDefaultColor(radioGroup.acroField); + var rectangle = widget.getRectangle(); + var ap = widget.getAppearanceCharacteristics(); + var bs = widget.getBorderStyle(); + var borderWidth = (_a = bs === null || bs === void 0 ? void 0 : bs.getWidth()) !== null && _a !== void 0 ? _a : 0; + var rotation = reduceRotation(ap === null || ap === void 0 ? void 0 : ap.getRotation()); + var _d = adjustDimsForRotation(rectangle, rotation), width = _d.width, height = _d.height; + var rotate = rotateInPlace(__assign(__assign({}, rectangle), { rotation: rotation })); + var black = rgb(0, 0, 0); + var borderColor = (_b = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBorderColor())) !== null && _b !== void 0 ? _b : black; + var normalBackgroundColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBackgroundColor()); + var downBackgroundColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBackgroundColor(), 0.8); + // Update color + var textColor = (_c = widgetColor !== null && widgetColor !== void 0 ? widgetColor : fieldColor) !== null && _c !== void 0 ? _c : black; + if (widgetColor) { + updateDefaultAppearance(widget, textColor); + } + else { + updateDefaultAppearance(radioGroup.acroField, textColor); + } + var options = { + x: width / 2, + y: height / 2, + width: width - borderWidth, + height: height - borderWidth, + borderWidth: borderWidth, + borderColor: borderColor, + dotColor: textColor, + }; + return { + normal: { + on: __spreadArrays(rotate, drawRadioButton(__assign(__assign({}, options), { color: normalBackgroundColor, filled: true }))), + off: __spreadArrays(rotate, drawRadioButton(__assign(__assign({}, options), { color: normalBackgroundColor, filled: false }))), + }, + down: { + on: __spreadArrays(rotate, drawRadioButton(__assign(__assign({}, options), { color: downBackgroundColor, filled: true }))), + off: __spreadArrays(rotate, drawRadioButton(__assign(__assign({}, options), { color: downBackgroundColor, filled: false }))), + }, + }; +}; +var defaultButtonAppearanceProvider = function (button, widget, font) { + var _a, _b, _c, _d, _e; + // The `/DA` entry can be at the widget or field level - so we handle both + var widgetColor = getDefaultColor(widget); + var fieldColor = getDefaultColor(button.acroField); + var widgetFontSize = getDefaultFontSize(widget); + var fieldFontSize = getDefaultFontSize(button.acroField); + var rectangle = widget.getRectangle(); + var ap = widget.getAppearanceCharacteristics(); + var bs = widget.getBorderStyle(); + var captions = ap === null || ap === void 0 ? void 0 : ap.getCaptions(); + var normalText = (_a = captions === null || captions === void 0 ? void 0 : captions.normal) !== null && _a !== void 0 ? _a : ''; + var downText = (_c = (_b = captions === null || captions === void 0 ? void 0 : captions.down) !== null && _b !== void 0 ? _b : normalText) !== null && _c !== void 0 ? _c : ''; + var borderWidth = (_d = bs === null || bs === void 0 ? void 0 : bs.getWidth()) !== null && _d !== void 0 ? _d : 0; + var rotation = reduceRotation(ap === null || ap === void 0 ? void 0 : ap.getRotation()); + var _f = adjustDimsForRotation(rectangle, rotation), width = _f.width, height = _f.height; + var rotate = rotateInPlace(__assign(__assign({}, rectangle), { rotation: rotation })); + var black = rgb(0, 0, 0); + var borderColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBorderColor()); + var normalBackgroundColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBackgroundColor()); + var downBackgroundColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBackgroundColor(), 0.8); + var bounds = { + x: borderWidth, + y: borderWidth, + width: width - borderWidth * 2, + height: height - borderWidth * 2, + }; + var normalLayout = layoutSinglelineText(normalText, { + alignment: TextAlignment.Center, + fontSize: widgetFontSize !== null && widgetFontSize !== void 0 ? widgetFontSize : fieldFontSize, + font: font, + bounds: bounds, + }); + var downLayout = layoutSinglelineText(downText, { + alignment: TextAlignment.Center, + fontSize: widgetFontSize !== null && widgetFontSize !== void 0 ? widgetFontSize : fieldFontSize, + font: font, + bounds: bounds, + }); + // Update font size and color + var fontSize = Math.min(normalLayout.fontSize, downLayout.fontSize); + var textColor = (_e = widgetColor !== null && widgetColor !== void 0 ? widgetColor : fieldColor) !== null && _e !== void 0 ? _e : black; + if (widgetColor || widgetFontSize !== undefined) { + updateDefaultAppearance(widget, textColor, font, fontSize); + } + else { + updateDefaultAppearance(button.acroField, textColor, font, fontSize); + } + var options = { + x: 0 + borderWidth / 2, + y: 0 + borderWidth / 2, + width: width - borderWidth, + height: height - borderWidth, + borderWidth: borderWidth, + borderColor: borderColor, + textColor: textColor, + font: font.name, + fontSize: fontSize, + }; + return { + normal: __spreadArrays(rotate, drawButton(__assign(__assign({}, options), { color: normalBackgroundColor, textLines: [normalLayout.line] }))), + down: __spreadArrays(rotate, drawButton(__assign(__assign({}, options), { color: downBackgroundColor, textLines: [downLayout.line] }))), + }; +}; +var defaultTextFieldAppearanceProvider = function (textField, widget, font) { + var _a, _b, _c, _d; + // The `/DA` entry can be at the widget or field level - so we handle both + var widgetColor = getDefaultColor(widget); + var fieldColor = getDefaultColor(textField.acroField); + var widgetFontSize = getDefaultFontSize(widget); + var fieldFontSize = getDefaultFontSize(textField.acroField); + var rectangle = widget.getRectangle(); + var ap = widget.getAppearanceCharacteristics(); + var bs = widget.getBorderStyle(); + var text = (_a = textField.getText()) !== null && _a !== void 0 ? _a : ''; + var borderWidth = (_b = bs === null || bs === void 0 ? void 0 : bs.getWidth()) !== null && _b !== void 0 ? _b : 0; + var rotation = reduceRotation(ap === null || ap === void 0 ? void 0 : ap.getRotation()); + var _e = adjustDimsForRotation(rectangle, rotation), width = _e.width, height = _e.height; + var rotate = rotateInPlace(__assign(__assign({}, rectangle), { rotation: rotation })); + var black = rgb(0, 0, 0); + var borderColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBorderColor()); + var normalBackgroundColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBackgroundColor()); + var textLines; + var fontSize; + var padding = textField.isCombed() ? 0 : 1; + var bounds = { + x: borderWidth + padding, + y: borderWidth + padding, + width: width - (borderWidth + padding) * 2, + height: height - (borderWidth + padding) * 2, + }; + if (textField.isMultiline()) { + var layout = layoutMultilineText(text, { + alignment: textField.getAlignment(), + fontSize: widgetFontSize !== null && widgetFontSize !== void 0 ? widgetFontSize : fieldFontSize, + font: font, + bounds: bounds, + }); + textLines = layout.lines; + fontSize = layout.fontSize; + } + else if (textField.isCombed()) { + var layout = layoutCombedText(text, { + fontSize: widgetFontSize !== null && widgetFontSize !== void 0 ? widgetFontSize : fieldFontSize, + font: font, + bounds: bounds, + cellCount: (_c = textField.getMaxLength()) !== null && _c !== void 0 ? _c : 0, + }); + textLines = layout.cells; + fontSize = layout.fontSize; + } + else { + var layout = layoutSinglelineText(text, { + alignment: textField.getAlignment(), + fontSize: widgetFontSize !== null && widgetFontSize !== void 0 ? widgetFontSize : fieldFontSize, + font: font, + bounds: bounds, + }); + textLines = [layout.line]; + fontSize = layout.fontSize; + } + // Update font size and color + var textColor = (_d = widgetColor !== null && widgetColor !== void 0 ? widgetColor : fieldColor) !== null && _d !== void 0 ? _d : black; + if (widgetColor || widgetFontSize !== undefined) { + updateDefaultAppearance(widget, textColor, font, fontSize); + } + else { + updateDefaultAppearance(textField.acroField, textColor, font, fontSize); + } + var options = { + x: 0 + borderWidth / 2, + y: 0 + borderWidth / 2, + width: width - borderWidth, + height: height - borderWidth, + borderWidth: borderWidth !== null && borderWidth !== void 0 ? borderWidth : 0, + borderColor: borderColor, + textColor: textColor, + font: font.name, + fontSize: fontSize, + color: normalBackgroundColor, + textLines: textLines, + padding: padding, + }; + return __spreadArrays(rotate, drawTextField(options)); +}; +var defaultDropdownAppearanceProvider = function (dropdown, widget, font) { + var _a, _b, _c; + // The `/DA` entry can be at the widget or field level - so we handle both + var widgetColor = getDefaultColor(widget); + var fieldColor = getDefaultColor(dropdown.acroField); + var widgetFontSize = getDefaultFontSize(widget); + var fieldFontSize = getDefaultFontSize(dropdown.acroField); + var rectangle = widget.getRectangle(); + var ap = widget.getAppearanceCharacteristics(); + var bs = widget.getBorderStyle(); + var text = (_a = dropdown.getSelected()[0]) !== null && _a !== void 0 ? _a : ''; + var borderWidth = (_b = bs === null || bs === void 0 ? void 0 : bs.getWidth()) !== null && _b !== void 0 ? _b : 0; + var rotation = reduceRotation(ap === null || ap === void 0 ? void 0 : ap.getRotation()); + var _d = adjustDimsForRotation(rectangle, rotation), width = _d.width, height = _d.height; + var rotate = rotateInPlace(__assign(__assign({}, rectangle), { rotation: rotation })); + var black = rgb(0, 0, 0); + var borderColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBorderColor()); + var normalBackgroundColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBackgroundColor()); + var padding = 1; + var bounds = { + x: borderWidth + padding, + y: borderWidth + padding, + width: width - (borderWidth + padding) * 2, + height: height - (borderWidth + padding) * 2, + }; + var _e = layoutSinglelineText(text, { + alignment: TextAlignment.Left, + fontSize: widgetFontSize !== null && widgetFontSize !== void 0 ? widgetFontSize : fieldFontSize, + font: font, + bounds: bounds, + }), line = _e.line, fontSize = _e.fontSize; + // Update font size and color + var textColor = (_c = widgetColor !== null && widgetColor !== void 0 ? widgetColor : fieldColor) !== null && _c !== void 0 ? _c : black; + if (widgetColor || widgetFontSize !== undefined) { + updateDefaultAppearance(widget, textColor, font, fontSize); + } + else { + updateDefaultAppearance(dropdown.acroField, textColor, font, fontSize); + } + var options = { + x: 0 + borderWidth / 2, + y: 0 + borderWidth / 2, + width: width - borderWidth, + height: height - borderWidth, + borderWidth: borderWidth !== null && borderWidth !== void 0 ? borderWidth : 0, + borderColor: borderColor, + textColor: textColor, + font: font.name, + fontSize: fontSize, + color: normalBackgroundColor, + textLines: [line], + padding: padding, + }; + return __spreadArrays(rotate, drawTextField(options)); +}; +var defaultOptionListAppearanceProvider = function (optionList, widget, font) { + var _a, _b; + // The `/DA` entry can be at the widget or field level - so we handle both + var widgetColor = getDefaultColor(widget); + var fieldColor = getDefaultColor(optionList.acroField); + var widgetFontSize = getDefaultFontSize(widget); + var fieldFontSize = getDefaultFontSize(optionList.acroField); + var rectangle = widget.getRectangle(); + var ap = widget.getAppearanceCharacteristics(); + var bs = widget.getBorderStyle(); + var borderWidth = (_a = bs === null || bs === void 0 ? void 0 : bs.getWidth()) !== null && _a !== void 0 ? _a : 0; + var rotation = reduceRotation(ap === null || ap === void 0 ? void 0 : ap.getRotation()); + var _c = adjustDimsForRotation(rectangle, rotation), width = _c.width, height = _c.height; + var rotate = rotateInPlace(__assign(__assign({}, rectangle), { rotation: rotation })); + var black = rgb(0, 0, 0); + var borderColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBorderColor()); + var normalBackgroundColor = componentsToColor(ap === null || ap === void 0 ? void 0 : ap.getBackgroundColor()); + var options = optionList.getOptions(); + var selected = optionList.getSelected(); + if (optionList.isSorted()) + options.sort(); + var text = ''; + for (var idx = 0, len = options.length; idx < len; idx++) { + text += options[idx]; + if (idx < len - 1) + text += '\n'; + } + var padding = 1; + var bounds = { + x: borderWidth + padding, + y: borderWidth + padding, + width: width - (borderWidth + padding) * 2, + height: height - (borderWidth + padding) * 2, + }; + var _d = layoutMultilineText(text, { + alignment: TextAlignment.Left, + fontSize: widgetFontSize !== null && widgetFontSize !== void 0 ? widgetFontSize : fieldFontSize, + font: font, + bounds: bounds, + }), lines = _d.lines, fontSize = _d.fontSize, lineHeight = _d.lineHeight; + var selectedLines = []; + for (var idx = 0, len = lines.length; idx < len; idx++) { + var line = lines[idx]; + if (selected.includes(line.text)) + selectedLines.push(idx); + } + var blue = rgb(153 / 255, 193 / 255, 218 / 255); + // Update font size and color + var textColor = (_b = widgetColor !== null && widgetColor !== void 0 ? widgetColor : fieldColor) !== null && _b !== void 0 ? _b : black; + if (widgetColor || widgetFontSize !== undefined) { + updateDefaultAppearance(widget, textColor, font, fontSize); + } + else { + updateDefaultAppearance(optionList.acroField, textColor, font, fontSize); + } + return __spreadArrays(rotate, drawOptionList({ + x: 0 + borderWidth / 2, + y: 0 + borderWidth / 2, + width: width - borderWidth, + height: height - borderWidth, + borderWidth: borderWidth !== null && borderWidth !== void 0 ? borderWidth : 0, + borderColor: borderColor, + textColor: textColor, + font: font.name, + fontSize: fontSize, + color: normalBackgroundColor, + textLines: lines, + lineHeight: lineHeight, + selectedColor: blue, + selectedLines: selectedLines, + padding: padding, + })); +}; + +/** + * Represents a PDF page that has been embedded in a [[PDFDocument]]. + */ +var PDFEmbeddedPage = /** @class */ (function () { + function PDFEmbeddedPage(ref, doc, embedder) { + this.alreadyEmbedded = false; + assertIs(ref, 'ref', [[PDFRef, 'PDFRef']]); + assertIs(doc, 'doc', [[PDFDocument, 'PDFDocument']]); + assertIs(embedder, 'embedder', [[PDFPageEmbedder, 'PDFPageEmbedder']]); + this.ref = ref; + this.doc = doc; + this.width = embedder.width; + this.height = embedder.height; + this.embedder = embedder; + } + /** + * Compute the width and height of this page after being scaled by the + * given `factor`. For example: + * ```js + * embeddedPage.width // => 500 + * embeddedPage.height // => 250 + * + * const scaled = embeddedPage.scale(0.5) + * scaled.width // => 250 + * scaled.height // => 125 + * ``` + * This operation is often useful before drawing a page with + * [[PDFPage.drawPage]] to compute the `width` and `height` options. + * @param factor The factor by which this page should be scaled. + * @returns The width and height of the page after being scaled. + */ + PDFEmbeddedPage.prototype.scale = function (factor) { + assertIs(factor, 'factor', ['number']); + return { width: this.width * factor, height: this.height * factor }; + }; + /** + * Get the width and height of this page. For example: + * ```js + * const { width, height } = embeddedPage.size() + * ``` + * @returns The width and height of the page. + */ + PDFEmbeddedPage.prototype.size = function () { + return this.scale(1); + }; + /** + * > **NOTE:** You probably don't need to call this method directly. The + * > [[PDFDocument.save]] and [[PDFDocument.saveAsBase64]] methods will + * > automatically ensure all embeddable pages get embedded. + * + * Embed this embeddable page in its document. + * + * @returns Resolves when the embedding is complete. + */ + PDFEmbeddedPage.prototype.embed = function () { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!!this.alreadyEmbedded) return [3 /*break*/, 2]; + return [4 /*yield*/, this.embedder.embedIntoContext(this.doc.context, this.ref)]; + case 1: + _a.sent(); + this.alreadyEmbedded = true; + _a.label = 2; + case 2: return [2 /*return*/]; + } + }); + }); + }; + /** + * > **NOTE:** You probably don't want to call this method directly. Instead, + * > consider using the [[PDFDocument.embedPdf]] and + * > [[PDFDocument.embedPage]] methods, which will create instances of + * > [[PDFEmbeddedPage]] for you. + * + * Create an instance of [[PDFEmbeddedPage]] from an existing ref and embedder + * + * @param ref The unique reference for this embedded page. + * @param doc The document to which the embedded page will belong. + * @param embedder The embedder that will be used to embed the page. + */ + PDFEmbeddedPage.of = function (ref, doc, embedder) { + return new PDFEmbeddedPage(ref, doc, embedder); + }; + return PDFEmbeddedPage; +}()); + +/** + * Represents a font that has been embedded in a [[PDFDocument]]. + */ +var PDFFont = /** @class */ (function () { + function PDFFont(ref, doc, embedder) { + this.modified = true; + assertIs(ref, 'ref', [[PDFRef, 'PDFRef']]); + assertIs(doc, 'doc', [[PDFDocument, 'PDFDocument']]); + assertIs(embedder, 'embedder', [ + [CustomFontEmbedder, 'CustomFontEmbedder'], + [StandardFontEmbedder, 'StandardFontEmbedder'], + ]); + this.ref = ref; + this.doc = doc; + this.name = embedder.fontName; + this.embedder = embedder; + } + /** + * > **NOTE:** You probably don't need to call this method directly. The + * > [[PDFPage.drawText]] method will automatically encode the text it is + * > given. + * + * Encodes a string of text in this font. + * + * @param text The text to be encoded. + * @returns The encoded text as a hex string. + */ + PDFFont.prototype.encodeText = function (text) { + assertIs(text, 'text', ['string']); + this.modified = true; + return this.embedder.encodeText(text); + }; + /** + * Measure the width of a string of text drawn in this font at a given size. + * For example: + * ```js + * const width = font.widthOfTextAtSize('Foo Bar Qux Baz', 36) + * ``` + * @param text The string of text to be measured. + * @param size The font size to be used for this measurement. + * @returns The width of the string of text when drawn in this font at the + * given size. + */ + PDFFont.prototype.widthOfTextAtSize = function (text, size) { + assertIs(text, 'text', ['string']); + assertIs(size, 'size', ['number']); + return this.embedder.widthOfTextAtSize(text, size); + }; + /** + * Measure the height of this font at a given size. For example: + * ```js + * const height = font.heightAtSize(24) + * ``` + * + * The `options.descender` value controls whether or not the font's + * descender is included in the height calculation. + * + * @param size The font size to be used for this measurement. + * @param options The options to be used when computing this measurement. + * @returns The height of this font at the given size. + */ + PDFFont.prototype.heightAtSize = function (size, options) { + var _a; + assertIs(size, 'size', ['number']); + assertOrUndefined(options === null || options === void 0 ? void 0 : options.descender, 'options.descender', ['boolean']); + return this.embedder.heightOfFontAtSize(size, { + descender: (_a = options === null || options === void 0 ? void 0 : options.descender) !== null && _a !== void 0 ? _a : true, + }); + }; + /** + * Compute the font size at which this font is a given height. For example: + * ```js + * const fontSize = font.sizeAtHeight(12) + * ``` + * @param height The height to be used for this calculation. + * @returns The font size at which this font is the given height. + */ + PDFFont.prototype.sizeAtHeight = function (height) { + assertIs(height, 'height', ['number']); + return this.embedder.sizeOfFontAtHeight(height); + }; + /** + * Get the set of unicode code points that can be represented by this font. + * @returns The set of unicode code points supported by this font. + */ + PDFFont.prototype.getCharacterSet = function () { + if (this.embedder instanceof StandardFontEmbedder) { + return this.embedder.encoding.supportedCodePoints; + } + else { + return this.embedder.font.characterSet; + } + }; + /** + * > **NOTE:** You probably don't need to call this method directly. The + * > [[PDFDocument.save]] and [[PDFDocument.saveAsBase64]] methods will + * > automatically ensure all fonts get embedded. + * + * Embed this font in its document. + * + * @returns Resolves when the embedding is complete. + */ + PDFFont.prototype.embed = function () { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!this.modified) return [3 /*break*/, 2]; + return [4 /*yield*/, this.embedder.embedIntoContext(this.doc.context, this.ref)]; + case 1: + _a.sent(); + this.modified = false; + _a.label = 2; + case 2: return [2 /*return*/]; + } + }); + }); + }; + /** + * > **NOTE:** You probably don't want to call this method directly. Instead, + * > consider using the [[PDFDocument.embedFont]] and + * > [[PDFDocument.embedStandardFont]] methods, which will create instances + * > of [[PDFFont]] for you. + * + * Create an instance of [[PDFFont]] from an existing ref and embedder + * + * @param ref The unique reference for this font. + * @param doc The document to which the font will belong. + * @param embedder The embedder that will be used to embed the font. + */ + PDFFont.of = function (ref, doc, embedder) { + return new PDFFont(ref, doc, embedder); + }; + return PDFFont; +}()); + +/** + * Represents an image that has been embedded in a [[PDFDocument]]. + */ +var PDFImage = /** @class */ (function () { + function PDFImage(ref, doc, embedder) { + assertIs(ref, 'ref', [[PDFRef, 'PDFRef']]); + assertIs(doc, 'doc', [[PDFDocument, 'PDFDocument']]); + assertIs(embedder, 'embedder', [ + [JpegEmbedder, 'JpegEmbedder'], + [PngEmbedder, 'PngEmbedder'], + ]); + this.ref = ref; + this.doc = doc; + this.width = embedder.width; + this.height = embedder.height; + this.embedder = embedder; + } + /** + * Compute the width and height of this image after being scaled by the + * given `factor`. For example: + * ```js + * image.width // => 500 + * image.height // => 250 + * + * const scaled = image.scale(0.5) + * scaled.width // => 250 + * scaled.height // => 125 + * ``` + * This operation is often useful before drawing an image with + * [[PDFPage.drawImage]] to compute the `width` and `height` options. + * @param factor The factor by which this image should be scaled. + * @returns The width and height of the image after being scaled. + */ + PDFImage.prototype.scale = function (factor) { + assertIs(factor, 'factor', ['number']); + return { width: this.width * factor, height: this.height * factor }; + }; + /** + * Get the width and height of this image after scaling it as large as + * possible while maintaining its aspect ratio and not exceeding the + * specified `width` and `height`. For example: + * ``` + * image.width // => 500 + * image.height // => 250 + * + * const scaled = image.scaleToFit(750, 1000) + * scaled.width // => 750 + * scaled.height // => 375 + * ``` + * The `width` and `height` parameters can also be thought of as the width + * and height of a box that the scaled image must fit within. + * @param width The bounding box's width. + * @param height The bounding box's height. + * @returns The width and height of the image after being scaled. + */ + PDFImage.prototype.scaleToFit = function (width, height) { + assertIs(width, 'width', ['number']); + assertIs(height, 'height', ['number']); + var imgWidthScale = width / this.width; + var imgHeightScale = height / this.height; + var scale = Math.min(imgWidthScale, imgHeightScale); + return this.scale(scale); + }; + /** + * Get the width and height of this image. For example: + * ```js + * const { width, height } = image.size() + * ``` + * @returns The width and height of the image. + */ + PDFImage.prototype.size = function () { + return this.scale(1); + }; + /** + * > **NOTE:** You probably don't need to call this method directly. The + * > [[PDFDocument.save]] and [[PDFDocument.saveAsBase64]] methods will + * > automatically ensure all images get embedded. + * + * Embed this image in its document. + * + * @returns Resolves when the embedding is complete. + */ + PDFImage.prototype.embed = function () { + return __awaiter(this, void 0, void 0, function () { + var _a, doc, ref; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!this.embedder) + return [2 /*return*/]; + // The image should only be embedded once. If there's a pending embed + // operation then wait on it. Otherwise we need to start the embed. + if (!this.embedTask) { + _a = this, doc = _a.doc, ref = _a.ref; + this.embedTask = this.embedder.embedIntoContext(doc.context, ref); + } + return [4 /*yield*/, this.embedTask]; + case 1: + _b.sent(); + // We clear `this.embedder` so that the indirectly referenced image data + // can be garbage collected, thus avoiding a memory leak. + // See https://github.com/Hopding/pdf-lib/pull/1032/files. + this.embedder = undefined; + return [2 /*return*/]; + } + }); + }); + }; + /** + * > **NOTE:** You probably don't want to call this method directly. Instead, + * > consider using the [[PDFDocument.embedPng]] and [[PDFDocument.embedJpg]] + * > methods, which will create instances of [[PDFImage]] for you. + * + * Create an instance of [[PDFImage]] from an existing ref and embedder + * + * @param ref The unique reference for this image. + * @param doc The document to which the image will belong. + * @param embedder The embedder that will be used to embed the image. + */ + PDFImage.of = function (ref, doc, embedder) { + return new PDFImage(ref, doc, embedder); + }; + return PDFImage; +}()); + +var ImageAlignment; +(function (ImageAlignment) { + ImageAlignment[ImageAlignment["Left"] = 0] = "Left"; + ImageAlignment[ImageAlignment["Center"] = 1] = "Center"; + ImageAlignment[ImageAlignment["Right"] = 2] = "Right"; +})(ImageAlignment || (ImageAlignment = {})); + +var assertFieldAppearanceOptions = function (options) { + assertOrUndefined(options === null || options === void 0 ? void 0 : options.x, 'options.x', ['number']); + assertOrUndefined(options === null || options === void 0 ? void 0 : options.y, 'options.y', ['number']); + assertOrUndefined(options === null || options === void 0 ? void 0 : options.width, 'options.width', ['number']); + assertOrUndefined(options === null || options === void 0 ? void 0 : options.height, 'options.height', ['number']); + assertOrUndefined(options === null || options === void 0 ? void 0 : options.textColor, 'options.textColor', [ + [Object, 'Color'], + ]); + assertOrUndefined(options === null || options === void 0 ? void 0 : options.backgroundColor, 'options.backgroundColor', [ + [Object, 'Color'], + ]); + assertOrUndefined(options === null || options === void 0 ? void 0 : options.borderColor, 'options.borderColor', [ + [Object, 'Color'], + ]); + assertOrUndefined(options === null || options === void 0 ? void 0 : options.borderWidth, 'options.borderWidth', ['number']); + assertOrUndefined(options === null || options === void 0 ? void 0 : options.rotate, 'options.rotate', [[Object, 'Rotation']]); +}; +/** + * Represents a field of a [[PDFForm]]. + * + * This class is effectively abstract. All fields in a [[PDFForm]] will + * actually be an instance of a subclass of this class. + * + * Note that each field in a PDF is represented by a single field object. + * However, a given field object may be rendered at multiple locations within + * the document (across one or more pages). The rendering of a field is + * controlled by its widgets. Each widget causes its field to be displayed at a + * particular location in the document. + * + * Most of the time each field in a PDF has only a single widget, and thus is + * only rendered once. However, if a field is rendered multiple times, it will + * have multiple widgets - one for each location it is rendered. + * + * This abstraction of field objects and widgets is defined in the PDF + * specification and dictates how PDF files store fields and where they are + * to be rendered. + */ +var PDFField = /** @class */ (function () { + function PDFField(acroField, ref, doc) { + assertIs(acroField, 'acroField', [[PDFAcroTerminal, 'PDFAcroTerminal']]); + assertIs(ref, 'ref', [[PDFRef, 'PDFRef']]); + assertIs(doc, 'doc', [[PDFDocument, 'PDFDocument']]); + this.acroField = acroField; + this.ref = ref; + this.doc = doc; + } + /** + * Get the fully qualified name of this field. For example: + * ```js + * const fields = form.getFields() + * fields.forEach(field => { + * const name = field.getName() + * console.log('Field name:', name) + * }) + * ``` + * Note that PDF fields are structured as a tree. Each field is the + * descendent of a series of ancestor nodes all the way up to the form node, + * which is always the root of the tree. Each node in the tree (except for + * the form node) has a partial name. Partial names can be composed of any + * unicode characters except a period (`.`). The fully qualified name of a + * field is composed of the partial names of all its ancestors joined + * with periods. This means that splitting the fully qualified name on + * periods and taking the last element of the resulting array will give you + * the partial name of a specific field. + * @returns The fully qualified name of this field. + */ + PDFField.prototype.getName = function () { + var _a; + return (_a = this.acroField.getFullyQualifiedName()) !== null && _a !== void 0 ? _a : ''; + }; + /** + * Returns `true` if this field is read only. This means that PDF readers + * will not allow users to interact with the field or change its value. See + * [[PDFField.enableReadOnly]] and [[PDFField.disableReadOnly]]. + * For example: + * ```js + * const field = form.getField('some.field') + * if (field.isReadOnly()) console.log('Read only is enabled') + * ``` + * @returns Whether or not this is a read only field. + */ + PDFField.prototype.isReadOnly = function () { + return this.acroField.hasFlag(AcroFieldFlags.ReadOnly); + }; + /** + * Prevent PDF readers from allowing users to interact with this field or + * change its value. The field will not respond to mouse or keyboard input. + * For example: + * ```js + * const field = form.getField('some.field') + * field.enableReadOnly() + * ``` + * Useful for fields whose values are computed, imported from a database, or + * prefilled by software before being displayed to the user. + */ + PDFField.prototype.enableReadOnly = function () { + this.acroField.setFlagTo(AcroFieldFlags.ReadOnly, true); + }; + /** + * Allow users to interact with this field and change its value in PDF + * readers via mouse and keyboard input. For example: + * ```js + * const field = form.getField('some.field') + * field.disableReadOnly() + * ``` + */ + PDFField.prototype.disableReadOnly = function () { + this.acroField.setFlagTo(AcroFieldFlags.ReadOnly, false); + }; + /** + * Returns `true` if this field must have a value when the form is submitted. + * See [[PDFField.enableRequired]] and [[PDFField.disableRequired]]. + * For example: + * ```js + * const field = form.getField('some.field') + * if (field.isRequired()) console.log('Field is required') + * ``` + * @returns Whether or not this field is required. + */ + PDFField.prototype.isRequired = function () { + return this.acroField.hasFlag(AcroFieldFlags.Required); + }; + /** + * Require this field to have a value when the form is submitted. + * For example: + * ```js + * const field = form.getField('some.field') + * field.enableRequired() + * ``` + */ + PDFField.prototype.enableRequired = function () { + this.acroField.setFlagTo(AcroFieldFlags.Required, true); + }; + /** + * Do not require this field to have a value when the form is submitted. + * For example: + * ```js + * const field = form.getField('some.field') + * field.disableRequired() + * ``` + */ + PDFField.prototype.disableRequired = function () { + this.acroField.setFlagTo(AcroFieldFlags.Required, false); + }; + /** + * Returns `true` if this field's value should be exported when the form is + * submitted. See [[PDFField.enableExporting]] and + * [[PDFField.disableExporting]]. + * For example: + * ```js + * const field = form.getField('some.field') + * if (field.isExported()) console.log('Exporting is enabled') + * ``` + * @returns Whether or not this field's value should be exported. + */ + PDFField.prototype.isExported = function () { + return !this.acroField.hasFlag(AcroFieldFlags.NoExport); + }; + /** + * Indicate that this field's value should be exported when the form is + * submitted in a PDF reader. For example: + * ```js + * const field = form.getField('some.field') + * field.enableExporting() + * ``` + */ + PDFField.prototype.enableExporting = function () { + this.acroField.setFlagTo(AcroFieldFlags.NoExport, false); + }; + /** + * Indicate that this field's value should **not** be exported when the form + * is submitted in a PDF reader. For example: + * ```js + * const field = form.getField('some.field') + * field.disableExporting() + * ``` + */ + PDFField.prototype.disableExporting = function () { + this.acroField.setFlagTo(AcroFieldFlags.NoExport, true); + }; + /** @ignore */ + PDFField.prototype.needsAppearancesUpdate = function () { + throw new MethodNotImplementedError(this.constructor.name, 'needsAppearancesUpdate'); + }; + /** @ignore */ + PDFField.prototype.defaultUpdateAppearances = function (_font) { + throw new MethodNotImplementedError(this.constructor.name, 'defaultUpdateAppearances'); + }; + PDFField.prototype.markAsDirty = function () { + this.doc.getForm().markFieldAsDirty(this.ref); + }; + PDFField.prototype.markAsClean = function () { + this.doc.getForm().markFieldAsClean(this.ref); + }; + PDFField.prototype.isDirty = function () { + return this.doc.getForm().fieldIsDirty(this.ref); + }; + PDFField.prototype.createWidget = function (options) { + var _a; + var textColor = options.textColor; + var backgroundColor = options.backgroundColor; + var borderColor = options.borderColor; + var borderWidth = options.borderWidth; + var degreesAngle = toDegrees(options.rotate); + var caption = options.caption; + var x = options.x; + var y = options.y; + var width = options.width + borderWidth; + var height = options.height + borderWidth; + var hidden = Boolean(options.hidden); + var pageRef = options.page; + assertMultiple(degreesAngle, 'degreesAngle', 90); + // Create a widget for this field + var widget = PDFWidgetAnnotation.create(this.doc.context, this.ref); + // Set widget properties + var rect = rotateRectangle({ x: x, y: y, width: width, height: height }, borderWidth, degreesAngle); + widget.setRectangle(rect); + if (pageRef) + widget.setP(pageRef); + var ac = widget.getOrCreateAppearanceCharacteristics(); + if (backgroundColor) { + ac.setBackgroundColor(colorToComponents(backgroundColor)); + } + ac.setRotation(degreesAngle); + if (caption) + ac.setCaptions({ normal: caption }); + if (borderColor) + ac.setBorderColor(colorToComponents(borderColor)); + var bs = widget.getOrCreateBorderStyle(); + if (borderWidth !== undefined) + bs.setWidth(borderWidth); + widget.setFlagTo(AnnotationFlags.Print, true); + widget.setFlagTo(AnnotationFlags.Hidden, hidden); + widget.setFlagTo(AnnotationFlags.Invisible, false); + // Set acrofield properties + if (textColor) { + var da = (_a = this.acroField.getDefaultAppearance()) !== null && _a !== void 0 ? _a : ''; + var newDa = da + '\n' + setFillingColor(textColor).toString(); + this.acroField.setDefaultAppearance(newDa); + } + return widget; + }; + PDFField.prototype.updateWidgetAppearanceWithFont = function (widget, font, _a) { + var normal = _a.normal, rollover = _a.rollover, down = _a.down; + this.updateWidgetAppearances(widget, { + normal: this.createAppearanceStream(widget, normal, font), + rollover: rollover && this.createAppearanceStream(widget, rollover, font), + down: down && this.createAppearanceStream(widget, down, font), + }); + }; + PDFField.prototype.updateOnOffWidgetAppearance = function (widget, onValue, _a) { + var normal = _a.normal, rollover = _a.rollover, down = _a.down; + this.updateWidgetAppearances(widget, { + normal: this.createAppearanceDict(widget, normal, onValue), + rollover: rollover && this.createAppearanceDict(widget, rollover, onValue), + down: down && this.createAppearanceDict(widget, down, onValue), + }); + }; + PDFField.prototype.updateWidgetAppearances = function (widget, _a) { + var normal = _a.normal, rollover = _a.rollover, down = _a.down; + widget.setNormalAppearance(normal); + if (rollover) { + widget.setRolloverAppearance(rollover); + } + else { + widget.removeRolloverAppearance(); + } + if (down) { + widget.setDownAppearance(down); + } + else { + widget.removeDownAppearance(); + } + }; + // // TODO: Do we need to do this...? + // private foo(font: PDFFont, dict: PDFDict) { + // if (!dict.lookup(PDFName.of('DR'))) { + // dict.set(PDFName.of('DR'), dict.context.obj({})); + // } + // const DR = dict.lookup(PDFName.of('DR'), PDFDict); + // if (!DR.lookup(PDFName.of('Font'))) { + // DR.set(PDFName.of('Font'), dict.context.obj({})); + // } + // const Font = DR.lookup(PDFName.of('Font'), PDFDict); + // Font.set(PDFName.of(font.name), font.ref); + // } + PDFField.prototype.createAppearanceStream = function (widget, appearance, font) { + var _a; + var context = this.acroField.dict.context; + var _b = widget.getRectangle(), width = _b.width, height = _b.height; + // TODO: Do we need to do this...? + // if (font) { + // this.foo(font, widget.dict); + // this.foo(font, this.doc.getForm().acroForm.dict); + // } + // END TODO + var Resources = font && { Font: (_a = {}, _a[font.name] = font.ref, _a) }; + var stream = context.formXObject(appearance, { + Resources: Resources, + BBox: context.obj([0, 0, width, height]), + Matrix: context.obj([1, 0, 0, 1, 0, 0]), + }); + var streamRef = context.register(stream); + return streamRef; + }; + /** + * Create a FormXObject of the supplied image and add it to context. + * The FormXObject size is calculated based on the widget (including + * the alignment). + * @param widget The widget that should display the image. + * @param alignment The alignment of the image. + * @param image The image that should be displayed. + * @returns The ref for the FormXObject that was added to the context. + */ + PDFField.prototype.createImageAppearanceStream = function (widget, image, alignment) { + // NOTE: This implementation doesn't handle image borders. + // NOTE: Acrobat seems to resize the image (maybe even skewing its aspect + // ratio) to fit perfectly within the widget's rectangle. This method + // does not currently do that. Should there be an option for that? + var _a; + var _b; + var context = this.acroField.dict.context; + var rectangle = widget.getRectangle(); + var ap = widget.getAppearanceCharacteristics(); + var bs = widget.getBorderStyle(); + var borderWidth = (_b = bs === null || bs === void 0 ? void 0 : bs.getWidth()) !== null && _b !== void 0 ? _b : 0; + var rotation = reduceRotation(ap === null || ap === void 0 ? void 0 : ap.getRotation()); + var rotate = rotateInPlace(__assign(__assign({}, rectangle), { rotation: rotation })); + var adj = adjustDimsForRotation(rectangle, rotation); + var imageDims = image.scaleToFit(adj.width - borderWidth * 2, adj.height - borderWidth * 2); + // Support borders on images and maybe other properties + var options = { + x: borderWidth, + y: borderWidth, + width: imageDims.width, + height: imageDims.height, + // + rotate: degrees(0), + xSkew: degrees(0), + ySkew: degrees(0), + }; + if (alignment === ImageAlignment.Center) { + options.x += (adj.width - borderWidth * 2) / 2 - imageDims.width / 2; + options.y += (adj.height - borderWidth * 2) / 2 - imageDims.height / 2; + } + else if (alignment === ImageAlignment.Right) { + options.x = adj.width - borderWidth - imageDims.width; + options.y = adj.height - borderWidth - imageDims.height; + } + var imageName = this.doc.context.addRandomSuffix('Image', 10); + var appearance = __spreadArrays(rotate, drawImage(imageName, options)); + //////////// + var Resources = { XObject: (_a = {}, _a[imageName] = image.ref, _a) }; + var stream = context.formXObject(appearance, { + Resources: Resources, + BBox: context.obj([0, 0, rectangle.width, rectangle.height]), + Matrix: context.obj([1, 0, 0, 1, 0, 0]), + }); + return context.register(stream); + }; + PDFField.prototype.createAppearanceDict = function (widget, appearance, onValue) { + var context = this.acroField.dict.context; + var onStreamRef = this.createAppearanceStream(widget, appearance.on); + var offStreamRef = this.createAppearanceStream(widget, appearance.off); + var appearanceDict = context.obj({}); + appearanceDict.set(onValue, onStreamRef); + appearanceDict.set(PDFName.of('Off'), offStreamRef); + return appearanceDict; + }; + return PDFField; +}()); + +/** + * Represents a check box field of a [[PDFForm]]. + * + * [[PDFCheckBox]] fields are interactive boxes that users can click with their + * mouse. This type of [[PDFField]] has two states: `on` and `off`. The purpose + * of a check box is to enable users to select from one or more options, where + * each option is represented by a single check box. Check boxes are typically + * square in shape and display a check mark when they are in the `on` state. + */ +var PDFCheckBox = /** @class */ (function (_super) { + __extends(PDFCheckBox, _super); + function PDFCheckBox(acroCheckBox, ref, doc) { + var _this = _super.call(this, acroCheckBox, ref, doc) || this; + assertIs(acroCheckBox, 'acroCheckBox', [ + [PDFAcroCheckBox, 'PDFAcroCheckBox'], + ]); + _this.acroField = acroCheckBox; + return _this; + } + /** + * Mark this check box. This operation is analogous to a human user clicking + * a check box to fill it in a PDF reader. This method will update the + * underlying state of the check box field to indicate it has been selected. + * PDF libraries and readers will be able to extract this value from the + * saved document and determine that it was selected. + * + * For example: + * ```js + * const checkBox = form.getCheckBox('some.checkBox.field') + * checkBox.check() + * ``` + * + * This method will mark this check box as dirty, causing its appearance + * streams to be updated when either [[PDFDocument.save]] or + * [[PDFForm.updateFieldAppearances]] is called. The updated appearance + * streams will display a check mark inside the widgets of this check box + * field. + */ + PDFCheckBox.prototype.check = function () { + var _a; + var onValue = (_a = this.acroField.getOnValue()) !== null && _a !== void 0 ? _a : PDFName.of('Yes'); + this.markAsDirty(); + this.acroField.setValue(onValue); + }; + /** + * Clears this check box. This operation is analogous to a human user clicking + * a check box to unmark it in a PDF reader. This method will update the + * underlying state of the check box field to indicate it has been deselected. + * PDF libraries and readers will be able to extract this value from the + * saved document and determine that it was not selected. + * + * For example: + * ```js + * const checkBox = form.getCheckBox('some.checkBox.field') + * checkBox.uncheck() + * ``` + * + * This method will mark this check box as dirty. See [[PDFCheckBox.check]] + * for more details about what this means. + */ + PDFCheckBox.prototype.uncheck = function () { + this.markAsDirty(); + this.acroField.setValue(PDFName.of('Off')); + }; + /** + * Returns `true` if this check box is selected (either by a human user via + * a PDF reader, or else programmatically via software). For example: + * ```js + * const checkBox = form.getCheckBox('some.checkBox.field') + * if (checkBox.isChecked()) console.log('check box is selected') + * ``` + * @returns Whether or not this check box is selected. + */ + PDFCheckBox.prototype.isChecked = function () { + var onValue = this.acroField.getOnValue(); + return !!onValue && onValue === this.acroField.getValue(); + }; + /** + * Show this check box on the specified page. For example: + * ```js + * const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica) + * const page = pdfDoc.addPage() + * + * const form = pdfDoc.getForm() + * const checkBox = form.createCheckBox('some.checkBox.field') + * + * checkBox.addToPage(page, { + * x: 50, + * y: 75, + * width: 25, + * height: 25, + * textColor: rgb(1, 0, 0), + * backgroundColor: rgb(0, 1, 0), + * borderColor: rgb(0, 0, 1), + * borderWidth: 2, + * rotate: degrees(90), + * }) + * ``` + * This will create a new widget for this check box field. + * @param page The page to which this check box widget should be added. + * @param options The options to be used when adding this check box widget. + */ + PDFCheckBox.prototype.addToPage = function (page, options) { + var _a, _b, _c, _d, _e, _f; + assertIs(page, 'page', [[PDFPage, 'PDFPage']]); + assertFieldAppearanceOptions(options); + if (!options) + options = {}; + if (!('textColor' in options)) + options.textColor = rgb(0, 0, 0); + if (!('backgroundColor' in options)) + options.backgroundColor = rgb(1, 1, 1); + if (!('borderColor' in options)) + options.borderColor = rgb(0, 0, 0); + if (!('borderWidth' in options)) + options.borderWidth = 1; + // Create a widget for this check box + var widget = this.createWidget({ + x: (_a = options.x) !== null && _a !== void 0 ? _a : 0, + y: (_b = options.y) !== null && _b !== void 0 ? _b : 0, + width: (_c = options.width) !== null && _c !== void 0 ? _c : 50, + height: (_d = options.height) !== null && _d !== void 0 ? _d : 50, + textColor: options.textColor, + backgroundColor: options.backgroundColor, + borderColor: options.borderColor, + borderWidth: (_e = options.borderWidth) !== null && _e !== void 0 ? _e : 0, + rotate: (_f = options.rotate) !== null && _f !== void 0 ? _f : degrees(0), + hidden: options.hidden, + page: page.ref, + }); + var widgetRef = this.doc.context.register(widget.dict); + // Add widget to this field + this.acroField.addWidget(widgetRef); + // Set appearance streams for widget + widget.setAppearanceState(PDFName.of('Off')); + this.updateWidgetAppearance(widget, PDFName.of('Yes')); + // Add widget to the given page + page.node.addAnnot(widgetRef); + }; + /** + * Returns `true` if any of this check box's widgets do not have an + * appearance stream for its current state. For example: + * ```js + * const checkBox = form.getCheckBox('some.checkBox.field') + * if (checkBox.needsAppearancesUpdate()) console.log('Needs update') + * ``` + * @returns Whether or not this check box needs an appearance update. + */ + PDFCheckBox.prototype.needsAppearancesUpdate = function () { + var _a; + var widgets = this.acroField.getWidgets(); + for (var idx = 0, len = widgets.length; idx < len; idx++) { + var widget = widgets[idx]; + var state = widget.getAppearanceState(); + var normal = (_a = widget.getAppearances()) === null || _a === void 0 ? void 0 : _a.normal; + if (!(normal instanceof PDFDict)) + return true; + if (state && !normal.has(state)) + return true; + } + return false; + }; + /** + * Update the appearance streams for each of this check box's widgets using + * the default appearance provider for check boxes. For example: + * ```js + * const checkBox = form.getCheckBox('some.checkBox.field') + * checkBox.defaultUpdateAppearances() + * ``` + */ + PDFCheckBox.prototype.defaultUpdateAppearances = function () { + this.updateAppearances(); + }; + /** + * Update the appearance streams for each of this check box's widgets using + * the given appearance provider. If no `provider` is passed, the default + * appearance provider for check boxs will be used. For example: + * ```js + * const checkBox = form.getCheckBox('some.checkBox.field') + * checkBox.updateAppearances((field, widget) => { + * ... + * return { + * normal: { on: drawCheckBox(...), off: drawCheckBox(...) }, + * down: { on: drawCheckBox(...), off: drawCheckBox(...) }, + * } + * }) + * ``` + * @param provider Optionally, the appearance provider to be used for + * generating the contents of the appearance streams. + */ + PDFCheckBox.prototype.updateAppearances = function (provider) { + var _a; + assertOrUndefined(provider, 'provider', [Function]); + var widgets = this.acroField.getWidgets(); + for (var idx = 0, len = widgets.length; idx < len; idx++) { + var widget = widgets[idx]; + var onValue = (_a = widget.getOnValue()) !== null && _a !== void 0 ? _a : PDFName.of('Yes'); + if (!onValue) + continue; + this.updateWidgetAppearance(widget, onValue, provider); + } + this.markAsClean(); + }; + PDFCheckBox.prototype.updateWidgetAppearance = function (widget, onValue, provider) { + var apProvider = provider !== null && provider !== void 0 ? provider : defaultCheckBoxAppearanceProvider; + var appearances = normalizeAppearance(apProvider(this, widget)); + this.updateOnOffWidgetAppearance(widget, onValue, appearances); + }; + /** + * > **NOTE:** You probably don't want to call this method directly. Instead, + * > consider using the [[PDFForm.getCheckBox]] method, which will create an + * > instance of [[PDFCheckBox]] for you. + * + * Create an instance of [[PDFCheckBox]] from an existing acroCheckBox and ref + * + * @param acroCheckBox The underlying `PDFAcroCheckBox` for this check box. + * @param ref The unique reference for this check box. + * @param doc The document to which this check box will belong. + */ + PDFCheckBox.of = function (acroCheckBox, ref, doc) { + return new PDFCheckBox(acroCheckBox, ref, doc); + }; + return PDFCheckBox; +}(PDFField)); + +/** + * Represents a dropdown field of a [[PDFForm]]. + * + * [[PDFDropdown]] fields are interactive text boxes that display a single + * element (the currently selected value). The purpose of a dropdown is to + * enable users to select a single option from a set of possible options. Users + * can click on a dropdown to view the full list of options it provides. + * Clicking on an option in the list will cause it to be selected and displayed + * in the dropdown's text box. Some dropdowns allow users to enter text + * directly into the box from their keyboard, rather than only being allowed to + * choose an option from the list (see [[PDFDropdown.isEditable]]). + */ +var PDFDropdown = /** @class */ (function (_super) { + __extends(PDFDropdown, _super); + function PDFDropdown(acroComboBox, ref, doc) { + var _this = _super.call(this, acroComboBox, ref, doc) || this; + assertIs(acroComboBox, 'acroComboBox', [ + [PDFAcroComboBox, 'PDFAcroComboBox'], + ]); + _this.acroField = acroComboBox; + return _this; + } + /** + * Get the list of available options for this dropdown. These options will be + * displayed to users who click on this dropdown in a PDF reader. + * For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * const options = dropdown.getOptions() + * console.log('Dropdown options:', options) + * ``` + * @returns The options for this dropdown. + */ + PDFDropdown.prototype.getOptions = function () { + var rawOptions = this.acroField.getOptions(); + var options = new Array(rawOptions.length); + for (var idx = 0, len = options.length; idx < len; idx++) { + var _a = rawOptions[idx], display = _a.display, value = _a.value; + options[idx] = (display !== null && display !== void 0 ? display : value).decodeText(); + } + return options; + }; + /** + * Get the selected options for this dropdown. These are the values that were + * selected by a human user via a PDF reader, or programatically via + * software. + * For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * const selections = dropdown.getSelected() + * console.log('Dropdown selections:', selections) + * ``` + * > **NOTE:** Note that PDF readers only display one selected option when + * > rendering dropdowns. However, the PDF specification does allow for + * > multiple values to be selected in a dropdown. As such, the `pdf-lib` + * > API supports this. However, in most cases the array returned by this + * > method will contain only a single element (or no elements). + * @returns The selected options in this dropdown. + */ + PDFDropdown.prototype.getSelected = function () { + var values = this.acroField.getValues(); + var selected = new Array(values.length); + for (var idx = 0, len = values.length; idx < len; idx++) { + selected[idx] = values[idx].decodeText(); + } + return selected; + }; + /** + * Set the list of options that are available for this dropdown. These are + * the values that will be available for users to select when they view this + * dropdown in a PDF reader. Note that preexisting options for this dropdown + * will be removed. Only the values passed as `options` will be available to + * select. + * For example: + * ```js + * const dropdown = form.getDropdown('planets.dropdown') + * dropdown.setOptions(['Earth', 'Mars', 'Pluto', 'Venus']) + * ``` + * @param options The options that should be available in this dropdown. + */ + PDFDropdown.prototype.setOptions = function (options) { + assertIs(options, 'options', [Array]); + var optionObjects = new Array(options.length); + for (var idx = 0, len = options.length; idx < len; idx++) { + optionObjects[idx] = { value: PDFHexString.fromText(options[idx]) }; + } + this.acroField.setOptions(optionObjects); + }; + /** + * Add to the list of options that are available for this dropdown. Users + * will be able to select these values in a PDF reader. In addition to the + * values passed as `options`, any preexisting options for this dropdown will + * still be available for users to select. + * For example: + * ```js + * const dropdown = form.getDropdown('rockets.dropdown') + * dropdown.addOptions(['Saturn IV', 'Falcon Heavy']) + * ``` + * @param options New options that should be available in this dropdown. + */ + PDFDropdown.prototype.addOptions = function (options) { + assertIs(options, 'options', ['string', Array]); + var optionsArr = Array.isArray(options) ? options : [options]; + var existingOptions = this.acroField.getOptions(); + var newOptions = new Array(optionsArr.length); + for (var idx = 0, len = optionsArr.length; idx < len; idx++) { + newOptions[idx] = { value: PDFHexString.fromText(optionsArr[idx]) }; + } + this.acroField.setOptions(existingOptions.concat(newOptions)); + }; + /** + * Select one or more values for this dropdown. This operation is analogous + * to a human user opening the dropdown in a PDF reader and clicking on a + * value to select it. This method will update the underlying state of the + * dropdown to indicate which values have been selected. PDF libraries and + * readers will be able to extract these values from the saved document and + * determine which values were selected. + * + * For example: + * ```js + * const dropdown = form.getDropdown('best.superhero.dropdown') + * dropdown.select('One Punch Man') + * ``` + * + * This method will mark this dropdown as dirty, causing its appearance + * streams to be updated when either [[PDFDocument.save]] or + * [[PDFForm.updateFieldAppearances]] is called. The updated streams will + * display the selected option inside the widgets of this dropdown. + * + * **IMPORTANT:** The default font used to update appearance streams is + * [[StandardFonts.Helvetica]]. Note that this is a WinAnsi font. This means + * that encoding errors will be thrown if the selected option for this field + * contains characters outside the WinAnsi character set (the latin alphabet). + * + * Embedding a custom font and passing it to + * [[PDFForm.updateFieldAppearances]] or [[PDFDropdown.updateAppearances]] + * allows you to generate appearance streams with characters outside the + * latin alphabet (assuming the custom font supports them). + * + * Selecting an option that does not exist in this dropdown's option list + * (see [[PDFDropdown.getOptions]]) will enable editing on this dropdown + * (see [[PDFDropdown.enableEditing]]). + * + * > **NOTE:** PDF readers only display one selected option when rendering + * > dropdowns. However, the PDF specification does allow for multiple values + * > to be selected in a dropdown. As such, the `pdf-lib` API supports this. + * > However, it is not recommended to select more than one value with this + * > method, as only one will be visible. [[PDFOptionList]] fields are better + * > suited for displaying multiple selected values. + * + * @param options The options to be selected. + * @param merge Whether or not existing selections should be preserved. + */ + PDFDropdown.prototype.select = function (options, merge) { + if (merge === void 0) { merge = false; } + assertIs(options, 'options', ['string', Array]); + assertIs(merge, 'merge', ['boolean']); + var optionsArr = Array.isArray(options) ? options : [options]; + var validOptions = this.getOptions(); + var hasCustomOption = optionsArr.find(function (option) { return !validOptions.includes(option); }); + if (hasCustomOption) + this.enableEditing(); + this.markAsDirty(); + if (optionsArr.length > 1 || (optionsArr.length === 1 && merge)) { + this.enableMultiselect(); + } + var values = new Array(optionsArr.length); + for (var idx = 0, len = optionsArr.length; idx < len; idx++) { + values[idx] = PDFHexString.fromText(optionsArr[idx]); + } + if (merge) { + var existingValues = this.acroField.getValues(); + this.acroField.setValues(existingValues.concat(values)); + } + else { + this.acroField.setValues(values); + } + }; + /** + * Clear all selected values for this dropdown. This operation is equivalent + * to selecting an empty list. This method will update the underlying state + * of the dropdown to indicate that no values have been selected. + * For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * dropdown.clear() + * ``` + * This method will mark this text field as dirty. See [[PDFDropdown.select]] + * for more details about what this means. + */ + PDFDropdown.prototype.clear = function () { + this.markAsDirty(); + this.acroField.setValues([]); + }; + /** + * Set the font size for this field. Larger font sizes will result in larger + * text being displayed when PDF readers render this dropdown. Font sizes may + * be integer or floating point numbers. Supplying a negative font size will + * cause this method to throw an error. + * + * For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * dropdown.setFontSize(4) + * dropdown.setFontSize(15.7) + * ``` + * + * > This method depends upon the existence of a default appearance + * > (`/DA`) string. If this field does not have a default appearance string, + * > or that string does not contain a font size (via the `Tf` operator), + * > then this method will throw an error. + * + * @param fontSize The font size to be used when rendering text in this field. + */ + PDFDropdown.prototype.setFontSize = function (fontSize) { + assertPositive(fontSize, 'fontSize'); + this.acroField.setFontSize(fontSize); + this.markAsDirty(); + }; + /** + * Returns `true` if users are allowed to edit the selected value of this + * dropdown directly and are not constrained by the list of available + * options. See [[PDFDropdown.enableEditing]] and + * [[PDFDropdown.disableEditing]]. For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * if (dropdown.isEditable()) console.log('Editing is enabled') + * ``` + * @returns Whether or not this dropdown is editable. + */ + PDFDropdown.prototype.isEditable = function () { + return this.acroField.hasFlag(AcroChoiceFlags.Edit); + }; + /** + * Allow users to edit the selected value of this dropdown in PDF readers + * with their keyboard. This means that the selected value of this dropdown + * will not be constrained by the list of available options. However, if this + * dropdown has any available options, users will still be allowed to select + * from that list. + * For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * dropdown.enableEditing() + * ``` + */ + PDFDropdown.prototype.enableEditing = function () { + this.acroField.setFlagTo(AcroChoiceFlags.Edit, true); + }; + /** + * Do not allow users to edit the selected value of this dropdown in PDF + * readers with their keyboard. This will constrain the selected value of + * this dropdown to the list of available options. Users will only be able + * to select an option from that list. + * For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * dropdown.disableEditing() + * ``` + */ + PDFDropdown.prototype.disableEditing = function () { + this.acroField.setFlagTo(AcroChoiceFlags.Edit, false); + }; + /** + * Returns `true` if the option list of this dropdown is always displayed + * in alphabetical order, irrespective of the order in which the options + * were added to the dropdown. See [[PDFDropdown.enableSorting]] and + * [[PDFDropdown.disableSorting]]. For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * if (dropdown.isSorted()) console.log('Sorting is enabled') + * ``` + * @returns Whether or not this dropdown's options are sorted. + */ + PDFDropdown.prototype.isSorted = function () { + return this.acroField.hasFlag(AcroChoiceFlags.Sort); + }; + /** + * Always display the option list of this dropdown in alphabetical order, + * irrespective of the order in which the options were added to this dropdown. + * For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * dropdown.enableSorting() + * ``` + */ + PDFDropdown.prototype.enableSorting = function () { + this.acroField.setFlagTo(AcroChoiceFlags.Sort, true); + }; + /** + * Do not always display the option list of this dropdown in alphabetical + * order. Instead, display the options in whichever order they were added + * to the list. For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * dropdown.disableSorting() + * ``` + */ + PDFDropdown.prototype.disableSorting = function () { + this.acroField.setFlagTo(AcroChoiceFlags.Sort, false); + }; + /** + * Returns `true` if multiple options can be selected from this dropdown's + * option list. See [[PDFDropdown.enableMultiselect]] and + * [[PDFDropdown.disableMultiselect]]. For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * if (dropdown.isMultiselect()) console.log('Multiselect is enabled') + * ``` + * @returns Whether or not multiple options can be selected. + */ + PDFDropdown.prototype.isMultiselect = function () { + return this.acroField.hasFlag(AcroChoiceFlags.MultiSelect); + }; + /** + * Allow users to select more than one option from this dropdown's option + * list. For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * dropdown.enableMultiselect() + * ``` + */ + PDFDropdown.prototype.enableMultiselect = function () { + this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect, true); + }; + /** + * Do not allow users to select more than one option from this dropdown's + * option list. For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * dropdown.disableMultiselect() + * ``` + */ + PDFDropdown.prototype.disableMultiselect = function () { + this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect, false); + }; + /** + * Returns `true` if the selected option should be spell checked by PDF + * readers. Spell checking will only be performed if this dropdown allows + * editing (see [[PDFDropdown.isEditable]]). See + * [[PDFDropdown.enableSpellChecking]] and + * [[PDFDropdown.disableSpellChecking]]. For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * if (dropdown.isSpellChecked()) console.log('Spell checking is enabled') + * ``` + * @returns Whether or not this dropdown can be spell checked. + */ + PDFDropdown.prototype.isSpellChecked = function () { + return !this.acroField.hasFlag(AcroChoiceFlags.DoNotSpellCheck); + }; + /** + * Allow PDF readers to spell check the selected option of this dropdown. + * For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * dropdown.enableSpellChecking() + * ``` + */ + PDFDropdown.prototype.enableSpellChecking = function () { + this.acroField.setFlagTo(AcroChoiceFlags.DoNotSpellCheck, false); + }; + /** + * Do not allow PDF readers to spell check the selected option of this + * dropdown. For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * dropdown.disableSpellChecking() + * ``` + */ + PDFDropdown.prototype.disableSpellChecking = function () { + this.acroField.setFlagTo(AcroChoiceFlags.DoNotSpellCheck, true); + }; + /** + * Returns `true` if the option selected by a user is stored, or "committed", + * when the user clicks the option. The alternative is that the user's + * selection is stored when the user leaves this dropdown field (by clicking + * outside of it - on another field, for example). See + * [[PDFDropdown.enableSelectOnClick]] and + * [[PDFDropdown.disableSelectOnClick]]. For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * if (dropdown.isSelectOnClick()) console.log('Select on click is enabled') + * ``` + * @returns Whether or not options are selected immediately after they are + * clicked. + */ + PDFDropdown.prototype.isSelectOnClick = function () { + return this.acroField.hasFlag(AcroChoiceFlags.CommitOnSelChange); + }; + /** + * Store the option selected by a user immediately after the user clicks the + * option. Do not wait for the user to leave this dropdown field (by clicking + * outside of it - on another field, for example). For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * dropdown.enableSelectOnClick() + * ``` + */ + PDFDropdown.prototype.enableSelectOnClick = function () { + this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange, true); + }; + /** + * Wait to store the option selected by a user until they leave this dropdown + * field (by clicking outside of it - on another field, for example). + * For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * dropdown.disableSelectOnClick() + * ``` + */ + PDFDropdown.prototype.disableSelectOnClick = function () { + this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange, false); + }; + /** + * Show this dropdown on the specified page. For example: + * ```js + * const ubuntuFont = await pdfDoc.embedFont(ubuntuFontBytes) + * const page = pdfDoc.addPage() + * + * const form = pdfDoc.getForm() + * const dropdown = form.createDropdown('best.gundam') + * dropdown.setOptions(['Exia', 'Dynames']) + * dropdown.select('Exia') + * + * dropdown.addToPage(page, { + * x: 50, + * y: 75, + * width: 200, + * height: 100, + * textColor: rgb(1, 0, 0), + * backgroundColor: rgb(0, 1, 0), + * borderColor: rgb(0, 0, 1), + * borderWidth: 2, + * rotate: degrees(90), + * font: ubuntuFont, + * }) + * ``` + * This will create a new widget for this dropdown field. + * @param page The page to which this dropdown widget should be added. + * @param options The options to be used when adding this dropdown widget. + */ + PDFDropdown.prototype.addToPage = function (page, options) { + var _a, _b, _c, _d, _e, _f, _g; + assertIs(page, 'page', [[PDFPage, 'PDFPage']]); + assertFieldAppearanceOptions(options); + if (!options) + options = {}; + if (!('textColor' in options)) + options.textColor = rgb(0, 0, 0); + if (!('backgroundColor' in options)) + options.backgroundColor = rgb(1, 1, 1); + if (!('borderColor' in options)) + options.borderColor = rgb(0, 0, 0); + if (!('borderWidth' in options)) + options.borderWidth = 1; + // Create a widget for this dropdown + var widget = this.createWidget({ + x: (_a = options.x) !== null && _a !== void 0 ? _a : 0, + y: (_b = options.y) !== null && _b !== void 0 ? _b : 0, + width: (_c = options.width) !== null && _c !== void 0 ? _c : 200, + height: (_d = options.height) !== null && _d !== void 0 ? _d : 50, + textColor: options.textColor, + backgroundColor: options.backgroundColor, + borderColor: options.borderColor, + borderWidth: (_e = options.borderWidth) !== null && _e !== void 0 ? _e : 0, + rotate: (_f = options.rotate) !== null && _f !== void 0 ? _f : degrees(0), + hidden: options.hidden, + page: page.ref, + }); + var widgetRef = this.doc.context.register(widget.dict); + // Add widget to this field + this.acroField.addWidget(widgetRef); + // Set appearance streams for widget + var font = (_g = options.font) !== null && _g !== void 0 ? _g : this.doc.getForm().getDefaultFont(); + this.updateWidgetAppearance(widget, font); + // Add widget to the given page + page.node.addAnnot(widgetRef); + }; + /** + * Returns `true` if this dropdown has been marked as dirty, or if any of + * this dropdown's widgets do not have an appearance stream. For example: + * ```js + * const dropdown = form.getDropdown('some.dropdown.field') + * if (dropdown.needsAppearancesUpdate()) console.log('Needs update') + * ``` + * @returns Whether or not this dropdown needs an appearance update. + */ + PDFDropdown.prototype.needsAppearancesUpdate = function () { + var _a; + if (this.isDirty()) + return true; + var widgets = this.acroField.getWidgets(); + for (var idx = 0, len = widgets.length; idx < len; idx++) { + var widget = widgets[idx]; + var hasAppearances = ((_a = widget.getAppearances()) === null || _a === void 0 ? void 0 : _a.normal) instanceof PDFStream; + if (!hasAppearances) + return true; + } + return false; + }; + /** + * Update the appearance streams for each of this dropdown's widgets using + * the default appearance provider for dropdowns. For example: + * ```js + * const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica) + * const dropdown = form.getDropdown('some.dropdown.field') + * dropdown.defaultUpdateAppearances(helvetica) + * ``` + * @param font The font to be used for creating the appearance streams. + */ + PDFDropdown.prototype.defaultUpdateAppearances = function (font) { + assertIs(font, 'font', [[PDFFont, 'PDFFont']]); + this.updateAppearances(font); + }; + /** + * Update the appearance streams for each of this dropdown's widgets using + * the given appearance provider. If no `provider` is passed, the default + * appearance provider for dropdowns will be used. For example: + * ```js + * const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica) + * const dropdown = form.getDropdown('some.dropdown.field') + * dropdown.updateAppearances(helvetica, (field, widget, font) => { + * ... + * return drawTextField(...) + * }) + * ``` + * @param font The font to be used for creating the appearance streams. + * @param provider Optionally, the appearance provider to be used for + * generating the contents of the appearance streams. + */ + PDFDropdown.prototype.updateAppearances = function (font, provider) { + assertIs(font, 'font', [[PDFFont, 'PDFFont']]); + assertOrUndefined(provider, 'provider', [Function]); + var widgets = this.acroField.getWidgets(); + for (var idx = 0, len = widgets.length; idx < len; idx++) { + var widget = widgets[idx]; + this.updateWidgetAppearance(widget, font, provider); + } + this.markAsClean(); + }; + // getOption(index: number): string {} + // getSelectedIndices(): number[] {} + // removeOptions(option: string | string[]) {} + // removeIndices(option: number[]) {} + // deselect(options: string | string[]) {} + // deselectIndices(optionIndices: number[]) {} + PDFDropdown.prototype.updateWidgetAppearance = function (widget, font, provider) { + var apProvider = provider !== null && provider !== void 0 ? provider : defaultDropdownAppearanceProvider; + var appearances = normalizeAppearance(apProvider(this, widget, font)); + this.updateWidgetAppearanceWithFont(widget, font, appearances); + }; + /** + * > **NOTE:** You probably don't want to call this method directly. Instead, + * > consider using the [[PDFForm.getDropdown]] method, which will create an + * > instance of [[PDFDropdown]] for you. + * + * Create an instance of [[PDFDropdown]] from an existing acroComboBox and ref + * + * @param acroComboBox The underlying `PDFAcroComboBox` for this dropdown. + * @param ref The unique reference for this dropdown. + * @param doc The document to which this dropdown will belong. + */ + PDFDropdown.of = function (acroComboBox, ref, doc) { + return new PDFDropdown(acroComboBox, ref, doc); + }; + return PDFDropdown; +}(PDFField)); + +/** + * Represents an option list field of a [[PDFForm]]. + * + * [[PDFOptionList]] fields are interactive lists of options. The purpose of an + * option list is to enable users to select one or more options from a set of + * possible options. Users are able to see the full set of options without + * first having to click on the field (though scrolling may be necessary). + * Clicking an option in the list will cause it to be selected and displayed + * with a highlighted background. Some option lists allow users to select + * more than one option (see [[PDFOptionList.isMultiselect]]). + */ +var PDFOptionList = /** @class */ (function (_super) { + __extends(PDFOptionList, _super); + function PDFOptionList(acroListBox, ref, doc) { + var _this = _super.call(this, acroListBox, ref, doc) || this; + assertIs(acroListBox, 'acroListBox', [[PDFAcroListBox, 'PDFAcroListBox']]); + _this.acroField = acroListBox; + return _this; + } + /** + * Get the list of available options for this option list. These options will + * be displayed to users who view this option list in a PDF reader. + * For example: + * ```js + * const optionList = form.getOptionList('some.optionList.field') + * const options = optionList.getOptions() + * console.log('Option List options:', options) + * ``` + * @returns The options for this option list. + */ + PDFOptionList.prototype.getOptions = function () { + var rawOptions = this.acroField.getOptions(); + var options = new Array(rawOptions.length); + for (var idx = 0, len = options.length; idx < len; idx++) { + var _a = rawOptions[idx], display = _a.display, value = _a.value; + options[idx] = (display !== null && display !== void 0 ? display : value).decodeText(); + } + return options; + }; + /** + * Get the selected options for this option list. These are the values that + * were selected by a human user via a PDF reader, or programatically via + * software. + * For example: + * ```js + * const optionList = form.getOptionList('some.optionList.field') + * const selections = optionList.getSelected() + * console.log('Option List selections:', selections) + * ``` + * @returns The selected options for this option list. + */ + PDFOptionList.prototype.getSelected = function () { + var values = this.acroField.getValues(); + var selected = new Array(values.length); + for (var idx = 0, len = values.length; idx < len; idx++) { + selected[idx] = values[idx].decodeText(); + } + return selected; + }; + /** + * Set the list of options that are available for this option list. These are + * the values that will be available for users to select when they view this + * option list in a PDF reader. Note that preexisting options for this + * option list will be removed. Only the values passed as `options` will be + * available to select. + * + * For example: + * ```js + * const optionList = form.getOptionList('planets.optionList') + * optionList.setOptions(['Earth', 'Mars', 'Pluto', 'Venus']) + * ``` + * + * This method will mark this option list as dirty, causing its appearance + * streams to be updated when either [[PDFDocument.save]] or + * [[PDFForm.updateFieldAppearances]] is called. The updated streams will + * display the options this field contains inside the widgets of this text + * field (with selected options highlighted). + * + * **IMPORTANT:** The default font used to update appearance streams is + * [[StandardFonts.Helvetica]]. Note that this is a WinAnsi font. This means + * that encoding errors will be thrown if this field contains any options + * with characters outside the WinAnsi character set (the latin alphabet). + * + * Embedding a custom font and passing it to + * [[PDFForm.updateFieldAppearances]] or [[PDFOptionList.updateAppearances]] + * allows you to generate appearance streams with characters outside the + * latin alphabet (assuming the custom font supports them). + * + * @param options The options that should be available in this option list. + */ + PDFOptionList.prototype.setOptions = function (options) { + assertIs(options, 'options', [Array]); + this.markAsDirty(); + var optionObjects = new Array(options.length); + for (var idx = 0, len = options.length; idx < len; idx++) { + optionObjects[idx] = { value: PDFHexString.fromText(options[idx]) }; + } + this.acroField.setOptions(optionObjects); + }; + /** + * Add to the list of options that are available for this option list. Users + * will be able to select these values in a PDF reader. In addition to the + * values passed as `options`, any preexisting options for this option list + * will still be available for users to select. + * For example: + * ```js + * const optionList = form.getOptionList('rockets.optionList') + * optionList.addOptions(['Saturn IV', 'Falcon Heavy']) + * ``` + * This method will mark this option list as dirty. See + * [[PDFOptionList.setOptions]] for more details about what this means. + * @param options New options that should be available in this option list. + */ + PDFOptionList.prototype.addOptions = function (options) { + assertIs(options, 'options', ['string', Array]); + this.markAsDirty(); + var optionsArr = Array.isArray(options) ? options : [options]; + var existingOptions = this.acroField.getOptions(); + var newOptions = new Array(optionsArr.length); + for (var idx = 0, len = optionsArr.length; idx < len; idx++) { + newOptions[idx] = { value: PDFHexString.fromText(optionsArr[idx]) }; + } + this.acroField.setOptions(existingOptions.concat(newOptions)); + }; + /** + * Select one or more values for this option list. This operation is analogous + * to a human user opening the option list in a PDF reader and clicking on one + * or more values to select them. This method will update the underlying state + * of the option list to indicate which values have been selected. PDF + * libraries and readers will be able to extract these values from the saved + * document and determine which values were selected. + * For example: + * ```js + * const optionList = form.getOptionList('best.superheroes.optionList') + * optionList.select(['One Punch Man', 'Iron Man']) + * ``` + * This method will mark this option list as dirty. See + * [[PDFOptionList.setOptions]] for more details about what this means. + * @param options The options to be selected. + * @param merge Whether or not existing selections should be preserved. + */ + PDFOptionList.prototype.select = function (options, merge) { + if (merge === void 0) { merge = false; } + assertIs(options, 'options', ['string', Array]); + assertIs(merge, 'merge', ['boolean']); + var optionsArr = Array.isArray(options) ? options : [options]; + var validOptions = this.getOptions(); + assertIsSubset(optionsArr, 'option', validOptions); + this.markAsDirty(); + if (optionsArr.length > 1 || (optionsArr.length === 1 && merge)) { + this.enableMultiselect(); + } + var values = new Array(optionsArr.length); + for (var idx = 0, len = optionsArr.length; idx < len; idx++) { + values[idx] = PDFHexString.fromText(optionsArr[idx]); + } + if (merge) { + var existingValues = this.acroField.getValues(); + this.acroField.setValues(existingValues.concat(values)); + } + else { + this.acroField.setValues(values); + } + }; + /** + * Clear all selected values for this option list. This operation is + * equivalent to selecting an empty list. This method will update the + * underlying state of the option list to indicate that no values have been + * selected. + * For example: + * ```js + * const optionList = form.getOptionList('some.optionList.field') + * optionList.clear() + * ``` + * This method will mark this option list as dirty. See + * [[PDFOptionList.setOptions]] for more details about what this means. + */ + PDFOptionList.prototype.clear = function () { + this.markAsDirty(); + this.acroField.setValues([]); + }; + /** + * Set the font size for the text in this field. There needs to be a + * default appearance string (DA) set with a font value specified + * for this to work. For example: + * ```js + * const optionList = form.getOptionList('some.optionList.field') + * optionList.setFontSize(4); + * ``` + * @param fontSize The font size to set the font to. + */ + /** + * Set the font size for this field. Larger font sizes will result in larger + * text being displayed when PDF readers render this option list. Font sizes + * may be integer or floating point numbers. Supplying a negative font size + * will cause this method to throw an error. + * + * For example: + * ```js + * const optionList = form.getOptionList('some.optionList.field') + * optionList.setFontSize(4) + * optionList.setFontSize(15.7) + * ``` + * + * > This method depends upon the existence of a default appearance + * > (`/DA`) string. If this field does not have a default appearance string, + * > or that string does not contain a font size (via the `Tf` operator), + * > then this method will throw an error. + * + * @param fontSize The font size to be used when rendering text in this field. + */ + PDFOptionList.prototype.setFontSize = function (fontSize) { + assertPositive(fontSize, 'fontSize'); + this.acroField.setFontSize(fontSize); + this.markAsDirty(); + }; + /** + * Returns `true` if the options of this option list are always displayed + * in alphabetical order, irrespective of the order in which the options + * were added to the option list. See [[PDFOptionList.enableSorting]] and + * [[PDFOptionList.disableSorting]]. For example: + * ```js + * const optionList = form.getOptionList('some.optionList.field') + * if (optionList.isSorted()) console.log('Sorting is enabled') + * ``` + * @returns Whether or not this option list is sorted. + */ + PDFOptionList.prototype.isSorted = function () { + return this.acroField.hasFlag(AcroChoiceFlags.Sort); + }; + /** + * Always display the options of this option list in alphabetical order, + * irrespective of the order in which the options were added to this option + * list. + * For example: + * ```js + * const optionList = form.getOptionList('some.optionList.field') + * optionList.enableSorting() + * ``` + */ + PDFOptionList.prototype.enableSorting = function () { + this.acroField.setFlagTo(AcroChoiceFlags.Sort, true); + }; + /** + * Do not always display the options of this option list in alphabetical + * order. Instead, display the options in whichever order they were added + * to this option list. For example: + * ```js + * const optionList = form.getOptionList('some.optionList.field') + * optionList.disableSorting() + * ``` + */ + PDFOptionList.prototype.disableSorting = function () { + this.acroField.setFlagTo(AcroChoiceFlags.Sort, false); + }; + /** + * Returns `true` if multiple options can be selected from this option list. + * See [[PDFOptionList.enableMultiselect]] and + * [[PDFOptionList.disableMultiselect]]. For example: + * ```js + * const optionList = form.getOptionList('some.optionList.field') + * if (optionList.isMultiselect()) console.log('Multiselect is enabled') + * ``` + * @returns Whether or not multiple options can be selected. + */ + PDFOptionList.prototype.isMultiselect = function () { + return this.acroField.hasFlag(AcroChoiceFlags.MultiSelect); + }; + /** + * Allow users to select more than one option from this option list. + * For example: + * ```js + * const optionList = form.getOptionList('some.optionList.field') + * optionList.enableMultiselect() + * ``` + */ + PDFOptionList.prototype.enableMultiselect = function () { + this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect, true); + }; + /** + * Do not allow users to select more than one option from this option list. + * For example: + * ```js + * const optionList = form.getOptionList('some.optionList.field') + * optionList.disableMultiselect() + * ``` + */ + PDFOptionList.prototype.disableMultiselect = function () { + this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect, false); + }; + /** + * Returns `true` if the option selected by a user is stored, or "committed", + * when the user clicks the option. The alternative is that the user's + * selection is stored when the user leaves this option list field (by + * clicking outside of it - on another field, for example). See + * [[PDFOptionList.enableSelectOnClick]] and + * [[PDFOptionList.disableSelectOnClick]]. For example: + * ```js + * const optionList = form.getOptionList('some.optionList.field') + * if (optionList.isSelectOnClick()) console.log('Select on click is enabled') + * ``` + * @returns Whether or not options are selected immediately after they are + * clicked. + */ + PDFOptionList.prototype.isSelectOnClick = function () { + return this.acroField.hasFlag(AcroChoiceFlags.CommitOnSelChange); + }; + /** + * Store the option selected by a user immediately after the user clicks the + * option. Do not wait for the user to leave this option list field (by + * clicking outside of it - on another field, for example). For example: + * ```js + * const optionList = form.getOptionList('some.optionList.field') + * optionList.enableSelectOnClick() + * ``` + */ + PDFOptionList.prototype.enableSelectOnClick = function () { + this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange, true); + }; + /** + * Wait to store the option selected by a user until they leave this option + * list field (by clicking outside of it - on another field, for example). + * For example: + * ```js + * const optionList = form.getOptionList('some.optionList.field') + * optionList.disableSelectOnClick() + * ``` + */ + PDFOptionList.prototype.disableSelectOnClick = function () { + this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange, false); + }; + /** + * Show this option list on the specified page. For example: + * ```js + * const ubuntuFont = await pdfDoc.embedFont(ubuntuFontBytes) + * const page = pdfDoc.addPage() + * + * const form = pdfDoc.getForm() + * const optionList = form.createOptionList('best.gundams') + * optionList.setOptions(['Exia', 'Dynames', 'Kyrios', 'Virtue']) + * optionList.select(['Exia', 'Virtue']) + * + * optionList.addToPage(page, { + * x: 50, + * y: 75, + * width: 200, + * height: 100, + * textColor: rgb(1, 0, 0), + * backgroundColor: rgb(0, 1, 0), + * borderColor: rgb(0, 0, 1), + * borderWidth: 2, + * rotate: degrees(90), + * font: ubuntuFont, + * }) + * ``` + * This will create a new widget for this option list field. + * @param page The page to which this option list widget should be added. + * @param options The options to be used when adding this option list widget. + */ + PDFOptionList.prototype.addToPage = function (page, options) { + var _a, _b, _c, _d, _e, _f, _g; + assertIs(page, 'page', [[PDFPage, 'PDFPage']]); + assertFieldAppearanceOptions(options); + if (!options) + options = {}; + if (!('textColor' in options)) + options.textColor = rgb(0, 0, 0); + if (!('backgroundColor' in options)) + options.backgroundColor = rgb(1, 1, 1); + if (!('borderColor' in options)) + options.borderColor = rgb(0, 0, 0); + if (!('borderWidth' in options)) + options.borderWidth = 1; + // Create a widget for this option list + var widget = this.createWidget({ + x: (_a = options.x) !== null && _a !== void 0 ? _a : 0, + y: (_b = options.y) !== null && _b !== void 0 ? _b : 0, + width: (_c = options.width) !== null && _c !== void 0 ? _c : 200, + height: (_d = options.height) !== null && _d !== void 0 ? _d : 100, + textColor: options.textColor, + backgroundColor: options.backgroundColor, + borderColor: options.borderColor, + borderWidth: (_e = options.borderWidth) !== null && _e !== void 0 ? _e : 0, + rotate: (_f = options.rotate) !== null && _f !== void 0 ? _f : degrees(0), + hidden: options.hidden, + page: page.ref, + }); + var widgetRef = this.doc.context.register(widget.dict); + // Add widget to this field + this.acroField.addWidget(widgetRef); + // Set appearance streams for widget + var font = (_g = options.font) !== null && _g !== void 0 ? _g : this.doc.getForm().getDefaultFont(); + this.updateWidgetAppearance(widget, font); + // Add widget to the given page + page.node.addAnnot(widgetRef); + }; + /** + * Returns `true` if this option list has been marked as dirty, or if any of + * this option list's widgets do not have an appearance stream. For example: + * ```js + * const optionList = form.getOptionList('some.optionList.field') + * if (optionList.needsAppearancesUpdate()) console.log('Needs update') + * ``` + * @returns Whether or not this option list needs an appearance update. + */ + PDFOptionList.prototype.needsAppearancesUpdate = function () { + var _a; + if (this.isDirty()) + return true; + var widgets = this.acroField.getWidgets(); + for (var idx = 0, len = widgets.length; idx < len; idx++) { + var widget = widgets[idx]; + var hasAppearances = ((_a = widget.getAppearances()) === null || _a === void 0 ? void 0 : _a.normal) instanceof PDFStream; + if (!hasAppearances) + return true; + } + return false; + }; + /** + * Update the appearance streams for each of this option list's widgets using + * the default appearance provider for option lists. For example: + * ```js + * const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica) + * const optionList = form.getOptionList('some.optionList.field') + * optionList.defaultUpdateAppearances(helvetica) + * ``` + * @param font The font to be used for creating the appearance streams. + */ + PDFOptionList.prototype.defaultUpdateAppearances = function (font) { + assertIs(font, 'font', [[PDFFont, 'PDFFont']]); + this.updateAppearances(font); + }; + /** + * Update the appearance streams for each of this option list's widgets using + * the given appearance provider. If no `provider` is passed, the default + * appearance provider for option lists will be used. For example: + * ```js + * const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica) + * const optionList = form.getOptionList('some.optionList.field') + * optionList.updateAppearances(helvetica, (field, widget, font) => { + * ... + * return drawOptionList(...) + * }) + * ``` + * @param font The font to be used for creating the appearance streams. + * @param provider Optionally, the appearance provider to be used for + * generating the contents of the appearance streams. + */ + PDFOptionList.prototype.updateAppearances = function (font, provider) { + assertIs(font, 'font', [[PDFFont, 'PDFFont']]); + assertOrUndefined(provider, 'provider', [Function]); + var widgets = this.acroField.getWidgets(); + for (var idx = 0, len = widgets.length; idx < len; idx++) { + var widget = widgets[idx]; + this.updateWidgetAppearance(widget, font, provider); + } + this.markAsClean(); + }; + // getOption(index: number): string {} + // getSelectedIndices(): number[] {} + // removeOptions(option: string | string[]) {} + // removeIndices(option: number[]) {} + // deselect(options: string | string[]) {} + // deselectIndices(optionIndices: number[]) {} + PDFOptionList.prototype.updateWidgetAppearance = function (widget, font, provider) { + var apProvider = provider !== null && provider !== void 0 ? provider : defaultOptionListAppearanceProvider; + var appearances = normalizeAppearance(apProvider(this, widget, font)); + this.updateWidgetAppearanceWithFont(widget, font, appearances); + }; + /** + * > **NOTE:** You probably don't want to call this method directly. Instead, + * > consider using the [[PDFForm.getOptionList]] method, which will create + * > an instance of [[PDFOptionList]] for you. + * + * Create an instance of [[PDFOptionList]] from an existing acroListBox and + * ref + * + * @param acroComboBox The underlying `PDFAcroListBox` for this option list. + * @param ref The unique reference for this option list. + * @param doc The document to which this option list will belong. + */ + PDFOptionList.of = function (acroListBox, ref, doc) { + return new PDFOptionList(acroListBox, ref, doc); + }; + return PDFOptionList; +}(PDFField)); + +/** + * Represents a radio group field of a [[PDFForm]]. + * + * [[PDFRadioGroup]] fields are collections of radio buttons. The purpose of a + * radio group is to enable users to select one option from a set of mutually + * exclusive choices. Each choice in a radio group is represented by a radio + * button. Radio buttons each have two states: `on` and `off`. At most one + * radio button in a group may be in the `on` state at any time. Users can + * click on a radio button to select it (and thereby automatically deselect any + * other radio button that might have already been selected). Some radio + * groups allow users to toggle a selected radio button `off` by clicking on + * it (see [[PDFRadioGroup.isOffToggleable]]). + * + * Note that some radio groups allow multiple radio buttons to be in the `on` + * state at the same type **if** they represent the same underlying value (see + * [[PDFRadioGroup.isMutuallyExclusive]]). + */ +var PDFRadioGroup = /** @class */ (function (_super) { + __extends(PDFRadioGroup, _super); + function PDFRadioGroup(acroRadioButton, ref, doc) { + var _this = _super.call(this, acroRadioButton, ref, doc) || this; + assertIs(acroRadioButton, 'acroRadioButton', [ + [PDFAcroRadioButton, 'PDFAcroRadioButton'], + ]); + _this.acroField = acroRadioButton; + return _this; + } + /** + * Get the list of available options for this radio group. Each option is + * represented by a radio button. These radio buttons are displayed at + * various locations in the document, potentially on different pages (though + * typically they are stacked horizontally or vertically on the same page). + * For example: + * ```js + * const radioGroup = form.getRadioGroup('some.radioGroup.field') + * const options = radioGroup.getOptions() + * console.log('Radio Group options:', options) + * ``` + * @returns The options for this radio group. + */ + PDFRadioGroup.prototype.getOptions = function () { + var exportValues = this.acroField.getExportValues(); + if (exportValues) { + var exportOptions = new Array(exportValues.length); + for (var idx = 0, len = exportValues.length; idx < len; idx++) { + exportOptions[idx] = exportValues[idx].decodeText(); + } + return exportOptions; + } + var onValues = this.acroField.getOnValues(); + var onOptions = new Array(onValues.length); + for (var idx = 0, len = onOptions.length; idx < len; idx++) { + onOptions[idx] = onValues[idx].decodeText(); + } + return onOptions; + }; + /** + * Get the selected option for this radio group. The selected option is + * represented by the radio button in this group that is turned on. At most + * one radio button in a group can be selected. If no buttons in this group + * are selected, `undefined` is returned. + * For example: + * ```js + * const radioGroup = form.getRadioGroup('some.radioGroup.field') + * const selected = radioGroup.getSelected() + * console.log('Selected radio button:', selected) + * ``` + * @returns The selected option for this radio group. + */ + PDFRadioGroup.prototype.getSelected = function () { + var value = this.acroField.getValue(); + if (value === PDFName.of('Off')) + return undefined; + var exportValues = this.acroField.getExportValues(); + if (exportValues) { + var onValues = this.acroField.getOnValues(); + for (var idx = 0, len = onValues.length; idx < len; idx++) { + if (onValues[idx] === value) + return exportValues[idx].decodeText(); + } + } + return value.decodeText(); + }; + // // TODO: Figure out why this seems to crash Acrobat. Maybe it's because we + // // aren't removing the widget reference from the page's Annots? + // removeOption(option: string) { + // assertIs(option, 'option', ['string']); + // // TODO: Assert is valid `option`! + // const onValues = this.acroField.getOnValues(); + // const exportValues = this.acroField.getExportValues(); + // if (exportValues) { + // for (let idx = 0, len = exportValues.length; idx < len; idx++) { + // if (exportValues[idx].decodeText() === option) { + // this.acroField.removeWidget(idx); + // this.acroField.removeExportValue(idx); + // } + // } + // } else { + // for (let idx = 0, len = onValues.length; idx < len; idx++) { + // const value = onValues[idx]; + // if (value.decodeText() === option) { + // this.acroField.removeWidget(idx); + // this.acroField.removeExportValue(idx); + // } + // } + // } + // } + /** + * Select an option for this radio group. This operation is analogous to a + * human user clicking one of the radio buttons in this group via a PDF + * reader to toggle it on. This method will update the underlying state of + * the radio group to indicate which option has been selected. PDF libraries + * and readers will be able to extract this value from the saved document and + * determine which option was selected. + * + * For example: + * ```js + * const radioGroup = form.getRadioGroup('best.superhero.radioGroup') + * radioGroup.select('One Punch Man') + * ``` + * + * This method will mark this radio group as dirty, causing its appearance + * streams to be updated when either [[PDFDocument.save]] or + * [[PDFForm.updateFieldAppearances]] is called. The updated appearance + * streams will display a dot inside the widget of this check box field + * that represents the selected option. + * + * @param option The option to be selected. + */ + PDFRadioGroup.prototype.select = function (option) { + assertIs(option, 'option', ['string']); + var validOptions = this.getOptions(); + assertIsOneOf(option, 'option', validOptions); + this.markAsDirty(); + var onValues = this.acroField.getOnValues(); + var exportValues = this.acroField.getExportValues(); + if (exportValues) { + for (var idx = 0, len = exportValues.length; idx < len; idx++) { + if (exportValues[idx].decodeText() === option) { + this.acroField.setValue(onValues[idx]); + } + } + } + else { + for (var idx = 0, len = onValues.length; idx < len; idx++) { + var value = onValues[idx]; + if (value.decodeText() === option) + this.acroField.setValue(value); + } + } + }; + /** + * Clear any selected option for this dropdown. This will result in all + * radio buttons in this group being toggled off. This method will update + * the underlying state of the dropdown to indicate that no radio buttons + * have been selected. + * For example: + * ```js + * const radioGroup = form.getRadioGroup('some.radioGroup.field') + * radioGroup.clear() + * ``` + * This method will mark this radio group as dirty. See + * [[PDFRadioGroup.select]] for more details about what this means. + */ + PDFRadioGroup.prototype.clear = function () { + this.markAsDirty(); + this.acroField.setValue(PDFName.of('Off')); + }; + /** + * Returns `true` if users can click on radio buttons in this group to toggle + * them off. The alternative is that once a user clicks on a radio button + * to select it, the only way to deselect it is by selecting on another radio + * button in the group. See [[PDFRadioGroup.enableOffToggling]] and + * [[PDFRadioGroup.disableOffToggling]]. For example: + * ```js + * const radioGroup = form.getRadioGroup('some.radioGroup.field') + * if (radioGroup.isOffToggleable()) console.log('Off toggling is enabled') + * ``` + */ + PDFRadioGroup.prototype.isOffToggleable = function () { + return !this.acroField.hasFlag(AcroButtonFlags.NoToggleToOff); + }; + /** + * Allow users to click on selected radio buttons in this group to toggle + * them off. For example: + * ```js + * const radioGroup = form.getRadioGroup('some.radioGroup.field') + * radioGroup.enableOffToggling() + * ``` + * > **NOTE:** This feature is documented in the PDF specification + * > (Table 226). However, most PDF readers do not respect this option and + * > prevent users from toggling radio buttons off even when it is enabled. + * > At the time of this writing (9/6/2020) Mac's Preview software did + * > respect the option. Adobe Acrobat, Foxit Reader, and Google Chrome did + * > not. + */ + PDFRadioGroup.prototype.enableOffToggling = function () { + this.acroField.setFlagTo(AcroButtonFlags.NoToggleToOff, false); + }; + /** + * Prevent users from clicking on selected radio buttons in this group to + * toggle them off. Clicking on a selected radio button will have no effect. + * The only way to deselect a selected radio button is to click on a + * different radio button in the group. For example: + * ```js + * const radioGroup = form.getRadioGroup('some.radioGroup.field') + * radioGroup.disableOffToggling() + * ``` + */ + PDFRadioGroup.prototype.disableOffToggling = function () { + this.acroField.setFlagTo(AcroButtonFlags.NoToggleToOff, true); + }; + /** + * Returns `true` if the radio buttons in this group are mutually exclusive. + * This means that when the user selects a radio button, only that specific + * button will be turned on. Even if other radio buttons in the group + * represent the same value, they will not be enabled. The alternative to + * this is that clicking a radio button will select that button along with + * any other radio buttons in the group that share the same value. See + * [[PDFRadioGroup.enableMutualExclusion]] and + * [[PDFRadioGroup.disableMutualExclusion]]. + * For example: + * ```js + * const radioGroup = form.getRadioGroup('some.radioGroup.field') + * if (radioGroup.isMutuallyExclusive()) console.log('Mutual exclusion is enabled') + * ``` + */ + PDFRadioGroup.prototype.isMutuallyExclusive = function () { + return !this.acroField.hasFlag(AcroButtonFlags.RadiosInUnison); + }; + /** + * When the user clicks a radio button in this group it will be selected. In + * addition, any other radio buttons in this group that share the same + * underlying value will also be selected. For example: + * ```js + * const radioGroup = form.getRadioGroup('some.radioGroup.field') + * radioGroup.enableMutualExclusion() + * ``` + * Note that this option must be enabled prior to adding options to the + * radio group. It does not currently apply retroactively to existing + * radio buttons in the group. + */ + PDFRadioGroup.prototype.enableMutualExclusion = function () { + this.acroField.setFlagTo(AcroButtonFlags.RadiosInUnison, false); + }; + /** + * When the user clicks a radio button in this group only it will be selected. + * No other radio buttons in the group will be selected, even if they share + * the same underlying value. For example: + * ```js + * const radioGroup = form.getRadioGroup('some.radioGroup.field') + * radioGroup.disableMutualExclusion() + * ``` + * Note that this option must be disabled prior to adding options to the + * radio group. It does not currently apply retroactively to existing + * radio buttons in the group. + */ + PDFRadioGroup.prototype.disableMutualExclusion = function () { + this.acroField.setFlagTo(AcroButtonFlags.RadiosInUnison, true); + }; + /** + * Add a new radio button to this group on the specified page. For example: + * ```js + * const page = pdfDoc.addPage() + * + * const form = pdfDoc.getForm() + * const radioGroup = form.createRadioGroup('best.gundam') + * + * const options = { + * x: 50, + * width: 25, + * height: 25, + * textColor: rgb(1, 0, 0), + * backgroundColor: rgb(0, 1, 0), + * borderColor: rgb(0, 0, 1), + * borderWidth: 2, + * rotate: degrees(90), + * } + * + * radioGroup.addOptionToPage('Exia', page, { ...options, y: 50 }) + * radioGroup.addOptionToPage('Dynames', page, { ...options, y: 110 }) + * ``` + * This will create a new radio button widget for this radio group field. + * @param option The option that the radio button widget represents. + * @param page The page to which the radio button widget should be added. + * @param options The options to be used when adding the radio button widget. + */ + PDFRadioGroup.prototype.addOptionToPage = function (option, page, options) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + assertIs(option, 'option', ['string']); + assertIs(page, 'page', [[PDFPage, 'PDFPage']]); + assertFieldAppearanceOptions(options); + // Create a widget for this radio button + var widget = this.createWidget({ + x: (_a = options === null || options === void 0 ? void 0 : options.x) !== null && _a !== void 0 ? _a : 0, + y: (_b = options === null || options === void 0 ? void 0 : options.y) !== null && _b !== void 0 ? _b : 0, + width: (_c = options === null || options === void 0 ? void 0 : options.width) !== null && _c !== void 0 ? _c : 50, + height: (_d = options === null || options === void 0 ? void 0 : options.height) !== null && _d !== void 0 ? _d : 50, + textColor: (_e = options === null || options === void 0 ? void 0 : options.textColor) !== null && _e !== void 0 ? _e : rgb(0, 0, 0), + backgroundColor: (_f = options === null || options === void 0 ? void 0 : options.backgroundColor) !== null && _f !== void 0 ? _f : rgb(1, 1, 1), + borderColor: (_g = options === null || options === void 0 ? void 0 : options.borderColor) !== null && _g !== void 0 ? _g : rgb(0, 0, 0), + borderWidth: (_h = options === null || options === void 0 ? void 0 : options.borderWidth) !== null && _h !== void 0 ? _h : 1, + rotate: (_j = options === null || options === void 0 ? void 0 : options.rotate) !== null && _j !== void 0 ? _j : degrees(0), + hidden: options === null || options === void 0 ? void 0 : options.hidden, + page: page.ref, + }); + var widgetRef = this.doc.context.register(widget.dict); + // Add widget to this field + var apStateValue = this.acroField.addWidgetWithOpt(widgetRef, PDFHexString.fromText(option), !this.isMutuallyExclusive()); + // Set appearance streams for widget + widget.setAppearanceState(PDFName.of('Off')); + this.updateWidgetAppearance(widget, apStateValue); + // Add widget to the given page + page.node.addAnnot(widgetRef); + }; + /** + * Returns `true` if any of this group's radio button widgets do not have an + * appearance stream for their current state. For example: + * ```js + * const radioGroup = form.getRadioGroup('some.radioGroup.field') + * if (radioGroup.needsAppearancesUpdate()) console.log('Needs update') + * ``` + * @returns Whether or not this radio group needs an appearance update. + */ + PDFRadioGroup.prototype.needsAppearancesUpdate = function () { + var _a; + var widgets = this.acroField.getWidgets(); + for (var idx = 0, len = widgets.length; idx < len; idx++) { + var widget = widgets[idx]; + var state = widget.getAppearanceState(); + var normal = (_a = widget.getAppearances()) === null || _a === void 0 ? void 0 : _a.normal; + if (!(normal instanceof PDFDict)) + return true; + if (state && !normal.has(state)) + return true; + } + return false; + }; + /** + * Update the appearance streams for each of this group's radio button widgets + * using the default appearance provider for radio groups. For example: + * ```js + * const radioGroup = form.getRadioGroup('some.radioGroup.field') + * radioGroup.defaultUpdateAppearances() + * ``` + */ + PDFRadioGroup.prototype.defaultUpdateAppearances = function () { + this.updateAppearances(); + }; + // rg.updateAppearances((field: any, widget: any) => { + // assert(field === rg); + // assert(widget instanceof PDFWidgetAnnotation); + // return { on: [...rectangle, ...circle], off: [...rectangle, ...circle] }; + // }); + /** + * Update the appearance streams for each of this group's radio button widgets + * using the given appearance provider. If no `provider` is passed, the + * default appearance provider for radio groups will be used. For example: + * ```js + * const radioGroup = form.getRadioGroup('some.radioGroup.field') + * radioGroup.updateAppearances((field, widget) => { + * ... + * return { + * normal: { on: drawRadioButton(...), off: drawRadioButton(...) }, + * down: { on: drawRadioButton(...), off: drawRadioButton(...) }, + * } + * }) + * ``` + * @param provider Optionally, the appearance provider to be used for + * generating the contents of the appearance streams. + */ + PDFRadioGroup.prototype.updateAppearances = function (provider) { + assertOrUndefined(provider, 'provider', [Function]); + var widgets = this.acroField.getWidgets(); + for (var idx = 0, len = widgets.length; idx < len; idx++) { + var widget = widgets[idx]; + var onValue = widget.getOnValue(); + if (!onValue) + continue; + this.updateWidgetAppearance(widget, onValue, provider); + } + }; + PDFRadioGroup.prototype.updateWidgetAppearance = function (widget, onValue, provider) { + var apProvider = provider !== null && provider !== void 0 ? provider : defaultRadioGroupAppearanceProvider; + var appearances = normalizeAppearance(apProvider(this, widget)); + this.updateOnOffWidgetAppearance(widget, onValue, appearances); + }; + /** + * > **NOTE:** You probably don't want to call this method directly. Instead, + * > consider using the [[PDFForm.getOptionList]] method, which will create an + * > instance of [[PDFOptionList]] for you. + * + * Create an instance of [[PDFOptionList]] from an existing acroRadioButton + * and ref + * + * @param acroRadioButton The underlying `PDFAcroRadioButton` for this + * radio group. + * @param ref The unique reference for this radio group. + * @param doc The document to which this radio group will belong. + */ + PDFRadioGroup.of = function (acroRadioButton, ref, doc) { return new PDFRadioGroup(acroRadioButton, ref, doc); }; + return PDFRadioGroup; +}(PDFField)); + +/** + * Represents a signature field of a [[PDFForm]]. + * + * [[PDFSignature]] fields are digital signatures. `pdf-lib` does not + * currently provide any specialized APIs for creating digital signatures or + * reading the contents of existing digital signatures. + */ +var PDFSignature = /** @class */ (function (_super) { + __extends(PDFSignature, _super); + function PDFSignature(acroSignature, ref, doc) { + var _this = _super.call(this, acroSignature, ref, doc) || this; + assertIs(acroSignature, 'acroSignature', [ + [PDFAcroSignature, 'PDFAcroSignature'], + ]); + _this.acroField = acroSignature; + return _this; + } + PDFSignature.prototype.needsAppearancesUpdate = function () { + return false; + }; + /** + * > **NOTE:** You probably don't want to call this method directly. Instead, + * > consider using the [[PDFForm.getSignature]] method, which will create an + * > instance of [[PDFSignature]] for you. + * + * Create an instance of [[PDFSignature]] from an existing acroSignature and + * ref + * + * @param acroSignature The underlying `PDFAcroSignature` for this signature. + * @param ref The unique reference for this signature. + * @param doc The document to which this signature will belong. + */ + PDFSignature.of = function (acroSignature, ref, doc) { return new PDFSignature(acroSignature, ref, doc); }; + return PDFSignature; +}(PDFField)); + +/** + * Represents a text field of a [[PDFForm]]. + * + * [[PDFTextField]] fields are boxes that display text entered by the user. The + * purpose of a text field is to enable users to enter text or view text values + * in the document prefilled by software. Users can click on a text field and + * input text via their keyboard. Some text fields allow multiple lines of text + * to be entered (see [[PDFTextField.isMultiline]]). + */ +var PDFTextField = /** @class */ (function (_super) { + __extends(PDFTextField, _super); + function PDFTextField(acroText, ref, doc) { + var _this = _super.call(this, acroText, ref, doc) || this; + assertIs(acroText, 'acroText', [[PDFAcroText, 'PDFAcroText']]); + _this.acroField = acroText; + return _this; + } + /** + * Get the text that this field contains. This text is visible to users who + * view this field in a PDF reader. + * + * For example: + * ```js + * const textField = form.getTextField('some.text.field') + * const text = textField.getText() + * console.log('Text field contents:', text) + * ``` + * + * Note that if this text field contains no underlying value, `undefined` + * will be returned. Text fields may also contain an underlying value that + * is simply an empty string (`''`). This detail is largely irrelevant for + * most applications. In general, you'll want to treat both cases the same + * way and simply consider the text field to be empty. In either case, the + * text field will appear empty to users when viewed in a PDF reader. + * + * An error will be thrown if this is a rich text field. `pdf-lib` does not + * support reading rich text fields. Nor do most PDF readers and writers. + * Rich text fields are based on XFA (XML Forms Architecture). Relatively few + * PDFs use rich text fields or XFA. Unlike PDF itself, XFA is not an ISO + * standard. XFA has been deprecated in PDF 2.0: + * * https://en.wikipedia.org/wiki/XFA + * * http://blog.pdfshareforms.com/pdf-2-0-release-bid-farewell-xfa-forms/ + * + * @returns The text contained in this text field. + */ + PDFTextField.prototype.getText = function () { + var value = this.acroField.getValue(); + if (!value && this.isRichFormatted()) { + throw new RichTextFieldReadError(this.getName()); + } + return value === null || value === void 0 ? void 0 : value.decodeText(); + }; + /** + * Set the text for this field. This operation is analogous to a human user + * clicking on the text field in a PDF reader and typing in text via their + * keyboard. This method will update the underlying state of the text field + * to indicate what text has been set. PDF libraries and readers will be able + * to extract these values from the saved document and determine what text + * was set. + * + * For example: + * ```js + * const textField = form.getTextField('best.superhero.text.field') + * textField.setText('One Punch Man') + * ``` + * + * This method will mark this text field as dirty, causing its appearance + * streams to be updated when either [[PDFDocument.save]] or + * [[PDFForm.updateFieldAppearances]] is called. The updated streams will + * display the text this field contains inside the widgets of this text + * field. + * + * **IMPORTANT:** The default font used to update appearance streams is + * [[StandardFonts.Helvetica]]. Note that this is a WinAnsi font. This means + * that encoding errors will be thrown if this field contains text outside + * the WinAnsi character set (the latin alphabet). + * + * Embedding a custom font and passing it to + * [[PDFForm.updateFieldAppearances]] or [[PDFTextField.updateAppearances]] + * allows you to generate appearance streams with characters outside the + * latin alphabet (assuming the custom font supports them). + * + * If this is a rich text field, it will be converted to a standard text + * field in order to set the text. `pdf-lib` does not support writing rich + * text strings. Nor do most PDF readers and writers. See + * [[PDFTextField.getText]] for more information about rich text fields and + * their deprecation in PDF 2.0. + * + * @param text The text this field should contain. + */ + PDFTextField.prototype.setText = function (text) { + assertOrUndefined(text, 'text', ['string']); + var maxLength = this.getMaxLength(); + if (maxLength !== undefined && text && text.length > maxLength) { + throw new ExceededMaxLengthError(text.length, maxLength, this.getName()); + } + this.markAsDirty(); + this.disableRichFormatting(); + if (text) { + this.acroField.setValue(PDFHexString.fromText(text)); + } + else { + this.acroField.removeValue(); + } + }; + /** + * Get the alignment for this text field. This value represents the + * justification of the text when it is displayed to the user in PDF readers. + * There are three possible alignments: left, center, and right. For example: + * ```js + * const textField = form.getTextField('some.text.field') + * const alignment = textField.getAlignment() + * if (alignment === TextAlignment.Left) console.log('Text is left justified') + * if (alignment === TextAlignment.Center) console.log('Text is centered') + * if (alignment === TextAlignment.Right) console.log('Text is right justified') + * ``` + * @returns The alignment of this text field. + */ + PDFTextField.prototype.getAlignment = function () { + var quadding = this.acroField.getQuadding(); + // prettier-ignore + return (quadding === 0 ? TextAlignment.Left + : quadding === 1 ? TextAlignment.Center + : quadding === 2 ? TextAlignment.Right + : TextAlignment.Left); + }; + /** + * Set the alignment for this text field. This will determine the + * justification of the text when it is displayed to the user in PDF readers. + * There are three possible alignments: left, center, and right. For example: + * ```js + * const textField = form.getTextField('some.text.field') + * + * // Text will be left justified when displayed + * textField.setAlignment(TextAlignment.Left) + * + * // Text will be centered when displayed + * textField.setAlignment(TextAlignment.Center) + * + * // Text will be right justified when displayed + * textField.setAlignment(TextAlignment.Right) + * ``` + * This method will mark this text field as dirty. See + * [[PDFTextField.setText]] for more details about what this means. + * @param alignment The alignment for this text field. + */ + PDFTextField.prototype.setAlignment = function (alignment) { + assertIsOneOf(alignment, 'alignment', TextAlignment); + this.markAsDirty(); + this.acroField.setQuadding(alignment); + }; + /** + * Get the maximum length of this field. This value represents the maximum + * number of characters that can be typed into this field by the user. If + * this field does not have a maximum length, `undefined` is returned. + * For example: + * ```js + * const textField = form.getTextField('some.text.field') + * const maxLength = textField.getMaxLength() + * if (maxLength === undefined) console.log('No max length') + * else console.log(`Max length is ${maxLength}`) + * ``` + * @returns The maximum number of characters allowed in this field, or + * `undefined` if no limit exists. + */ + PDFTextField.prototype.getMaxLength = function () { + return this.acroField.getMaxLength(); + }; + /** + * Set the maximum length of this field. This limits the number of characters + * that can be typed into this field by the user. This also limits the length + * of the string that can be passed to [[PDFTextField.setText]]. This limit + * can be removed by passing `undefined` as `maxLength`. For example: + * ```js + * const textField = form.getTextField('some.text.field') + * + * // Allow between 0 and 5 characters to be entered + * textField.setMaxLength(5) + * + * // Allow any number of characters to be entered + * textField.setMaxLength(undefined) + * ``` + * This method will mark this text field as dirty. See + * [[PDFTextField.setText]] for more details about what this means. + * @param maxLength The maximum number of characters allowed in this field, or + * `undefined` to remove the limit. + */ + PDFTextField.prototype.setMaxLength = function (maxLength) { + assertRangeOrUndefined(maxLength, 'maxLength', 0, Number.MAX_SAFE_INTEGER); + this.markAsDirty(); + if (maxLength === undefined) { + this.acroField.removeMaxLength(); + } + else { + var text = this.getText(); + if (text && text.length > maxLength) { + throw new InvalidMaxLengthError(text.length, maxLength, this.getName()); + } + this.acroField.setMaxLength(maxLength); + } + }; + /** + * Remove the maximum length for this text field. This allows any number of + * characters to be typed into this field by the user. For example: + * ```js + * const textField = form.getTextField('some.text.field') + * textField.removeMaxLength() + * ``` + * Calling this method is equivalent to passing `undefined` to + * [[PDFTextField.setMaxLength]]. + */ + PDFTextField.prototype.removeMaxLength = function () { + this.markAsDirty(); + this.acroField.removeMaxLength(); + }; + /** + * Display an image inside the bounds of this text field's widgets. For example: + * ```js + * const pngImage = await pdfDoc.embedPng(...) + * const textField = form.getTextField('some.text.field') + * textField.setImage(pngImage) + * ``` + * This will update the appearances streams for each of this text field's widgets. + * @param image The image that should be displayed. + */ + PDFTextField.prototype.setImage = function (image) { + var fieldAlignment = this.getAlignment(); + // prettier-ignore + var alignment = fieldAlignment === TextAlignment.Center ? ImageAlignment.Center + : fieldAlignment === TextAlignment.Right ? ImageAlignment.Right + : ImageAlignment.Left; + var widgets = this.acroField.getWidgets(); + for (var idx = 0, len = widgets.length; idx < len; idx++) { + var widget = widgets[idx]; + var streamRef = this.createImageAppearanceStream(widget, image, alignment); + this.updateWidgetAppearances(widget, { normal: streamRef }); + } + this.markAsClean(); + }; + /** + * Set the font size for this field. Larger font sizes will result in larger + * text being displayed when PDF readers render this text field. Font sizes + * may be integer or floating point numbers. Supplying a negative font size + * will cause this method to throw an error. + * + * For example: + * ```js + * const textField = form.getTextField('some.text.field') + * textField.setFontSize(4) + * textField.setFontSize(15.7) + * ``` + * + * > This method depends upon the existence of a default appearance + * > (`/DA`) string. If this field does not have a default appearance string, + * > or that string does not contain a font size (via the `Tf` operator), + * > then this method will throw an error. + * + * @param fontSize The font size to be used when rendering text in this field. + */ + PDFTextField.prototype.setFontSize = function (fontSize) { + assertPositive(fontSize, 'fontSize'); + this.acroField.setFontSize(fontSize); + this.markAsDirty(); + }; + /** + * Returns `true` if each line of text is shown on a new line when this + * field is displayed in a PDF reader. The alternative is that all lines of + * text are merged onto a single line when displayed. See + * [[PDFTextField.enableMultiline]] and [[PDFTextField.disableMultiline]]. + * For example: + * ```js + * const textField = form.getTextField('some.text.field') + * if (textField.isMultiline()) console.log('Multiline is enabled') + * ``` + * @returns Whether or not this is a multiline text field. + */ + PDFTextField.prototype.isMultiline = function () { + return this.acroField.hasFlag(AcroTextFlags.Multiline); + }; + /** + * Display each line of text on a new line when this field is displayed in a + * PDF reader. For example: + * ```js + * const textField = form.getTextField('some.text.field') + * textField.enableMultiline() + * ``` + * This method will mark this text field as dirty. See + * [[PDFTextField.setText]] for more details about what this means. + */ + PDFTextField.prototype.enableMultiline = function () { + this.markAsDirty(); + this.acroField.setFlagTo(AcroTextFlags.Multiline, true); + }; + /** + * Display each line of text on the same line when this field is displayed + * in a PDF reader. For example: + * ```js + * const textField = form.getTextField('some.text.field') + * textField.disableMultiline() + * ``` + * This method will mark this text field as dirty. See + * [[PDFTextField.setText]] for more details about what this means. + */ + PDFTextField.prototype.disableMultiline = function () { + this.markAsDirty(); + this.acroField.setFlagTo(AcroTextFlags.Multiline, false); + }; + /** + * Returns `true` if this is a password text field. This means that the field + * is intended for storing a secure password. See + * [[PDFTextField.enablePassword]] and [[PDFTextField.disablePassword]]. + * For example: + * ```js + * const textField = form.getTextField('some.text.field') + * if (textField.isPassword()) console.log('Password is enabled') + * ``` + * @returns Whether or not this is a password text field. + */ + PDFTextField.prototype.isPassword = function () { + return this.acroField.hasFlag(AcroTextFlags.Password); + }; + /** + * Indicate that this text field is intended for storing a secure password. + * For example: + * ```js + * const textField = form.getTextField('some.text.field') + * textField.enablePassword() + * ``` + * Values entered into password text fields should not be displayed on the + * screen by PDF readers. Most PDF readers will display the value as + * asterisks or bullets. PDF readers should never store values entered by the + * user into password text fields. Similarly, applications should not + * write data to a password text field. + * + * **Please note that this method does not cause entered values to be + * encrypted or secured in any way! It simply sets a flag that PDF software + * and readers can access to determine the _purpose_ of this field.** + */ + PDFTextField.prototype.enablePassword = function () { + this.acroField.setFlagTo(AcroTextFlags.Password, true); + }; + /** + * Indicate that this text field is **not** intended for storing a secure + * password. For example: + * ```js + * const textField = form.getTextField('some.text.field') + * textField.disablePassword() + * ``` + */ + PDFTextField.prototype.disablePassword = function () { + this.acroField.setFlagTo(AcroTextFlags.Password, false); + }; + /** + * Returns `true` if the contents of this text field represent a file path. + * See [[PDFTextField.enableFileSelection]] and + * [[PDFTextField.disableFileSelection]]. For example: + * ```js + * const textField = form.getTextField('some.text.field') + * if (textField.isFileSelector()) console.log('Is a file selector') + * ``` + * @returns Whether or not this field should contain file paths. + */ + PDFTextField.prototype.isFileSelector = function () { + return this.acroField.hasFlag(AcroTextFlags.FileSelect); + }; + /** + * Indicate that this text field is intended to store a file path. The + * contents of the file stored at that path should be submitted as the value + * of the field. For example: + * ```js + * const textField = form.getTextField('some.text.field') + * textField.enableFileSelection() + * ``` + */ + PDFTextField.prototype.enableFileSelection = function () { + this.acroField.setFlagTo(AcroTextFlags.FileSelect, true); + }; + /** + * Indicate that this text field is **not** intended to store a file path. + * For example: + * ```js + * const textField = form.getTextField('some.text.field') + * textField.disableFileSelection() + * ``` + */ + PDFTextField.prototype.disableFileSelection = function () { + this.acroField.setFlagTo(AcroTextFlags.FileSelect, false); + }; + /** + * Returns `true` if the text entered in this field should be spell checked + * by PDF readers. See [[PDFTextField.enableSpellChecking]] and + * [[PDFTextField.disableSpellChecking]]. For example: + * ```js + * const textField = form.getTextField('some.text.field') + * if (textField.isSpellChecked()) console.log('Spell checking is enabled') + * ``` + * @returns Whether or not this field should be spell checked. + */ + PDFTextField.prototype.isSpellChecked = function () { + return !this.acroField.hasFlag(AcroTextFlags.DoNotSpellCheck); + }; + /** + * Allow PDF readers to spell check the text entered in this field. + * For example: + * ```js + * const textField = form.getTextField('some.text.field') + * textField.enableSpellChecking() + * ``` + */ + PDFTextField.prototype.enableSpellChecking = function () { + this.acroField.setFlagTo(AcroTextFlags.DoNotSpellCheck, false); + }; + /** + * Do not allow PDF readers to spell check the text entered in this field. + * For example: + * ```js + * const textField = form.getTextField('some.text.field') + * textField.disableSpellChecking() + * ``` + */ + PDFTextField.prototype.disableSpellChecking = function () { + this.acroField.setFlagTo(AcroTextFlags.DoNotSpellCheck, true); + }; + /** + * Returns `true` if PDF readers should allow the user to scroll the text + * field when its contents do not fit within the field's view bounds. See + * [[PDFTextField.enableScrolling]] and [[PDFTextField.disableScrolling]]. + * For example: + * ```js + * const textField = form.getTextField('some.text.field') + * if (textField.isScrollable()) console.log('Scrolling is enabled') + * ``` + * @returns Whether or not the field is scrollable in PDF readers. + */ + PDFTextField.prototype.isScrollable = function () { + return !this.acroField.hasFlag(AcroTextFlags.DoNotScroll); + }; + /** + * Allow PDF readers to present a scroll bar to the user when the contents + * of this text field do not fit within its view bounds. For example: + * ```js + * const textField = form.getTextField('some.text.field') + * textField.enableScrolling() + * ``` + * A horizontal scroll bar should be shown for singleline fields. A vertical + * scroll bar should be shown for multiline fields. + */ + PDFTextField.prototype.enableScrolling = function () { + this.acroField.setFlagTo(AcroTextFlags.DoNotScroll, false); + }; + /** + * Do not allow PDF readers to present a scroll bar to the user when the + * contents of this text field do not fit within its view bounds. For example: + * ```js + * const textField = form.getTextField('some.text.field') + * textField.disableScrolling() + * ``` + */ + PDFTextField.prototype.disableScrolling = function () { + this.acroField.setFlagTo(AcroTextFlags.DoNotScroll, true); + }; + /** + * Returns `true` if this is a combed text field. This means that the field + * is split into `n` equal size cells with one character in each (where `n` + * is equal to the max length of the text field). The result is that all + * characters in this field are displayed an equal distance apart from one + * another. See [[PDFTextField.enableCombing]] and + * [[PDFTextField.disableCombing]]. For example: + * ```js + * const textField = form.getTextField('some.text.field') + * if (textField.isCombed()) console.log('Combing is enabled') + * ``` + * Note that in order for a text field to be combed, the following must be + * true (in addition to enabling combing): + * * It must not be a multiline field (see [[PDFTextField.isMultiline]]) + * * It must not be a password field (see [[PDFTextField.isPassword]]) + * * It must not be a file selector field (see [[PDFTextField.isFileSelector]]) + * * It must have a max length defined (see [[PDFTextField.setMaxLength]]) + * @returns Whether or not this field is combed. + */ + PDFTextField.prototype.isCombed = function () { + return (this.acroField.hasFlag(AcroTextFlags.Comb) && + !this.isMultiline() && + !this.isPassword() && + !this.isFileSelector() && + this.getMaxLength() !== undefined); + }; + /** + * Split this field into `n` equal size cells with one character in each + * (where `n` is equal to the max length of the text field). This will cause + * all characters in the field to be displayed an equal distance apart from + * one another. For example: + * ```js + * const textField = form.getTextField('some.text.field') + * textField.enableCombing() + * ``` + * + * In addition to calling this method, text fields must have a max length + * defined in order to be combed (see [[PDFTextField.setMaxLength]]). + * + * This method will also call the following three methods internally: + * * [[PDFTextField.disableMultiline]] + * * [[PDFTextField.disablePassword]] + * * [[PDFTextField.disableFileSelection]] + * + * This method will mark this text field as dirty. See + * [[PDFTextField.setText]] for more details about what this means. + */ + PDFTextField.prototype.enableCombing = function () { + if (this.getMaxLength() === undefined) { + var msg = "PDFTextFields must have a max length in order to be combed"; + console.warn(msg); + } + this.markAsDirty(); + this.disableMultiline(); + this.disablePassword(); + this.disableFileSelection(); + this.acroField.setFlagTo(AcroTextFlags.Comb, true); + }; + /** + * Turn off combing for this text field. For example: + * ```js + * const textField = form.getTextField('some.text.field') + * textField.disableCombing() + * ``` + * See [[PDFTextField.isCombed]] and [[PDFTextField.enableCombing]] for more + * information about what combing is. + * + * This method will mark this text field as dirty. See + * [[PDFTextField.setText]] for more details about what this means. + */ + PDFTextField.prototype.disableCombing = function () { + this.markAsDirty(); + this.acroField.setFlagTo(AcroTextFlags.Comb, false); + }; + /** + * Returns `true` if this text field contains rich text. See + * [[PDFTextField.enableRichFormatting]] and + * [[PDFTextField.disableRichFormatting]]. For example: + * ```js + * const textField = form.getTextField('some.text.field') + * if (textField.isRichFormatted()) console.log('Rich formatting enabled') + * ``` + * @returns Whether or not this field contains rich text. + */ + PDFTextField.prototype.isRichFormatted = function () { + return this.acroField.hasFlag(AcroTextFlags.RichText); + }; + /** + * Indicate that this field contains XFA data - or rich text. For example: + * ```js + * const textField = form.getTextField('some.text.field') + * textField.enableRichFormatting() + * ``` + * Note that `pdf-lib` does not support reading or writing rich text fields. + * Nor do most PDF readers and writers. Rich text fields are based on XFA + * (XML Forms Architecture). Relatively few PDFs use rich text fields or XFA. + * Unlike PDF itself, XFA is not an ISO standard. XFA has been deprecated in + * PDF 2.0: + * * https://en.wikipedia.org/wiki/XFA + * * http://blog.pdfshareforms.com/pdf-2-0-release-bid-farewell-xfa-forms/ + */ + PDFTextField.prototype.enableRichFormatting = function () { + this.acroField.setFlagTo(AcroTextFlags.RichText, true); + }; + /** + * Indicate that this is a standard text field that does not XFA data (rich + * text). For example: + * ```js + * const textField = form.getTextField('some.text.field') + * textField.disableRichFormatting() + * ``` + */ + PDFTextField.prototype.disableRichFormatting = function () { + this.acroField.setFlagTo(AcroTextFlags.RichText, false); + }; + /** + * Show this text field on the specified page. For example: + * ```js + * const ubuntuFont = await pdfDoc.embedFont(ubuntuFontBytes) + * const page = pdfDoc.addPage() + * + * const form = pdfDoc.getForm() + * const textField = form.createTextField('best.gundam') + * textField.setText('Exia') + * + * textField.addToPage(page, { + * x: 50, + * y: 75, + * width: 200, + * height: 100, + * textColor: rgb(1, 0, 0), + * backgroundColor: rgb(0, 1, 0), + * borderColor: rgb(0, 0, 1), + * borderWidth: 2, + * rotate: degrees(90), + * font: ubuntuFont, + * }) + * ``` + * This will create a new widget for this text field. + * @param page The page to which this text field widget should be added. + * @param options The options to be used when adding this text field widget. + */ + PDFTextField.prototype.addToPage = function (page, options) { + var _a, _b, _c, _d, _e, _f, _g; + assertIs(page, 'page', [[PDFPage, 'PDFPage']]); + assertFieldAppearanceOptions(options); + if (!options) + options = {}; + if (!('textColor' in options)) + options.textColor = rgb(0, 0, 0); + if (!('backgroundColor' in options)) + options.backgroundColor = rgb(1, 1, 1); + if (!('borderColor' in options)) + options.borderColor = rgb(0, 0, 0); + if (!('borderWidth' in options)) + options.borderWidth = 1; + // Create a widget for this text field + var widget = this.createWidget({ + x: (_a = options.x) !== null && _a !== void 0 ? _a : 0, + y: (_b = options.y) !== null && _b !== void 0 ? _b : 0, + width: (_c = options.width) !== null && _c !== void 0 ? _c : 200, + height: (_d = options.height) !== null && _d !== void 0 ? _d : 50, + textColor: options.textColor, + backgroundColor: options.backgroundColor, + borderColor: options.borderColor, + borderWidth: (_e = options.borderWidth) !== null && _e !== void 0 ? _e : 0, + rotate: (_f = options.rotate) !== null && _f !== void 0 ? _f : degrees(0), + hidden: options.hidden, + page: page.ref, + }); + var widgetRef = this.doc.context.register(widget.dict); + // Add widget to this field + this.acroField.addWidget(widgetRef); + // Set appearance streams for widget + var font = (_g = options.font) !== null && _g !== void 0 ? _g : this.doc.getForm().getDefaultFont(); + this.updateWidgetAppearance(widget, font); + // Add widget to the given page + page.node.addAnnot(widgetRef); + }; + /** + * Returns `true` if this text field has been marked as dirty, or if any of + * this text field's widgets do not have an appearance stream. For example: + * ```js + * const textField = form.getTextField('some.text.field') + * if (textField.needsAppearancesUpdate()) console.log('Needs update') + * ``` + * @returns Whether or not this text field needs an appearance update. + */ + PDFTextField.prototype.needsAppearancesUpdate = function () { + var _a; + if (this.isDirty()) + return true; + var widgets = this.acroField.getWidgets(); + for (var idx = 0, len = widgets.length; idx < len; idx++) { + var widget = widgets[idx]; + var hasAppearances = ((_a = widget.getAppearances()) === null || _a === void 0 ? void 0 : _a.normal) instanceof PDFStream; + if (!hasAppearances) + return true; + } + return false; + }; + /** + * Update the appearance streams for each of this text field's widgets using + * the default appearance provider for text fields. For example: + * ```js + * const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica) + * const textField = form.getTextField('some.text.field') + * textField.defaultUpdateAppearances(helvetica) + * ``` + * @param font The font to be used for creating the appearance streams. + */ + PDFTextField.prototype.defaultUpdateAppearances = function (font) { + assertIs(font, 'font', [[PDFFont, 'PDFFont']]); + this.updateAppearances(font); + }; + /** + * Update the appearance streams for each of this text field's widgets using + * the given appearance provider. If no `provider` is passed, the default + * appearance provider for text fields will be used. For example: + * ```js + * const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica) + * const textField = form.getTextField('some.text.field') + * textField.updateAppearances(helvetica, (field, widget, font) => { + * ... + * return drawTextField(...) + * }) + * ``` + * @param font The font to be used for creating the appearance streams. + * @param provider Optionally, the appearance provider to be used for + * generating the contents of the appearance streams. + */ + PDFTextField.prototype.updateAppearances = function (font, provider) { + assertIs(font, 'font', [[PDFFont, 'PDFFont']]); + assertOrUndefined(provider, 'provider', [Function]); + var widgets = this.acroField.getWidgets(); + for (var idx = 0, len = widgets.length; idx < len; idx++) { + var widget = widgets[idx]; + this.updateWidgetAppearance(widget, font, provider); + } + this.markAsClean(); + }; + PDFTextField.prototype.updateWidgetAppearance = function (widget, font, provider) { + var apProvider = provider !== null && provider !== void 0 ? provider : defaultTextFieldAppearanceProvider; + var appearances = normalizeAppearance(apProvider(this, widget, font)); + this.updateWidgetAppearanceWithFont(widget, font, appearances); + }; + /** + * > **NOTE:** You probably don't want to call this method directly. Instead, + * > consider using the [[PDFForm.getTextField]] method, which will create an + * > instance of [[PDFTextField]] for you. + * + * Create an instance of [[PDFTextField]] from an existing acroText and ref + * + * @param acroText The underlying `PDFAcroText` for this text field. + * @param ref The unique reference for this text field. + * @param doc The document to which this text field will belong. + */ + PDFTextField.of = function (acroText, ref, doc) { + return new PDFTextField(acroText, ref, doc); + }; + return PDFTextField; +}(PDFField)); + +var StandardFonts; +(function (StandardFonts) { + StandardFonts["Courier"] = "Courier"; + StandardFonts["CourierBold"] = "Courier-Bold"; + StandardFonts["CourierOblique"] = "Courier-Oblique"; + StandardFonts["CourierBoldOblique"] = "Courier-BoldOblique"; + StandardFonts["Helvetica"] = "Helvetica"; + StandardFonts["HelveticaBold"] = "Helvetica-Bold"; + StandardFonts["HelveticaOblique"] = "Helvetica-Oblique"; + StandardFonts["HelveticaBoldOblique"] = "Helvetica-BoldOblique"; + StandardFonts["TimesRoman"] = "Times-Roman"; + StandardFonts["TimesRomanBold"] = "Times-Bold"; + StandardFonts["TimesRomanItalic"] = "Times-Italic"; + StandardFonts["TimesRomanBoldItalic"] = "Times-BoldItalic"; + StandardFonts["Symbol"] = "Symbol"; + StandardFonts["ZapfDingbats"] = "ZapfDingbats"; +})(StandardFonts || (StandardFonts = {})); + +/** + * Represents the interactive form of a [[PDFDocument]]. + * + * Interactive forms (sometimes called _AcroForms_) are collections of fields + * designed to gather information from a user. A PDF document may contains any + * number of fields that appear on various pages, all of which make up a single, + * global interactive form spanning the entire document. This means that + * instances of [[PDFDocument]] shall contain at most one [[PDFForm]]. + * + * The fields of an interactive form are represented by [[PDFField]] instances. + */ +var PDFForm = /** @class */ (function () { + function PDFForm(acroForm, doc) { + var _this = this; + this.embedDefaultFont = function () { + return _this.doc.embedStandardFont(StandardFonts.Helvetica); + }; + assertIs(acroForm, 'acroForm', [[PDFAcroForm, 'PDFAcroForm']]); + assertIs(doc, 'doc', [[PDFDocument, 'PDFDocument']]); + this.acroForm = acroForm; + this.doc = doc; + this.dirtyFields = new Set(); + this.defaultFontCache = Cache.populatedBy(this.embedDefaultFont); + } + /** + * Returns `true` if this [[PDFForm]] has XFA data. Most PDFs with form + * fields do not use XFA as it is not widely supported by PDF readers. + * + * > `pdf-lib` does not support creation, modification, or reading of XFA + * > fields. + * + * For example: + * ```js + * const form = pdfDoc.getForm() + * if (form.hasXFA()) console.log('PDF has XFA data') + * ``` + * @returns Whether or not this form has XFA data. + */ + PDFForm.prototype.hasXFA = function () { + return this.acroForm.dict.has(PDFName.of('XFA')); + }; + /** + * Disconnect the XFA data from this [[PDFForm]] (if any exists). This will + * force readers to fallback to standard fields if the [[PDFDocument]] + * contains any. For example: + * + * For example: + * ```js + * const form = pdfDoc.getForm() + * form.deleteXFA() + * ``` + */ + PDFForm.prototype.deleteXFA = function () { + this.acroForm.dict.delete(PDFName.of('XFA')); + }; + /** + * Get all fields contained in this [[PDFForm]]. For example: + * ```js + * const form = pdfDoc.getForm() + * const fields = form.getFields() + * fields.forEach(field => { + * const type = field.constructor.name + * const name = field.getName() + * console.log(`${type}: ${name}`) + * }) + * ``` + * @returns An array of all fields in this form. + */ + PDFForm.prototype.getFields = function () { + var allFields = this.acroForm.getAllFields(); + var fields = []; + for (var idx = 0, len = allFields.length; idx < len; idx++) { + var _a = allFields[idx], acroField = _a[0], ref = _a[1]; + var field = convertToPDFField(acroField, ref, this.doc); + if (field) + fields.push(field); + } + return fields; + }; + /** + * Get the field in this [[PDFForm]] with the given name. For example: + * ```js + * const form = pdfDoc.getForm() + * const field = form.getFieldMaybe('Page1.Foo.Bar[0]') + * if (field) console.log('Field exists!') + * ``` + * @param name A fully qualified field name. + * @returns The field with the specified name, if one exists. + */ + PDFForm.prototype.getFieldMaybe = function (name) { + assertIs(name, 'name', ['string']); + var fields = this.getFields(); + for (var idx = 0, len = fields.length; idx < len; idx++) { + var field = fields[idx]; + if (field.getName() === name) + return field; + } + return undefined; + }; + /** + * Get the field in this [[PDFForm]] with the given name. For example: + * ```js + * const form = pdfDoc.getForm() + * const field = form.getField('Page1.Foo.Bar[0]') + * ``` + * If no field exists with the provided name, an error will be thrown. + * @param name A fully qualified field name. + * @returns The field with the specified name. + */ + PDFForm.prototype.getField = function (name) { + assertIs(name, 'name', ['string']); + var field = this.getFieldMaybe(name); + if (field) + return field; + throw new NoSuchFieldError(name); + }; + /** + * Get the button field in this [[PDFForm]] with the given name. For example: + * ```js + * const form = pdfDoc.getForm() + * const button = form.getButton('Page1.Foo.Button[0]') + * ``` + * An error will be thrown if no field exists with the provided name, or if + * the field exists but is not a button. + * @param name A fully qualified button name. + * @returns The button with the specified name. + */ + PDFForm.prototype.getButton = function (name) { + assertIs(name, 'name', ['string']); + var field = this.getField(name); + if (field instanceof PDFButton) + return field; + throw new UnexpectedFieldTypeError(name, PDFButton, field); + }; + /** + * Get the check box field in this [[PDFForm]] with the given name. + * For example: + * ```js + * const form = pdfDoc.getForm() + * const checkBox = form.getCheckBox('Page1.Foo.CheckBox[0]') + * checkBox.check() + * ``` + * An error will be thrown if no field exists with the provided name, or if + * the field exists but is not a check box. + * @param name A fully qualified check box name. + * @returns The check box with the specified name. + */ + PDFForm.prototype.getCheckBox = function (name) { + assertIs(name, 'name', ['string']); + var field = this.getField(name); + if (field instanceof PDFCheckBox) + return field; + throw new UnexpectedFieldTypeError(name, PDFCheckBox, field); + }; + /** + * Get the dropdown field in this [[PDFForm]] with the given name. + * For example: + * ```js + * const form = pdfDoc.getForm() + * const dropdown = form.getDropdown('Page1.Foo.Dropdown[0]') + * const options = dropdown.getOptions() + * dropdown.select(options[0]) + * ``` + * An error will be thrown if no field exists with the provided name, or if + * the field exists but is not a dropdown. + * @param name A fully qualified dropdown name. + * @returns The dropdown with the specified name. + */ + PDFForm.prototype.getDropdown = function (name) { + assertIs(name, 'name', ['string']); + var field = this.getField(name); + if (field instanceof PDFDropdown) + return field; + throw new UnexpectedFieldTypeError(name, PDFDropdown, field); + }; + /** + * Get the option list field in this [[PDFForm]] with the given name. + * For example: + * ```js + * const form = pdfDoc.getForm() + * const optionList = form.getOptionList('Page1.Foo.OptionList[0]') + * const options = optionList.getOptions() + * optionList.select(options[0]) + * ``` + * An error will be thrown if no field exists with the provided name, or if + * the field exists but is not an option list. + * @param name A fully qualified option list name. + * @returns The option list with the specified name. + */ + PDFForm.prototype.getOptionList = function (name) { + assertIs(name, 'name', ['string']); + var field = this.getField(name); + if (field instanceof PDFOptionList) + return field; + throw new UnexpectedFieldTypeError(name, PDFOptionList, field); + }; + /** + * Get the radio group field in this [[PDFForm]] with the given name. + * For example: + * ```js + * const form = pdfDoc.getForm() + * const radioGroup = form.getRadioGroup('Page1.Foo.RadioGroup[0]') + * const options = radioGroup.getOptions() + * radioGroup.select(options[0]) + * ``` + * An error will be thrown if no field exists with the provided name, or if + * the field exists but is not a radio group. + * @param name A fully qualified radio group name. + * @returns The radio group with the specified name. + */ + PDFForm.prototype.getRadioGroup = function (name) { + assertIs(name, 'name', ['string']); + var field = this.getField(name); + if (field instanceof PDFRadioGroup) + return field; + throw new UnexpectedFieldTypeError(name, PDFRadioGroup, field); + }; + /** + * Get the signature field in this [[PDFForm]] with the given name. + * For example: + * ```js + * const form = pdfDoc.getForm() + * const signature = form.getSignature('Page1.Foo.Signature[0]') + * ``` + * An error will be thrown if no field exists with the provided name, or if + * the field exists but is not a signature. + * @param name A fully qualified signature name. + * @returns The signature with the specified name. + */ + PDFForm.prototype.getSignature = function (name) { + assertIs(name, 'name', ['string']); + var field = this.getField(name); + if (field instanceof PDFSignature) + return field; + throw new UnexpectedFieldTypeError(name, PDFSignature, field); + }; + /** + * Get the text field in this [[PDFForm]] with the given name. + * For example: + * ```js + * const form = pdfDoc.getForm() + * const textField = form.getTextField('Page1.Foo.TextField[0]') + * textField.setText('Are you designed to act or to be acted upon?') + * ``` + * An error will be thrown if no field exists with the provided name, or if + * the field exists but is not a text field. + * @param name A fully qualified text field name. + * @returns The text field with the specified name. + */ + PDFForm.prototype.getTextField = function (name) { + assertIs(name, 'name', ['string']); + var field = this.getField(name); + if (field instanceof PDFTextField) + return field; + throw new UnexpectedFieldTypeError(name, PDFTextField, field); + }; + /** + * Create a new button field in this [[PDFForm]] with the given name. + * For example: + * ```js + * const font = await pdfDoc.embedFont(StandardFonts.Helvetica) + * const page = pdfDoc.addPage() + * + * const form = pdfDoc.getForm() + * const button = form.createButton('cool.new.button') + * + * button.addToPage('Do Stuff', font, page) + * ``` + * An error will be thrown if a field already exists with the provided name. + * @param name The fully qualified name for the new button. + * @returns The new button field. + */ + PDFForm.prototype.createButton = function (name) { + assertIs(name, 'name', ['string']); + var nameParts = splitFieldName(name); + var parent = this.findOrCreateNonTerminals(nameParts.nonTerminal); + var button = PDFAcroPushButton.create(this.doc.context); + button.setPartialName(nameParts.terminal); + addFieldToParent(parent, [button, button.ref], nameParts.terminal); + return PDFButton.of(button, button.ref, this.doc); + }; + /** + * Create a new check box field in this [[PDFForm]] with the given name. + * For example: + * ```js + * const font = await pdfDoc.embedFont(StandardFonts.Helvetica) + * const page = pdfDoc.addPage() + * + * const form = pdfDoc.getForm() + * const checkBox = form.createCheckBox('cool.new.checkBox') + * + * checkBox.addToPage(page) + * ``` + * An error will be thrown if a field already exists with the provided name. + * @param name The fully qualified name for the new check box. + * @returns The new check box field. + */ + PDFForm.prototype.createCheckBox = function (name) { + assertIs(name, 'name', ['string']); + var nameParts = splitFieldName(name); + var parent = this.findOrCreateNonTerminals(nameParts.nonTerminal); + var checkBox = PDFAcroCheckBox.create(this.doc.context); + checkBox.setPartialName(nameParts.terminal); + addFieldToParent(parent, [checkBox, checkBox.ref], nameParts.terminal); + return PDFCheckBox.of(checkBox, checkBox.ref, this.doc); + }; + /** + * Create a new dropdown field in this [[PDFForm]] with the given name. + * For example: + * ```js + * const font = await pdfDoc.embedFont(StandardFonts.Helvetica) + * const page = pdfDoc.addPage() + * + * const form = pdfDoc.getForm() + * const dropdown = form.createDropdown('cool.new.dropdown') + * + * dropdown.addToPage(font, page) + * ``` + * An error will be thrown if a field already exists with the provided name. + * @param name The fully qualified name for the new dropdown. + * @returns The new dropdown field. + */ + PDFForm.prototype.createDropdown = function (name) { + assertIs(name, 'name', ['string']); + var nameParts = splitFieldName(name); + var parent = this.findOrCreateNonTerminals(nameParts.nonTerminal); + var comboBox = PDFAcroComboBox.create(this.doc.context); + comboBox.setPartialName(nameParts.terminal); + addFieldToParent(parent, [comboBox, comboBox.ref], nameParts.terminal); + return PDFDropdown.of(comboBox, comboBox.ref, this.doc); + }; + /** + * Create a new option list field in this [[PDFForm]] with the given name. + * For example: + * ```js + * const font = await pdfDoc.embedFont(StandardFonts.Helvetica) + * const page = pdfDoc.addPage() + * + * const form = pdfDoc.getForm() + * const optionList = form.createOptionList('cool.new.optionList') + * + * optionList.addToPage(font, page) + * ``` + * An error will be thrown if a field already exists with the provided name. + * @param name The fully qualified name for the new option list. + * @returns The new option list field. + */ + PDFForm.prototype.createOptionList = function (name) { + assertIs(name, 'name', ['string']); + var nameParts = splitFieldName(name); + var parent = this.findOrCreateNonTerminals(nameParts.nonTerminal); + var listBox = PDFAcroListBox.create(this.doc.context); + listBox.setPartialName(nameParts.terminal); + addFieldToParent(parent, [listBox, listBox.ref], nameParts.terminal); + return PDFOptionList.of(listBox, listBox.ref, this.doc); + }; + /** + * Create a new radio group field in this [[PDFForm]] with the given name. + * For example: + * ```js + * const font = await pdfDoc.embedFont(StandardFonts.Helvetica) + * const page = pdfDoc.addPage() + * + * const form = pdfDoc.getForm() + * const radioGroup = form.createRadioGroup('cool.new.radioGroup') + * + * radioGroup.addOptionToPage('is-dog', page, { y: 0 }) + * radioGroup.addOptionToPage('is-cat', page, { y: 75 }) + * ``` + * An error will be thrown if a field already exists with the provided name. + * @param name The fully qualified name for the new radio group. + * @returns The new radio group field. + */ + PDFForm.prototype.createRadioGroup = function (name) { + assertIs(name, 'name', ['string']); + var nameParts = splitFieldName(name); + var parent = this.findOrCreateNonTerminals(nameParts.nonTerminal); + var radioButton = PDFAcroRadioButton.create(this.doc.context); + radioButton.setPartialName(nameParts.terminal); + addFieldToParent(parent, [radioButton, radioButton.ref], nameParts.terminal); + return PDFRadioGroup.of(radioButton, radioButton.ref, this.doc); + }; + /** + * Create a new text field in this [[PDFForm]] with the given name. + * For example: + * ```js + * const font = await pdfDoc.embedFont(StandardFonts.Helvetica) + * const page = pdfDoc.addPage() + * + * const form = pdfDoc.getForm() + * const textField = form.createTextField('cool.new.textField') + * + * textField.addToPage(font, page) + * ``` + * An error will be thrown if a field already exists with the provided name. + * @param name The fully qualified name for the new radio group. + * @returns The new radio group field. + */ + PDFForm.prototype.createTextField = function (name) { + assertIs(name, 'name', ['string']); + var nameParts = splitFieldName(name); + var parent = this.findOrCreateNonTerminals(nameParts.nonTerminal); + var text = PDFAcroText.create(this.doc.context); + text.setPartialName(nameParts.terminal); + addFieldToParent(parent, [text, text.ref], nameParts.terminal); + return PDFTextField.of(text, text.ref, this.doc); + }; + /** + * Flatten all fields in this [[PDFForm]]. + * + * Flattening a form field will take the current appearance for each of that + * field's widgets and make them part of their page's content stream. All form + * fields and annotations associated are then removed. Note that once a form + * has been flattened its fields can no longer be accessed or edited. + * + * This operation is often used after filling form fields to ensure a + * consistent appearance across different PDF readers and/or printers. + * Another common use case is to copy a template document with form fields + * into another document. In this scenario you would load the template + * document, fill its fields, flatten it, and then copy its pages into the + * recipient document - the filled fields will be copied over. + * + * For example: + * ```js + * const form = pdfDoc.getForm(); + * form.flatten(); + * ``` + */ + PDFForm.prototype.flatten = function (options) { + if (options === void 0) { options = { updateFieldAppearances: true }; } + if (options.updateFieldAppearances) { + this.updateFieldAppearances(); + } + var fields = this.getFields(); + for (var i = 0, lenFields = fields.length; i < lenFields; i++) { + var field = fields[i]; + var widgets = field.acroField.getWidgets(); + for (var j = 0, lenWidgets = widgets.length; j < lenWidgets; j++) { + var widget = widgets[j]; + var page = this.findWidgetPage(widget); + var widgetRef = this.findWidgetAppearanceRef(field, widget); + var xObjectKey = page.node.newXObject('FlatWidget', widgetRef); + var rectangle = widget.getRectangle(); + var operators = __spreadArrays([ + pushGraphicsState(), + translate(rectangle.x, rectangle.y) + ], rotateInPlace(__assign(__assign({}, rectangle), { rotation: 0 })), [ + drawObject(xObjectKey), + popGraphicsState(), + ]).filter(Boolean); + page.pushOperators.apply(page, operators); + } + this.removeField(field); + } + }; + /** + * Remove a field from this [[PDFForm]]. + * + * For example: + * ```js + * const form = pdfDoc.getForm(); + * const ageField = form.getFields().find(x => x.getName() === 'Age'); + * form.removeField(ageField); + * ``` + */ + PDFForm.prototype.removeField = function (field) { + var widgets = field.acroField.getWidgets(); + var pages = new Set(); + for (var i = 0, len = widgets.length; i < len; i++) { + var widget = widgets[i]; + var widgetRef = this.findWidgetAppearanceRef(field, widget); + var page = this.findWidgetPage(widget); + pages.add(page); + page.node.removeAnnot(widgetRef); + } + pages.forEach(function (page) { return page.node.removeAnnot(field.ref); }); + this.acroForm.removeField(field.acroField); + var fieldKids = field.acroField.normalizedEntries().Kids; + var kidsCount = fieldKids.size(); + for (var childIndex = 0; childIndex < kidsCount; childIndex++) { + var child = fieldKids.get(childIndex); + if (child instanceof PDFRef) { + this.doc.context.delete(child); + } + } + this.doc.context.delete(field.ref); + }; + /** + * Update the appearance streams for all widgets of all fields in this + * [[PDFForm]]. Appearance streams will only be created for a widget if it + * does not have any existing appearance streams, or the field's value has + * changed (e.g. by calling [[PDFTextField.setText]] or + * [[PDFDropdown.select]]). + * + * For example: + * ```js + * const courier = await pdfDoc.embedFont(StandardFonts.Courier) + * const form = pdfDoc.getForm() + * form.updateFieldAppearances(courier) + * ``` + * + * **IMPORTANT:** The default value for the `font` parameter is + * [[StandardFonts.Helvetica]]. Note that this is a WinAnsi font. This means + * that encoding errors will be thrown if any fields contain text with + * characters outside the WinAnsi character set (the latin alphabet). + * + * Embedding a custom font and passing that as the `font` + * parameter allows you to generate appearance streams with non WinAnsi + * characters (assuming your custom font supports them). + * + * > **NOTE:** The [[PDFDocument.save]] method will call this method to + * > update appearances automatically if a form was accessed via the + * > [[PDFDocument.getForm]] method prior to saving. + * + * @param font Optionally, the font to use when creating new appearances. + */ + PDFForm.prototype.updateFieldAppearances = function (font) { + assertOrUndefined(font, 'font', [[PDFFont, 'PDFFont']]); + font = font !== null && font !== void 0 ? font : this.getDefaultFont(); + var fields = this.getFields(); + for (var idx = 0, len = fields.length; idx < len; idx++) { + var field = fields[idx]; + if (field.needsAppearancesUpdate()) { + field.defaultUpdateAppearances(font); + } + } + }; + /** + * Mark a field as dirty. This will cause its appearance streams to be + * updated by [[PDFForm.updateFieldAppearances]]. + * ```js + * const form = pdfDoc.getForm() + * const field = form.getField('foo.bar') + * form.markFieldAsDirty(field.ref) + * ``` + * @param fieldRef The reference to the field that should be marked. + */ + PDFForm.prototype.markFieldAsDirty = function (fieldRef) { + assertOrUndefined(fieldRef, 'fieldRef', [[PDFRef, 'PDFRef']]); + this.dirtyFields.add(fieldRef); + }; + /** + * Mark a field as dirty. This will cause its appearance streams to not be + * updated by [[PDFForm.updateFieldAppearances]]. + * ```js + * const form = pdfDoc.getForm() + * const field = form.getField('foo.bar') + * form.markFieldAsClean(field.ref) + * ``` + * @param fieldRef The reference to the field that should be marked. + */ + PDFForm.prototype.markFieldAsClean = function (fieldRef) { + assertOrUndefined(fieldRef, 'fieldRef', [[PDFRef, 'PDFRef']]); + this.dirtyFields.delete(fieldRef); + }; + /** + * Returns `true` is the specified field has been marked as dirty. + * ```js + * const form = pdfDoc.getForm() + * const field = form.getField('foo.bar') + * if (form.fieldIsDirty(field.ref)) console.log('Field is dirty') + * ``` + * @param fieldRef The reference to the field that should be checked. + * @returns Whether or not the specified field is dirty. + */ + PDFForm.prototype.fieldIsDirty = function (fieldRef) { + assertOrUndefined(fieldRef, 'fieldRef', [[PDFRef, 'PDFRef']]); + return this.dirtyFields.has(fieldRef); + }; + PDFForm.prototype.getDefaultFont = function () { + return this.defaultFontCache.access(); + }; + PDFForm.prototype.findWidgetPage = function (widget) { + var pageRef = widget.P(); + var page = this.doc.getPages().find(function (x) { return x.ref === pageRef; }); + if (page === undefined) { + var widgetRef = this.doc.context.getObjectRef(widget.dict); + if (widgetRef === undefined) { + throw new Error('Could not find PDFRef for PDFObject'); + } + page = this.doc.findPageForAnnotationRef(widgetRef); + if (page === undefined) { + throw new Error("Could not find page for PDFRef " + widgetRef); + } + } + return page; + }; + PDFForm.prototype.findWidgetAppearanceRef = function (field, widget) { + var _a; + var refOrDict = widget.getNormalAppearance(); + if (refOrDict instanceof PDFDict && + (field instanceof PDFCheckBox || field instanceof PDFRadioGroup)) { + var value = field.acroField.getValue(); + var ref = (_a = refOrDict.get(value)) !== null && _a !== void 0 ? _a : refOrDict.get(PDFName.of('Off')); + if (ref instanceof PDFRef) { + refOrDict = ref; + } + } + if (!(refOrDict instanceof PDFRef)) { + var name_1 = field.getName(); + throw new Error("Failed to extract appearance ref for: " + name_1); + } + return refOrDict; + }; + PDFForm.prototype.findOrCreateNonTerminals = function (partialNames) { + var nonTerminal = [ + this.acroForm, + ]; + for (var idx = 0, len = partialNames.length; idx < len; idx++) { + var namePart = partialNames[idx]; + if (!namePart) + throw new InvalidFieldNamePartError(namePart); + var parent_1 = nonTerminal[0], parentRef = nonTerminal[1]; + var res = this.findNonTerminal(namePart, parent_1); + if (res) { + nonTerminal = res; + } + else { + var node = PDFAcroNonTerminal.create(this.doc.context); + node.setPartialName(namePart); + node.setParent(parentRef); + var nodeRef = this.doc.context.register(node.dict); + parent_1.addField(nodeRef); + nonTerminal = [node, nodeRef]; + } + } + return nonTerminal; + }; + PDFForm.prototype.findNonTerminal = function (partialName, parent) { + var fields = parent instanceof PDFAcroForm + ? this.acroForm.getFields() + : createPDFAcroFields(parent.Kids()); + for (var idx = 0, len = fields.length; idx < len; idx++) { + var _a = fields[idx], field = _a[0], ref = _a[1]; + if (field.getPartialName() === partialName) { + if (field instanceof PDFAcroNonTerminal) + return [field, ref]; + throw new FieldAlreadyExistsError(partialName); + } + } + return undefined; + }; + /** + * > **NOTE:** You probably don't want to call this method directly. Instead, + * > consider using the [[PDFDocument.getForm]] method, which will create an + * > instance of [[PDFForm]] for you. + * + * Create an instance of [[PDFForm]] from an existing acroForm and embedder + * + * @param acroForm The underlying `PDFAcroForm` for this form. + * @param doc The document to which the form will belong. + */ + PDFForm.of = function (acroForm, doc) { + return new PDFForm(acroForm, doc); + }; + return PDFForm; +}()); +var convertToPDFField = function (field, ref, doc) { + if (field instanceof PDFAcroPushButton) + return PDFButton.of(field, ref, doc); + if (field instanceof PDFAcroCheckBox) + return PDFCheckBox.of(field, ref, doc); + if (field instanceof PDFAcroComboBox) + return PDFDropdown.of(field, ref, doc); + if (field instanceof PDFAcroListBox) + return PDFOptionList.of(field, ref, doc); + if (field instanceof PDFAcroText) + return PDFTextField.of(field, ref, doc); + if (field instanceof PDFAcroRadioButton) { + return PDFRadioGroup.of(field, ref, doc); + } + if (field instanceof PDFAcroSignature) { + return PDFSignature.of(field, ref, doc); + } + return undefined; +}; +var splitFieldName = function (fullyQualifiedName) { + if (fullyQualifiedName.length === 0) { + throw new Error('PDF field names must not be empty strings'); + } + var parts = fullyQualifiedName.split('.'); + for (var idx = 0, len = parts.length; idx < len; idx++) { + if (parts[idx] === '') { + throw new Error("Periods in PDF field names must be separated by at least one character: \"" + fullyQualifiedName + "\""); + } + } + if (parts.length === 1) + return { nonTerminal: [], terminal: parts[0] }; + return { + nonTerminal: parts.slice(0, parts.length - 1), + terminal: parts[parts.length - 1], + }; +}; +var addFieldToParent = function (_a, _b, partialName) { + var parent = _a[0], parentRef = _a[1]; + var field = _b[0], fieldRef = _b[1]; + var entries = parent.normalizedEntries(); + var fields = createPDFAcroFields('Kids' in entries ? entries.Kids : entries.Fields); + for (var idx = 0, len = fields.length; idx < len; idx++) { + if (fields[idx][0].getPartialName() === partialName) { + throw new FieldAlreadyExistsError(partialName); + } + } + parent.addField(fieldRef); + field.setParent(parentRef); +}; + +var PageSizes = { + '4A0': [4767.87, 6740.79], + '2A0': [3370.39, 4767.87], + A0: [2383.94, 3370.39], + A1: [1683.78, 2383.94], + A2: [1190.55, 1683.78], + A3: [841.89, 1190.55], + A4: [595.28, 841.89], + A5: [419.53, 595.28], + A6: [297.64, 419.53], + A7: [209.76, 297.64], + A8: [147.4, 209.76], + A9: [104.88, 147.4], + A10: [73.7, 104.88], + B0: [2834.65, 4008.19], + B1: [2004.09, 2834.65], + B2: [1417.32, 2004.09], + B3: [1000.63, 1417.32], + B4: [708.66, 1000.63], + B5: [498.9, 708.66], + B6: [354.33, 498.9], + B7: [249.45, 354.33], + B8: [175.75, 249.45], + B9: [124.72, 175.75], + B10: [87.87, 124.72], + C0: [2599.37, 3676.54], + C1: [1836.85, 2599.37], + C2: [1298.27, 1836.85], + C3: [918.43, 1298.27], + C4: [649.13, 918.43], + C5: [459.21, 649.13], + C6: [323.15, 459.21], + C7: [229.61, 323.15], + C8: [161.57, 229.61], + C9: [113.39, 161.57], + C10: [79.37, 113.39], + RA0: [2437.8, 3458.27], + RA1: [1729.13, 2437.8], + RA2: [1218.9, 1729.13], + RA3: [864.57, 1218.9], + RA4: [609.45, 864.57], + SRA0: [2551.18, 3628.35], + SRA1: [1814.17, 2551.18], + SRA2: [1275.59, 1814.17], + SRA3: [907.09, 1275.59], + SRA4: [637.8, 907.09], + Executive: [521.86, 756.0], + Folio: [612.0, 936.0], + Legal: [612.0, 1008.0], + Letter: [612.0, 792.0], + Tabloid: [792.0, 1224.0], +}; + +var ParseSpeeds; +(function (ParseSpeeds) { + ParseSpeeds[ParseSpeeds["Fastest"] = Infinity] = "Fastest"; + ParseSpeeds[ParseSpeeds["Fast"] = 1500] = "Fast"; + ParseSpeeds[ParseSpeeds["Medium"] = 500] = "Medium"; + ParseSpeeds[ParseSpeeds["Slow"] = 100] = "Slow"; +})(ParseSpeeds || (ParseSpeeds = {})); + +/** + * Represents a file that has been embedded in a [[PDFDocument]]. + */ +var PDFEmbeddedFile = /** @class */ (function () { + function PDFEmbeddedFile(ref, doc, embedder) { + this.alreadyEmbedded = false; + this.ref = ref; + this.doc = doc; + this.embedder = embedder; + } + /** + * > **NOTE:** You probably don't need to call this method directly. The + * > [[PDFDocument.save]] and [[PDFDocument.saveAsBase64]] methods will + * > automatically ensure all embeddable files get embedded. + * + * Embed this embeddable file in its document. + * + * @returns Resolves when the embedding is complete. + */ + PDFEmbeddedFile.prototype.embed = function () { + return __awaiter(this, void 0, void 0, function () { + var ref, Names, EmbeddedFiles, EFNames, AF; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!!this.alreadyEmbedded) return [3 /*break*/, 2]; + return [4 /*yield*/, this.embedder.embedIntoContext(this.doc.context, this.ref)]; + case 1: + ref = _a.sent(); + if (!this.doc.catalog.has(PDFName.of('Names'))) { + this.doc.catalog.set(PDFName.of('Names'), this.doc.context.obj({})); + } + Names = this.doc.catalog.lookup(PDFName.of('Names'), PDFDict); + if (!Names.has(PDFName.of('EmbeddedFiles'))) { + Names.set(PDFName.of('EmbeddedFiles'), this.doc.context.obj({})); + } + EmbeddedFiles = Names.lookup(PDFName.of('EmbeddedFiles'), PDFDict); + if (!EmbeddedFiles.has(PDFName.of('Names'))) { + EmbeddedFiles.set(PDFName.of('Names'), this.doc.context.obj([])); + } + EFNames = EmbeddedFiles.lookup(PDFName.of('Names'), PDFArray); + EFNames.push(PDFHexString.fromText(this.embedder.fileName)); + EFNames.push(ref); + /** + * The AF-Tag is needed to achieve PDF-A3 compliance for embedded files + * + * The following document outlines the uses cases of the associated files (AF) tag. + * See: + * https://www.pdfa.org/wp-content/uploads/2018/10/PDF20_AN002-AF.pdf + */ + if (!this.doc.catalog.has(PDFName.of('AF'))) { + this.doc.catalog.set(PDFName.of('AF'), this.doc.context.obj([])); + } + AF = this.doc.catalog.lookup(PDFName.of('AF'), PDFArray); + AF.push(ref); + this.alreadyEmbedded = true; + _a.label = 2; + case 2: return [2 /*return*/]; + } + }); + }); + }; + /** + * > **NOTE:** You probably don't want to call this method directly. Instead, + * > consider using the [[PDFDocument.attach]] method, which will create + * instances of [[PDFEmbeddedFile]] for you. + * + * Create an instance of [[PDFEmbeddedFile]] from an existing ref and embedder + * + * @param ref The unique reference for this file. + * @param doc The document to which the file will belong. + * @param embedder The embedder that will be used to embed the file. + */ + PDFEmbeddedFile.of = function (ref, doc, embedder) { + return new PDFEmbeddedFile(ref, doc, embedder); + }; + return PDFEmbeddedFile; +}()); + +/** + * Represents JavaScript that has been embedded in a [[PDFDocument]]. + */ +var PDFJavaScript = /** @class */ (function () { + function PDFJavaScript(ref, doc, embedder) { + this.alreadyEmbedded = false; + this.ref = ref; + this.doc = doc; + this.embedder = embedder; + } + /** + * > **NOTE:** You probably don't need to call this method directly. The + * > [[PDFDocument.save]] and [[PDFDocument.saveAsBase64]] methods will + * > automatically ensure all JavaScripts get embedded. + * + * Embed this JavaScript in its document. + * + * @returns Resolves when the embedding is complete. + */ + PDFJavaScript.prototype.embed = function () { + return __awaiter(this, void 0, void 0, function () { + var _a, catalog, context, ref, Names, Javascript, JSNames; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!!this.alreadyEmbedded) return [3 /*break*/, 2]; + _a = this.doc, catalog = _a.catalog, context = _a.context; + return [4 /*yield*/, this.embedder.embedIntoContext(this.doc.context, this.ref)]; + case 1: + ref = _b.sent(); + if (!catalog.has(PDFName.of('Names'))) { + catalog.set(PDFName.of('Names'), context.obj({})); + } + Names = catalog.lookup(PDFName.of('Names'), PDFDict); + if (!Names.has(PDFName.of('JavaScript'))) { + Names.set(PDFName.of('JavaScript'), context.obj({})); + } + Javascript = Names.lookup(PDFName.of('JavaScript'), PDFDict); + if (!Javascript.has(PDFName.of('Names'))) { + Javascript.set(PDFName.of('Names'), context.obj([])); + } + JSNames = Javascript.lookup(PDFName.of('Names'), PDFArray); + JSNames.push(PDFHexString.fromText(this.embedder.scriptName)); + JSNames.push(ref); + this.alreadyEmbedded = true; + _b.label = 2; + case 2: return [2 /*return*/]; + } + }); + }); + }; + /** + * > **NOTE:** You probably don't want to call this method directly. Instead, + * > consider using the [[PDFDocument.addJavaScript]] method, which will + * create instances of [[PDFJavaScript]] for you. + * + * Create an instance of [[PDFJavaScript]] from an existing ref and script + * + * @param ref The unique reference for this script. + * @param doc The document to which the script will belong. + * @param embedder The embedder that will be used to embed the script. + */ + PDFJavaScript.of = function (ref, doc, embedder) { + return new PDFJavaScript(ref, doc, embedder); + }; + return PDFJavaScript; +}()); + +var JavaScriptEmbedder = /** @class */ (function () { + function JavaScriptEmbedder(script, scriptName) { + this.script = script; + this.scriptName = scriptName; + } + JavaScriptEmbedder.for = function (script, scriptName) { + return new JavaScriptEmbedder(script, scriptName); + }; + JavaScriptEmbedder.prototype.embedIntoContext = function (context, ref) { + return __awaiter(this, void 0, void 0, function () { + var jsActionDict; + return __generator(this, function (_a) { + jsActionDict = context.obj({ + Type: 'Action', + S: 'JavaScript', + JS: PDFHexString.fromText(this.script), + }); + if (ref) { + context.assign(ref, jsActionDict); + return [2 /*return*/, ref]; + } + else { + return [2 /*return*/, context.register(jsActionDict)]; + } + }); + }); + }; + return JavaScriptEmbedder; +}()); + +/** + * Represents a PDF document. + */ +var PDFDocument = /** @class */ (function () { + function PDFDocument(context, ignoreEncryption, updateMetadata) { + var _this = this; + /** The default word breaks used in PDFPage.drawText */ + this.defaultWordBreaks = [' ']; + this.computePages = function () { + var pages = []; + _this.catalog.Pages().traverse(function (node, ref) { + if (node instanceof PDFPageLeaf) { + var page = _this.pageMap.get(node); + if (!page) { + page = PDFPage.of(node, ref, _this); + _this.pageMap.set(node, page); + } + pages.push(page); + } + }); + return pages; + }; + this.getOrCreateForm = function () { + var acroForm = _this.catalog.getOrCreateAcroForm(); + return PDFForm.of(acroForm, _this); + }; + assertIs(context, 'context', [[PDFContext, 'PDFContext']]); + assertIs(ignoreEncryption, 'ignoreEncryption', ['boolean']); + this.context = context; + this.catalog = context.lookup(context.trailerInfo.Root); + this.isEncrypted = !!context.lookup(context.trailerInfo.Encrypt); + this.pageCache = Cache.populatedBy(this.computePages); + this.pageMap = new Map(); + this.formCache = Cache.populatedBy(this.getOrCreateForm); + this.fonts = []; + this.images = []; + this.embeddedPages = []; + this.embeddedFiles = []; + this.javaScripts = []; + if (!ignoreEncryption && this.isEncrypted) + throw new EncryptedPDFError(); + if (updateMetadata) + this.updateInfoDict(); + } + /** + * Load an existing [[PDFDocument]]. The input data can be provided in + * multiple formats: + * + * | Type | Contents | + * | ------------- | ------------------------------------------------------ | + * | `string` | A base64 encoded string (or data URI) containing a PDF | + * | `Uint8Array` | The raw bytes of a PDF | + * | `ArrayBuffer` | The raw bytes of a PDF | + * + * For example: + * ```js + * import { PDFDocument } from 'pdf-lib' + * + * // pdf=string + * const base64 = + * 'JVBERi0xLjcKJYGBgYEKCjUgMCBvYmoKPDwKL0ZpbHRlciAvRmxhdGVEZWNvZGUKL0xlbm' + + * 'd0aCAxMDQKPj4Kc3RyZWFtCniccwrhMlAAwaJ0Ln2P1Jyy1JLM5ERdc0MjCwUjE4WQNC4Q' + + * '6cNlCFZkqGCqYGSqEJLLZWNuYGZiZmbkYuZsZmlmZGRgZmluDCQNzc3NTM2NzdzMXMxMjQ' + + * 'ztFEKyuEK0uFxDuAAOERdVCmVuZHN0cmVhbQplbmRvYmoKCjYgMCBvYmoKPDwKL0ZpbHRl' + + * 'ciAvRmxhdGVEZWNvZGUKL1R5cGUgL09ialN0bQovTiA0Ci9GaXJzdCAyMAovTGVuZ3RoID' + + * 'IxNQo+PgpzdHJlYW0KeJxVj9GqwjAMhu/zFHkBzTo3nCCCiiKIHPEICuJF3cKoSCu2E8/b' + + * '20wPIr1p8v9/8kVhgilmGfawX2CGaVrgcAi0/bsy0lrX7IGWpvJ4iJYEN3gEmrrGBlQwGs' + + * 'HHO9VBX1wNrxAqMX87RBD5xpJuddqwd82tjAHxzV1U5LPgy52DKXWnr1Lheg+j/c/pzGVr' + + * 'iqV0VlwZPXGPCJjElw/ybkwUmeoWgxesDXGhHJC/D/iikp1Av80ptKU0FdBEe25pPihAM1' + + * 'u6ytgaaWfs2Hrz35CJT1+EWmAKZW5kc3RyZWFtCmVuZG9iagoKNyAwIG9iago8PAovU2l6' + + * 'ZSA4Ci9Sb290IDIgMCBSCi9GaWx0ZXIgL0ZsYXRlRGVjb2RlCi9UeXBlIC9YUmVmCi9MZW' + + * '5ndGggMzgKL1cgWyAxIDIgMiBdCi9JbmRleCBbIDAgOCBdCj4+CnN0cmVhbQp4nBXEwREA' + + * 'EBAEsCwz3vrvRmOOyyOoGhZdutHN2MT55fIAVocD+AplbmRzdHJlYW0KZW5kb2JqCgpzdG' + + * 'FydHhyZWYKNTEwCiUlRU9G' + * + * const dataUri = 'data:application/pdf;base64,' + base64 + * + * const pdfDoc1 = await PDFDocument.load(base64) + * const pdfDoc2 = await PDFDocument.load(dataUri) + * + * // pdf=Uint8Array + * import fs from 'fs' + * const uint8Array = fs.readFileSync('with_update_sections.pdf') + * const pdfDoc3 = await PDFDocument.load(uint8Array) + * + * // pdf=ArrayBuffer + * const url = 'https://pdf-lib.js.org/assets/with_update_sections.pdf' + * const arrayBuffer = await fetch(url).then(res => res.arrayBuffer()) + * const pdfDoc4 = await PDFDocument.load(arrayBuffer) + * + * ``` + * + * @param pdf The input data containing a PDF document. + * @param options The options to be used when loading the document. + * @returns Resolves with a document loaded from the input. + */ + PDFDocument.load = function (pdf, options) { + if (options === void 0) { options = {}; } + return __awaiter(this, void 0, void 0, function () { + var _a, ignoreEncryption, _b, parseSpeed, _c, throwOnInvalidObject, _d, updateMetadata, _e, capNumbers, bytes, context; + return __generator(this, function (_f) { + switch (_f.label) { + case 0: + _a = options.ignoreEncryption, ignoreEncryption = _a === void 0 ? false : _a, _b = options.parseSpeed, parseSpeed = _b === void 0 ? ParseSpeeds.Slow : _b, _c = options.throwOnInvalidObject, throwOnInvalidObject = _c === void 0 ? false : _c, _d = options.updateMetadata, updateMetadata = _d === void 0 ? true : _d, _e = options.capNumbers, capNumbers = _e === void 0 ? false : _e; + assertIs(pdf, 'pdf', ['string', Uint8Array, ArrayBuffer]); + assertIs(ignoreEncryption, 'ignoreEncryption', ['boolean']); + assertIs(parseSpeed, 'parseSpeed', ['number']); + assertIs(throwOnInvalidObject, 'throwOnInvalidObject', ['boolean']); + bytes = toUint8Array(pdf); + return [4 /*yield*/, PDFParser.forBytesWithOptions(bytes, parseSpeed, throwOnInvalidObject, capNumbers).parseDocument()]; + case 1: + context = _f.sent(); + return [2 /*return*/, new PDFDocument(context, ignoreEncryption, updateMetadata)]; + } + }); + }); + }; + /** + * Create a new [[PDFDocument]]. + * @returns Resolves with the newly created document. + */ + PDFDocument.create = function (options) { + if (options === void 0) { options = {}; } + return __awaiter(this, void 0, void 0, function () { + var _a, updateMetadata, context, pageTree, pageTreeRef, catalog; + return __generator(this, function (_b) { + _a = options.updateMetadata, updateMetadata = _a === void 0 ? true : _a; + context = PDFContext.create(); + pageTree = PDFPageTree.withContext(context); + pageTreeRef = context.register(pageTree); + catalog = PDFCatalog.withContextAndPages(context, pageTreeRef); + context.trailerInfo.Root = context.register(catalog); + return [2 /*return*/, new PDFDocument(context, false, updateMetadata)]; + }); + }); + }; + /** + * Register a fontkit instance. This must be done before custom fonts can + * be embedded. See [here](https://github.com/Hopding/pdf-lib/tree/master#fontkit-installation) + * for instructions on how to install and register a fontkit instance. + * + * > You do **not** need to call this method to embed standard fonts. + * + * For example: + * ```js + * import { PDFDocument } from 'pdf-lib' + * import fontkit from '@pdf-lib/fontkit' + * + * const pdfDoc = await PDFDocument.create() + * pdfDoc.registerFontkit(fontkit) + * ``` + * + * @param fontkit The fontkit instance to be registered. + */ + PDFDocument.prototype.registerFontkit = function (fontkit) { + this.fontkit = fontkit; + }; + /** + * Get the [[PDFForm]] containing all interactive fields for this document. + * For example: + * ```js + * const form = pdfDoc.getForm() + * const fields = form.getFields() + * fields.forEach(field => { + * const type = field.constructor.name + * const name = field.getName() + * console.log(`${type}: ${name}`) + * }) + * ``` + * @returns The form for this document. + */ + PDFDocument.prototype.getForm = function () { + var form = this.formCache.access(); + if (form.hasXFA()) { + console.warn('Removing XFA form data as pdf-lib does not support reading or writing XFA'); + form.deleteXFA(); + } + return form; + }; + /** + * Get this document's title metadata. The title appears in the + * "Document Properties" section of most PDF readers. For example: + * ```js + * const title = pdfDoc.getTitle() + * ``` + * @returns A string containing the title of this document, if it has one. + */ + PDFDocument.prototype.getTitle = function () { + var title = this.getInfoDict().lookup(PDFName.Title); + if (!title) + return undefined; + assertIsLiteralOrHexString(title); + return title.decodeText(); + }; + /** + * Get this document's author metadata. The author appears in the + * "Document Properties" section of most PDF readers. For example: + * ```js + * const author = pdfDoc.getAuthor() + * ``` + * @returns A string containing the author of this document, if it has one. + */ + PDFDocument.prototype.getAuthor = function () { + var author = this.getInfoDict().lookup(PDFName.Author); + if (!author) + return undefined; + assertIsLiteralOrHexString(author); + return author.decodeText(); + }; + /** + * Get this document's subject metadata. The subject appears in the + * "Document Properties" section of most PDF readers. For example: + * ```js + * const subject = pdfDoc.getSubject() + * ``` + * @returns A string containing the subject of this document, if it has one. + */ + PDFDocument.prototype.getSubject = function () { + var subject = this.getInfoDict().lookup(PDFName.Subject); + if (!subject) + return undefined; + assertIsLiteralOrHexString(subject); + return subject.decodeText(); + }; + /** + * Get this document's keywords metadata. The keywords appear in the + * "Document Properties" section of most PDF readers. For example: + * ```js + * const keywords = pdfDoc.getKeywords() + * ``` + * @returns A string containing the keywords of this document, if it has any. + */ + PDFDocument.prototype.getKeywords = function () { + var keywords = this.getInfoDict().lookup(PDFName.Keywords); + if (!keywords) + return undefined; + assertIsLiteralOrHexString(keywords); + return keywords.decodeText(); + }; + /** + * Get this document's creator metadata. The creator appears in the + * "Document Properties" section of most PDF readers. For example: + * ```js + * const creator = pdfDoc.getCreator() + * ``` + * @returns A string containing the creator of this document, if it has one. + */ + PDFDocument.prototype.getCreator = function () { + var creator = this.getInfoDict().lookup(PDFName.Creator); + if (!creator) + return undefined; + assertIsLiteralOrHexString(creator); + return creator.decodeText(); + }; + /** + * Get this document's producer metadata. The producer appears in the + * "Document Properties" section of most PDF readers. For example: + * ```js + * const producer = pdfDoc.getProducer() + * ``` + * @returns A string containing the producer of this document, if it has one. + */ + PDFDocument.prototype.getProducer = function () { + var producer = this.getInfoDict().lookup(PDFName.Producer); + if (!producer) + return undefined; + assertIsLiteralOrHexString(producer); + return producer.decodeText(); + }; + /** + * Get this document's creation date metadata. The creation date appears in + * the "Document Properties" section of most PDF readers. For example: + * ```js + * const creationDate = pdfDoc.getCreationDate() + * ``` + * @returns A Date containing the creation date of this document, + * if it has one. + */ + PDFDocument.prototype.getCreationDate = function () { + var creationDate = this.getInfoDict().lookup(PDFName.CreationDate); + if (!creationDate) + return undefined; + assertIsLiteralOrHexString(creationDate); + return creationDate.decodeDate(); + }; + /** + * Get this document's modification date metadata. The modification date + * appears in the "Document Properties" section of most PDF readers. + * For example: + * ```js + * const modification = pdfDoc.getModificationDate() + * ``` + * @returns A Date containing the modification date of this document, + * if it has one. + */ + PDFDocument.prototype.getModificationDate = function () { + var modificationDate = this.getInfoDict().lookup(PDFName.ModDate); + if (!modificationDate) + return undefined; + assertIsLiteralOrHexString(modificationDate); + return modificationDate.decodeDate(); + }; + /** + * Set this document's title metadata. The title will appear in the + * "Document Properties" section of most PDF readers. For example: + * ```js + * pdfDoc.setTitle('🥚 The Life of an Egg 🍳') + * ``` + * + * To display the title in the window's title bar, set the + * `showInWindowTitleBar` option to `true` (works for _most_ PDF readers). + * For example: + * ```js + * pdfDoc.setTitle('🥚 The Life of an Egg 🍳', { showInWindowTitleBar: true }) + * ``` + * + * @param title The title of this document. + * @param options The options to be used when setting the title. + */ + PDFDocument.prototype.setTitle = function (title, options) { + assertIs(title, 'title', ['string']); + var key = PDFName.of('Title'); + this.getInfoDict().set(key, PDFHexString.fromText(title)); + // Indicate that readers should display the title rather than the filename + if (options === null || options === void 0 ? void 0 : options.showInWindowTitleBar) { + var prefs = this.catalog.getOrCreateViewerPreferences(); + prefs.setDisplayDocTitle(true); + } + }; + /** + * Set this document's author metadata. The author will appear in the + * "Document Properties" section of most PDF readers. For example: + * ```js + * pdfDoc.setAuthor('Humpty Dumpty') + * ``` + * @param author The author of this document. + */ + PDFDocument.prototype.setAuthor = function (author) { + assertIs(author, 'author', ['string']); + var key = PDFName.of('Author'); + this.getInfoDict().set(key, PDFHexString.fromText(author)); + }; + /** + * Set this document's subject metadata. The subject will appear in the + * "Document Properties" section of most PDF readers. For example: + * ```js + * pdfDoc.setSubject('📘 An Epic Tale of Woe 📖') + * ``` + * @param subject The subject of this document. + */ + PDFDocument.prototype.setSubject = function (subject) { + assertIs(subject, 'author', ['string']); + var key = PDFName.of('Subject'); + this.getInfoDict().set(key, PDFHexString.fromText(subject)); + }; + /** + * Set this document's keyword metadata. These keywords will appear in the + * "Document Properties" section of most PDF readers. For example: + * ```js + * pdfDoc.setKeywords(['eggs', 'wall', 'fall', 'king', 'horses', 'men']) + * ``` + * @param keywords An array of keywords associated with this document. + */ + PDFDocument.prototype.setKeywords = function (keywords) { + assertIs(keywords, 'keywords', [Array]); + var key = PDFName.of('Keywords'); + this.getInfoDict().set(key, PDFHexString.fromText(keywords.join(' '))); + }; + /** + * Set this document's creator metadata. The creator will appear in the + * "Document Properties" section of most PDF readers. For example: + * ```js + * pdfDoc.setCreator('PDF App 9000 🤖') + * ``` + * @param creator The creator of this document. + */ + PDFDocument.prototype.setCreator = function (creator) { + assertIs(creator, 'creator', ['string']); + var key = PDFName.of('Creator'); + this.getInfoDict().set(key, PDFHexString.fromText(creator)); + }; + /** + * Set this document's producer metadata. The producer will appear in the + * "Document Properties" section of most PDF readers. For example: + * ```js + * pdfDoc.setProducer('PDF App 9000 🤖') + * ``` + * @param producer The producer of this document. + */ + PDFDocument.prototype.setProducer = function (producer) { + assertIs(producer, 'creator', ['string']); + var key = PDFName.of('Producer'); + this.getInfoDict().set(key, PDFHexString.fromText(producer)); + }; + /** + * Set this document's language metadata. The language will appear in the + * "Document Properties" section of some PDF readers. For example: + * ```js + * pdfDoc.setLanguage('en-us') + * ``` + * + * @param language An RFC 3066 _Language-Tag_ denoting the language of this + * document, or an empty string if the language is unknown. + */ + PDFDocument.prototype.setLanguage = function (language) { + assertIs(language, 'language', ['string']); + var key = PDFName.of('Lang'); + this.catalog.set(key, PDFString.of(language)); + }; + /** + * Set this document's creation date metadata. The creation date will appear + * in the "Document Properties" section of most PDF readers. For example: + * ```js + * pdfDoc.setCreationDate(new Date()) + * ``` + * @param creationDate The date this document was created. + */ + PDFDocument.prototype.setCreationDate = function (creationDate) { + assertIs(creationDate, 'creationDate', [[Date, 'Date']]); + var key = PDFName.of('CreationDate'); + this.getInfoDict().set(key, PDFString.fromDate(creationDate)); + }; + /** + * Set this document's modification date metadata. The modification date will + * appear in the "Document Properties" section of most PDF readers. For + * example: + * ```js + * pdfDoc.setModificationDate(new Date()) + * ``` + * @param modificationDate The date this document was last modified. + */ + PDFDocument.prototype.setModificationDate = function (modificationDate) { + assertIs(modificationDate, 'modificationDate', [[Date, 'Date']]); + var key = PDFName.of('ModDate'); + this.getInfoDict().set(key, PDFString.fromDate(modificationDate)); + }; + /** + * Get the number of pages contained in this document. For example: + * ```js + * const totalPages = pdfDoc.getPageCount() + * ``` + * @returns The number of pages in this document. + */ + PDFDocument.prototype.getPageCount = function () { + if (this.pageCount === undefined) + this.pageCount = this.getPages().length; + return this.pageCount; + }; + /** + * Get an array of all the pages contained in this document. The pages are + * stored in the array in the same order that they are rendered in the + * document. For example: + * ```js + * const pages = pdfDoc.getPages() + * pages[0] // The first page of the document + * pages[2] // The third page of the document + * pages[197] // The 198th page of the document + * ``` + * @returns An array of all the pages contained in this document. + */ + PDFDocument.prototype.getPages = function () { + return this.pageCache.access(); + }; + /** + * Get the page rendered at a particular `index` of the document. For example: + * ```js + * pdfDoc.getPage(0) // The first page of the document + * pdfDoc.getPage(2) // The third page of the document + * pdfDoc.getPage(197) // The 198th page of the document + * ``` + * @returns The [[PDFPage]] rendered at the given `index` of the document. + */ + PDFDocument.prototype.getPage = function (index) { + var pages = this.getPages(); + assertRange(index, 'index', 0, pages.length - 1); + return pages[index]; + }; + /** + * Get an array of indices for all the pages contained in this document. The + * array will contain a range of integers from + * `0..pdfDoc.getPageCount() - 1`. For example: + * ```js + * const pdfDoc = await PDFDocument.create() + * pdfDoc.addPage() + * pdfDoc.addPage() + * pdfDoc.addPage() + * + * const indices = pdfDoc.getPageIndices() + * indices // => [0, 1, 2] + * ``` + * @returns An array of indices for all pages contained in this document. + */ + PDFDocument.prototype.getPageIndices = function () { + return range(0, this.getPageCount()); + }; + /** + * Remove the page at a given index from this document. For example: + * ```js + * pdfDoc.removePage(0) // Remove the first page of the document + * pdfDoc.removePage(2) // Remove the third page of the document + * pdfDoc.removePage(197) // Remove the 198th page of the document + * ``` + * Once a page has been removed, it will no longer be rendered at that index + * in the document. + * @param index The index of the page to be removed. + */ + PDFDocument.prototype.removePage = function (index) { + var pageCount = this.getPageCount(); + if (this.pageCount === 0) + throw new RemovePageFromEmptyDocumentError(); + assertRange(index, 'index', 0, pageCount - 1); + this.catalog.removeLeafNode(index); + this.pageCount = pageCount - 1; + }; + /** + * Add a page to the end of this document. This method accepts three + * different value types for the `page` parameter: + * + * | Type | Behavior | + * | ------------------ | ----------------------------------------------------------------------------------- | + * | `undefined` | Create a new page and add it to the end of this document | + * | `[number, number]` | Create a new page with the given dimensions and add it to the end of this document | + * | `PDFPage` | Add the existing page to the end of this document | + * + * For example: + * ```js + * // page=undefined + * const newPage = pdfDoc.addPage() + * + * // page=[number, number] + * import { PageSizes } from 'pdf-lib' + * const newPage1 = pdfDoc.addPage(PageSizes.A7) + * const newPage2 = pdfDoc.addPage(PageSizes.Letter) + * const newPage3 = pdfDoc.addPage([500, 750]) + * + * // page=PDFPage + * const pdfDoc1 = await PDFDocument.create() + * const pdfDoc2 = await PDFDocument.load(...) + * const [existingPage] = await pdfDoc1.copyPages(pdfDoc2, [0]) + * pdfDoc1.addPage(existingPage) + * ``` + * + * @param page Optionally, the desired dimensions or existing page. + * @returns The newly created (or existing) page. + */ + PDFDocument.prototype.addPage = function (page) { + assertIs(page, 'page', ['undefined', [PDFPage, 'PDFPage'], Array]); + return this.insertPage(this.getPageCount(), page); + }; + /** + * Insert a page at a given index within this document. This method accepts + * three different value types for the `page` parameter: + * + * | Type | Behavior | + * | ------------------ | ------------------------------------------------------------------------------ | + * | `undefined` | Create a new page and insert it into this document | + * | `[number, number]` | Create a new page with the given dimensions and insert it into this document | + * | `PDFPage` | Insert the existing page into this document | + * + * For example: + * ```js + * // page=undefined + * const newPage = pdfDoc.insertPage(2) + * + * // page=[number, number] + * import { PageSizes } from 'pdf-lib' + * const newPage1 = pdfDoc.insertPage(2, PageSizes.A7) + * const newPage2 = pdfDoc.insertPage(0, PageSizes.Letter) + * const newPage3 = pdfDoc.insertPage(198, [500, 750]) + * + * // page=PDFPage + * const pdfDoc1 = await PDFDocument.create() + * const pdfDoc2 = await PDFDocument.load(...) + * const [existingPage] = await pdfDoc1.copyPages(pdfDoc2, [0]) + * pdfDoc1.insertPage(0, existingPage) + * ``` + * + * @param index The index at which the page should be inserted (zero-based). + * @param page Optionally, the desired dimensions or existing page. + * @returns The newly created (or existing) page. + */ + PDFDocument.prototype.insertPage = function (index, page) { + var pageCount = this.getPageCount(); + assertRange(index, 'index', 0, pageCount); + assertIs(page, 'page', ['undefined', [PDFPage, 'PDFPage'], Array]); + if (!page || Array.isArray(page)) { + var dims = Array.isArray(page) ? page : PageSizes.A4; + page = PDFPage.create(this); + page.setSize.apply(page, dims); + } + else if (page.doc !== this) { + throw new ForeignPageError(); + } + var parentRef = this.catalog.insertLeafNode(page.ref, index); + page.node.setParent(parentRef); + this.pageMap.set(page.node, page); + this.pageCache.invalidate(); + this.pageCount = pageCount + 1; + return page; + }; + /** + * Copy pages from a source document into this document. Allows pages to be + * copied between different [[PDFDocument]] instances. For example: + * ```js + * const pdfDoc = await PDFDocument.create() + * const srcDoc = await PDFDocument.load(...) + * + * const copiedPages = await pdfDoc.copyPages(srcDoc, [0, 3, 89]) + * const [firstPage, fourthPage, ninetiethPage] = copiedPages; + * + * pdfDoc.addPage(fourthPage) + * pdfDoc.insertPage(0, ninetiethPage) + * pdfDoc.addPage(firstPage) + * ``` + * @param srcDoc The document from which pages should be copied. + * @param indices The indices of the pages that should be copied. + * @returns Resolves with an array of pages copied into this document. + */ + PDFDocument.prototype.copyPages = function (srcDoc, indices) { + return __awaiter(this, void 0, void 0, function () { + var copier, srcPages, copiedPages, idx, len, srcPage, copiedPage, ref; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + assertIs(srcDoc, 'srcDoc', [[PDFDocument, 'PDFDocument']]); + assertIs(indices, 'indices', [Array]); + return [4 /*yield*/, srcDoc.flush()]; + case 1: + _a.sent(); + copier = PDFObjectCopier.for(srcDoc.context, this.context); + srcPages = srcDoc.getPages(); + copiedPages = new Array(indices.length); + for (idx = 0, len = indices.length; idx < len; idx++) { + srcPage = srcPages[indices[idx]]; + copiedPage = copier.copy(srcPage.node); + ref = this.context.register(copiedPage); + copiedPages[idx] = PDFPage.of(copiedPage, ref, this); + } + return [2 /*return*/, copiedPages]; + } + }); + }); + }; + /** + * Get a copy of this document. + * + * For example: + * ```js + * const srcDoc = await PDFDocument.load(...) + * const pdfDoc = await srcDoc.copy() + * ``` + * + * > **NOTE:** This method won't copy all information over to the new + * > document (acroforms, outlines, etc...). + * + * @returns Resolves with a copy this document. + */ + PDFDocument.prototype.copy = function () { + return __awaiter(this, void 0, void 0, function () { + var pdfCopy, contentPages, idx, len; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, PDFDocument.create()]; + case 1: + pdfCopy = _a.sent(); + return [4 /*yield*/, pdfCopy.copyPages(this, this.getPageIndices())]; + case 2: + contentPages = _a.sent(); + for (idx = 0, len = contentPages.length; idx < len; idx++) { + pdfCopy.addPage(contentPages[idx]); + } + if (this.getAuthor() !== undefined) { + pdfCopy.setAuthor(this.getAuthor()); + } + if (this.getCreationDate() !== undefined) { + pdfCopy.setCreationDate(this.getCreationDate()); + } + if (this.getCreator() !== undefined) { + pdfCopy.setCreator(this.getCreator()); + } + if (this.getModificationDate() !== undefined) { + pdfCopy.setModificationDate(this.getModificationDate()); + } + if (this.getProducer() !== undefined) { + pdfCopy.setProducer(this.getProducer()); + } + if (this.getSubject() !== undefined) { + pdfCopy.setSubject(this.getSubject()); + } + if (this.getTitle() !== undefined) { + pdfCopy.setTitle(this.getTitle()); + } + pdfCopy.defaultWordBreaks = this.defaultWordBreaks; + return [2 /*return*/, pdfCopy]; + } + }); + }); + }; + /** + * Add JavaScript to this document. The supplied `script` is executed when the + * document is opened. The `script` can be used to perform some operation + * when the document is opened (e.g. logging to the console), or it can be + * used to define a function that can be referenced later in a JavaScript + * action. For example: + * ```js + * // Show "Hello World!" in the console when the PDF is opened + * pdfDoc.addJavaScript( + * 'main', + * 'console.show(); console.println("Hello World!");' + * ); + * + * // Define a function named "foo" that can be called in JavaScript Actions + * pdfDoc.addJavaScript( + * 'foo', + * 'function foo() { return "foo"; }' + * ); + * ``` + * See the [JavaScript for Acrobat API Reference](https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/js_api_reference.pdf) + * for details. + * @param name The name of the script. Must be unique per document. + * @param script The JavaScript to execute. + */ + PDFDocument.prototype.addJavaScript = function (name, script) { + assertIs(name, 'name', ['string']); + assertIs(script, 'script', ['string']); + var embedder = JavaScriptEmbedder.for(script, name); + var ref = this.context.nextRef(); + var javaScript = PDFJavaScript.of(ref, this, embedder); + this.javaScripts.push(javaScript); + }; + /** + * Add an attachment to this document. Attachments are visible in the + * "Attachments" panel of Adobe Acrobat and some other PDF readers. Any + * type of file can be added as an attachment. This includes, but is not + * limited to, `.png`, `.jpg`, `.pdf`, `.csv`, `.docx`, and `.xlsx` files. + * + * The input data can be provided in multiple formats: + * + * | Type | Contents | + * | ------------- | -------------------------------------------------------------- | + * | `string` | A base64 encoded string (or data URI) containing an attachment | + * | `Uint8Array` | The raw bytes of an attachment | + * | `ArrayBuffer` | The raw bytes of an attachment | + * + * For example: + * ```js + * // attachment=string + * await pdfDoc.attach('/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD...', 'cat_riding_unicorn.jpg', { + * mimeType: 'image/jpeg', + * description: 'Cool cat riding a unicorn! 🦄🐈🕶️', + * creationDate: new Date('2019/12/01'), + * modificationDate: new Date('2020/04/19'), + * }) + * await pdfDoc.attach('data:image/jpeg;base64,/9j/4AAQ...', 'cat_riding_unicorn.jpg', { + * mimeType: 'image/jpeg', + * description: 'Cool cat riding a unicorn! 🦄🐈🕶️', + * creationDate: new Date('2019/12/01'), + * modificationDate: new Date('2020/04/19'), + * }) + * + * // attachment=Uint8Array + * import fs from 'fs' + * const uint8Array = fs.readFileSync('cat_riding_unicorn.jpg') + * await pdfDoc.attach(uint8Array, 'cat_riding_unicorn.jpg', { + * mimeType: 'image/jpeg', + * description: 'Cool cat riding a unicorn! 🦄🐈🕶️', + * creationDate: new Date('2019/12/01'), + * modificationDate: new Date('2020/04/19'), + * }) + * + * // attachment=ArrayBuffer + * const url = 'https://pdf-lib.js.org/assets/cat_riding_unicorn.jpg' + * const arrayBuffer = await fetch(url).then(res => res.arrayBuffer()) + * await pdfDoc.attach(arrayBuffer, 'cat_riding_unicorn.jpg', { + * mimeType: 'image/jpeg', + * description: 'Cool cat riding a unicorn! 🦄🐈🕶️', + * creationDate: new Date('2019/12/01'), + * modificationDate: new Date('2020/04/19'), + * }) + * ``` + * + * @param attachment The input data containing the file to be attached. + * @param name The name of the file to be attached. + * @returns Resolves when the attachment is complete. + */ + PDFDocument.prototype.attach = function (attachment, name, options) { + if (options === void 0) { options = {}; } + return __awaiter(this, void 0, void 0, function () { + var bytes, embedder, ref, embeddedFile; + return __generator(this, function (_a) { + assertIs(attachment, 'attachment', ['string', Uint8Array, ArrayBuffer]); + assertIs(name, 'name', ['string']); + assertOrUndefined(options.mimeType, 'mimeType', ['string']); + assertOrUndefined(options.description, 'description', ['string']); + assertOrUndefined(options.creationDate, 'options.creationDate', [Date]); + assertOrUndefined(options.modificationDate, 'options.modificationDate', [ + Date, + ]); + assertIsOneOfOrUndefined(options.afRelationship, 'options.afRelationship', AFRelationship); + bytes = toUint8Array(attachment); + embedder = FileEmbedder.for(bytes, name, options); + ref = this.context.nextRef(); + embeddedFile = PDFEmbeddedFile.of(ref, this, embedder); + this.embeddedFiles.push(embeddedFile); + return [2 /*return*/]; + }); + }); + }; + /** + * Embed a font into this document. The input data can be provided in multiple + * formats: + * + * | Type | Contents | + * | --------------- | ------------------------------------------------------- | + * | `StandardFonts` | One of the standard 14 fonts | + * | `string` | A base64 encoded string (or data URI) containing a font | + * | `Uint8Array` | The raw bytes of a font | + * | `ArrayBuffer` | The raw bytes of a font | + * + * For example: + * ```js + * // font=StandardFonts + * import { StandardFonts } from 'pdf-lib' + * const font1 = await pdfDoc.embedFont(StandardFonts.Helvetica) + * + * // font=string + * const font2 = await pdfDoc.embedFont('AAEAAAAVAQAABABQRFNJRx/upe...') + * const font3 = await pdfDoc.embedFont('data:font/opentype;base64,AAEAAA...') + * + * // font=Uint8Array + * import fs from 'fs' + * const font4 = await pdfDoc.embedFont(fs.readFileSync('Ubuntu-R.ttf')) + * + * // font=ArrayBuffer + * const url = 'https://pdf-lib.js.org/assets/ubuntu/Ubuntu-R.ttf' + * const ubuntuBytes = await fetch(url).then(res => res.arrayBuffer()) + * const font5 = await pdfDoc.embedFont(ubuntuBytes) + * ``` + * See also: [[registerFontkit]] + * @param font The input data for a font. + * @param options The options to be used when embedding the font. + * @returns Resolves with the embedded font. + */ + PDFDocument.prototype.embedFont = function (font, options) { + if (options === void 0) { options = {}; } + return __awaiter(this, void 0, void 0, function () { + var _a, subset, customName, features, embedder, bytes, fontkit, _b, ref, pdfFont; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + _a = options.subset, subset = _a === void 0 ? false : _a, customName = options.customName, features = options.features; + assertIs(font, 'font', ['string', Uint8Array, ArrayBuffer]); + assertIs(subset, 'subset', ['boolean']); + if (!isStandardFont(font)) return [3 /*break*/, 1]; + embedder = StandardFontEmbedder.for(font, customName); + return [3 /*break*/, 7]; + case 1: + if (!canBeConvertedToUint8Array(font)) return [3 /*break*/, 6]; + bytes = toUint8Array(font); + fontkit = this.assertFontkit(); + if (!subset) return [3 /*break*/, 3]; + return [4 /*yield*/, CustomFontSubsetEmbedder.for(fontkit, bytes, customName, features)]; + case 2: + _b = _c.sent(); + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, CustomFontEmbedder.for(fontkit, bytes, customName, features)]; + case 4: + _b = _c.sent(); + _c.label = 5; + case 5: + embedder = _b; + return [3 /*break*/, 7]; + case 6: throw new TypeError('`font` must be one of `StandardFonts | string | Uint8Array | ArrayBuffer`'); + case 7: + ref = this.context.nextRef(); + pdfFont = PDFFont.of(ref, this, embedder); + this.fonts.push(pdfFont); + return [2 /*return*/, pdfFont]; + } + }); + }); + }; + /** + * Embed a standard font into this document. + * For example: + * ```js + * import { StandardFonts } from 'pdf-lib' + * const helveticaFont = pdfDoc.embedFont(StandardFonts.Helvetica) + * ``` + * @param font The standard font to be embedded. + * @param customName The name to be used when embedding the font. + * @returns The embedded font. + */ + PDFDocument.prototype.embedStandardFont = function (font, customName) { + assertIs(font, 'font', ['string']); + if (!isStandardFont(font)) { + throw new TypeError('`font` must be one of type `StandardFonts`'); + } + var embedder = StandardFontEmbedder.for(font, customName); + var ref = this.context.nextRef(); + var pdfFont = PDFFont.of(ref, this, embedder); + this.fonts.push(pdfFont); + return pdfFont; + }; + /** + * Embed a JPEG image into this document. The input data can be provided in + * multiple formats: + * + * | Type | Contents | + * | ------------- | ------------------------------------------------------------- | + * | `string` | A base64 encoded string (or data URI) containing a JPEG image | + * | `Uint8Array` | The raw bytes of a JPEG image | + * | `ArrayBuffer` | The raw bytes of a JPEG image | + * + * For example: + * ```js + * // jpg=string + * const image1 = await pdfDoc.embedJpg('/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD...') + * const image2 = await pdfDoc.embedJpg('data:image/jpeg;base64,/9j/4AAQ...') + * + * // jpg=Uint8Array + * import fs from 'fs' + * const uint8Array = fs.readFileSync('cat_riding_unicorn.jpg') + * const image3 = await pdfDoc.embedJpg(uint8Array) + * + * // jpg=ArrayBuffer + * const url = 'https://pdf-lib.js.org/assets/cat_riding_unicorn.jpg' + * const arrayBuffer = await fetch(url).then(res => res.arrayBuffer()) + * const image4 = await pdfDoc.embedJpg(arrayBuffer) + * ``` + * + * @param jpg The input data for a JPEG image. + * @returns Resolves with the embedded image. + */ + PDFDocument.prototype.embedJpg = function (jpg) { + return __awaiter(this, void 0, void 0, function () { + var bytes, embedder, ref, pdfImage; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + assertIs(jpg, 'jpg', ['string', Uint8Array, ArrayBuffer]); + bytes = toUint8Array(jpg); + return [4 /*yield*/, JpegEmbedder.for(bytes)]; + case 1: + embedder = _a.sent(); + ref = this.context.nextRef(); + pdfImage = PDFImage.of(ref, this, embedder); + this.images.push(pdfImage); + return [2 /*return*/, pdfImage]; + } + }); + }); + }; + /** + * Embed a PNG image into this document. The input data can be provided in + * multiple formats: + * + * | Type | Contents | + * | ------------- | ------------------------------------------------------------ | + * | `string` | A base64 encoded string (or data URI) containing a PNG image | + * | `Uint8Array` | The raw bytes of a PNG image | + * | `ArrayBuffer` | The raw bytes of a PNG image | + * + * For example: + * ```js + * // png=string + * const image1 = await pdfDoc.embedPng('iVBORw0KGgoAAAANSUhEUgAAAlgAAAF3...') + * const image2 = await pdfDoc.embedPng('data:image/png;base64,iVBORw0KGg...') + * + * // png=Uint8Array + * import fs from 'fs' + * const uint8Array = fs.readFileSync('small_mario.png') + * const image3 = await pdfDoc.embedPng(uint8Array) + * + * // png=ArrayBuffer + * const url = 'https://pdf-lib.js.org/assets/small_mario.png' + * const arrayBuffer = await fetch(url).then(res => res.arrayBuffer()) + * const image4 = await pdfDoc.embedPng(arrayBuffer) + * ``` + * + * @param png The input data for a PNG image. + * @returns Resolves with the embedded image. + */ + PDFDocument.prototype.embedPng = function (png) { + return __awaiter(this, void 0, void 0, function () { + var bytes, embedder, ref, pdfImage; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + assertIs(png, 'png', ['string', Uint8Array, ArrayBuffer]); + bytes = toUint8Array(png); + return [4 /*yield*/, PngEmbedder.for(bytes)]; + case 1: + embedder = _a.sent(); + ref = this.context.nextRef(); + pdfImage = PDFImage.of(ref, this, embedder); + this.images.push(pdfImage); + return [2 /*return*/, pdfImage]; + } + }); + }); + }; + /** + * Embed one or more PDF pages into this document. + * + * For example: + * ```js + * const pdfDoc = await PDFDocument.create() + * + * const sourcePdfUrl = 'https://pdf-lib.js.org/assets/with_large_page_count.pdf' + * const sourcePdf = await fetch(sourcePdfUrl).then((res) => res.arrayBuffer()) + * + * // Embed page 74 of `sourcePdf` into `pdfDoc` + * const [embeddedPage] = await pdfDoc.embedPdf(sourcePdf, [73]) + * ``` + * + * See [[PDFDocument.load]] for examples of the allowed input data formats. + * + * @param pdf The input data containing a PDF document. + * @param indices The indices of the pages that should be embedded. + * @returns Resolves with an array of the embedded pages. + */ + PDFDocument.prototype.embedPdf = function (pdf, indices) { + if (indices === void 0) { indices = [0]; } + return __awaiter(this, void 0, void 0, function () { + var srcDoc, _a, srcPages; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + assertIs(pdf, 'pdf', [ + 'string', + Uint8Array, + ArrayBuffer, + [PDFDocument, 'PDFDocument'], + ]); + assertIs(indices, 'indices', [Array]); + if (!(pdf instanceof PDFDocument)) return [3 /*break*/, 1]; + _a = pdf; + return [3 /*break*/, 3]; + case 1: return [4 /*yield*/, PDFDocument.load(pdf)]; + case 2: + _a = _b.sent(); + _b.label = 3; + case 3: + srcDoc = _a; + srcPages = pluckIndices(srcDoc.getPages(), indices); + return [2 /*return*/, this.embedPages(srcPages)]; + } + }); + }); + }; + /** + * Embed a single PDF page into this document. + * + * For example: + * ```js + * const pdfDoc = await PDFDocument.create() + * + * const sourcePdfUrl = 'https://pdf-lib.js.org/assets/with_large_page_count.pdf' + * const sourceBuffer = await fetch(sourcePdfUrl).then((res) => res.arrayBuffer()) + * const sourcePdfDoc = await PDFDocument.load(sourceBuffer) + * const sourcePdfPage = sourcePdfDoc.getPages()[73] + * + * const embeddedPage = await pdfDoc.embedPage( + * sourcePdfPage, + * + * // Clip a section of the source page so that we only embed part of it + * { left: 100, right: 450, bottom: 330, top: 570 }, + * + * // Translate all drawings of the embedded page by (10, 200) units + * [1, 0, 0, 1, 10, 200], + * ) + * ``` + * + * @param page The page to be embedded. + * @param boundingBox + * Optionally, an area of the source page that should be embedded + * (defaults to entire page). + * @param transformationMatrix + * Optionally, a transformation matrix that is always applied to the embedded + * page anywhere it is drawn. + * @returns Resolves with the embedded pdf page. + */ + PDFDocument.prototype.embedPage = function (page, boundingBox, transformationMatrix) { + return __awaiter(this, void 0, void 0, function () { + var embeddedPage; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + assertIs(page, 'page', [[PDFPage, 'PDFPage']]); + return [4 /*yield*/, this.embedPages([page], [boundingBox], [transformationMatrix])]; + case 1: + embeddedPage = (_a.sent())[0]; + return [2 /*return*/, embeddedPage]; + } + }); + }); + }; + /** + * Embed one or more PDF pages into this document. + * + * For example: + * ```js + * const pdfDoc = await PDFDocument.create() + * + * const sourcePdfUrl = 'https://pdf-lib.js.org/assets/with_large_page_count.pdf' + * const sourceBuffer = await fetch(sourcePdfUrl).then((res) => res.arrayBuffer()) + * const sourcePdfDoc = await PDFDocument.load(sourceBuffer) + * + * const page1 = sourcePdfDoc.getPages()[0] + * const page2 = sourcePdfDoc.getPages()[52] + * const page3 = sourcePdfDoc.getPages()[73] + * + * const embeddedPages = await pdfDoc.embedPages([page1, page2, page3]) + * ``` + * + * @param page + * The pages to be embedded (they must all share the same context). + * @param boundingBoxes + * Optionally, an array of clipping boundaries - one for each page + * (defaults to entirety of each page). + * @param transformationMatrices + * Optionally, an array of transformation matrices - one for each page + * (each page's transformation will apply anywhere it is drawn). + * @returns Resolves with an array of the embedded pdf pages. + */ + PDFDocument.prototype.embedPages = function (pages, boundingBoxes, transformationMatrices) { + if (boundingBoxes === void 0) { boundingBoxes = []; } + if (transformationMatrices === void 0) { transformationMatrices = []; } + return __awaiter(this, void 0, void 0, function () { + var idx, len, currPage, nextPage, context, maybeCopyPage, embeddedPages, idx, len, page, box, matrix, embedder, ref; + var _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (pages.length === 0) + return [2 /*return*/, []]; + // Assert all pages have the same context + for (idx = 0, len = pages.length - 1; idx < len; idx++) { + currPage = pages[idx]; + nextPage = pages[idx + 1]; + if (currPage.node.context !== nextPage.node.context) { + throw new PageEmbeddingMismatchedContextError(); + } + } + context = pages[0].node.context; + maybeCopyPage = context === this.context + ? function (p) { return p; } + : PDFObjectCopier.for(context, this.context).copy; + embeddedPages = new Array(pages.length); + idx = 0, len = pages.length; + _b.label = 1; + case 1: + if (!(idx < len)) return [3 /*break*/, 4]; + page = maybeCopyPage(pages[idx].node); + box = boundingBoxes[idx]; + matrix = transformationMatrices[idx]; + return [4 /*yield*/, PDFPageEmbedder.for(page, box, matrix)]; + case 2: + embedder = _b.sent(); + ref = this.context.nextRef(); + embeddedPages[idx] = PDFEmbeddedPage.of(ref, this, embedder); + _b.label = 3; + case 3: + idx++; + return [3 /*break*/, 1]; + case 4: + (_a = this.embeddedPages).push.apply(_a, embeddedPages); + return [2 /*return*/, embeddedPages]; + } + }); + }); + }; + /** + * > **NOTE:** You shouldn't need to call this method directly. The [[save]] + * > and [[saveAsBase64]] methods will automatically ensure that all embedded + * > assets are flushed before serializing the document. + * + * Flush all embedded fonts, PDF pages, and images to this document's + * [[context]]. + * + * @returns Resolves when the flush is complete. + */ + PDFDocument.prototype.flush = function () { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.embedAll(this.fonts)]; + case 1: + _a.sent(); + return [4 /*yield*/, this.embedAll(this.images)]; + case 2: + _a.sent(); + return [4 /*yield*/, this.embedAll(this.embeddedPages)]; + case 3: + _a.sent(); + return [4 /*yield*/, this.embedAll(this.embeddedFiles)]; + case 4: + _a.sent(); + return [4 /*yield*/, this.embedAll(this.javaScripts)]; + case 5: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }; + /** + * Serialize this document to an array of bytes making up a PDF file. + * For example: + * ```js + * const pdfBytes = await pdfDoc.save() + * ``` + * + * There are a number of things you can do with the serialized document, + * depending on the JavaScript environment you're running in: + * * Write it to a file in Node or React Native + * * Download it as a Blob in the browser + * * Render it in an `iframe` + * + * @param options The options to be used when saving the document. + * @returns Resolves with the bytes of the serialized document. + */ + PDFDocument.prototype.save = function (options) { + if (options === void 0) { options = {}; } + return __awaiter(this, void 0, void 0, function () { + var _a, useObjectStreams, _b, addDefaultPage, _c, objectsPerTick, _d, updateFieldAppearances, form, Writer; + return __generator(this, function (_e) { + switch (_e.label) { + case 0: + _a = options.useObjectStreams, useObjectStreams = _a === void 0 ? true : _a, _b = options.addDefaultPage, addDefaultPage = _b === void 0 ? true : _b, _c = options.objectsPerTick, objectsPerTick = _c === void 0 ? 50 : _c, _d = options.updateFieldAppearances, updateFieldAppearances = _d === void 0 ? true : _d; + assertIs(useObjectStreams, 'useObjectStreams', ['boolean']); + assertIs(addDefaultPage, 'addDefaultPage', ['boolean']); + assertIs(objectsPerTick, 'objectsPerTick', ['number']); + assertIs(updateFieldAppearances, 'updateFieldAppearances', ['boolean']); + if (addDefaultPage && this.getPageCount() === 0) + this.addPage(); + if (updateFieldAppearances) { + form = this.formCache.getValue(); + if (form) + form.updateFieldAppearances(); + } + return [4 /*yield*/, this.flush()]; + case 1: + _e.sent(); + Writer = useObjectStreams ? PDFStreamWriter : PDFWriter; + return [2 /*return*/, Writer.forContext(this.context, objectsPerTick).serializeToBuffer()]; + } + }); + }); + }; + /** + * Serialize this document to a base64 encoded string or data URI making up a + * PDF file. For example: + * ```js + * const base64String = await pdfDoc.saveAsBase64() + * base64String // => 'JVBERi0xLjcKJYGBgYEKC...' + * + * const base64DataUri = await pdfDoc.saveAsBase64({ dataUri: true }) + * base64DataUri // => 'data:application/pdf;base64,JVBERi0xLjcKJYGBgYEKC...' + * ``` + * + * @param options The options to be used when saving the document. + * @returns Resolves with a base64 encoded string or data URI of the + * serialized document. + */ + PDFDocument.prototype.saveAsBase64 = function (options) { + if (options === void 0) { options = {}; } + return __awaiter(this, void 0, void 0, function () { + var _a, dataUri, otherOptions, bytes, base64; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = options.dataUri, dataUri = _a === void 0 ? false : _a, otherOptions = __rest(options, ["dataUri"]); + assertIs(dataUri, 'dataUri', ['boolean']); + return [4 /*yield*/, this.save(otherOptions)]; + case 1: + bytes = _b.sent(); + base64 = encodeToBase64(bytes); + return [2 /*return*/, dataUri ? "data:application/pdf;base64," + base64 : base64]; + } + }); + }); + }; + PDFDocument.prototype.findPageForAnnotationRef = function (ref) { + var pages = this.getPages(); + for (var idx = 0, len = pages.length; idx < len; idx++) { + var page = pages[idx]; + var annotations = page.node.Annots(); + if ((annotations === null || annotations === void 0 ? void 0 : annotations.indexOf(ref)) !== undefined) { + return page; + } + } + return undefined; + }; + PDFDocument.prototype.embedAll = function (embeddables) { + return __awaiter(this, void 0, void 0, function () { + var idx, len; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + idx = 0, len = embeddables.length; + _a.label = 1; + case 1: + if (!(idx < len)) return [3 /*break*/, 4]; + return [4 /*yield*/, embeddables[idx].embed()]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + idx++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + }); + }; + PDFDocument.prototype.updateInfoDict = function () { + var pdfLib = "pdf-lib (https://github.com/Hopding/pdf-lib)"; + var now = new Date(); + var info = this.getInfoDict(); + this.setProducer(pdfLib); + this.setModificationDate(now); + if (!info.get(PDFName.of('Creator'))) + this.setCreator(pdfLib); + if (!info.get(PDFName.of('CreationDate'))) + this.setCreationDate(now); + }; + PDFDocument.prototype.getInfoDict = function () { + var existingInfo = this.context.lookup(this.context.trailerInfo.Info); + if (existingInfo instanceof PDFDict) + return existingInfo; + var newInfo = this.context.obj({}); + this.context.trailerInfo.Info = this.context.register(newInfo); + return newInfo; + }; + PDFDocument.prototype.assertFontkit = function () { + if (!this.fontkit) + throw new FontkitNotRegisteredError(); + return this.fontkit; + }; + return PDFDocument; +}()); +/* tslint:disable-next-line only-arrow-functions */ +function assertIsLiteralOrHexString(pdfObject) { + if (!(pdfObject instanceof PDFHexString) && + !(pdfObject instanceof PDFString)) { + throw new UnexpectedObjectTypeError([PDFHexString, PDFString], pdfObject); + } +} + +var BlendMode; +(function (BlendMode) { + BlendMode["Normal"] = "Normal"; + BlendMode["Multiply"] = "Multiply"; + BlendMode["Screen"] = "Screen"; + BlendMode["Overlay"] = "Overlay"; + BlendMode["Darken"] = "Darken"; + BlendMode["Lighten"] = "Lighten"; + BlendMode["ColorDodge"] = "ColorDodge"; + BlendMode["ColorBurn"] = "ColorBurn"; + BlendMode["HardLight"] = "HardLight"; + BlendMode["SoftLight"] = "SoftLight"; + BlendMode["Difference"] = "Difference"; + BlendMode["Exclusion"] = "Exclusion"; +})(BlendMode || (BlendMode = {})); + +/** + * Represents a single page of a [[PDFDocument]]. + */ +var PDFPage = /** @class */ (function () { + function PDFPage(leafNode, ref, doc) { + this.fontSize = 24; + this.fontColor = rgb(0, 0, 0); + this.lineHeight = 24; + this.x = 0; + this.y = 0; + assertIs(leafNode, 'leafNode', [[PDFPageLeaf, 'PDFPageLeaf']]); + assertIs(ref, 'ref', [[PDFRef, 'PDFRef']]); + assertIs(doc, 'doc', [[PDFDocument, 'PDFDocument']]); + this.node = leafNode; + this.ref = ref; + this.doc = doc; + } + /** + * Rotate this page by a multiple of 90 degrees. For example: + * ```js + * import { degrees } from 'pdf-lib' + * + * page.setRotation(degrees(-90)) + * page.setRotation(degrees(0)) + * page.setRotation(degrees(90)) + * page.setRotation(degrees(180)) + * page.setRotation(degrees(270)) + * ``` + * @param angle The angle to rotate this page. + */ + PDFPage.prototype.setRotation = function (angle) { + var degreesAngle = toDegrees(angle); + assertMultiple(degreesAngle, 'degreesAngle', 90); + this.node.set(PDFName.of('Rotate'), this.doc.context.obj(degreesAngle)); + }; + /** + * Get this page's rotation angle in degrees. For example: + * ```js + * const rotationAngle = page.getRotation().angle; + * ``` + * @returns The rotation angle of the page in degrees (always a multiple of + * 90 degrees). + */ + PDFPage.prototype.getRotation = function () { + var Rotate = this.node.Rotate(); + return degrees(Rotate ? Rotate.asNumber() : 0); + }; + /** + * Resize this page by increasing or decreasing its width and height. For + * example: + * ```js + * page.setSize(250, 500) + * page.setSize(page.getWidth() + 50, page.getHeight() + 100) + * page.setSize(page.getWidth() - 50, page.getHeight() - 100) + * ``` + * + * Note that the PDF specification does not allow for pages to have explicit + * widths and heights. Instead it defines the "size" of a page in terms of + * five rectangles: the MediaBox, CropBox, BleedBox, TrimBox, and ArtBox. As a + * result, this method cannot directly change the width and height of a page. + * Instead, it works by adjusting these five boxes. + * + * This method performs the following steps: + * 1. Set width & height of MediaBox. + * 2. Set width & height of CropBox, if it has same dimensions as MediaBox. + * 3. Set width & height of BleedBox, if it has same dimensions as MediaBox. + * 4. Set width & height of TrimBox, if it has same dimensions as MediaBox. + * 5. Set width & height of ArtBox, if it has same dimensions as MediaBox. + * + * This approach works well for most PDF documents as all PDF pages must + * have a MediaBox, but relatively few have a CropBox, BleedBox, TrimBox, or + * ArtBox. And when they do have these additional boxes, they often have the + * same dimensions as the MediaBox. However, if you find this method does not + * work for your document, consider setting the boxes directly: + * * [[PDFPage.setMediaBox]] + * * [[PDFPage.setCropBox]] + * * [[PDFPage.setBleedBox]] + * * [[PDFPage.setTrimBox]] + * * [[PDFPage.setArtBox]] + * + * @param width The new width of the page. + * @param height The new height of the page. + */ + PDFPage.prototype.setSize = function (width, height) { + assertIs(width, 'width', ['number']); + assertIs(height, 'height', ['number']); + var mediaBox = this.getMediaBox(); + this.setMediaBox(mediaBox.x, mediaBox.y, width, height); + var cropBox = this.getCropBox(); + var bleedBox = this.getBleedBox(); + var trimBox = this.getTrimBox(); + var artBox = this.getArtBox(); + var hasCropBox = this.node.CropBox(); + var hasBleedBox = this.node.BleedBox(); + var hasTrimBox = this.node.TrimBox(); + var hasArtBox = this.node.ArtBox(); + if (hasCropBox && rectanglesAreEqual(cropBox, mediaBox)) { + this.setCropBox(mediaBox.x, mediaBox.y, width, height); + } + if (hasBleedBox && rectanglesAreEqual(bleedBox, mediaBox)) { + this.setBleedBox(mediaBox.x, mediaBox.y, width, height); + } + if (hasTrimBox && rectanglesAreEqual(trimBox, mediaBox)) { + this.setTrimBox(mediaBox.x, mediaBox.y, width, height); + } + if (hasArtBox && rectanglesAreEqual(artBox, mediaBox)) { + this.setArtBox(mediaBox.x, mediaBox.y, width, height); + } + }; + /** + * Resize this page by increasing or decreasing its width. For example: + * ```js + * page.setWidth(250) + * page.setWidth(page.getWidth() + 50) + * page.setWidth(page.getWidth() - 50) + * ``` + * + * This method uses [[PDFPage.setSize]] to set the page's width. + * + * @param width The new width of the page. + */ + PDFPage.prototype.setWidth = function (width) { + assertIs(width, 'width', ['number']); + this.setSize(width, this.getSize().height); + }; + /** + * Resize this page by increasing or decreasing its height. For example: + * ```js + * page.setHeight(500) + * page.setHeight(page.getWidth() + 100) + * page.setHeight(page.getWidth() - 100) + * ``` + * + * This method uses [[PDFPage.setSize]] to set the page's height. + * + * @param height The new height of the page. + */ + PDFPage.prototype.setHeight = function (height) { + assertIs(height, 'height', ['number']); + this.setSize(this.getSize().width, height); + }; + /** + * Set the MediaBox of this page. For example: + * ```js + * const mediaBox = page.getMediaBox() + * + * page.setMediaBox(0, 0, 250, 500) + * page.setMediaBox(mediaBox.x, mediaBox.y, 50, 100) + * page.setMediaBox(15, 5, mediaBox.width - 50, mediaBox.height - 100) + * ``` + * + * See [[PDFPage.getMediaBox]] for details about what the MediaBox represents. + * + * @param x The x coordinate of the lower left corner of the new MediaBox. + * @param y The y coordinate of the lower left corner of the new MediaBox. + * @param width The width of the new MediaBox. + * @param height The height of the new MediaBox. + */ + PDFPage.prototype.setMediaBox = function (x, y, width, height) { + assertIs(x, 'x', ['number']); + assertIs(y, 'y', ['number']); + assertIs(width, 'width', ['number']); + assertIs(height, 'height', ['number']); + var mediaBox = this.doc.context.obj([x, y, x + width, y + height]); + this.node.set(PDFName.MediaBox, mediaBox); + }; + /** + * Set the CropBox of this page. For example: + * ```js + * const cropBox = page.getCropBox() + * + * page.setCropBox(0, 0, 250, 500) + * page.setCropBox(cropBox.x, cropBox.y, 50, 100) + * page.setCropBox(15, 5, cropBox.width - 50, cropBox.height - 100) + * ``` + * + * See [[PDFPage.getCropBox]] for details about what the CropBox represents. + * + * @param x The x coordinate of the lower left corner of the new CropBox. + * @param y The y coordinate of the lower left corner of the new CropBox. + * @param width The width of the new CropBox. + * @param height The height of the new CropBox. + */ + PDFPage.prototype.setCropBox = function (x, y, width, height) { + assertIs(x, 'x', ['number']); + assertIs(y, 'y', ['number']); + assertIs(width, 'width', ['number']); + assertIs(height, 'height', ['number']); + var cropBox = this.doc.context.obj([x, y, x + width, y + height]); + this.node.set(PDFName.CropBox, cropBox); + }; + /** + * Set the BleedBox of this page. For example: + * ```js + * const bleedBox = page.getBleedBox() + * + * page.setBleedBox(0, 0, 250, 500) + * page.setBleedBox(bleedBox.x, bleedBox.y, 50, 100) + * page.setBleedBox(15, 5, bleedBox.width - 50, bleedBox.height - 100) + * ``` + * + * See [[PDFPage.getBleedBox]] for details about what the BleedBox represents. + * + * @param x The x coordinate of the lower left corner of the new BleedBox. + * @param y The y coordinate of the lower left corner of the new BleedBox. + * @param width The width of the new BleedBox. + * @param height The height of the new BleedBox. + */ + PDFPage.prototype.setBleedBox = function (x, y, width, height) { + assertIs(x, 'x', ['number']); + assertIs(y, 'y', ['number']); + assertIs(width, 'width', ['number']); + assertIs(height, 'height', ['number']); + var bleedBox = this.doc.context.obj([x, y, x + width, y + height]); + this.node.set(PDFName.BleedBox, bleedBox); + }; + /** + * Set the TrimBox of this page. For example: + * ```js + * const trimBox = page.getTrimBox() + * + * page.setTrimBox(0, 0, 250, 500) + * page.setTrimBox(trimBox.x, trimBox.y, 50, 100) + * page.setTrimBox(15, 5, trimBox.width - 50, trimBox.height - 100) + * ``` + * + * See [[PDFPage.getTrimBox]] for details about what the TrimBox represents. + * + * @param x The x coordinate of the lower left corner of the new TrimBox. + * @param y The y coordinate of the lower left corner of the new TrimBox. + * @param width The width of the new TrimBox. + * @param height The height of the new TrimBox. + */ + PDFPage.prototype.setTrimBox = function (x, y, width, height) { + assertIs(x, 'x', ['number']); + assertIs(y, 'y', ['number']); + assertIs(width, 'width', ['number']); + assertIs(height, 'height', ['number']); + var trimBox = this.doc.context.obj([x, y, x + width, y + height]); + this.node.set(PDFName.TrimBox, trimBox); + }; + /** + * Set the ArtBox of this page. For example: + * ```js + * const artBox = page.getArtBox() + * + * page.setArtBox(0, 0, 250, 500) + * page.setArtBox(artBox.x, artBox.y, 50, 100) + * page.setArtBox(15, 5, artBox.width - 50, artBox.height - 100) + * ``` + * + * See [[PDFPage.getArtBox]] for details about what the ArtBox represents. + * + * @param x The x coordinate of the lower left corner of the new ArtBox. + * @param y The y coordinate of the lower left corner of the new ArtBox. + * @param width The width of the new ArtBox. + * @param height The height of the new ArtBox. + */ + PDFPage.prototype.setArtBox = function (x, y, width, height) { + assertIs(x, 'x', ['number']); + assertIs(y, 'y', ['number']); + assertIs(width, 'width', ['number']); + assertIs(height, 'height', ['number']); + var artBox = this.doc.context.obj([x, y, x + width, y + height]); + this.node.set(PDFName.ArtBox, artBox); + }; + /** + * Get this page's width and height. For example: + * ```js + * const { width, height } = page.getSize() + * ``` + * + * This method uses [[PDFPage.getMediaBox]] to obtain the page's + * width and height. + * + * @returns The width and height of the page. + */ + PDFPage.prototype.getSize = function () { + var _a = this.getMediaBox(), width = _a.width, height = _a.height; + return { width: width, height: height }; + }; + /** + * Get this page's width. For example: + * ```js + * const width = page.getWidth() + * ``` + * + * This method uses [[PDFPage.getSize]] to obtain the page's size. + * + * @returns The width of the page. + */ + PDFPage.prototype.getWidth = function () { + return this.getSize().width; + }; + /** + * Get this page's height. For example: + * ```js + * const height = page.getHeight() + * ``` + * + * This method uses [[PDFPage.getSize]] to obtain the page's size. + * + * @returns The height of the page. + */ + PDFPage.prototype.getHeight = function () { + return this.getSize().height; + }; + /** + * Get the rectangle defining this page's MediaBox. For example: + * ```js + * const { x, y, width, height } = page.getMediaBox() + * ``` + * + * The MediaBox of a page defines the boundaries of the physical medium on + * which the page is to be displayed/printed. It may include extended area + * surrounding the page content for bleed marks, printing marks, etc... + * It may also include areas close to the edges of the medium that cannot be + * marked because of physical limitations of the output device. Content + * falling outside this boundary may safely be discarded without affecting + * the meaning of the PDF file. + * + * @returns An object defining the lower left corner of the MediaBox and its + * width & height. + */ + PDFPage.prototype.getMediaBox = function () { + var mediaBox = this.node.MediaBox(); + return mediaBox.asRectangle(); + }; + /** + * Get the rectangle defining this page's CropBox. For example: + * ```js + * const { x, y, width, height } = page.getCropBox() + * ``` + * + * The CropBox of a page defines the region to which the contents of the page + * shall be clipped when displayed or printed. Unlike the other boxes, the + * CropBox does not necessarily represent the physical page geometry. It + * merely imposes clipping on the page contents. + * + * The CropBox's default value is the page's MediaBox. + * + * @returns An object defining the lower left corner of the CropBox and its + * width & height. + */ + PDFPage.prototype.getCropBox = function () { + var _a; + var cropBox = this.node.CropBox(); + return (_a = cropBox === null || cropBox === void 0 ? void 0 : cropBox.asRectangle()) !== null && _a !== void 0 ? _a : this.getMediaBox(); + }; + /** + * Get the rectangle defining this page's BleedBox. For example: + * ```js + * const { x, y, width, height } = page.getBleedBox() + * ``` + * + * The BleedBox of a page defines the region to which the contents of the + * page shall be clipped when output in a production environment. This may + * include any extra bleed area needed to accommodate the physical + * limitations of cutting, folding, and trimming equipment. The actual + * printed page may include printing marks that fall outside the BleedBox. + * + * The BleedBox's default value is the page's CropBox. + * + * @returns An object defining the lower left corner of the BleedBox and its + * width & height. + */ + PDFPage.prototype.getBleedBox = function () { + var _a; + var bleedBox = this.node.BleedBox(); + return (_a = bleedBox === null || bleedBox === void 0 ? void 0 : bleedBox.asRectangle()) !== null && _a !== void 0 ? _a : this.getCropBox(); + }; + /** + * Get the rectangle defining this page's TrimBox. For example: + * ```js + * const { x, y, width, height } = page.getTrimBox() + * ``` + * + * The TrimBox of a page defines the intended dimensions of the finished + * page after trimming. It may be smaller than the MediaBox to allow for + * production-related content, such as printing instructions, cut marks, or + * color bars. + * + * The TrimBox's default value is the page's CropBox. + * + * @returns An object defining the lower left corner of the TrimBox and its + * width & height. + */ + PDFPage.prototype.getTrimBox = function () { + var _a; + var trimBox = this.node.TrimBox(); + return (_a = trimBox === null || trimBox === void 0 ? void 0 : trimBox.asRectangle()) !== null && _a !== void 0 ? _a : this.getCropBox(); + }; + /** + * Get the rectangle defining this page's ArtBox. For example: + * ```js + * const { x, y, width, height } = page.getArtBox() + * ``` + * + * The ArtBox of a page defines the extent of the page's meaningful content + * (including potential white space). + * + * The ArtBox's default value is the page's CropBox. + * + * @returns An object defining the lower left corner of the ArtBox and its + * width & height. + */ + PDFPage.prototype.getArtBox = function () { + var _a; + var artBox = this.node.ArtBox(); + return (_a = artBox === null || artBox === void 0 ? void 0 : artBox.asRectangle()) !== null && _a !== void 0 ? _a : this.getCropBox(); + }; + /** + * Translate this page's content to a new location on the page. This operation + * is often useful after resizing the page with [[setSize]]. For example: + * ```js + * // Add 50 units of whitespace to the top and right of the page + * page.setSize(page.getWidth() + 50, page.getHeight() + 50) + * + * // Move the page's content from the lower-left corner of the page + * // to the top-right corner. + * page.translateContent(50, 50) + * + * // Now there are 50 units of whitespace to the left and bottom of the page + * ``` + * See also: [[resetPosition]] + * @param x The new position on the x-axis for this page's content. + * @param y The new position on the y-axis for this page's content. + */ + PDFPage.prototype.translateContent = function (x, y) { + assertIs(x, 'x', ['number']); + assertIs(y, 'y', ['number']); + this.node.normalize(); + this.getContentStream(); + var start = this.createContentStream(pushGraphicsState(), translate(x, y)); + var startRef = this.doc.context.register(start); + var end = this.createContentStream(popGraphicsState()); + var endRef = this.doc.context.register(end); + this.node.wrapContentStreams(startRef, endRef); + }; + /** + * Scale the size, content, and annotations of a page. + * + * For example: + * ```js + * page.scale(0.5, 0.5); + * ``` + * + * @param x The factor by which the width for the page should be scaled + * (e.g. `0.5` is 50%). + * @param y The factor by which the height for the page should be scaled + * (e.g. `2.0` is 200%). + */ + PDFPage.prototype.scale = function (x, y) { + assertIs(x, 'x', ['number']); + assertIs(y, 'y', ['number']); + this.setSize(this.getWidth() * x, this.getHeight() * y); + this.scaleContent(x, y); + this.scaleAnnotations(x, y); + }; + /** + * Scale the content of a page. This is useful after resizing an existing + * page. This scales only the content, not the annotations. + * + * For example: + * ```js + * // Bisect the size of the page + * page.setSize(page.getWidth() / 2, page.getHeight() / 2); + * + * // Scale the content of the page down by 50% in x and y + * page.scaleContent(0.5, 0.5); + * ``` + * See also: [[scaleAnnotations]] + * @param x The factor by which the x-axis for the content should be scaled + * (e.g. `0.5` is 50%). + * @param y The factor by which the y-axis for the content should be scaled + * (e.g. `2.0` is 200%). + */ + PDFPage.prototype.scaleContent = function (x, y) { + assertIs(x, 'x', ['number']); + assertIs(y, 'y', ['number']); + this.node.normalize(); + this.getContentStream(); + var start = this.createContentStream(pushGraphicsState(), scale(x, y)); + var startRef = this.doc.context.register(start); + var end = this.createContentStream(popGraphicsState()); + var endRef = this.doc.context.register(end); + this.node.wrapContentStreams(startRef, endRef); + }; + /** + * Scale the annotations of a page. This is useful if you want to scale a + * page with comments or other annotations. + * ```js + * // Scale the content of the page down by 50% in x and y + * page.scaleContent(0.5, 0.5); + * + * // Scale the content of the page down by 50% in x and y + * page.scaleAnnotations(0.5, 0.5); + * ``` + * See also: [[scaleContent]] + * @param x The factor by which the x-axis for the annotations should be + * scaled (e.g. `0.5` is 50%). + * @param y The factor by which the y-axis for the annotations should be + * scaled (e.g. `2.0` is 200%). + */ + PDFPage.prototype.scaleAnnotations = function (x, y) { + assertIs(x, 'x', ['number']); + assertIs(y, 'y', ['number']); + var annots = this.node.Annots(); + if (!annots) + return; + for (var idx = 0; idx < annots.size(); idx++) { + var annot = annots.lookup(idx); + if (annot instanceof PDFDict) + this.scaleAnnot(annot, x, y); + } + }; + /** + * Reset the x and y coordinates of this page to `(0, 0)`. This operation is + * often useful after calling [[translateContent]]. For example: + * ```js + * // Shift the page's contents up and to the right by 50 units + * page.translateContent(50, 50) + * + * // This text will shifted - it will be drawn at (50, 50) + * page.drawText('I am shifted') + * + * // Move back to (0, 0) + * page.resetPosition() + * + * // This text will not be shifted - it will be drawn at (0, 0) + * page.drawText('I am not shifted') + * ``` + */ + PDFPage.prototype.resetPosition = function () { + this.getContentStream(false); + this.x = 0; + this.y = 0; + }; + /** + * Choose a default font for this page. The default font will be used whenever + * text is drawn on this page and no font is specified. For example: + * ```js + * import { StandardFonts } from 'pdf-lib' + * + * const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman) + * const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica) + * const courierFont = await pdfDoc.embedFont(StandardFonts.Courier) + * + * const page = pdfDoc.addPage() + * + * page.setFont(helveticaFont) + * page.drawText('I will be drawn in Helvetica') + * + * page.setFont(timesRomanFont) + * page.drawText('I will be drawn in Courier', { font: courierFont }) + * ``` + * @param font The default font to be used when drawing text on this page. + */ + PDFPage.prototype.setFont = function (font) { + // TODO: Reuse image Font name if we've already added this image to Resources.Fonts + assertIs(font, 'font', [[PDFFont, 'PDFFont']]); + this.font = font; + this.fontKey = this.node.newFontDictionary(this.font.name, this.font.ref); + }; + /** + * Choose a default font size for this page. The default font size will be + * used whenever text is drawn on this page and no font size is specified. + * For example: + * ```js + * page.setFontSize(12) + * page.drawText('I will be drawn in size 12') + * + * page.setFontSize(36) + * page.drawText('I will be drawn in size 24', { fontSize: 24 }) + * ``` + * @param fontSize The default font size to be used when drawing text on this + * page. + */ + PDFPage.prototype.setFontSize = function (fontSize) { + assertIs(fontSize, 'fontSize', ['number']); + this.fontSize = fontSize; + }; + /** + * Choose a default font color for this page. The default font color will be + * used whenever text is drawn on this page and no font color is specified. + * For example: + * ```js + * import { rgb, cmyk, grayscale } from 'pdf-lib' + * + * page.setFontColor(rgb(0.97, 0.02, 0.97)) + * page.drawText('I will be drawn in pink') + * + * page.setFontColor(cmyk(0.4, 0.7, 0.39, 0.15)) + * page.drawText('I will be drawn in gray', { color: grayscale(0.5) }) + * ``` + * @param fontColor The default font color to be used when drawing text on + * this page. + */ + PDFPage.prototype.setFontColor = function (fontColor) { + assertIs(fontColor, 'fontColor', [[Object, 'Color']]); + this.fontColor = fontColor; + }; + /** + * Choose a default line height for this page. The default line height will be + * used whenever text is drawn on this page and no line height is specified. + * For example: + * ```js + * page.setLineHeight(12); + * page.drawText('These lines will be vertically \n separated by 12 units') + * + * page.setLineHeight(36); + * page.drawText('These lines will be vertically \n separated by 24 units', { + * lineHeight: 24 + * }) + * ``` + * @param lineHeight The default line height to be used when drawing text on + * this page. + */ + PDFPage.prototype.setLineHeight = function (lineHeight) { + assertIs(lineHeight, 'lineHeight', ['number']); + this.lineHeight = lineHeight; + }; + /** + * Get the default position of this page. For example: + * ```js + * const { x, y } = page.getPosition() + * ``` + * @returns The default position of the page. + */ + PDFPage.prototype.getPosition = function () { + return { x: this.x, y: this.y }; + }; + /** + * Get the default x coordinate of this page. For example: + * ```js + * const x = page.getX() + * ``` + * @returns The default x coordinate of the page. + */ + PDFPage.prototype.getX = function () { + return this.x; + }; + /** + * Get the default y coordinate of this page. For example: + * ```js + * const y = page.getY() + * ``` + * @returns The default y coordinate of the page. + */ + PDFPage.prototype.getY = function () { + return this.y; + }; + /** + * Change the default position of this page. For example: + * ```js + * page.moveTo(0, 0) + * page.drawText('I will be drawn at the origin') + * + * page.moveTo(0, 25) + * page.drawText('I will be drawn 25 units up') + * + * page.moveTo(25, 25) + * page.drawText('I will be drawn 25 units up and 25 units to the right') + * ``` + * @param x The new default position on the x-axis for this page. + * @param y The new default position on the y-axis for this page. + */ + PDFPage.prototype.moveTo = function (x, y) { + assertIs(x, 'x', ['number']); + assertIs(y, 'y', ['number']); + this.x = x; + this.y = y; + }; + /** + * Change the default position of this page to be further down the y-axis. + * For example: + * ```js + * page.moveTo(50, 50) + * page.drawText('I will be drawn at (50, 50)') + * + * page.moveDown(10) + * page.drawText('I will be drawn at (50, 40)') + * ``` + * @param yDecrease The amount by which the page's default position along the + * y-axis should be decreased. + */ + PDFPage.prototype.moveDown = function (yDecrease) { + assertIs(yDecrease, 'yDecrease', ['number']); + this.y -= yDecrease; + }; + /** + * Change the default position of this page to be further up the y-axis. + * For example: + * ```js + * page.moveTo(50, 50) + * page.drawText('I will be drawn at (50, 50)') + * + * page.moveUp(10) + * page.drawText('I will be drawn at (50, 60)') + * ``` + * @param yIncrease The amount by which the page's default position along the + * y-axis should be increased. + */ + PDFPage.prototype.moveUp = function (yIncrease) { + assertIs(yIncrease, 'yIncrease', ['number']); + this.y += yIncrease; + }; + /** + * Change the default position of this page to be further left on the x-axis. + * For example: + * ```js + * page.moveTo(50, 50) + * page.drawText('I will be drawn at (50, 50)') + * + * page.moveLeft(10) + * page.drawText('I will be drawn at (40, 50)') + * ``` + * @param xDecrease The amount by which the page's default position along the + * x-axis should be decreased. + */ + PDFPage.prototype.moveLeft = function (xDecrease) { + assertIs(xDecrease, 'xDecrease', ['number']); + this.x -= xDecrease; + }; + /** + * Change the default position of this page to be further right on the y-axis. + * For example: + * ```js + * page.moveTo(50, 50) + * page.drawText('I will be drawn at (50, 50)') + * + * page.moveRight(10) + * page.drawText('I will be drawn at (60, 50)') + * ``` + * @param xIncrease The amount by which the page's default position along the + * x-axis should be increased. + */ + PDFPage.prototype.moveRight = function (xIncrease) { + assertIs(xIncrease, 'xIncrease', ['number']); + this.x += xIncrease; + }; + /** + * Push one or more operators to the end of this page's current content + * stream. For example: + * ```js + * import { + * pushGraphicsState, + * moveTo, + * lineTo, + * closePath, + * setFillingColor, + * rgb, + * fill, + * popGraphicsState, + * } from 'pdf-lib' + * + * // Draw a green triangle in the lower-left corner of the page + * page.pushOperators( + * pushGraphicsState(), + * moveTo(0, 0), + * lineTo(100, 0), + * lineTo(50, 100), + * closePath(), + * setFillingColor(rgb(0.0, 1.0, 0.0)), + * fill(), + * popGraphicsState(), + * ) + * ``` + * @param operator The operators to be pushed. + */ + PDFPage.prototype.pushOperators = function () { + var operator = []; + for (var _i = 0; _i < arguments.length; _i++) { + operator[_i] = arguments[_i]; + } + assertEachIs(operator, 'operator', [[PDFOperator, 'PDFOperator']]); + var contentStream = this.getContentStream(); + contentStream.push.apply(contentStream, operator); + }; + /** + * Draw one or more lines of text on this page. For example: + * ```js + * import { StandardFonts, rgb } from 'pdf-lib' + * + * const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica) + * const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman) + * + * const page = pdfDoc.addPage() + * + * page.setFont(helveticaFont) + * + * page.moveTo(5, 200) + * page.drawText('The Life of an Egg', { size: 36 }) + * + * page.moveDown(36) + * page.drawText('An Epic Tale of Woe', { size: 30 }) + * + * page.drawText( + * `Humpty Dumpty sat on a wall \n` + + * `Humpty Dumpty had a great fall; \n` + + * `All the king's horses and all the king's men \n` + + * `Couldn't put Humpty together again. \n`, + * { + * x: 25, + * y: 100, + * font: timesRomanFont, + * size: 24, + * color: rgb(1, 0, 0), + * lineHeight: 24, + * opacity: 0.75, + * }, + * ) + * ``` + * @param text The text to be drawn. + * @param options The options to be used when drawing the text. + */ + PDFPage.prototype.drawText = function (text, options) { + var _a, _b, _c, _d, _e, _f, _g; + if (options === void 0) { options = {}; } + assertIs(text, 'text', ['string']); + assertOrUndefined(options.color, 'options.color', [[Object, 'Color']]); + assertRangeOrUndefined(options.opacity, 'opacity.opacity', 0, 1); + assertOrUndefined(options.font, 'options.font', [[PDFFont, 'PDFFont']]); + assertOrUndefined(options.size, 'options.size', ['number']); + assertOrUndefined(options.rotate, 'options.rotate', [[Object, 'Rotation']]); + assertOrUndefined(options.xSkew, 'options.xSkew', [[Object, 'Rotation']]); + assertOrUndefined(options.ySkew, 'options.ySkew', [[Object, 'Rotation']]); + assertOrUndefined(options.x, 'options.x', ['number']); + assertOrUndefined(options.y, 'options.y', ['number']); + assertOrUndefined(options.lineHeight, 'options.lineHeight', ['number']); + assertOrUndefined(options.maxWidth, 'options.maxWidth', ['number']); + assertOrUndefined(options.wordBreaks, 'options.wordBreaks', [Array]); + assertIsOneOfOrUndefined(options.blendMode, 'options.blendMode', BlendMode); + var _h = this.setOrEmbedFont(options.font), oldFont = _h.oldFont, newFont = _h.newFont, newFontKey = _h.newFontKey; + var fontSize = options.size || this.fontSize; + var wordBreaks = options.wordBreaks || this.doc.defaultWordBreaks; + var textWidth = function (t) { return newFont.widthOfTextAtSize(t, fontSize); }; + var lines = options.maxWidth === undefined + ? lineSplit(cleanText(text)) + : breakTextIntoLines(text, wordBreaks, options.maxWidth, textWidth); + var encodedLines = new Array(lines.length); + for (var idx = 0, len = lines.length; idx < len; idx++) { + encodedLines[idx] = newFont.encodeText(lines[idx]); + } + var graphicsStateKey = this.maybeEmbedGraphicsState({ + opacity: options.opacity, + blendMode: options.blendMode, + }); + var contentStream = this.getContentStream(); + contentStream.push.apply(contentStream, drawLinesOfText(encodedLines, { + color: (_a = options.color) !== null && _a !== void 0 ? _a : this.fontColor, + font: newFontKey, + size: fontSize, + rotate: (_b = options.rotate) !== null && _b !== void 0 ? _b : degrees(0), + xSkew: (_c = options.xSkew) !== null && _c !== void 0 ? _c : degrees(0), + ySkew: (_d = options.ySkew) !== null && _d !== void 0 ? _d : degrees(0), + x: (_e = options.x) !== null && _e !== void 0 ? _e : this.x, + y: (_f = options.y) !== null && _f !== void 0 ? _f : this.y, + lineHeight: (_g = options.lineHeight) !== null && _g !== void 0 ? _g : this.lineHeight, + graphicsState: graphicsStateKey, + })); + if (options.font) { + if (oldFont) + this.setFont(oldFont); + else + this.resetFont(); + } + }; + /** + * Draw an image on this page. For example: + * ```js + * import { degrees } from 'pdf-lib' + * + * const jpgUrl = 'https://pdf-lib.js.org/assets/cat_riding_unicorn.jpg' + * const jpgImageBytes = await fetch(jpgUrl).then((res) => res.arrayBuffer()) + * + * const jpgImage = await pdfDoc.embedJpg(jpgImageBytes) + * const jpgDims = jpgImage.scale(0.5) + * + * const page = pdfDoc.addPage() + * + * page.drawImage(jpgImage, { + * x: 25, + * y: 25, + * width: jpgDims.width, + * height: jpgDims.height, + * rotate: degrees(30), + * opacity: 0.75, + * }) + * ``` + * @param image The image to be drawn. + * @param options The options to be used when drawing the image. + */ + PDFPage.prototype.drawImage = function (image, options) { + var _a, _b, _c, _d, _e, _f, _g; + if (options === void 0) { options = {}; } + // TODO: Reuse image XObject name if we've already added this image to Resources.XObjects + assertIs(image, 'image', [[PDFImage, 'PDFImage']]); + assertOrUndefined(options.x, 'options.x', ['number']); + assertOrUndefined(options.y, 'options.y', ['number']); + assertOrUndefined(options.width, 'options.width', ['number']); + assertOrUndefined(options.height, 'options.height', ['number']); + assertOrUndefined(options.rotate, 'options.rotate', [[Object, 'Rotation']]); + assertOrUndefined(options.xSkew, 'options.xSkew', [[Object, 'Rotation']]); + assertOrUndefined(options.ySkew, 'options.ySkew', [[Object, 'Rotation']]); + assertRangeOrUndefined(options.opacity, 'opacity.opacity', 0, 1); + assertIsOneOfOrUndefined(options.blendMode, 'options.blendMode', BlendMode); + var xObjectKey = this.node.newXObject('Image', image.ref); + var graphicsStateKey = this.maybeEmbedGraphicsState({ + opacity: options.opacity, + blendMode: options.blendMode, + }); + var contentStream = this.getContentStream(); + contentStream.push.apply(contentStream, drawImage(xObjectKey, { + x: (_a = options.x) !== null && _a !== void 0 ? _a : this.x, + y: (_b = options.y) !== null && _b !== void 0 ? _b : this.y, + width: (_c = options.width) !== null && _c !== void 0 ? _c : image.size().width, + height: (_d = options.height) !== null && _d !== void 0 ? _d : image.size().height, + rotate: (_e = options.rotate) !== null && _e !== void 0 ? _e : degrees(0), + xSkew: (_f = options.xSkew) !== null && _f !== void 0 ? _f : degrees(0), + ySkew: (_g = options.ySkew) !== null && _g !== void 0 ? _g : degrees(0), + graphicsState: graphicsStateKey, + })); + }; + /** + * Draw an embedded PDF page on this page. For example: + * ```js + * import { degrees } from 'pdf-lib' + * + * const pdfDoc = await PDFDocument.create() + * const page = pdfDoc.addPage() + * + * const sourcePdfUrl = 'https://pdf-lib.js.org/assets/with_large_page_count.pdf' + * const sourcePdf = await fetch(sourcePdfUrl).then((res) => res.arrayBuffer()) + * + * // Embed page 74 from the PDF + * const [embeddedPage] = await pdfDoc.embedPdf(sourcePdf, 73) + * + * page.drawPage(embeddedPage, { + * x: 250, + * y: 200, + * xScale: 0.5, + * yScale: 0.5, + * rotate: degrees(30), + * opacity: 0.75, + * }) + * ``` + * + * The `options` argument accepts both `width`/`height` and `xScale`/`yScale` + * as options. Since each of these options defines the size of the drawn page, + * if both options are given, `width` and `height` take precedence and the + * corresponding scale variants are ignored. + * + * @param embeddedPage The embedded page to be drawn. + * @param options The options to be used when drawing the embedded page. + */ + PDFPage.prototype.drawPage = function (embeddedPage, options) { + var _a, _b, _c, _d, _e; + if (options === void 0) { options = {}; } + // TODO: Reuse embeddedPage XObject name if we've already added this embeddedPage to Resources.XObjects + assertIs(embeddedPage, 'embeddedPage', [ + [PDFEmbeddedPage, 'PDFEmbeddedPage'], + ]); + assertOrUndefined(options.x, 'options.x', ['number']); + assertOrUndefined(options.y, 'options.y', ['number']); + assertOrUndefined(options.xScale, 'options.xScale', ['number']); + assertOrUndefined(options.yScale, 'options.yScale', ['number']); + assertOrUndefined(options.width, 'options.width', ['number']); + assertOrUndefined(options.height, 'options.height', ['number']); + assertOrUndefined(options.rotate, 'options.rotate', [[Object, 'Rotation']]); + assertOrUndefined(options.xSkew, 'options.xSkew', [[Object, 'Rotation']]); + assertOrUndefined(options.ySkew, 'options.ySkew', [[Object, 'Rotation']]); + assertRangeOrUndefined(options.opacity, 'opacity.opacity', 0, 1); + assertIsOneOfOrUndefined(options.blendMode, 'options.blendMode', BlendMode); + var xObjectKey = this.node.newXObject('EmbeddedPdfPage', embeddedPage.ref); + var graphicsStateKey = this.maybeEmbedGraphicsState({ + opacity: options.opacity, + blendMode: options.blendMode, + }); + // prettier-ignore + var xScale = (options.width !== undefined ? options.width / embeddedPage.width + : options.xScale !== undefined ? options.xScale + : 1); + // prettier-ignore + var yScale = (options.height !== undefined ? options.height / embeddedPage.height + : options.yScale !== undefined ? options.yScale + : 1); + var contentStream = this.getContentStream(); + contentStream.push.apply(contentStream, drawPage(xObjectKey, { + x: (_a = options.x) !== null && _a !== void 0 ? _a : this.x, + y: (_b = options.y) !== null && _b !== void 0 ? _b : this.y, + xScale: xScale, + yScale: yScale, + rotate: (_c = options.rotate) !== null && _c !== void 0 ? _c : degrees(0), + xSkew: (_d = options.xSkew) !== null && _d !== void 0 ? _d : degrees(0), + ySkew: (_e = options.ySkew) !== null && _e !== void 0 ? _e : degrees(0), + graphicsState: graphicsStateKey, + })); + }; + /** + * Draw an SVG path on this page. For example: + * ```js + * import { rgb } from 'pdf-lib' + * + * const svgPath = 'M 0,20 L 100,160 Q 130,200 150,120 C 190,-40 200,200 300,150 L 400,90' + * + * // Draw path as black line + * page.drawSvgPath(svgPath, { x: 25, y: 75 }) + * + * // Change border style and opacity + * page.drawSvgPath(svgPath, { + * x: 25, + * y: 275, + * borderColor: rgb(0.5, 0.5, 0.5), + * borderWidth: 2, + * borderOpacity: 0.75, + * }) + * + * // Set fill color and opacity + * page.drawSvgPath(svgPath, { + * x: 25, + * y: 475, + * color: rgb(1.0, 0, 0), + * opacity: 0.75, + * }) + * + * // Draw 50% of original size + * page.drawSvgPath(svgPath, { + * x: 25, + * y: 675, + * scale: 0.5, + * }) + * ``` + * @param path The SVG path to be drawn. + * @param options The options to be used when drawing the SVG path. + */ + PDFPage.prototype.drawSvgPath = function (path, options) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (options === void 0) { options = {}; } + assertIs(path, 'path', ['string']); + assertOrUndefined(options.x, 'options.x', ['number']); + assertOrUndefined(options.y, 'options.y', ['number']); + assertOrUndefined(options.scale, 'options.scale', ['number']); + assertOrUndefined(options.rotate, 'options.rotate', [[Object, 'Rotation']]); + assertOrUndefined(options.borderWidth, 'options.borderWidth', ['number']); + assertOrUndefined(options.color, 'options.color', [[Object, 'Color']]); + assertRangeOrUndefined(options.opacity, 'opacity.opacity', 0, 1); + assertOrUndefined(options.borderColor, 'options.borderColor', [ + [Object, 'Color'], + ]); + assertOrUndefined(options.borderDashArray, 'options.borderDashArray', [ + Array, + ]); + assertOrUndefined(options.borderDashPhase, 'options.borderDashPhase', [ + 'number', + ]); + assertIsOneOfOrUndefined(options.borderLineCap, 'options.borderLineCap', LineCapStyle); + assertRangeOrUndefined(options.borderOpacity, 'options.borderOpacity', 0, 1); + assertIsOneOfOrUndefined(options.blendMode, 'options.blendMode', BlendMode); + var graphicsStateKey = this.maybeEmbedGraphicsState({ + opacity: options.opacity, + borderOpacity: options.borderOpacity, + blendMode: options.blendMode, + }); + if (!('color' in options) && !('borderColor' in options)) { + options.borderColor = rgb(0, 0, 0); + } + var contentStream = this.getContentStream(); + contentStream.push.apply(contentStream, drawSvgPath(path, { + x: (_a = options.x) !== null && _a !== void 0 ? _a : this.x, + y: (_b = options.y) !== null && _b !== void 0 ? _b : this.y, + scale: options.scale, + rotate: (_c = options.rotate) !== null && _c !== void 0 ? _c : degrees(0), + color: (_d = options.color) !== null && _d !== void 0 ? _d : undefined, + borderColor: (_e = options.borderColor) !== null && _e !== void 0 ? _e : undefined, + borderWidth: (_f = options.borderWidth) !== null && _f !== void 0 ? _f : 0, + borderDashArray: (_g = options.borderDashArray) !== null && _g !== void 0 ? _g : undefined, + borderDashPhase: (_h = options.borderDashPhase) !== null && _h !== void 0 ? _h : undefined, + borderLineCap: (_j = options.borderLineCap) !== null && _j !== void 0 ? _j : undefined, + graphicsState: graphicsStateKey, + })); + }; + /** + * Draw a line on this page. For example: + * ```js + * import { rgb } from 'pdf-lib' + * + * page.drawLine({ + * start: { x: 25, y: 75 }, + * end: { x: 125, y: 175 }, + * thickness: 2, + * color: rgb(0.75, 0.2, 0.2), + * opacity: 0.75, + * }) + * ``` + * @param options The options to be used when drawing the line. + */ + PDFPage.prototype.drawLine = function (options) { + var _a, _b, _c, _d, _e; + assertIs(options.start, 'options.start', [ + [Object, '{ x: number, y: number }'], + ]); + assertIs(options.end, 'options.end', [ + [Object, '{ x: number, y: number }'], + ]); + assertIs(options.start.x, 'options.start.x', ['number']); + assertIs(options.start.y, 'options.start.y', ['number']); + assertIs(options.end.x, 'options.end.x', ['number']); + assertIs(options.end.y, 'options.end.y', ['number']); + assertOrUndefined(options.thickness, 'options.thickness', ['number']); + assertOrUndefined(options.color, 'options.color', [[Object, 'Color']]); + assertOrUndefined(options.dashArray, 'options.dashArray', [Array]); + assertOrUndefined(options.dashPhase, 'options.dashPhase', ['number']); + assertIsOneOfOrUndefined(options.lineCap, 'options.lineCap', LineCapStyle); + assertRangeOrUndefined(options.opacity, 'opacity.opacity', 0, 1); + assertIsOneOfOrUndefined(options.blendMode, 'options.blendMode', BlendMode); + var graphicsStateKey = this.maybeEmbedGraphicsState({ + borderOpacity: options.opacity, + blendMode: options.blendMode, + }); + if (!('color' in options)) { + options.color = rgb(0, 0, 0); + } + var contentStream = this.getContentStream(); + contentStream.push.apply(contentStream, drawLine({ + start: options.start, + end: options.end, + thickness: (_a = options.thickness) !== null && _a !== void 0 ? _a : 1, + color: (_b = options.color) !== null && _b !== void 0 ? _b : undefined, + dashArray: (_c = options.dashArray) !== null && _c !== void 0 ? _c : undefined, + dashPhase: (_d = options.dashPhase) !== null && _d !== void 0 ? _d : undefined, + lineCap: (_e = options.lineCap) !== null && _e !== void 0 ? _e : undefined, + graphicsState: graphicsStateKey, + })); + }; + /** + * Draw a rectangle on this page. For example: + * ```js + * import { degrees, grayscale, rgb } from 'pdf-lib' + * + * page.drawRectangle({ + * x: 25, + * y: 75, + * width: 250, + * height: 75, + * rotate: degrees(-15), + * borderWidth: 5, + * borderColor: grayscale(0.5), + * color: rgb(0.75, 0.2, 0.2), + * opacity: 0.5, + * borderOpacity: 0.75, + * }) + * ``` + * @param options The options to be used when drawing the rectangle. + */ + PDFPage.prototype.drawRectangle = function (options) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o; + if (options === void 0) { options = {}; } + assertOrUndefined(options.x, 'options.x', ['number']); + assertOrUndefined(options.y, 'options.y', ['number']); + assertOrUndefined(options.width, 'options.width', ['number']); + assertOrUndefined(options.height, 'options.height', ['number']); + assertOrUndefined(options.rotate, 'options.rotate', [[Object, 'Rotation']]); + assertOrUndefined(options.xSkew, 'options.xSkew', [[Object, 'Rotation']]); + assertOrUndefined(options.ySkew, 'options.ySkew', [[Object, 'Rotation']]); + assertOrUndefined(options.borderWidth, 'options.borderWidth', ['number']); + assertOrUndefined(options.color, 'options.color', [[Object, 'Color']]); + assertRangeOrUndefined(options.opacity, 'opacity.opacity', 0, 1); + assertOrUndefined(options.borderColor, 'options.borderColor', [ + [Object, 'Color'], + ]); + assertOrUndefined(options.borderDashArray, 'options.borderDashArray', [ + Array, + ]); + assertOrUndefined(options.borderDashPhase, 'options.borderDashPhase', [ + 'number', + ]); + assertIsOneOfOrUndefined(options.borderLineCap, 'options.borderLineCap', LineCapStyle); + assertRangeOrUndefined(options.borderOpacity, 'options.borderOpacity', 0, 1); + assertIsOneOfOrUndefined(options.blendMode, 'options.blendMode', BlendMode); + var graphicsStateKey = this.maybeEmbedGraphicsState({ + opacity: options.opacity, + borderOpacity: options.borderOpacity, + blendMode: options.blendMode, + }); + if (!('color' in options) && !('borderColor' in options)) { + options.color = rgb(0, 0, 0); + } + var contentStream = this.getContentStream(); + contentStream.push.apply(contentStream, drawRectangle({ + x: (_a = options.x) !== null && _a !== void 0 ? _a : this.x, + y: (_b = options.y) !== null && _b !== void 0 ? _b : this.y, + width: (_c = options.width) !== null && _c !== void 0 ? _c : 150, + height: (_d = options.height) !== null && _d !== void 0 ? _d : 100, + rotate: (_e = options.rotate) !== null && _e !== void 0 ? _e : degrees(0), + xSkew: (_f = options.xSkew) !== null && _f !== void 0 ? _f : degrees(0), + ySkew: (_g = options.ySkew) !== null && _g !== void 0 ? _g : degrees(0), + borderWidth: (_h = options.borderWidth) !== null && _h !== void 0 ? _h : 0, + color: (_j = options.color) !== null && _j !== void 0 ? _j : undefined, + borderColor: (_k = options.borderColor) !== null && _k !== void 0 ? _k : undefined, + borderDashArray: (_l = options.borderDashArray) !== null && _l !== void 0 ? _l : undefined, + borderDashPhase: (_m = options.borderDashPhase) !== null && _m !== void 0 ? _m : undefined, + graphicsState: graphicsStateKey, + borderLineCap: (_o = options.borderLineCap) !== null && _o !== void 0 ? _o : undefined, + })); + }; + /** + * Draw a square on this page. For example: + * ```js + * import { degrees, grayscale, rgb } from 'pdf-lib' + * + * page.drawSquare({ + * x: 25, + * y: 75, + * size: 100, + * rotate: degrees(-15), + * borderWidth: 5, + * borderColor: grayscale(0.5), + * color: rgb(0.75, 0.2, 0.2), + * opacity: 0.5, + * borderOpacity: 0.75, + * }) + * ``` + * @param options The options to be used when drawing the square. + */ + PDFPage.prototype.drawSquare = function (options) { + if (options === void 0) { options = {}; } + var size = options.size; + assertOrUndefined(size, 'size', ['number']); + this.drawRectangle(__assign(__assign({}, options), { width: size, height: size })); + }; + /** + * Draw an ellipse on this page. For example: + * ```js + * import { grayscale, rgb } from 'pdf-lib' + * + * page.drawEllipse({ + * x: 200, + * y: 75, + * xScale: 100, + * yScale: 50, + * borderWidth: 5, + * borderColor: grayscale(0.5), + * color: rgb(0.75, 0.2, 0.2), + * opacity: 0.5, + * borderOpacity: 0.75, + * }) + * ``` + * @param options The options to be used when drawing the ellipse. + */ + PDFPage.prototype.drawEllipse = function (options) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; + if (options === void 0) { options = {}; } + assertOrUndefined(options.x, 'options.x', ['number']); + assertOrUndefined(options.y, 'options.y', ['number']); + assertOrUndefined(options.xScale, 'options.xScale', ['number']); + assertOrUndefined(options.yScale, 'options.yScale', ['number']); + assertOrUndefined(options.rotate, 'options.rotate', [[Object, 'Rotation']]); + assertOrUndefined(options.color, 'options.color', [[Object, 'Color']]); + assertRangeOrUndefined(options.opacity, 'opacity.opacity', 0, 1); + assertOrUndefined(options.borderColor, 'options.borderColor', [ + [Object, 'Color'], + ]); + assertRangeOrUndefined(options.borderOpacity, 'options.borderOpacity', 0, 1); + assertOrUndefined(options.borderWidth, 'options.borderWidth', ['number']); + assertOrUndefined(options.borderDashArray, 'options.borderDashArray', [ + Array, + ]); + assertOrUndefined(options.borderDashPhase, 'options.borderDashPhase', [ + 'number', + ]); + assertIsOneOfOrUndefined(options.borderLineCap, 'options.borderLineCap', LineCapStyle); + assertIsOneOfOrUndefined(options.blendMode, 'options.blendMode', BlendMode); + var graphicsStateKey = this.maybeEmbedGraphicsState({ + opacity: options.opacity, + borderOpacity: options.borderOpacity, + blendMode: options.blendMode, + }); + if (!('color' in options) && !('borderColor' in options)) { + options.color = rgb(0, 0, 0); + } + var contentStream = this.getContentStream(); + contentStream.push.apply(contentStream, drawEllipse({ + x: (_a = options.x) !== null && _a !== void 0 ? _a : this.x, + y: (_b = options.y) !== null && _b !== void 0 ? _b : this.y, + xScale: (_c = options.xScale) !== null && _c !== void 0 ? _c : 100, + yScale: (_d = options.yScale) !== null && _d !== void 0 ? _d : 100, + rotate: (_e = options.rotate) !== null && _e !== void 0 ? _e : undefined, + color: (_f = options.color) !== null && _f !== void 0 ? _f : undefined, + borderColor: (_g = options.borderColor) !== null && _g !== void 0 ? _g : undefined, + borderWidth: (_h = options.borderWidth) !== null && _h !== void 0 ? _h : 0, + borderDashArray: (_j = options.borderDashArray) !== null && _j !== void 0 ? _j : undefined, + borderDashPhase: (_k = options.borderDashPhase) !== null && _k !== void 0 ? _k : undefined, + borderLineCap: (_l = options.borderLineCap) !== null && _l !== void 0 ? _l : undefined, + graphicsState: graphicsStateKey, + })); + }; + /** + * Draw a circle on this page. For example: + * ```js + * import { grayscale, rgb } from 'pdf-lib' + * + * page.drawCircle({ + * x: 200, + * y: 150, + * size: 100, + * borderWidth: 5, + * borderColor: grayscale(0.5), + * color: rgb(0.75, 0.2, 0.2), + * opacity: 0.5, + * borderOpacity: 0.75, + * }) + * ``` + * @param options The options to be used when drawing the ellipse. + */ + PDFPage.prototype.drawCircle = function (options) { + if (options === void 0) { options = {}; } + var _a = options.size, size = _a === void 0 ? 100 : _a; + assertOrUndefined(size, 'size', ['number']); + this.drawEllipse(__assign(__assign({}, options), { xScale: size, yScale: size })); + }; + PDFPage.prototype.setOrEmbedFont = function (font) { + var oldFont = this.font; + var oldFontKey = this.fontKey; + if (font) + this.setFont(font); + else + this.getFont(); + var newFont = this.font; + var newFontKey = this.fontKey; + return { oldFont: oldFont, oldFontKey: oldFontKey, newFont: newFont, newFontKey: newFontKey }; + }; + PDFPage.prototype.getFont = function () { + if (!this.font || !this.fontKey) { + var font = this.doc.embedStandardFont(StandardFonts.Helvetica); + this.setFont(font); + } + return [this.font, this.fontKey]; + }; + PDFPage.prototype.resetFont = function () { + this.font = undefined; + this.fontKey = undefined; + }; + PDFPage.prototype.getContentStream = function (useExisting) { + if (useExisting === void 0) { useExisting = true; } + if (useExisting && this.contentStream) + return this.contentStream; + this.contentStream = this.createContentStream(); + this.contentStreamRef = this.doc.context.register(this.contentStream); + this.node.addContentStream(this.contentStreamRef); + return this.contentStream; + }; + PDFPage.prototype.createContentStream = function () { + var operators = []; + for (var _i = 0; _i < arguments.length; _i++) { + operators[_i] = arguments[_i]; + } + var dict = this.doc.context.obj({}); + var contentStream = PDFContentStream.of(dict, operators); + return contentStream; + }; + PDFPage.prototype.maybeEmbedGraphicsState = function (options) { + var opacity = options.opacity, borderOpacity = options.borderOpacity, blendMode = options.blendMode; + if (opacity === undefined && + borderOpacity === undefined && + blendMode === undefined) { + return undefined; + } + var graphicsState = this.doc.context.obj({ + Type: 'ExtGState', + ca: opacity, + CA: borderOpacity, + BM: blendMode, + }); + var key = this.node.newExtGState('GS', graphicsState); + return key; + }; + PDFPage.prototype.scaleAnnot = function (annot, x, y) { + var selectors = ['RD', 'CL', 'Vertices', 'QuadPoints', 'L', 'Rect']; + for (var idx = 0, len = selectors.length; idx < len; idx++) { + var list = annot.lookup(PDFName.of(selectors[idx])); + if (list instanceof PDFArray) + list.scalePDFNumbers(x, y); + } + var inkLists = annot.lookup(PDFName.of('InkList')); + if (inkLists instanceof PDFArray) { + for (var idx = 0, len = inkLists.size(); idx < len; idx++) { + var arr = inkLists.lookup(idx); + if (arr instanceof PDFArray) + arr.scalePDFNumbers(x, y); + } + } + }; + /** + * > **NOTE:** You probably don't want to call this method directly. Instead, + * > consider using the [[PDFDocument.addPage]] and [[PDFDocument.insertPage]] + * > methods, which can create instances of [[PDFPage]] for you. + * + * Create an instance of [[PDFPage]] from an existing leaf node. + * + * @param leafNode The leaf node to be wrapped. + * @param ref The unique reference for the page. + * @param doc The document to which the page will belong. + */ + PDFPage.of = function (leafNode, ref, doc) { + return new PDFPage(leafNode, ref, doc); + }; + /** + * > **NOTE:** You probably don't want to call this method directly. Instead, + * > consider using the [[PDFDocument.addPage]] and [[PDFDocument.insertPage]] + * > methods, which can create instances of [[PDFPage]] for you. + * + * Create an instance of [[PDFPage]]. + * + * @param doc The document to which the page will belong. + */ + PDFPage.create = function (doc) { + assertIs(doc, 'doc', [[PDFDocument, 'PDFDocument']]); + var dummyRef = PDFRef.of(-1); + var pageLeaf = PDFPageLeaf.withContextAndParent(doc.context, dummyRef); + var pageRef = doc.context.register(pageLeaf); + return new PDFPage(pageLeaf, pageRef, doc); + }; + return PDFPage; +}()); + +/** + * Represents a button field of a [[PDFForm]]. + * + * [[PDFButton]] fields are interactive controls that users can click with their + * mouse. This type of [[PDFField]] is not stateful. The purpose of a button + * is to perform an action when the user clicks on it, such as opening a print + * modal or resetting the form. Buttons are typically rectangular in shape and + * have a text label describing the action that they perform when clicked. + */ +var PDFButton = /** @class */ (function (_super) { + __extends(PDFButton, _super); + function PDFButton(acroPushButton, ref, doc) { + var _this = _super.call(this, acroPushButton, ref, doc) || this; + assertIs(acroPushButton, 'acroButton', [ + [PDFAcroPushButton, 'PDFAcroPushButton'], + ]); + _this.acroField = acroPushButton; + return _this; + } + /** + * Display an image inside the bounds of this button's widgets. For example: + * ```js + * const pngImage = await pdfDoc.embedPng(...) + * const button = form.getButton('some.button.field') + * button.setImage(pngImage, ImageAlignment.Center) + * ``` + * This will update the appearances streams for each of this button's widgets. + * @param image The image that should be displayed. + * @param alignment The alignment of the image. + */ + PDFButton.prototype.setImage = function (image, alignment) { + if (alignment === void 0) { alignment = ImageAlignment.Center; } + var widgets = this.acroField.getWidgets(); + for (var idx = 0, len = widgets.length; idx < len; idx++) { + var widget = widgets[idx]; + var streamRef = this.createImageAppearanceStream(widget, image, alignment); + this.updateWidgetAppearances(widget, { normal: streamRef }); + } + this.markAsClean(); + }; + /** + * Set the font size for this field. Larger font sizes will result in larger + * text being displayed when PDF readers render this button. Font sizes may + * be integer or floating point numbers. Supplying a negative font size will + * cause this method to throw an error. + * + * For example: + * ```js + * const button = form.getButton('some.button.field') + * button.setFontSize(4) + * button.setFontSize(15.7) + * ``` + * + * > This method depends upon the existence of a default appearance + * > (`/DA`) string. If this field does not have a default appearance string, + * > or that string does not contain a font size (via the `Tf` operator), + * > then this method will throw an error. + * + * @param fontSize The font size to be used when rendering text in this field. + */ + PDFButton.prototype.setFontSize = function (fontSize) { + assertPositive(fontSize, 'fontSize'); + this.acroField.setFontSize(fontSize); + this.markAsDirty(); + }; + /** + * Show this button on the specified page with the given text. For example: + * ```js + * const ubuntuFont = await pdfDoc.embedFont(ubuntuFontBytes) + * const page = pdfDoc.addPage() + * + * const form = pdfDoc.getForm() + * const button = form.createButton('some.button.field') + * + * button.addToPage('Do Stuff', page, { + * x: 50, + * y: 75, + * width: 200, + * height: 100, + * textColor: rgb(1, 0, 0), + * backgroundColor: rgb(0, 1, 0), + * borderColor: rgb(0, 0, 1), + * borderWidth: 2, + * rotate: degrees(90), + * font: ubuntuFont, + * }) + * ``` + * This will create a new widget for this button field. + * @param text The text to be displayed for this button widget. + * @param page The page to which this button widget should be added. + * @param options The options to be used when adding this button widget. + */ + PDFButton.prototype.addToPage = function ( + // TODO: This needs to be optional, e.g. for image buttons + text, page, options) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; + assertOrUndefined(text, 'text', ['string']); + assertOrUndefined(page, 'page', [[PDFPage, 'PDFPage']]); + assertFieldAppearanceOptions(options); + // Create a widget for this button + var widget = this.createWidget({ + x: ((_a = options === null || options === void 0 ? void 0 : options.x) !== null && _a !== void 0 ? _a : 0) - ((_b = options === null || options === void 0 ? void 0 : options.borderWidth) !== null && _b !== void 0 ? _b : 0) / 2, + y: ((_c = options === null || options === void 0 ? void 0 : options.y) !== null && _c !== void 0 ? _c : 0) - ((_d = options === null || options === void 0 ? void 0 : options.borderWidth) !== null && _d !== void 0 ? _d : 0) / 2, + width: (_e = options === null || options === void 0 ? void 0 : options.width) !== null && _e !== void 0 ? _e : 100, + height: (_f = options === null || options === void 0 ? void 0 : options.height) !== null && _f !== void 0 ? _f : 50, + textColor: (_g = options === null || options === void 0 ? void 0 : options.textColor) !== null && _g !== void 0 ? _g : rgb(0, 0, 0), + backgroundColor: (_h = options === null || options === void 0 ? void 0 : options.backgroundColor) !== null && _h !== void 0 ? _h : rgb(0.75, 0.75, 0.75), + borderColor: options === null || options === void 0 ? void 0 : options.borderColor, + borderWidth: (_j = options === null || options === void 0 ? void 0 : options.borderWidth) !== null && _j !== void 0 ? _j : 0, + rotate: (_k = options === null || options === void 0 ? void 0 : options.rotate) !== null && _k !== void 0 ? _k : degrees(0), + caption: text, + hidden: options === null || options === void 0 ? void 0 : options.hidden, + page: page.ref, + }); + var widgetRef = this.doc.context.register(widget.dict); + // Add widget to this field + this.acroField.addWidget(widgetRef); + // Set appearance streams for widget + var font = (_l = options === null || options === void 0 ? void 0 : options.font) !== null && _l !== void 0 ? _l : this.doc.getForm().getDefaultFont(); + this.updateWidgetAppearance(widget, font); + // Add widget to the given page + page.node.addAnnot(widgetRef); + }; + /** + * Returns `true` if this button has been marked as dirty, or if any of this + * button's widgets do not have an appearance stream. For example: + * ```js + * const button = form.getButton('some.button.field') + * if (button.needsAppearancesUpdate()) console.log('Needs update') + * ``` + * @returns Whether or not this button needs an appearance update. + */ + PDFButton.prototype.needsAppearancesUpdate = function () { + var _a; + if (this.isDirty()) + return true; + var widgets = this.acroField.getWidgets(); + for (var idx = 0, len = widgets.length; idx < len; idx++) { + var widget = widgets[idx]; + var hasAppearances = ((_a = widget.getAppearances()) === null || _a === void 0 ? void 0 : _a.normal) instanceof PDFStream; + if (!hasAppearances) + return true; + } + return false; + }; + /** + * Update the appearance streams for each of this button's widgets using + * the default appearance provider for buttons. For example: + * ```js + * const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica) + * const button = form.getButton('some.button.field') + * button.defaultUpdateAppearances(helvetica) + * ``` + * @param font The font to be used for creating the appearance streams. + */ + PDFButton.prototype.defaultUpdateAppearances = function (font) { + assertIs(font, 'font', [[PDFFont, 'PDFFont']]); + this.updateAppearances(font); + }; + /** + * Update the appearance streams for each of this button's widgets using + * the given appearance provider. If no `provider` is passed, the default + * appearance provider for buttons will be used. For example: + * ```js + * const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica) + * const button = form.getButton('some.button.field') + * button.updateAppearances(helvetica, (field, widget, font) => { + * ... + * return { + * normal: drawButton(...), + * down: drawButton(...), + * } + * }) + * ``` + * @param font The font to be used for creating the appearance streams. + * @param provider Optionally, the appearance provider to be used for + * generating the contents of the appearance streams. + */ + PDFButton.prototype.updateAppearances = function (font, provider) { + assertIs(font, 'font', [[PDFFont, 'PDFFont']]); + assertOrUndefined(provider, 'provider', [Function]); + var widgets = this.acroField.getWidgets(); + for (var idx = 0, len = widgets.length; idx < len; idx++) { + var widget = widgets[idx]; + this.updateWidgetAppearance(widget, font, provider); + } + }; + PDFButton.prototype.updateWidgetAppearance = function (widget, font, provider) { + var apProvider = provider !== null && provider !== void 0 ? provider : defaultButtonAppearanceProvider; + var appearances = normalizeAppearance(apProvider(this, widget, font)); + this.updateWidgetAppearanceWithFont(widget, font, appearances); + }; + /** + * > **NOTE:** You probably don't want to call this method directly. Instead, + * > consider using the [[PDFForm.getButton]] method, which will create an + * > instance of [[PDFButton]] for you. + * + * Create an instance of [[PDFButton]] from an existing acroPushButton and ref + * + * @param acroPushButton The underlying `PDFAcroPushButton` for this button. + * @param ref The unique reference for this button. + * @param doc The document to which this button will belong. + */ + PDFButton.of = function (acroPushButton, ref, doc) { return new PDFButton(acroPushButton, ref, doc); }; + return PDFButton; +}(PDFField)); + +export { AFRelationship, AcroButtonFlags, AcroChoiceFlags, AcroFieldFlags, AcroTextFlags, AnnotationFlags, AppearanceCharacteristics, BlendMode, Cache, CharCodes$1 as CharCodes, ColorTypes, CombedTextLayoutError, CorruptPageTreeError, CustomFontEmbedder, CustomFontSubsetEmbedder, Duplex, EncryptedPDFError, ExceededMaxLengthError, FieldAlreadyExistsError, FieldExistsAsNonTerminalError, FileEmbedder, FontkitNotRegisteredError, ForeignPageError, ImageAlignment, IndexOutOfBoundsError, InvalidAcroFieldValueError, InvalidFieldNamePartError, InvalidMaxLengthError, InvalidPDFDateStringError, InvalidTargetIndexError, JpegEmbedder, LineCapStyle, LineJoinStyle, MethodNotImplementedError, MissingCatalogError, MissingDAEntryError, MissingKeywordError, MissingOnValueCheckError, MissingPDFHeaderError, MissingPageContentsEmbeddingError, MissingTfOperatorError, MultiSelectValueError, NextByteAssertionError, NoSuchFieldError, NonFullScreenPageMode, NumberParsingError, PDFAcroButton, PDFAcroCheckBox, PDFAcroChoice, PDFAcroComboBox, PDFAcroField, PDFAcroForm, PDFAcroListBox, PDFAcroNonTerminal, PDFAcroPushButton, PDFAcroRadioButton, PDFAcroSignature, PDFAcroTerminal, PDFAcroText, PDFAnnotation, PDFArray, PDFArrayIsNotRectangleError, PDFBool, PDFButton, PDFCatalog, PDFCheckBox, PDFContentStream, PDFContext, PDFCrossRefSection, PDFCrossRefStream, PDFDict, PDFDocument, PDFDropdown, PDFEmbeddedPage, PDFField, PDFFlateStream, PDFFont, PDFForm, PDFHeader, PDFHexString, PDFImage, PDFInvalidObject, PDFInvalidObjectParsingError, PDFJavaScript, PDFName, PDFNull$1 as PDFNull, PDFNumber, PDFObject, PDFObjectCopier, PDFObjectParser, PDFObjectParsingError, PDFObjectStream, PDFObjectStreamParser, PDFOperator, Ops as PDFOperatorNames, PDFOptionList, PDFPage, PDFPageEmbedder, PDFPageLeaf, PDFPageTree, PDFParser, PDFParsingError, PDFRadioGroup, PDFRawStream, PDFRef, PDFSignature, PDFStream, PDFStreamParsingError, PDFStreamWriter, PDFString, PDFTextField, PDFTrailer, PDFTrailerDict, PDFWidgetAnnotation, PDFWriter, PDFXRefStreamParser, PageEmbeddingMismatchedContextError, PageSizes, ParseSpeeds, PngEmbedder, PrintScaling, PrivateConstructorError, ReadingDirection, RemovePageFromEmptyDocumentError, ReparseError, RichTextFieldReadError, RotationTypes, StalledParserError, StandardFontEmbedder, StandardFontValues, StandardFonts, TextAlignment, TextRenderingMode, UnbalancedParenthesisError, UnexpectedFieldTypeError, UnexpectedObjectTypeError, UnrecognizedStreamTypeError, UnsupportedEncodingError, ViewerPreferences, addRandomSuffix, adjustDimsForRotation, appendBezierCurve, appendQuadraticCurve, arrayAsString, asNumber, asPDFName, asPDFNumber, assertEachIs, assertInteger, assertIs, assertIsOneOf, assertIsOneOfOrUndefined, assertIsSubset, assertMultiple, assertOrUndefined, assertPositive, assertRange, assertRangeOrUndefined, backtick, beginMarkedContent, beginText, breakTextIntoLines, byAscendingId, bytesFor, canBeConvertedToUint8Array, charAtIndex, charFromCode, charFromHexCode, charSplit, cleanText, clip, clipEvenOdd, closePath, cmyk, colorToComponents, componentsToColor, concatTransformationMatrix, copyStringIntoBuffer, createPDFAcroField, createPDFAcroFields, createTypeErrorMsg, createValueErrorMsg, decodeFromBase64, decodeFromBase64DataUri, decodePDFRawStream, defaultButtonAppearanceProvider, defaultCheckBoxAppearanceProvider, defaultDropdownAppearanceProvider, defaultOptionListAppearanceProvider, defaultRadioGroupAppearanceProvider, defaultTextFieldAppearanceProvider, degrees, degreesToRadians, drawButton, drawCheckBox, drawCheckMark, drawEllipse, drawEllipsePath, drawImage, drawLine, drawLinesOfText, drawObject, drawOptionList, drawPage, drawRadioButton, drawRectangle, drawSvgPath, drawText, drawTextField, drawTextLines, encodeToBase64, endMarkedContent, endPath, endText, error, escapeRegExp, escapedNewlineChars, fill, fillAndStroke, findLastMatch, getType, grayscale, hasSurrogates, hasUtf16BOM, highSurrogate, isNewlineChar, isStandardFont, isType, isWithinBMP, last, layoutCombedText, layoutMultilineText, layoutSinglelineText, lineSplit, lineTo, lowSurrogate, mergeIntoTypedArray, mergeLines, mergeUint8Arrays, moveText, moveTo, newlineChars, nextLine, normalizeAppearance, numberToString, padStart, parseDate, pdfDocEncodingDecode, pluckIndices, popGraphicsState, pushGraphicsState, radians, radiansToDegrees, range, rectangle, rectanglesAreEqual, reduceRotation, restoreDashPattern, reverseArray, rgb, rotateAndSkewTextDegreesAndTranslate, rotateAndSkewTextRadiansAndTranslate, rotateDegrees, rotateInPlace, rotateRadians, rotateRectangle, scale, setCharacterSpacing, setCharacterSqueeze, setDashPattern, setFillingCmykColor, setFillingColor, setFillingGrayscaleColor, setFillingRgbColor, setFontAndSize, setGraphicsState, setLineCap, setLineHeight, setLineJoin, setLineWidth, setStrokingCmykColor, setStrokingColor, setStrokingGrayscaleColor, setStrokingRgbColor, setTextMatrix, setTextRenderingMode, setTextRise, setWordSpacing, showText, singleQuote, sizeInBytes, skewDegrees, skewRadians, sortedUniq, square, stroke, sum, toCharCode, toCodePoint, toDegrees, toHexString, toHexStringOfMinLength, toRadians, toUint8Array, translate, typedArrayFor, utf16Decode, utf16Encode, utf8Encode, values, waitForTick }; +//# sourceMappingURL=pdf-lib.esm.js.map diff --git a/go/cmd/kjol-web/frontend/vendor/pdf-lib/package.json b/go/cmd/kjol-web/frontend/vendor/pdf-lib/package.json new file mode 100644 index 00000000..090b03ea --- /dev/null +++ b/go/cmd/kjol-web/frontend/vendor/pdf-lib/package.json @@ -0,0 +1,141 @@ +{ + "name": "pdf-lib", + "version": "1.17.1", + "description": "Create and modify PDF files with JavaScript", + "author": "Andrew Dillon <andrew.dillon.j@gmail.com>", + "contributors": [ + "jerp (https://github.com/jerp)", + "Greg Bacchus (https://github.com/gregbacchus)", + "Mickael Lecoq (https://github.com/mlecoq)", + "Philip Murphy (https://github.com/philipjmurphy)", + "Dmitry Kozliuk (https://github.com/PlushBeaver)", + "Said Amezyane (https://github.com/samezyane)", + "Georges Gabereau (https://github.com/multiplegeorges)", + "Gerard Smit (https://github.com/GerardSmit)", + "jlmessenger (https://github.com/jlmessenger)", + "thebenlamm (https://github.com/thebenlamm)", + "cshenks (https://github.com/cshenks)", + "James Woodrow (https://github.com/jwoodrow)", + "Guillaume Grossetie (https://github.com/Mogztter)", + "Philipp Tessenow (https://github.com/tessi)", + "Tim Kräuter (https://github.com/timKraeuter)", + "Richard Bateman (https://github.com/taxilian)", + "Sebastian Martinez (https://github.com/sebastinez)", + "soadzoor (https://github.com/soadzoor)", + "Slobodan Babic (https://github.com/bockoblur)", + "Zach Toben (https://github.com/ztoben)", + "Zack Sheppard (https://github.com/zackdotcomputer)", + "DkDavid (https://github.com/DkDavid)", + "Bj Tecu (https://github.com/btecu)", + "Brent McSharry (https://github.com/mcshaz)", + "Tim Knapp (https://github.com/duffyd)", + "Ching Chang (https://github.com/ChingChang9)" + ], + "scripts": { + "release:latest": "yarn publish --tag latest && yarn pack && yarn release:tag", + "release:next": "yarn publish --tag next", + "release:prep": "yarn clean && yarn lint && yarn typecheck && yarn test && yarn build", + "release:tag": "TAG=\"v$(yarn --silent get:version)\" && git tag $TAG && git push origin $TAG", + "get:version": "node --eval 'console.log(require(`./package.json`).version)'", + "clean": "rimraf ts3.4 build cjs dist es scratchpad/build coverage tsBuildInfo.json apps/node-build apps/node/tsBuildInfo.json isolate*.log flamegraph.html out.pdf", + "typecheck": "tsc --noEmit --incremental false --tsBuildInfoFile null", + "test": "jest --config jest.json --runInBand", + "testw": "jest --config jest.json --watch", + "testc": "jest --config jest.json --coverage && open coverage/index.html", + "lint": "yarn lint:prettier && yarn lint:tslint:src && yarn lint:tslint:tests", + "lint:tslint:src": "tslint --project tsconfig.json --fix", + "lint:tslint:tests": "tslint --project tests/tsconfig.json --fix", + "lint:prettier": "prettier --write \"./{src,tests,apps}/**/*.{ts,js,json,html,css}\" --loglevel error", + "build": "yarn build:cjs && yarn build:es && yarn build:esm && yarn build:esm:min && yarn build:umd && yarn build:umd:min && yarn build:downlevel-dts", + "build:cjs": "ttsc --module commonjs --outDir cjs", + "build:es": "ttsc --module ES2015 --outDir es", + "build:esm": "rollup --config rollup.config.js --file dist/pdf-lib.esm.js --environment MODULE_TYPE:es", + "build:esm:min": "rollup --config rollup.config.js --file dist/pdf-lib.esm.min.js --environment MINIFY,MODULE_TYPE:es", + "build:umd": "rollup --config rollup.config.js --file dist/pdf-lib.js --environment MODULE_TYPE:umd", + "build:umd:min": "rollup --config rollup.config.js --file dist/pdf-lib.min.js --environment MINIFY,MODULE_TYPE:umd", + "build:downlevel-dts": "rimraf ts3.4 && yarn downlevel-dts . ts3.4 && rimraf ts3.4/scratchpad", + "scratchpad:start": "ttsc --build scratchpad/tsconfig.json --watch", + "scratchpad:run": "node scratchpad/build/scratchpad/index.js", + "scratchpad:flame": "rimraf isolate*.log && node --prof scratchpad/build/scratchpad/index.js && node --prof-process --preprocess -j isolate*.log | flamebearer", + "apps:node": "ttsc --build apps/node/tsconfig.json && node apps/node-build/index.js", + "apps:deno": "deno run --allow-read --allow-write --allow-run apps/deno/index.ts", + "apps:web": "http-server -c-1 .", + "apps:web:mac": "bash -c 'sleep 1 && open http://localhost:8080/apps/web/test1.html' & yarn apps:web", + "apps:rn:ios": "cd apps/rn && yarn add ./../.. --force && react-native run-ios", + "apps:rn:android": "yarn apps:rn:emulator & cd apps/rn && yarn add ./../.. --force && react-native run-android", + "apps:rn:emulator": "emulator -avd \"$(emulator -list-avds | head -n 1)\" & bash -c 'sleep 5 && adb reverse tcp:8080 tcp:8080 && adb reverse tcp:8081 tcp:8081'" + }, + "main": "cjs/index.js", + "module": "es/index.js", + "unpkg": "dist/pdf-lib.min.js", + "types": "cjs/index.d.ts", + "typesVersions": { + "<=3.5": { + "*": [ + "ts3.4/*" + ] + } + }, + "files": [ + "cjs/", + "dist/", + "es/", + "src/", + "ts3.4", + "LICENSE.md", + "package.json", + "README.md", + "yarn.lock" + ], + "dependencies": { + "@pdf-lib/standard-fonts": "^1.0.0", + "@pdf-lib/upng": "^1.0.1", + "pako": "^1.0.11", + "tslib": "^1.11.1" + }, + "devDependencies": { + "@pdf-lib/fontkit": "^1.1.0", + "@rollup/plugin-commonjs": "^13.0.0", + "@rollup/plugin-json": "^4.1.0", + "@rollup/plugin-node-resolve": "^8.0.1", + "@types/jest": "^26.0.0", + "@types/node-fetch": "^2.5.7", + "@types/pako": "^1.0.1", + "@zerollup/ts-transform-paths": "^1.7.18", + "downlevel-dts": "^0.5.0", + "flamebearer": "^1.1.3", + "http-server": "^0.12.3", + "jest": "^26.0.1", + "node-fetch": "^2.6.0", + "prettier": "^2.0.5", + "rimraf": "^3.0.2", + "rollup": "^2.17.1", + "rollup-plugin-terser": "^6.1.0", + "ts-jest": "^26.1.0", + "tslint": "^6.1.2", + "tslint-config-prettier": "^1.18.0", + "ttypescript": "^1.5.10", + "typescript": "^3.9.5" + }, + "license": "MIT", + "private": false, + "homepage": "https://pdf-lib.js.org", + "repository": "git+https://github.com/Hopding/pdf-lib.git", + "bugs": { + "url": "https://github.com/Hopding/pdf-lib/issues" + }, + "keywords": [ + "pdf-lib", + "pdf", + "document", + "create", + "modify", + "creation", + "modification", + "edit", + "editing", + "typescript", + "javascript", + "library" + ] +} diff --git a/go/cmd/kjol-web/frontend/vendor/pdfjs-dist/build/pdf.mjs b/go/cmd/kjol-web/frontend/vendor/pdfjs-dist/build/pdf.mjs new file mode 100644 index 00000000..bd281289 --- /dev/null +++ b/go/cmd/kjol-web/frontend/vendor/pdfjs-dist/build/pdf.mjs @@ -0,0 +1,26465 @@ +/** + * @licstart The following is the entire license notice for the + * JavaScript code in this page + * + * Copyright 2024 Mozilla Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @licend The above is the entire license notice for the + * JavaScript code in this page + */ + +/** + * pdfjsVersion = 5.5.207 + * pdfjsBuild = 527964698 + */ +/******/ // The require scope +/******/ var __webpack_require__ = {}; +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __webpack_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/************************************************************************/ +var __webpack_exports__ = {}; + +;// ./src/shared/util.js +const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser"); +const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; +const LINE_FACTOR = 1.35; +const LINE_DESCENT_FACTOR = 0.35; +const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR; +const RenderingIntentFlag = { + ANY: 0x01, + DISPLAY: 0x02, + PRINT: 0x04, + SAVE: 0x08, + ANNOTATIONS_FORMS: 0x10, + ANNOTATIONS_STORAGE: 0x20, + ANNOTATIONS_DISABLE: 0x40, + IS_EDITING: 0x80, + OPLIST: 0x100 +}; +const AnnotationMode = { + DISABLE: 0, + ENABLE: 1, + ENABLE_FORMS: 2, + ENABLE_STORAGE: 3 +}; +const AnnotationEditorPrefix = "pdfjs_internal_editor_"; +const AnnotationEditorType = { + DISABLE: -1, + NONE: 0, + FREETEXT: 3, + HIGHLIGHT: 9, + STAMP: 13, + INK: 15, + POPUP: 16, + SIGNATURE: 101, + COMMENT: 102 +}; +const AnnotationEditorParamsType = { + RESIZE: 1, + CREATE: 2, + FREETEXT_SIZE: 11, + FREETEXT_COLOR: 12, + FREETEXT_OPACITY: 13, + INK_COLOR: 21, + INK_THICKNESS: 22, + INK_OPACITY: 23, + HIGHLIGHT_COLOR: 31, + HIGHLIGHT_THICKNESS: 32, + HIGHLIGHT_FREE: 33, + HIGHLIGHT_SHOW_ALL: 34, + DRAW_STEP: 41 +}; +const PermissionFlag = { + PRINT: 0x04, + MODIFY_CONTENTS: 0x08, + COPY: 0x10, + MODIFY_ANNOTATIONS: 0x20, + FILL_INTERACTIVE_FORMS: 0x100, + COPY_FOR_ACCESSIBILITY: 0x200, + ASSEMBLE: 0x400, + PRINT_HIGH_QUALITY: 0x800 +}; +const MeshFigureType = { + TRIANGLES: 1, + LATTICE: 2, + PATCH: 3 +}; +const TextRenderingMode = { + FILL: 0, + STROKE: 1, + FILL_STROKE: 2, + INVISIBLE: 3, + FILL_ADD_TO_PATH: 4, + STROKE_ADD_TO_PATH: 5, + FILL_STROKE_ADD_TO_PATH: 6, + ADD_TO_PATH: 7, + FILL_STROKE_MASK: 3, + ADD_TO_PATH_FLAG: 4 +}; +const ImageKind = { + GRAYSCALE_1BPP: 1, + RGB_24BPP: 2, + RGBA_32BPP: 3 +}; +const AnnotationType = { + TEXT: 1, + LINK: 2, + FREETEXT: 3, + LINE: 4, + SQUARE: 5, + CIRCLE: 6, + POLYGON: 7, + POLYLINE: 8, + HIGHLIGHT: 9, + UNDERLINE: 10, + SQUIGGLY: 11, + STRIKEOUT: 12, + STAMP: 13, + CARET: 14, + INK: 15, + POPUP: 16, + FILEATTACHMENT: 17, + SOUND: 18, + MOVIE: 19, + WIDGET: 20, + SCREEN: 21, + PRINTERMARK: 22, + TRAPNET: 23, + WATERMARK: 24, + THREED: 25, + REDACT: 26 +}; +const AnnotationReplyType = { + GROUP: "Group", + REPLY: "R" +}; +const AnnotationFlag = { + INVISIBLE: 0x01, + HIDDEN: 0x02, + PRINT: 0x04, + NOZOOM: 0x08, + NOROTATE: 0x10, + NOVIEW: 0x20, + READONLY: 0x40, + LOCKED: 0x80, + TOGGLENOVIEW: 0x100, + LOCKEDCONTENTS: 0x200 +}; +const AnnotationFieldFlag = { + READONLY: 0x0000001, + REQUIRED: 0x0000002, + NOEXPORT: 0x0000004, + MULTILINE: 0x0001000, + PASSWORD: 0x0002000, + NOTOGGLETOOFF: 0x0004000, + RADIO: 0x0008000, + PUSHBUTTON: 0x0010000, + COMBO: 0x0020000, + EDIT: 0x0040000, + SORT: 0x0080000, + FILESELECT: 0x0100000, + MULTISELECT: 0x0200000, + DONOTSPELLCHECK: 0x0400000, + DONOTSCROLL: 0x0800000, + COMB: 0x1000000, + RICHTEXT: 0x2000000, + RADIOSINUNISON: 0x2000000, + COMMITONSELCHANGE: 0x4000000 +}; +const AnnotationBorderStyleType = { + SOLID: 1, + DASHED: 2, + BEVELED: 3, + INSET: 4, + UNDERLINE: 5 +}; +const AnnotationActionEventType = { + E: "Mouse Enter", + X: "Mouse Exit", + D: "Mouse Down", + U: "Mouse Up", + Fo: "Focus", + Bl: "Blur", + PO: "PageOpen", + PC: "PageClose", + PV: "PageVisible", + PI: "PageInvisible", + K: "Keystroke", + F: "Format", + V: "Validate", + C: "Calculate" +}; +const DocumentActionEventType = { + WC: "WillClose", + WS: "WillSave", + DS: "DidSave", + WP: "WillPrint", + DP: "DidPrint" +}; +const PageActionEventType = { + O: "PageOpen", + C: "PageClose" +}; +const VerbosityLevel = { + ERRORS: 0, + WARNINGS: 1, + INFOS: 5 +}; +const OPS = { + dependency: 1, + setLineWidth: 2, + setLineCap: 3, + setLineJoin: 4, + setMiterLimit: 5, + setDash: 6, + setRenderingIntent: 7, + setFlatness: 8, + setGState: 9, + save: 10, + restore: 11, + transform: 12, + moveTo: 13, + lineTo: 14, + curveTo: 15, + curveTo2: 16, + curveTo3: 17, + closePath: 18, + rectangle: 19, + stroke: 20, + closeStroke: 21, + fill: 22, + eoFill: 23, + fillStroke: 24, + eoFillStroke: 25, + closeFillStroke: 26, + closeEOFillStroke: 27, + endPath: 28, + clip: 29, + eoClip: 30, + beginText: 31, + endText: 32, + setCharSpacing: 33, + setWordSpacing: 34, + setHScale: 35, + setLeading: 36, + setFont: 37, + setTextRenderingMode: 38, + setTextRise: 39, + moveText: 40, + setLeadingMoveText: 41, + setTextMatrix: 42, + nextLine: 43, + showText: 44, + showSpacedText: 45, + nextLineShowText: 46, + nextLineSetSpacingShowText: 47, + setCharWidth: 48, + setCharWidthAndBounds: 49, + setStrokeColorSpace: 50, + setFillColorSpace: 51, + setStrokeColor: 52, + setStrokeColorN: 53, + setFillColor: 54, + setFillColorN: 55, + setStrokeGray: 56, + setFillGray: 57, + setStrokeRGBColor: 58, + setFillRGBColor: 59, + setStrokeCMYKColor: 60, + setFillCMYKColor: 61, + shadingFill: 62, + beginInlineImage: 63, + beginImageData: 64, + endInlineImage: 65, + paintXObject: 66, + markPoint: 67, + markPointProps: 68, + beginMarkedContent: 69, + beginMarkedContentProps: 70, + endMarkedContent: 71, + beginCompat: 72, + endCompat: 73, + paintFormXObjectBegin: 74, + paintFormXObjectEnd: 75, + beginGroup: 76, + endGroup: 77, + beginAnnotation: 80, + endAnnotation: 81, + paintImageMaskXObject: 83, + paintImageMaskXObjectGroup: 84, + paintImageXObject: 85, + paintInlineImageXObject: 86, + paintInlineImageXObjectGroup: 87, + paintImageXObjectRepeat: 88, + paintImageMaskXObjectRepeat: 89, + paintSolidColorImageMask: 90, + constructPath: 91, + setStrokeTransparent: 92, + setFillTransparent: 93, + rawFillPath: 94 +}; +const DrawOPS = { + moveTo: 0, + lineTo: 1, + curveTo: 2, + quadraticCurveTo: 3, + closePath: 4 +}; +const PasswordResponses = { + NEED_PASSWORD: 1, + INCORRECT_PASSWORD: 2 +}; +let verbosity = VerbosityLevel.WARNINGS; +function setVerbosityLevel(level) { + if (Number.isInteger(level)) { + verbosity = level; + } +} +function getVerbosityLevel() { + return verbosity; +} +function info(msg) { + if (verbosity >= VerbosityLevel.INFOS) { + console.info(`Info: ${msg}`); + } +} +function warn(msg) { + if (verbosity >= VerbosityLevel.WARNINGS) { + console.warn(`Warning: ${msg}`); + } +} +function unreachable(msg) { + throw new Error(msg); +} +function assert(cond, msg) { + if (!cond) { + unreachable(msg); + } +} +function _isValidProtocol(url) { + switch (url?.protocol) { + case "http:": + case "https:": + case "ftp:": + case "mailto:": + case "tel:": + return true; + default: + return false; + } +} +function createValidAbsoluteUrl(url, baseUrl = null, options = null) { + if (!url) { + return null; + } + if (options && typeof url === "string") { + if (options.addDefaultProtocol && url.startsWith("www.")) { + const dots = url.match(/\./g); + if (dots?.length >= 2) { + url = `http://${url}`; + } + } + if (options.tryConvertEncoding) { + try { + url = stringToUTF8String(url); + } catch {} + } + } + const absoluteUrl = baseUrl ? URL.parse(url, baseUrl) : URL.parse(url); + return _isValidProtocol(absoluteUrl) ? absoluteUrl : null; +} +function updateUrlHash(url, hash, allowRel = false) { + const res = URL.parse(url); + if (res) { + res.hash = hash; + return res.href; + } + if (allowRel && createValidAbsoluteUrl(url, "http://example.com")) { + return url.split("#", 1)[0] + `${hash ? `#${hash}` : ""}`; + } + return ""; +} +function stripPath(str) { + return str.substring(str.lastIndexOf("/") + 1); +} +function shadow(obj, prop, value, nonSerializable = false) { + Object.defineProperty(obj, prop, { + value, + enumerable: !nonSerializable, + configurable: true, + writable: false + }); + return value; +} +const BaseException = function BaseExceptionClosure() { + function BaseException(message, name) { + this.message = message; + this.name = name; + } + BaseException.prototype = new Error(); + BaseException.constructor = BaseException; + return BaseException; +}(); +class PasswordException extends BaseException { + constructor(msg, code) { + super(msg, "PasswordException"); + this.code = code; + } +} +class UnknownErrorException extends BaseException { + constructor(msg, details) { + super(msg, "UnknownErrorException"); + this.details = details; + } +} +class InvalidPDFException extends BaseException { + constructor(msg) { + super(msg, "InvalidPDFException"); + } +} +class ResponseException extends BaseException { + constructor(msg, status, missing) { + super(msg, "ResponseException"); + this.status = status; + this.missing = missing; + } +} +class FormatError extends BaseException { + constructor(msg) { + super(msg, "FormatError"); + } +} +class AbortException extends BaseException { + constructor(msg) { + super(msg, "AbortException"); + } +} +function bytesToString(bytes) { + if (typeof bytes !== "object" || bytes?.length === undefined) { + unreachable("Invalid argument for bytesToString"); + } + const length = bytes.length; + const MAX_ARGUMENT_COUNT = 8192; + if (length < MAX_ARGUMENT_COUNT) { + return String.fromCharCode.apply(null, bytes); + } + const strBuf = []; + for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) { + const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length); + const chunk = bytes.subarray(i, chunkEnd); + strBuf.push(String.fromCharCode.apply(null, chunk)); + } + return strBuf.join(""); +} +function stringToBytes(str) { + if (typeof str !== "string") { + unreachable("Invalid argument for stringToBytes"); + } + const length = str.length; + const bytes = new Uint8Array(length); + for (let i = 0; i < length; ++i) { + bytes[i] = str.charCodeAt(i) & 0xff; + } + return bytes; +} +function string32(value) { + return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff); +} +function objectSize(obj) { + return Object.keys(obj).length; +} +function isLittleEndian() { + const buffer8 = new Uint8Array(4); + buffer8[0] = 1; + const view32 = new Uint32Array(buffer8.buffer, 0, 1); + return view32[0] === 1; +} +function isEvalSupported() { + try { + new Function(""); + return true; + } catch { + return false; + } +} +class FeatureTest { + static get isLittleEndian() { + return shadow(this, "isLittleEndian", isLittleEndian()); + } + static get isEvalSupported() { + return shadow(this, "isEvalSupported", isEvalSupported()); + } + static get isOffscreenCanvasSupported() { + return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined"); + } + static get isImageDecoderSupported() { + return shadow(this, "isImageDecoderSupported", typeof ImageDecoder !== "undefined"); + } + static get isFloat16ArraySupported() { + return shadow(this, "isFloat16ArraySupported", typeof Float16Array !== "undefined"); + } + static get isSanitizerSupported() { + return shadow(this, "isSanitizerSupported", typeof Sanitizer !== "undefined"); + } + static get platform() { + const { + platform, + userAgent + } = navigator; + return shadow(this, "platform", { + isAndroid: userAgent.includes("Android"), + isLinux: platform.includes("Linux"), + isMac: platform.includes("Mac"), + isWindows: platform.includes("Win"), + isFirefox: userAgent.includes("Firefox") + }); + } + static get isCSSRoundSupported() { + return shadow(this, "isCSSRoundSupported", globalThis.CSS?.supports?.("width: round(1.5px, 1px)")); + } +} +const hexNumbers = Array.from(Array(256).keys(), n => n.toString(16).padStart(2, "0")); +class Util { + static makeHexColor(r, g, b) { + return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`; + } + static domMatrixToTransform(dm) { + return [dm.a, dm.b, dm.c, dm.d, dm.e, dm.f]; + } + static scaleMinMax(transform, minMax) { + let temp; + if (transform[0]) { + if (transform[0] < 0) { + temp = minMax[0]; + minMax[0] = minMax[2]; + minMax[2] = temp; + } + minMax[0] *= transform[0]; + minMax[2] *= transform[0]; + if (transform[3] < 0) { + temp = minMax[1]; + minMax[1] = minMax[3]; + minMax[3] = temp; + } + minMax[1] *= transform[3]; + minMax[3] *= transform[3]; + } else { + temp = minMax[0]; + minMax[0] = minMax[1]; + minMax[1] = temp; + temp = minMax[2]; + minMax[2] = minMax[3]; + minMax[3] = temp; + if (transform[1] < 0) { + temp = minMax[1]; + minMax[1] = minMax[3]; + minMax[3] = temp; + } + minMax[1] *= transform[1]; + minMax[3] *= transform[1]; + if (transform[2] < 0) { + temp = minMax[0]; + minMax[0] = minMax[2]; + minMax[2] = temp; + } + minMax[0] *= transform[2]; + minMax[2] *= transform[2]; + } + minMax[0] += transform[4]; + minMax[1] += transform[5]; + minMax[2] += transform[4]; + minMax[3] += transform[5]; + } + static transform(m1, m2) { + return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]]; + } + static multiplyByDOMMatrix(m, md) { + return [m[0] * md.a + m[2] * md.b, m[1] * md.a + m[3] * md.b, m[0] * md.c + m[2] * md.d, m[1] * md.c + m[3] * md.d, m[0] * md.e + m[2] * md.f + m[4], m[1] * md.e + m[3] * md.f + m[5]]; + } + static applyTransform(p, m, pos = 0) { + const p0 = p[pos]; + const p1 = p[pos + 1]; + p[pos] = p0 * m[0] + p1 * m[2] + m[4]; + p[pos + 1] = p0 * m[1] + p1 * m[3] + m[5]; + } + static applyTransformToBezier(p, transform, pos = 0) { + const m0 = transform[0]; + const m1 = transform[1]; + const m2 = transform[2]; + const m3 = transform[3]; + const m4 = transform[4]; + const m5 = transform[5]; + for (let i = 0; i < 6; i += 2) { + const pI = p[pos + i]; + const pI1 = p[pos + i + 1]; + p[pos + i] = pI * m0 + pI1 * m2 + m4; + p[pos + i + 1] = pI * m1 + pI1 * m3 + m5; + } + } + static applyInverseTransform(p, m) { + const p0 = p[0]; + const p1 = p[1]; + const d = m[0] * m[3] - m[1] * m[2]; + p[0] = (p0 * m[3] - p1 * m[2] + m[2] * m[5] - m[4] * m[3]) / d; + p[1] = (-p0 * m[1] + p1 * m[0] + m[4] * m[1] - m[5] * m[0]) / d; + } + static axialAlignedBoundingBox(rect, transform, output) { + const m0 = transform[0]; + const m1 = transform[1]; + const m2 = transform[2]; + const m3 = transform[3]; + const m4 = transform[4]; + const m5 = transform[5]; + const r0 = rect[0]; + const r1 = rect[1]; + const r2 = rect[2]; + const r3 = rect[3]; + let a0 = m0 * r0 + m4; + let a2 = a0; + let a1 = m0 * r2 + m4; + let a3 = a1; + let b0 = m3 * r1 + m5; + let b2 = b0; + let b1 = m3 * r3 + m5; + let b3 = b1; + if (m1 !== 0 || m2 !== 0) { + const m1r0 = m1 * r0; + const m1r2 = m1 * r2; + const m2r1 = m2 * r1; + const m2r3 = m2 * r3; + a0 += m2r1; + a3 += m2r1; + a1 += m2r3; + a2 += m2r3; + b0 += m1r0; + b3 += m1r0; + b1 += m1r2; + b2 += m1r2; + } + output[0] = Math.min(output[0], a0, a1, a2, a3); + output[1] = Math.min(output[1], b0, b1, b2, b3); + output[2] = Math.max(output[2], a0, a1, a2, a3); + output[3] = Math.max(output[3], b0, b1, b2, b3); + } + static inverseTransform(m) { + const d = m[0] * m[3] - m[1] * m[2]; + return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d]; + } + static singularValueDecompose2dScale(matrix, output) { + const m0 = matrix[0]; + const m1 = matrix[1]; + const m2 = matrix[2]; + const m3 = matrix[3]; + const a = m0 ** 2 + m1 ** 2; + const b = m0 * m2 + m1 * m3; + const c = m2 ** 2 + m3 ** 2; + const first = (a + c) / 2; + const second = Math.sqrt(first ** 2 - (a * c - b ** 2)); + output[0] = Math.sqrt(first + second || 1); + output[1] = Math.sqrt(first - second || 1); + } + static normalizeRect(rect) { + const r = rect.slice(0); + if (rect[0] > rect[2]) { + r[0] = rect[2]; + r[2] = rect[0]; + } + if (rect[1] > rect[3]) { + r[1] = rect[3]; + r[3] = rect[1]; + } + return r; + } + static intersect(rect1, rect2) { + const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2])); + const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2])); + if (xLow > xHigh) { + return null; + } + const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3])); + const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3])); + if (yLow > yHigh) { + return null; + } + return [xLow, yLow, xHigh, yHigh]; + } + static pointBoundingBox(x, y, minMax) { + minMax[0] = Math.min(minMax[0], x); + minMax[1] = Math.min(minMax[1], y); + minMax[2] = Math.max(minMax[2], x); + minMax[3] = Math.max(minMax[3], y); + } + static rectBoundingBox(x0, y0, x1, y1, minMax) { + minMax[0] = Math.min(minMax[0], x0, x1); + minMax[1] = Math.min(minMax[1], y0, y1); + minMax[2] = Math.max(minMax[2], x0, x1); + minMax[3] = Math.max(minMax[3], y0, y1); + } + static #getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, t, minMax) { + if (t <= 0 || t >= 1) { + return; + } + const mt = 1 - t; + const tt = t * t; + const ttt = tt * t; + const x = mt * (mt * (mt * x0 + 3 * t * x1) + 3 * tt * x2) + ttt * x3; + const y = mt * (mt * (mt * y0 + 3 * t * y1) + 3 * tt * y2) + ttt * y3; + minMax[0] = Math.min(minMax[0], x); + minMax[1] = Math.min(minMax[1], y); + minMax[2] = Math.max(minMax[2], x); + minMax[3] = Math.max(minMax[3], y); + } + static #getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, a, b, c, minMax) { + if (Math.abs(a) < 1e-12) { + if (Math.abs(b) >= 1e-12) { + this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, -c / b, minMax); + } + return; + } + const delta = b ** 2 - 4 * c * a; + if (delta < 0) { + return; + } + const sqrtDelta = Math.sqrt(delta); + const a2 = 2 * a; + this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b + sqrtDelta) / a2, minMax); + this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b - sqrtDelta) / a2, minMax); + } + static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax) { + minMax[0] = Math.min(minMax[0], x0, x3); + minMax[1] = Math.min(minMax[1], y0, y3); + minMax[2] = Math.max(minMax[2], x0, x3); + minMax[3] = Math.max(minMax[3], y0, y3); + this.#getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, 3 * (-x0 + 3 * (x1 - x2) + x3), 6 * (x0 - 2 * x1 + x2), 3 * (x1 - x0), minMax); + this.#getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, 3 * (-y0 + 3 * (y1 - y2) + y3), 6 * (y0 - 2 * y1 + y2), 3 * (y1 - y0), minMax); + } +} +const PDFStringTranslateTable = (/* unused pure expression or super */ null && ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2d8, 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d, 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac])); +function stringToPDFString(str, keepEscapeSequence = false) { + if (str[0] >= "\xEF") { + let encoding; + if (str[0] === "\xFE" && str[1] === "\xFF") { + encoding = "utf-16be"; + if (str.length % 2 === 1) { + str = str.slice(0, -1); + } + } else if (str[0] === "\xFF" && str[1] === "\xFE") { + encoding = "utf-16le"; + if (str.length % 2 === 1) { + str = str.slice(0, -1); + } + } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") { + encoding = "utf-8"; + } + if (encoding) { + try { + const decoder = new TextDecoder(encoding, { + fatal: true + }); + const buffer = stringToBytes(str); + const decoded = decoder.decode(buffer); + if (keepEscapeSequence || !decoded.includes("\x1b")) { + return decoded; + } + return decoded.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g, ""); + } catch (ex) { + warn(`stringToPDFString: "${ex}".`); + } + } + } + const strBuf = []; + for (let i = 0, ii = str.length; i < ii; i++) { + const charCode = str.charCodeAt(i); + if (!keepEscapeSequence && charCode === 0x1b) { + while (++i < ii && str.charCodeAt(i) !== 0x1b) {} + continue; + } + const code = PDFStringTranslateTable[charCode]; + strBuf.push(code ? String.fromCharCode(code) : str.charAt(i)); + } + return strBuf.join(""); +} +function stringToUTF8String(str) { + return decodeURIComponent(escape(str)); +} +function utf8StringToString(str) { + return unescape(encodeURIComponent(str)); +} +function isArrayEqual(arr1, arr2) { + if (arr1.length !== arr2.length) { + return false; + } + for (let i = 0, ii = arr1.length; i < ii; i++) { + if (arr1[i] !== arr2[i]) { + return false; + } + } + return true; +} +function getModificationDate(date = new Date()) { + if (!(date instanceof Date)) { + date = new Date(date); + } + const buffer = [date.getUTCFullYear().toString(), (date.getUTCMonth() + 1).toString().padStart(2, "0"), date.getUTCDate().toString().padStart(2, "0"), date.getUTCHours().toString().padStart(2, "0"), date.getUTCMinutes().toString().padStart(2, "0"), date.getUTCSeconds().toString().padStart(2, "0")]; + return buffer.join(""); +} +let NormalizeRegex = null; +let NormalizationMap = null; +function normalizeUnicode(str) { + if (!NormalizeRegex) { + NormalizeRegex = /([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu; + NormalizationMap = new Map([["ſt", "ſt"]]); + } + return str.replaceAll(NormalizeRegex, (_, p1, p2) => p1 ? p1.normalize("NFKC") : NormalizationMap.get(p2)); +} +function getUuid() { + if (typeof crypto.randomUUID === "function") { + return crypto.randomUUID(); + } + const buf = new Uint8Array(32); + crypto.getRandomValues(buf); + return bytesToString(buf); +} +const AnnotationPrefix = "pdfjs_internal_id_"; +function _isValidExplicitDest(validRef, validName, dest) { + if (!Array.isArray(dest) || dest.length < 2) { + return false; + } + const [page, zoom, ...args] = dest; + if (!validRef(page) && !Number.isInteger(page)) { + return false; + } + if (!validName(zoom)) { + return false; + } + const argsLen = args.length; + let allowNull = true; + switch (zoom.name) { + case "XYZ": + if (argsLen < 2 || argsLen > 3) { + return false; + } + break; + case "Fit": + case "FitB": + return argsLen === 0; + case "FitH": + case "FitBH": + case "FitV": + case "FitBV": + if (argsLen > 1) { + return false; + } + break; + case "FitR": + if (argsLen !== 4) { + return false; + } + allowNull = false; + break; + default: + return false; + } + for (const arg of args) { + if (typeof arg === "number" || allowNull && arg === null) { + continue; + } + return false; + } + return true; +} +const makeArr = () => []; +const makeMap = () => new Map(); +const makeObj = () => Object.create(null); +function MathClamp(v, min, max) { + return Math.min(Math.max(v, min), max); +} +if (typeof Math.sumPrecise !== "function") { + Math.sumPrecise = function (numbers) { + return numbers.reduce((a, b) => a + b, 0); + }; +} + +;// ./src/display/xfa_text.js +class XfaText { + static textContent(xfa) { + const items = []; + const output = { + items, + styles: Object.create(null) + }; + function walk(node) { + if (!node) { + return; + } + let str = null; + const name = node.name; + if (name === "#text") { + str = node.value; + } else if (!XfaText.shouldBuildText(name)) { + return; + } else if (node?.attributes?.textContent) { + str = node.attributes.textContent; + } else if (node.value) { + str = node.value; + } + if (str !== null) { + items.push({ + str + }); + } + if (!node.children) { + return; + } + for (const child of node.children) { + walk(child); + } + } + walk(xfa); + return output; + } + static shouldBuildText(name) { + return !(name === "textarea" || name === "input" || name === "option" || name === "select"); + } +} + +;// ./src/display/xfa_layer.js + +class XfaLayer { + static setupStorage(html, id, element, storage, intent) { + const storedData = storage.getValue(id, { + value: null + }); + switch (element.name) { + case "textarea": + if (storedData.value !== null) { + html.textContent = storedData.value; + } + if (intent === "print") { + break; + } + html.addEventListener("input", event => { + storage.setValue(id, { + value: event.target.value + }); + }); + break; + case "input": + if (element.attributes.type === "radio" || element.attributes.type === "checkbox") { + if (storedData.value === element.attributes.xfaOn) { + html.setAttribute("checked", true); + } else if (storedData.value === element.attributes.xfaOff) { + html.removeAttribute("checked"); + } + if (intent === "print") { + break; + } + html.addEventListener("change", event => { + storage.setValue(id, { + value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff") + }); + }); + } else { + if (storedData.value !== null) { + html.setAttribute("value", storedData.value); + } + if (intent === "print") { + break; + } + html.addEventListener("input", event => { + storage.setValue(id, { + value: event.target.value + }); + }); + } + break; + case "select": + if (storedData.value !== null) { + html.setAttribute("value", storedData.value); + for (const option of element.children) { + if (option.attributes.value === storedData.value) { + option.attributes.selected = true; + } else if (option.attributes.hasOwnProperty("selected")) { + delete option.attributes.selected; + } + } + } + html.addEventListener("input", event => { + const options = event.target.options; + const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value; + storage.setValue(id, { + value + }); + }); + break; + } + } + static setAttributes({ + html, + element, + storage = null, + intent, + linkService + }) { + const { + attributes + } = element; + const isHTMLAnchorElement = html instanceof HTMLAnchorElement; + if (attributes.type === "radio") { + attributes.name = `${attributes.name}-${intent}`; + } + for (const [key, value] of Object.entries(attributes)) { + if (value === null || value === undefined) { + continue; + } + switch (key) { + case "class": + if (value.length) { + html.setAttribute(key, value.join(" ")); + } + break; + case "dataId": + break; + case "id": + html.setAttribute("data-element-id", value); + break; + case "style": + Object.assign(html.style, value); + break; + case "textContent": + html.textContent = value; + break; + default: + if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") { + html.setAttribute(key, value); + } + } + } + if (isHTMLAnchorElement) { + linkService.addLinkAttributes(html, attributes.href, attributes.newWindow); + } + if (storage && attributes.dataId) { + this.setupStorage(html, attributes.dataId, element, storage); + } + } + static render(parameters) { + const storage = parameters.annotationStorage; + const linkService = parameters.linkService; + const root = parameters.xfaHtml; + const intent = parameters.intent || "display"; + const rootHtml = document.createElement(root.name); + if (root.attributes) { + this.setAttributes({ + html: rootHtml, + element: root, + intent, + linkService + }); + } + const isNotForRichText = intent !== "richText"; + const rootDiv = parameters.div; + rootDiv.append(rootHtml); + if (parameters.viewport) { + const transform = `matrix(${parameters.viewport.transform.join(",")})`; + rootDiv.style.transform = transform; + } + if (isNotForRichText) { + rootDiv.setAttribute("class", "xfaLayer xfaFont"); + } + const textDivs = []; + if (root.children.length === 0) { + if (root.value) { + const node = document.createTextNode(root.value); + rootHtml.append(node); + if (isNotForRichText && XfaText.shouldBuildText(root.name)) { + textDivs.push(node); + } + } + return { + textDivs + }; + } + const stack = [[root, -1, rootHtml]]; + while (stack.length > 0) { + const [parent, i, html] = stack.at(-1); + if (i + 1 === parent.children.length) { + stack.pop(); + continue; + } + const child = parent.children[++stack.at(-1)[1]]; + if (child === null) { + continue; + } + const { + name + } = child; + if (name === "#text") { + const node = document.createTextNode(child.value); + textDivs.push(node); + html.append(node); + continue; + } + const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name); + html.append(childHtml); + if (child.attributes) { + this.setAttributes({ + html: childHtml, + element: child, + storage, + intent, + linkService + }); + } + if (child.children?.length > 0) { + stack.push([child, -1, childHtml]); + } else if (child.value) { + const node = document.createTextNode(child.value); + if (isNotForRichText && XfaText.shouldBuildText(name)) { + textDivs.push(node); + } + childHtml.append(node); + } + } + for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) { + el.setAttribute("readOnly", true); + } + return { + textDivs + }; + } + static update(parameters) { + const transform = `matrix(${parameters.viewport.transform.join(",")})`; + parameters.div.style.transform = transform; + parameters.div.hidden = false; + } +} + +;// ./src/display/display_utils.js + + +const SVG_NS = "http://www.w3.org/2000/svg"; +class PixelsPerInch { + static CSS = 96.0; + static PDF = 72.0; + static PDF_TO_CSS_UNITS = this.CSS / this.PDF; +} +async function fetchData(url, type = "text") { + if (isValidFetchUrl(url, document.baseURI)) { + const response = await fetch(url); + if (!response.ok) { + throw new Error(response.statusText); + } + switch (type) { + case "blob": + return response.blob(); + case "bytes": + return response.bytes(); + case "json": + return response.json(); + } + return response.text(); + } + return new Promise((resolve, reject) => { + const request = new XMLHttpRequest(); + request.open("GET", url, true); + request.responseType = type === "bytes" ? "arraybuffer" : type; + request.onreadystatechange = () => { + if (request.readyState !== XMLHttpRequest.DONE) { + return; + } + if (request.status === 200 || request.status === 0) { + switch (type) { + case "bytes": + resolve(new Uint8Array(request.response)); + return; + case "blob": + case "json": + resolve(request.response); + return; + } + resolve(request.responseText); + return; + } + reject(new Error(request.statusText)); + }; + request.send(null); + }); +} +class PageViewport { + constructor({ + viewBox, + userUnit, + scale, + rotation, + offsetX = 0, + offsetY = 0, + dontFlip = false + }) { + this.viewBox = viewBox; + this.userUnit = userUnit; + this.scale = scale; + this.rotation = rotation; + this.offsetX = offsetX; + this.offsetY = offsetY; + scale *= userUnit; + const centerX = (viewBox[2] + viewBox[0]) / 2; + const centerY = (viewBox[3] + viewBox[1]) / 2; + let rotateA, rotateB, rotateC, rotateD; + rotation %= 360; + if (rotation < 0) { + rotation += 360; + } + switch (rotation) { + case 180: + rotateA = -1; + rotateB = 0; + rotateC = 0; + rotateD = 1; + break; + case 90: + rotateA = 0; + rotateB = 1; + rotateC = 1; + rotateD = 0; + break; + case 270: + rotateA = 0; + rotateB = -1; + rotateC = -1; + rotateD = 0; + break; + case 0: + rotateA = 1; + rotateB = 0; + rotateC = 0; + rotateD = -1; + break; + default: + throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees."); + } + if (dontFlip) { + rotateC = -rotateC; + rotateD = -rotateD; + } + let offsetCanvasX, offsetCanvasY; + let width, height; + if (rotateA === 0) { + offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; + offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; + width = (viewBox[3] - viewBox[1]) * scale; + height = (viewBox[2] - viewBox[0]) * scale; + } else { + offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX; + offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY; + width = (viewBox[2] - viewBox[0]) * scale; + height = (viewBox[3] - viewBox[1]) * scale; + } + this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY]; + this.width = width; + this.height = height; + } + get rawDims() { + const dims = this.viewBox; + return shadow(this, "rawDims", { + pageWidth: dims[2] - dims[0], + pageHeight: dims[3] - dims[1], + pageX: dims[0], + pageY: dims[1] + }); + } + clone({ + scale = this.scale, + rotation = this.rotation, + offsetX = this.offsetX, + offsetY = this.offsetY, + dontFlip = false + } = {}) { + return new PageViewport({ + viewBox: this.viewBox.slice(), + userUnit: this.userUnit, + scale, + rotation, + offsetX, + offsetY, + dontFlip + }); + } + convertToViewportPoint(x, y) { + const p = [x, y]; + Util.applyTransform(p, this.transform); + return p; + } + convertToViewportRectangle(rect) { + const topLeft = [rect[0], rect[1]]; + Util.applyTransform(topLeft, this.transform); + const bottomRight = [rect[2], rect[3]]; + Util.applyTransform(bottomRight, this.transform); + return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]]; + } + convertToPdfPoint(x, y) { + const p = [x, y]; + Util.applyInverseTransform(p, this.transform); + return p; + } +} +class RenderingCancelledException extends BaseException { + constructor(msg, extraDelay = 0) { + super(msg, "RenderingCancelledException"); + this.extraDelay = extraDelay; + } +} +function isDataScheme(url) { + const ii = url.length; + let i = 0; + while (i < ii && url[i].trim() === "") { + i++; + } + return url.substring(i, i + 5).toLowerCase() === "data:"; +} +function isPdfFile(filename) { + return typeof filename === "string" && /\.pdf$/i.test(filename); +} +function getFilenameFromUrl(url) { + [url] = url.split(/[#?]/, 1); + return stripPath(url); +} +function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") { + if (typeof url !== "string") { + return defaultFilename; + } + if (isDataScheme(url)) { + warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'); + return defaultFilename; + } + const getURL = urlString => { + try { + return new URL(urlString); + } catch { + try { + return new URL(decodeURIComponent(urlString)); + } catch { + try { + return new URL(urlString, "https://foo.bar"); + } catch { + try { + return new URL(decodeURIComponent(urlString), "https://foo.bar"); + } catch { + return null; + } + } + } + } + }; + const newURL = getURL(url); + if (!newURL) { + return defaultFilename; + } + const decode = name => { + try { + let decoded = decodeURIComponent(name); + if (decoded.includes("/")) { + decoded = stripPath(decoded); + if (/^\.pdf$/i.test(decoded)) { + return name; + } + } + return decoded; + } catch { + return name; + } + }; + const pdfRegex = /\.pdf$/i; + const filename = stripPath(newURL.pathname); + if (pdfRegex.test(filename)) { + return decode(filename); + } + if (newURL.searchParams.size > 0) { + const getLast = iterator => [...iterator].findLast(v => pdfRegex.test(v)); + const name = getLast(newURL.searchParams.values()) ?? getLast(newURL.searchParams.keys()); + if (name) { + return decode(name); + } + } + if (newURL.hash) { + const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i; + const hashFilename = reFilename.exec(newURL.hash); + if (hashFilename) { + return decode(hashFilename[0]); + } + } + return defaultFilename; +} +class StatTimer { + started = Object.create(null); + times = []; + time(name) { + if (name in this.started) { + warn(`Timer is already running for ${name}`); + } + this.started[name] = Date.now(); + } + timeEnd(name) { + if (!(name in this.started)) { + warn(`Timer has not been started for ${name}`); + } + this.times.push({ + name, + start: this.started[name], + end: Date.now() + }); + delete this.started[name]; + } + toString() { + const outBuf = []; + let longest = 0; + for (const { + name + } of this.times) { + longest = Math.max(name.length, longest); + } + for (const { + name, + start, + end + } of this.times) { + outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`); + } + return outBuf.join(""); + } +} +function isValidFetchUrl(url, baseUrl) { + const res = baseUrl ? URL.parse(url, baseUrl) : URL.parse(url); + return /https?:/.test(res?.protocol ?? ""); +} +function noContextMenu(e) { + e.preventDefault(); +} +function stopEvent(e) { + e.preventDefault(); + e.stopPropagation(); +} +function deprecated(details) { + console.log("Deprecated API usage: " + details); +} +class PDFDateString { + static #regex; + static toDateObject(input) { + if (input instanceof Date) { + return input; + } + if (!input || typeof input !== "string") { + return null; + } + this.#regex ||= new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?"); + const matches = this.#regex.exec(input); + if (!matches) { + return null; + } + const year = parseInt(matches[1], 10); + let month = parseInt(matches[2], 10); + month = month >= 1 && month <= 12 ? month - 1 : 0; + let day = parseInt(matches[3], 10); + day = day >= 1 && day <= 31 ? day : 1; + let hour = parseInt(matches[4], 10); + hour = hour >= 0 && hour <= 23 ? hour : 0; + let minute = parseInt(matches[5], 10); + minute = minute >= 0 && minute <= 59 ? minute : 0; + let second = parseInt(matches[6], 10); + second = second >= 0 && second <= 59 ? second : 0; + const universalTimeRelation = matches[7] || "Z"; + let offsetHour = parseInt(matches[8], 10); + offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0; + let offsetMinute = parseInt(matches[9], 10) || 0; + offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0; + if (universalTimeRelation === "-") { + hour += offsetHour; + minute += offsetMinute; + } else if (universalTimeRelation === "+") { + hour -= offsetHour; + minute -= offsetMinute; + } + return new Date(Date.UTC(year, month, day, hour, minute, second)); + } +} +function getXfaPageViewport(xfaPage, { + scale = 1, + rotation = 0 +}) { + const { + width, + height + } = xfaPage.attributes.style; + const viewBox = [0, 0, parseInt(width), parseInt(height)]; + return new PageViewport({ + viewBox, + userUnit: 1, + scale, + rotation + }); +} +function getRGB(color) { + if (color.startsWith("#")) { + const colorRGB = parseInt(color.slice(1), 16); + return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff]; + } + if (color.startsWith("rgb(")) { + return color.slice(4, -1).split(",").map(x => parseInt(x)); + } + if (color.startsWith("rgba(")) { + return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3); + } + warn(`Not a valid color format: "${color}"`); + return [0, 0, 0]; +} +function getColorValues(colors) { + const span = document.createElement("span"); + span.style.visibility = "hidden"; + span.style.colorScheme = "only light"; + document.body.append(span); + for (const name of colors.keys()) { + span.style.color = name; + const computedColor = window.getComputedStyle(span).color; + colors.set(name, getRGB(computedColor)); + } + span.remove(); +} +function getCurrentTransform(ctx) { + const { + a, + b, + c, + d, + e, + f + } = ctx.getTransform(); + return [a, b, c, d, e, f]; +} +function getCurrentTransformInverse(ctx) { + const { + a, + b, + c, + d, + e, + f + } = ctx.getTransform().invertSelf(); + return [a, b, c, d, e, f]; +} +function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) { + if (viewport instanceof PageViewport) { + const { + pageWidth, + pageHeight + } = viewport.rawDims; + const { + style + } = div; + const useRound = FeatureTest.isCSSRoundSupported; + const w = `var(--total-scale-factor) * ${pageWidth}px`, + h = `var(--total-scale-factor) * ${pageHeight}px`; + const widthStr = useRound ? `round(down, ${w}, var(--scale-round-x))` : `calc(${w})`, + heightStr = useRound ? `round(down, ${h}, var(--scale-round-y))` : `calc(${h})`; + if (!mustFlip || viewport.rotation % 180 === 0) { + style.width = widthStr; + style.height = heightStr; + } else { + style.width = heightStr; + style.height = widthStr; + } + } + if (mustRotate) { + div.setAttribute("data-main-rotation", viewport.rotation); + } +} +class OutputScale { + constructor() { + const { + pixelRatio + } = OutputScale; + this.sx = pixelRatio; + this.sy = pixelRatio; + } + get scaled() { + return this.sx !== 1 || this.sy !== 1; + } + get symmetric() { + return this.sx === this.sy; + } + limitCanvas(width, height, maxPixels, maxDim, capAreaFactor = -1) { + let maxAreaScale = Infinity, + maxWidthScale = Infinity, + maxHeightScale = Infinity; + maxPixels = OutputScale.capPixels(maxPixels, capAreaFactor); + if (maxPixels > 0) { + maxAreaScale = Math.sqrt(maxPixels / (width * height)); + } + if (maxDim !== -1) { + maxWidthScale = maxDim / width; + maxHeightScale = maxDim / height; + } + const maxScale = Math.min(maxAreaScale, maxWidthScale, maxHeightScale); + if (this.sx > maxScale || this.sy > maxScale) { + this.sx = maxScale; + this.sy = maxScale; + return true; + } + return false; + } + static get pixelRatio() { + return globalThis.devicePixelRatio || 1; + } + static capPixels(maxPixels, capAreaFactor) { + if (capAreaFactor >= 0) { + const winPixels = Math.ceil(window.screen.availWidth * window.screen.availHeight * this.pixelRatio ** 2 * (1 + capAreaFactor / 100)); + return maxPixels > 0 ? Math.min(maxPixels, winPixels) : winPixels; + } + return maxPixels; + } +} +const SupportedImageMimeTypes = ["image/apng", "image/avif", "image/bmp", "image/gif", "image/jpeg", "image/png", "image/svg+xml", "image/webp", "image/x-icon"]; +class ColorScheme { + static get isDarkMode() { + return shadow(this, "isDarkMode", !!window?.matchMedia?.("(prefers-color-scheme: dark)").matches); + } +} +class CSSConstants { + static get commentForegroundColor() { + const element = document.createElement("span"); + element.classList.add("comment", "sidebar"); + const { + style + } = element; + style.width = style.height = "0"; + style.display = "none"; + style.color = "var(--comment-fg-color)"; + document.body.append(element); + const { + color + } = window.getComputedStyle(element); + element.remove(); + return shadow(this, "commentForegroundColor", getRGB(color)); + } +} +function applyOpacity(r, g, b, opacity) { + opacity = MathClamp(opacity ?? 1, 0, 1); + const white = 255 * (1 - opacity); + r = Math.round(r * opacity + white); + g = Math.round(g * opacity + white); + b = Math.round(b * opacity + white); + return [r, g, b]; +} +function RGBToHSL(rgb, output) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + const l = (max + min) / 2; + if (max === min) { + output[0] = output[1] = 0; + } else { + const d = max - min; + output[1] = l < 0.5 ? d / (max + min) : d / (2 - max - min); + switch (max) { + case r: + output[0] = ((g - b) / d + (g < b ? 6 : 0)) * 60; + break; + case g: + output[0] = ((b - r) / d + 2) * 60; + break; + case b: + output[0] = ((r - g) / d + 4) * 60; + break; + } + } + output[2] = l; +} +function HSLToRGB(hsl, output) { + const h = hsl[0]; + const s = hsl[1]; + const l = hsl[2]; + const c = (1 - Math.abs(2 * l - 1)) * s; + const x = c * (1 - Math.abs(h / 60 % 2 - 1)); + const m = l - c / 2; + switch (Math.floor(h / 60)) { + case 0: + output[0] = c + m; + output[1] = x + m; + output[2] = m; + break; + case 1: + output[0] = x + m; + output[1] = c + m; + output[2] = m; + break; + case 2: + output[0] = m; + output[1] = c + m; + output[2] = x + m; + break; + case 3: + output[0] = m; + output[1] = x + m; + output[2] = c + m; + break; + case 4: + output[0] = x + m; + output[1] = m; + output[2] = c + m; + break; + case 5: + case 6: + output[0] = c + m; + output[1] = m; + output[2] = x + m; + break; + } +} +function computeLuminance(x) { + return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4; +} +function contrastRatio(hsl1, hsl2, output) { + HSLToRGB(hsl1, output); + output.map(computeLuminance); + const lum1 = 0.2126 * output[0] + 0.7152 * output[1] + 0.0722 * output[2]; + HSLToRGB(hsl2, output); + output.map(computeLuminance); + const lum2 = 0.2126 * output[0] + 0.7152 * output[1] + 0.0722 * output[2]; + return lum1 > lum2 ? (lum1 + 0.05) / (lum2 + 0.05) : (lum2 + 0.05) / (lum1 + 0.05); +} +const contrastCache = new Map(); +function findContrastColor(baseColor, fixedColor) { + const key = baseColor[0] + baseColor[1] * 0x100 + baseColor[2] * 0x10000 + fixedColor[0] * 0x1000000 + fixedColor[1] * 0x100000000 + fixedColor[2] * 0x10000000000; + let cachedValue = contrastCache.get(key); + if (cachedValue) { + return cachedValue; + } + const array = new Float32Array(9); + const output = array.subarray(0, 3); + const baseHSL = array.subarray(3, 6); + RGBToHSL(baseColor, baseHSL); + const fixedHSL = array.subarray(6, 9); + RGBToHSL(fixedColor, fixedHSL); + const isFixedColorDark = fixedHSL[2] < 0.5; + const minContrast = isFixedColorDark ? 12 : 4.5; + baseHSL[2] = isFixedColorDark ? Math.sqrt(baseHSL[2]) : 1 - Math.sqrt(1 - baseHSL[2]); + if (contrastRatio(baseHSL, fixedHSL, output) < minContrast) { + let start, end; + if (isFixedColorDark) { + start = baseHSL[2]; + end = 1; + } else { + start = 0; + end = baseHSL[2]; + } + const PRECISION = 0.005; + while (end - start > PRECISION) { + const mid = baseHSL[2] = (start + end) / 2; + if (isFixedColorDark === contrastRatio(baseHSL, fixedHSL, output) < minContrast) { + start = mid; + } else { + end = mid; + } + } + baseHSL[2] = isFixedColorDark ? end : start; + } + HSLToRGB(baseHSL, output); + cachedValue = Util.makeHexColor(Math.round(output[0] * 255), Math.round(output[1] * 255), Math.round(output[2] * 255)); + contrastCache.set(key, cachedValue); + return cachedValue; +} +function renderRichText({ + html, + dir, + className +}, container) { + const fragment = document.createDocumentFragment(); + if (typeof html === "string") { + const p = document.createElement("p"); + p.dir = dir || "auto"; + const lines = html.split(/(?:\r\n?|\n)/); + for (let i = 0, ii = lines.length; i < ii; ++i) { + const line = lines[i]; + p.append(document.createTextNode(line)); + if (i < ii - 1) { + p.append(document.createElement("br")); + } + } + fragment.append(p); + } else { + XfaLayer.render({ + xfaHtml: html, + div: fragment, + intent: "richText" + }); + } + fragment.firstElementChild.classList.add("richText", className); + container.append(fragment); +} +function makePathFromDrawOPS(data) { + const path = new Path2D(); + if (!data) { + return path; + } + for (let i = 0, ii = data.length; i < ii;) { + switch (data[i++]) { + case DrawOPS.moveTo: + path.moveTo(data[i++], data[i++]); + break; + case DrawOPS.lineTo: + path.lineTo(data[i++], data[i++]); + break; + case DrawOPS.curveTo: + path.bezierCurveTo(data[i++], data[i++], data[i++], data[i++], data[i++], data[i++]); + break; + case DrawOPS.quadraticCurveTo: + path.quadraticCurveTo(data[i++], data[i++], data[i++], data[i++]); + break; + case DrawOPS.closePath: + path.closePath(); + break; + default: + warn(`Unrecognized drawing path operator: ${data[i - 1]}`); + break; + } + } + return path; +} +class PagesMapper { + #idToPageNumber = null; + #pageNumberToId = null; + #prevPageNumbers = null; + #pagesNumber = 0; + #listeners = []; + #copiedPageIds = null; + #copiedPageNumbers = null; + get pagesNumber() { + return this.#pagesNumber; + } + set pagesNumber(n) { + if (this.#pagesNumber === n) { + return; + } + this.#pagesNumber = n; + this.#reset(); + } + #reset() { + this.#pageNumberToId = null; + this.#idToPageNumber = null; + } + addListener(listener) { + this.#listeners.push(listener); + } + removeListener(listener) { + const index = this.#listeners.indexOf(listener); + if (index >= 0) { + this.#listeners.splice(index, 1); + } + } + #updateListeners(data) { + for (const listener of this.#listeners) { + listener(data); + } + } + #init(mustInit) { + if (this.#pageNumberToId) { + return; + } + const n = this.#pagesNumber; + const pageNumberToId = this.#pageNumberToId = new Uint32Array(n); + this.#prevPageNumbers = new Int32Array(pageNumberToId); + const idToPageNumber = this.#idToPageNumber = new Map(); + if (mustInit) { + for (let i = 1; i <= n; i++) { + pageNumberToId[i - 1] = i; + idToPageNumber.set(i, [i]); + } + } + } + #updateIdToPageNumber() { + const idToPageNumber = this.#idToPageNumber; + const pageNumberToId = this.#pageNumberToId; + idToPageNumber.clear(); + for (let i = 0, ii = this.#pagesNumber; i < ii; i++) { + const id = pageNumberToId[i]; + const pageNumbers = idToPageNumber.get(id); + if (pageNumbers) { + pageNumbers.push(i + 1); + } else { + idToPageNumber.set(id, [i + 1]); + } + } + } + movePages(selectedPages, pagesToMove, index) { + this.#init(true); + const pageNumberToId = this.#pageNumberToId; + const idToPageNumber = this.#idToPageNumber; + const movedCount = pagesToMove.length; + const mappedPagesToMove = new Uint32Array(movedCount); + let removedBeforeTarget = 0; + for (let i = 0; i < movedCount; i++) { + const pageIndex = pagesToMove[i] - 1; + mappedPagesToMove[i] = pageNumberToId[pageIndex]; + if (pageIndex < index) { + removedBeforeTarget += 1; + } + } + const pagesNumber = this.#pagesNumber; + let adjustedTarget = index - removedBeforeTarget; + const remainingLen = pagesNumber - movedCount; + adjustedTarget = MathClamp(adjustedTarget, 0, remainingLen); + for (let i = 0, r = 0; i < pagesNumber; i++) { + if (!selectedPages.has(i + 1)) { + pageNumberToId[r++] = pageNumberToId[i]; + } + } + pageNumberToId.copyWithin(adjustedTarget + movedCount, adjustedTarget, remainingLen); + pageNumberToId.set(mappedPagesToMove, adjustedTarget); + this.#setPrevPageNumbers(idToPageNumber, null); + this.#updateIdToPageNumber(); + this.#updateListeners({ + type: "move" + }); + if (pageNumberToId.every((id, i) => id === i + 1)) { + this.#reset(); + } + } + deletePages(pagesToDelete) { + this.#init(true); + const pageNumberToId = this.#pageNumberToId; + const prevIdToPageNumber = this.#idToPageNumber; + this.pagesNumber -= pagesToDelete.length; + this.#init(false); + const newPageNumberToId = this.#pageNumberToId; + let sourceIndex = 0; + let destIndex = 0; + for (const pageNumber of pagesToDelete) { + const pageIndex = pageNumber - 1; + if (pageIndex !== sourceIndex) { + newPageNumberToId.set(pageNumberToId.subarray(sourceIndex, pageIndex), destIndex); + destIndex += pageIndex - sourceIndex; + } + sourceIndex = pageIndex + 1; + } + if (sourceIndex < pageNumberToId.length) { + newPageNumberToId.set(pageNumberToId.subarray(sourceIndex), destIndex); + } + this.#setPrevPageNumbers(prevIdToPageNumber, null); + this.#updateIdToPageNumber(); + this.#updateListeners({ + type: "delete", + pageNumbers: pagesToDelete + }); + } + copyPages(pagesToCopy) { + this.#init(true); + this.#copiedPageNumbers = pagesToCopy; + this.#copiedPageIds = pagesToCopy.map(pageNumber => this.#pageNumberToId[pageNumber - 1]); + this.#updateListeners({ + type: "copy", + pageNumbers: pagesToCopy + }); + } + pastePages(index) { + this.#init(true); + const pageNumberToId = this.#pageNumberToId; + const prevIdToPageNumber = this.#idToPageNumber; + const copiedPageNumbers = this.#copiedPageNumbers; + const copiedPageMapping = new Map(); + let base = index; + for (const pageNumber of copiedPageNumbers) { + copiedPageMapping.set(++base, pageNumber); + } + this.pagesNumber += copiedPageNumbers.length; + this.#init(false); + const newPageNumberToId = this.#pageNumberToId; + newPageNumberToId.set(pageNumberToId.subarray(0, index), 0); + newPageNumberToId.set(this.#copiedPageIds, index); + newPageNumberToId.set(pageNumberToId.subarray(index), index + copiedPageNumbers.length); + this.#setPrevPageNumbers(prevIdToPageNumber, copiedPageMapping); + this.#updateIdToPageNumber(); + this.#updateListeners({ + type: "paste" + }); + this.#copiedPageIds = null; + } + #setPrevPageNumbers(prevIdToPageNumber, copiedPageMapping) { + const prevPageNumbers = this.#prevPageNumbers; + const newPageNumberToId = this.#pageNumberToId; + const idsIndices = new Map(); + for (let i = 0, ii = this.#pagesNumber; i < ii; i++) { + const oldPageNumber = copiedPageMapping?.get(i + 1); + if (oldPageNumber) { + prevPageNumbers[i] = -oldPageNumber; + continue; + } + const id = newPageNumberToId[i]; + const j = idsIndices.get(id) || 0; + prevPageNumbers[i] = prevIdToPageNumber.get(id)?.[j]; + idsIndices.set(id, j + 1); + } + } + hasBeenAltered() { + return this.#pageNumberToId !== null; + } + getPageMappingForSaving() { + const idToPageNumber = this.#idToPageNumber; + let nCopy = 0; + for (const pageNumbers of idToPageNumber.values()) { + nCopy = Math.max(nCopy, pageNumbers.length); + } + const extractParams = new Array(nCopy); + for (let i = 0; i < nCopy; i++) { + extractParams[i] = { + document: null, + pageIndices: [], + includePages: [] + }; + } + for (const [id, pageNumbers] of idToPageNumber) { + for (let i = 0, ii = pageNumbers.length; i < ii; i++) { + extractParams[i].includePages.push([id - 1, pageNumbers[i] - 1]); + } + } + for (const { + includePages, + pageIndices + } of extractParams) { + includePages.sort((a, b) => a[0] - b[0]); + for (let i = 0, ii = includePages.length; i < ii; i++) { + pageIndices.push(includePages[i][1]); + includePages[i] = includePages[i][0]; + } + } + return extractParams; + } + getPrevPageNumber(pageNumber) { + return this.#prevPageNumbers[pageNumber - 1] ?? 0; + } + getPageNumber(id) { + return this.#idToPageNumber ? this.#idToPageNumber.get(id)?.[0] ?? 0 : id; + } + getPageId(pageNumber) { + return this.#pageNumberToId?.[pageNumber - 1] ?? pageNumber; + } + getMapping() { + return this.#pageNumberToId.subarray(0, this.pagesNumber); + } +} + +;// ./src/display/editor/toolbar.js + +class EditorToolbar { + #toolbar = null; + #colorPicker = null; + #editor; + #buttons = null; + #altText = null; + #comment = null; + #commentButtonDivider = null; + #signatureDescriptionButton = null; + static #l10nRemove = null; + constructor(editor) { + this.#editor = editor; + EditorToolbar.#l10nRemove ||= Object.freeze({ + freetext: "pdfjs-editor-remove-freetext-button", + highlight: "pdfjs-editor-remove-highlight-button", + ink: "pdfjs-editor-remove-ink-button", + stamp: "pdfjs-editor-remove-stamp-button", + signature: "pdfjs-editor-remove-signature-button" + }); + } + render() { + const editToolbar = this.#toolbar = document.createElement("div"); + editToolbar.classList.add("editToolbar", "hidden"); + editToolbar.setAttribute("role", "toolbar"); + const signal = this.#editor._uiManager._signal; + if (signal instanceof AbortSignal && !signal.aborted) { + editToolbar.addEventListener("contextmenu", noContextMenu, { + signal + }); + editToolbar.addEventListener("pointerdown", EditorToolbar.#pointerDown, { + signal + }); + } + const buttons = this.#buttons = document.createElement("div"); + buttons.className = "buttons"; + editToolbar.append(buttons); + const position = this.#editor.toolbarPosition; + if (position) { + const { + style + } = editToolbar; + const x = this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0]; + style.insetInlineEnd = `${100 * x}%`; + style.top = `calc(${100 * position[1]}% + var(--editor-toolbar-vert-offset))`; + } + return editToolbar; + } + get div() { + return this.#toolbar; + } + static #pointerDown(e) { + e.stopPropagation(); + } + #focusIn(e) { + this.#editor._focusEventsAllowed = false; + stopEvent(e); + } + #focusOut(e) { + this.#editor._focusEventsAllowed = true; + stopEvent(e); + } + #addListenersToElement(element) { + const signal = this.#editor._uiManager._signal; + if (!(signal instanceof AbortSignal) || signal.aborted) { + return false; + } + element.addEventListener("focusin", this.#focusIn.bind(this), { + capture: true, + signal + }); + element.addEventListener("focusout", this.#focusOut.bind(this), { + capture: true, + signal + }); + element.addEventListener("contextmenu", noContextMenu, { + signal + }); + return true; + } + hide() { + this.#toolbar.classList.add("hidden"); + this.#colorPicker?.hideDropdown(); + } + show() { + this.#toolbar.classList.remove("hidden"); + this.#altText?.shown(); + this.#comment?.shown(); + } + addDeleteButton() { + const { + editorType, + _uiManager + } = this.#editor; + const button = document.createElement("button"); + button.classList.add("basic", "deleteButton"); + button.tabIndex = 0; + button.setAttribute("data-l10n-id", EditorToolbar.#l10nRemove[editorType]); + if (this.#addListenersToElement(button)) { + button.addEventListener("click", e => { + _uiManager.delete(); + }, { + signal: _uiManager._signal + }); + } + this.#buttons.append(button); + } + get #divider() { + const divider = document.createElement("div"); + divider.className = "divider"; + return divider; + } + async addAltText(altText) { + const button = await altText.render(); + this.#addListenersToElement(button); + this.#buttons.append(button, this.#divider); + this.#altText = altText; + } + addComment(comment, beforeElement = null) { + if (this.#comment) { + return; + } + const button = comment.renderForToolbar(); + if (!button) { + return; + } + this.#addListenersToElement(button); + const divider = this.#commentButtonDivider = this.#divider; + if (!beforeElement) { + this.#buttons.append(button, divider); + } else { + this.#buttons.insertBefore(button, beforeElement); + this.#buttons.insertBefore(divider, beforeElement); + } + this.#comment = comment; + comment.toolbar = this; + } + addColorPicker(colorPicker) { + if (this.#colorPicker) { + return; + } + this.#colorPicker = colorPicker; + const button = colorPicker.renderButton(); + this.#addListenersToElement(button); + this.#buttons.append(button, this.#divider); + } + async addEditSignatureButton(signatureManager) { + const button = this.#signatureDescriptionButton = await signatureManager.renderEditButton(this.#editor); + this.#addListenersToElement(button); + this.#buttons.append(button, this.#divider); + } + removeButton(name) { + switch (name) { + case "comment": + this.#comment?.removeToolbarCommentButton(); + this.#comment = null; + this.#commentButtonDivider?.remove(); + this.#commentButtonDivider = null; + break; + } + } + async addButton(name, tool) { + switch (name) { + case "colorPicker": + if (tool) { + this.addColorPicker(tool); + } + break; + case "altText": + if (tool) { + await this.addAltText(tool); + } + break; + case "editSignature": + if (tool) { + await this.addEditSignatureButton(tool); + } + break; + case "delete": + this.addDeleteButton(); + break; + case "comment": + if (tool) { + this.addComment(tool); + } + break; + } + } + async addButtonBefore(name, tool, beforeSelector) { + if (!tool && name === "comment") { + return; + } + const beforeElement = this.#buttons.querySelector(beforeSelector); + if (!beforeElement) { + return; + } + if (name === "comment") { + this.addComment(tool, beforeElement); + } + } + updateEditSignatureButton(description) { + if (this.#signatureDescriptionButton) { + this.#signatureDescriptionButton.title = description; + } + } + remove() { + this.#toolbar.remove(); + this.#colorPicker?.destroy(); + this.#colorPicker = null; + } +} +class FloatingToolbar { + #buttons = null; + #toolbar = null; + #uiManager; + constructor(uiManager) { + this.#uiManager = uiManager; + } + #render() { + const editToolbar = this.#toolbar = document.createElement("div"); + editToolbar.className = "editToolbar"; + editToolbar.setAttribute("role", "toolbar"); + const signal = this.#uiManager._signal; + if (signal instanceof AbortSignal && !signal.aborted) { + editToolbar.addEventListener("contextmenu", noContextMenu, { + signal + }); + } + const buttons = this.#buttons = document.createElement("div"); + buttons.className = "buttons"; + editToolbar.append(buttons); + if (this.#uiManager.hasCommentManager()) { + this.#makeButton("commentButton", `pdfjs-comment-floating-button`, "pdfjs-comment-floating-button-label", () => { + this.#uiManager.commentSelection("floating_button"); + }); + } + this.#makeButton("highlightButton", `pdfjs-highlight-floating-button1`, "pdfjs-highlight-floating-button-label", () => { + this.#uiManager.highlightSelection("floating_button"); + }); + return editToolbar; + } + #getLastPoint(boxes, isLTR) { + let lastY = 0; + let lastX = 0; + for (const box of boxes) { + const y = box.y + box.height; + if (y < lastY) { + continue; + } + const x = box.x + (isLTR ? box.width : 0); + if (y > lastY) { + lastX = x; + lastY = y; + continue; + } + if (isLTR) { + if (x > lastX) { + lastX = x; + } + } else if (x < lastX) { + lastX = x; + } + } + return [isLTR ? 1 - lastX : lastX, lastY]; + } + show(parent, boxes, isLTR) { + const [x, y] = this.#getLastPoint(boxes, isLTR); + const { + style + } = this.#toolbar ||= this.#render(); + parent.append(this.#toolbar); + style.insetInlineEnd = `${100 * x}%`; + style.top = `calc(${100 * y}% + var(--editor-toolbar-vert-offset))`; + } + hide() { + this.#toolbar.remove(); + } + #makeButton(buttonClass, l10nId, labelL10nId, clickHandler) { + const button = document.createElement("button"); + button.classList.add("basic", buttonClass); + button.tabIndex = 0; + button.setAttribute("data-l10n-id", l10nId); + const span = document.createElement("span"); + button.append(span); + span.className = "visuallyHidden"; + span.setAttribute("data-l10n-id", labelL10nId); + const signal = this.#uiManager._signal; + if (signal instanceof AbortSignal && !signal.aborted) { + button.addEventListener("contextmenu", noContextMenu, { + signal + }); + button.addEventListener("click", clickHandler, { + signal + }); + } + this.#buttons.append(button); + } +} + +;// ./src/display/editor/tools.js + + + +function bindEvents(obj, element, names) { + for (const name of names) { + element.addEventListener(name, obj[name].bind(obj)); + } +} +class CurrentPointers { + static #pointerId = NaN; + static #pointerIds = null; + static #moveTimestamp = NaN; + static #pointerType = null; + static initializeAndAddPointerId(pointerId) { + (CurrentPointers.#pointerIds ||= new Set()).add(pointerId); + } + static setPointer(pointerType, pointerId) { + CurrentPointers.#pointerId ||= pointerId; + CurrentPointers.#pointerType ??= pointerType; + } + static setTimeStamp(timeStamp) { + CurrentPointers.#moveTimestamp = timeStamp; + } + static isSamePointerId(pointerId) { + return CurrentPointers.#pointerId === pointerId; + } + static isSamePointerIdOrRemove(pointerId) { + if (CurrentPointers.#pointerId === pointerId) { + return true; + } + CurrentPointers.#pointerIds?.delete(pointerId); + return false; + } + static isSamePointerType(pointerType) { + return CurrentPointers.#pointerType === pointerType; + } + static isInitializedAndDifferentPointerType(pointerType) { + return CurrentPointers.#pointerType !== null && !CurrentPointers.isSamePointerType(pointerType); + } + static isSameTimeStamp(timeStamp) { + return CurrentPointers.#moveTimestamp === timeStamp; + } + static isUsingMultiplePointers() { + return CurrentPointers.#pointerIds?.size >= 1; + } + static clearPointerType() { + CurrentPointers.#pointerType = null; + } + static clearPointerIds() { + CurrentPointers.#pointerId = NaN; + CurrentPointers.#pointerIds = null; + } + static clearTimeStamp() { + CurrentPointers.#moveTimestamp = NaN; + } +} +class IdManager { + #id = 0; + get id() { + return `${AnnotationEditorPrefix}${this.#id++}`; + } +} +class ImageManager { + #baseId = getUuid(); + #id = 0; + #cache = null; + static get _isSVGFittingCanvas() { + const svg = `data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>`; + const canvas = new OffscreenCanvas(1, 3); + const ctx = canvas.getContext("2d", { + willReadFrequently: true + }); + const image = new Image(); + image.src = svg; + const promise = image.decode().then(() => { + ctx.drawImage(image, 0, 0, 1, 1, 0, 0, 1, 3); + return new Uint32Array(ctx.getImageData(0, 0, 1, 1).data.buffer)[0] === 0; + }); + return shadow(this, "_isSVGFittingCanvas", promise); + } + async #get(key, rawData) { + this.#cache ||= new Map(); + let data = this.#cache.get(key); + if (data === null) { + return null; + } + if (data?.bitmap) { + data.refCounter += 1; + return data; + } + try { + data ||= { + bitmap: null, + id: `image_${this.#baseId}_${this.#id++}`, + refCounter: 0, + isSvg: false + }; + let image; + if (typeof rawData === "string") { + data.url = rawData; + image = await fetchData(rawData, "blob"); + } else if (rawData instanceof File) { + image = data.file = rawData; + } else if (rawData instanceof Blob) { + image = rawData; + } + if (image.type === "image/svg+xml") { + const mustRemoveAspectRatioPromise = ImageManager._isSVGFittingCanvas; + const fileReader = new FileReader(); + const imageElement = new Image(); + const imagePromise = new Promise((resolve, reject) => { + imageElement.onload = () => { + data.bitmap = imageElement; + data.isSvg = true; + resolve(); + }; + fileReader.onload = async () => { + const url = data.svgUrl = fileReader.result; + imageElement.src = (await mustRemoveAspectRatioPromise) ? `${url}#svgView(preserveAspectRatio(none))` : url; + }; + imageElement.onerror = fileReader.onerror = reject; + }); + fileReader.readAsDataURL(image); + await imagePromise; + } else { + data.bitmap = await createImageBitmap(image); + } + data.refCounter = 1; + } catch (e) { + warn(e); + data = null; + } + this.#cache.set(key, data); + if (data) { + this.#cache.set(data.id, data); + } + return data; + } + async getFromFile(file) { + const { + lastModified, + name, + size, + type + } = file; + return this.#get(`${lastModified}_${name}_${size}_${type}`, file); + } + async getFromUrl(url) { + return this.#get(url, url); + } + async getFromBlob(id, blobPromise) { + const blob = await blobPromise; + return this.#get(id, blob); + } + async getFromId(id) { + this.#cache ||= new Map(); + const data = this.#cache.get(id); + if (!data) { + return null; + } + if (data.bitmap) { + data.refCounter += 1; + return data; + } + if (data.file) { + return this.getFromFile(data.file); + } + if (data.blobPromise) { + const { + blobPromise + } = data; + delete data.blobPromise; + return this.getFromBlob(data.id, blobPromise); + } + return this.getFromUrl(data.url); + } + getFromCanvas(id, canvas) { + this.#cache ||= new Map(); + let data = this.#cache.get(id); + if (data?.bitmap) { + data.refCounter += 1; + return data; + } + const offscreen = new OffscreenCanvas(canvas.width, canvas.height); + const ctx = offscreen.getContext("2d"); + ctx.drawImage(canvas, 0, 0); + data = { + bitmap: offscreen.transferToImageBitmap(), + id: `image_${this.#baseId}_${this.#id++}`, + refCounter: 1, + isSvg: false + }; + this.#cache.set(id, data); + this.#cache.set(data.id, data); + return data; + } + getSvgUrl(id) { + const data = this.#cache.get(id); + if (!data?.isSvg) { + return null; + } + return data.svgUrl; + } + deleteId(id) { + this.#cache ||= new Map(); + const data = this.#cache.get(id); + if (!data) { + return; + } + data.refCounter -= 1; + if (data.refCounter !== 0) { + return; + } + const { + bitmap + } = data; + if (!data.url && !data.file) { + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); + const ctx = canvas.getContext("bitmaprenderer"); + ctx.transferFromImageBitmap(bitmap); + data.blobPromise = canvas.convertToBlob(); + } + bitmap.close?.(); + data.bitmap = null; + } + isValidId(id) { + return id.startsWith(`image_${this.#baseId}_`); + } +} +class CommandManager { + #commands = []; + #locked = false; + #maxSize; + #position = -1; + constructor(maxSize = 128) { + this.#maxSize = maxSize; + } + add({ + cmd, + undo, + post, + mustExec, + type = NaN, + overwriteIfSameType = false, + keepUndo = false + }) { + if (mustExec) { + cmd(); + } + if (this.#locked) { + return; + } + const save = { + cmd, + undo, + post, + type + }; + if (this.#position === -1) { + if (this.#commands.length > 0) { + this.#commands.length = 0; + } + this.#position = 0; + this.#commands.push(save); + return; + } + if (overwriteIfSameType && this.#commands[this.#position].type === type) { + if (keepUndo) { + save.undo = this.#commands[this.#position].undo; + } + this.#commands[this.#position] = save; + return; + } + const next = this.#position + 1; + if (next === this.#maxSize) { + this.#commands.splice(0, 1); + } else { + this.#position = next; + if (next < this.#commands.length) { + this.#commands.splice(next); + } + } + this.#commands.push(save); + } + undo() { + if (this.#position === -1) { + return; + } + this.#locked = true; + const { + undo, + post + } = this.#commands[this.#position]; + undo(); + post?.(); + this.#locked = false; + this.#position -= 1; + } + redo() { + if (this.#position < this.#commands.length - 1) { + this.#position += 1; + this.#locked = true; + const { + cmd, + post + } = this.#commands[this.#position]; + cmd(); + post?.(); + this.#locked = false; + } + } + hasSomethingToUndo() { + return this.#position !== -1; + } + hasSomethingToRedo() { + return this.#position < this.#commands.length - 1; + } + cleanType(type) { + if (this.#position === -1) { + return; + } + for (let i = this.#position; i >= 0; i--) { + if (this.#commands[i].type !== type) { + this.#commands.splice(i + 1, this.#position - i); + this.#position = i; + return; + } + } + this.#commands.length = 0; + this.#position = -1; + } + destroy() { + this.#commands = null; + } +} +class KeyboardManager { + constructor(callbacks) { + this.buffer = []; + this.callbacks = new Map(); + this.allKeys = new Set(); + const { + isMac + } = FeatureTest.platform; + for (const [keys, callback, options = {}] of callbacks) { + for (const key of keys) { + const isMacKey = key.startsWith("mac+"); + if (isMac && isMacKey) { + this.callbacks.set(key.slice(4), { + callback, + options + }); + this.allKeys.add(key.split("+").at(-1)); + } else if (!isMac && !isMacKey) { + this.callbacks.set(key, { + callback, + options + }); + this.allKeys.add(key.split("+").at(-1)); + } + } + } + } + #serialize(event) { + if (event.altKey) { + this.buffer.push("alt"); + } + if (event.ctrlKey) { + this.buffer.push("ctrl"); + } + if (event.metaKey) { + this.buffer.push("meta"); + } + if (event.shiftKey) { + this.buffer.push("shift"); + } + this.buffer.push(event.key); + const str = this.buffer.join("+"); + this.buffer.length = 0; + return str; + } + exec(self, event) { + if (!this.allKeys.has(event.key)) { + return; + } + const info = this.callbacks.get(this.#serialize(event)); + if (!info) { + return; + } + const { + callback, + options: { + bubbles = false, + args = [], + checker = null + } + } = info; + if (checker && !checker(self, event)) { + return; + } + callback.bind(self, ...args, event)(); + if (!bubbles) { + stopEvent(event); + } + } +} +class ColorManager { + static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]); + get _colors() { + const colors = new Map([["CanvasText", null], ["Canvas", null]]); + getColorValues(colors); + return shadow(this, "_colors", colors); + } + convert(color) { + const rgb = getRGB(color); + if (!window.matchMedia("(forced-colors: active)").matches) { + return rgb; + } + for (const [name, RGB] of this._colors) { + if (RGB.every((x, i) => x === rgb[i])) { + return ColorManager._colorsMapping.get(name); + } + } + return rgb; + } + getHexCode(name) { + const rgb = this._colors.get(name); + if (!rgb) { + return name; + } + return Util.makeHexColor(...rgb); + } +} +class AnnotationEditorUIManager { + #abortController = new AbortController(); + #activeEditor = null; + #allEditableAnnotations = null; + #allEditors = new Map(); + #allLayers = new Map(); + #altTextManager = null; + #annotationStorage = null; + #changedExistingAnnotations = null; + #commandManager = new CommandManager(); + #commentManager = null; + #copyPasteAC = null; + #currentDrawingSession = null; + #currentPageIndex = 0; + #deletedAnnotationsElementIds = new Set(); + #draggingEditors = null; + #editorTypes = null; + #editorsToRescale = new Set(); + _editorUndoBar = null; + #enableHighlightFloatingButton = false; + #enableUpdatedAddImage = false; + #enableNewAltTextWhenAddingImage = false; + #filterFactory = null; + #focusMainContainerTimeoutId = null; + #focusManagerAC = null; + #highlightColors = null; + #highlightWhenShiftUp = false; + #floatingToolbar = null; + #idManager = new IdManager(); + #isEnabled = false; + #isPointerDown = false; + #isWaiting = false; + #keyboardManagerAC = null; + #lastActiveElement = null; + #mainHighlightColorPicker = null; + #missingCanvases = null; + #mlManager = null; + #mode = AnnotationEditorType.NONE; + #selectedEditors = new Set(); + #selectedTextNode = null; + #signatureManager = null; + #pageColors = null; + #showAllStates = null; + #pdfDocument = null; + #previousStates = { + isEditing: false, + isEmpty: true, + hasSomethingToUndo: false, + hasSomethingToRedo: false, + hasSelectedEditor: false, + hasSelectedText: false + }; + #translation = [0, 0]; + #translationTimeoutId = null; + #container = null; + #viewer = null; + #viewerAlert = null; + #updateModeCapability = null; + static TRANSLATE_SMALL = 1; + static TRANSLATE_BIG = 10; + static get _keyboardManager() { + const proto = AnnotationEditorUIManager.prototype; + const arrowChecker = self => self.#container.contains(document.activeElement) && document.activeElement.tagName !== "BUTTON" && self.hasSomethingToControl(); + const textInputChecker = (_self, { + target: el + }) => { + if (el instanceof HTMLInputElement) { + const { + type + } = el; + return type !== "text" && type !== "number"; + } + return true; + }; + const small = this.TRANSLATE_SMALL; + const big = this.TRANSLATE_BIG; + return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+a", "mac+meta+a"], proto.selectAll, { + checker: textInputChecker + }], [["ctrl+z", "mac+meta+z"], proto.undo, { + checker: textInputChecker + }], [["ctrl+y", "ctrl+shift+z", "mac+meta+shift+z", "ctrl+shift+Z", "mac+meta+shift+Z"], proto.redo, { + checker: textInputChecker + }], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete", "mac+Delete"], proto.delete, { + checker: textInputChecker + }], [["Enter", "mac+Enter"], proto.addNewEditorFromKeyboard, { + checker: (self, { + target: el + }) => !(el instanceof HTMLButtonElement) && self.#container.contains(el) && !self.isEnterHandled + }], [[" ", "mac+ "], proto.addNewEditorFromKeyboard, { + checker: (self, { + target: el + }) => !(el instanceof HTMLButtonElement) && self.#container.contains(document.activeElement) + }], [["Escape", "mac+Escape"], proto.unselectAll], [["ArrowLeft", "mac+ArrowLeft"], proto.translateSelectedEditors, { + args: [-small, 0], + checker: arrowChecker + }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto.translateSelectedEditors, { + args: [-big, 0], + checker: arrowChecker + }], [["ArrowRight", "mac+ArrowRight"], proto.translateSelectedEditors, { + args: [small, 0], + checker: arrowChecker + }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto.translateSelectedEditors, { + args: [big, 0], + checker: arrowChecker + }], [["ArrowUp", "mac+ArrowUp"], proto.translateSelectedEditors, { + args: [0, -small], + checker: arrowChecker + }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto.translateSelectedEditors, { + args: [0, -big], + checker: arrowChecker + }], [["ArrowDown", "mac+ArrowDown"], proto.translateSelectedEditors, { + args: [0, small], + checker: arrowChecker + }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto.translateSelectedEditors, { + args: [0, big], + checker: arrowChecker + }]])); + } + constructor(container, viewer, viewerAlert, altTextManager, commentManager, signatureManager, eventBus, pdfDocument, pageColors, highlightColors, enableHighlightFloatingButton, enableUpdatedAddImage, enableNewAltTextWhenAddingImage, mlManager, editorUndoBar, supportsPinchToZoom) { + const signal = this._signal = this.#abortController.signal; + this.#container = container; + this.#viewer = viewer; + this.#viewerAlert = viewerAlert; + this.#altTextManager = altTextManager; + this.#commentManager = commentManager; + this.#signatureManager = signatureManager; + this.#pdfDocument = pdfDocument; + this._eventBus = eventBus; + eventBus._on("editingaction", this.onEditingAction.bind(this), { + signal + }); + eventBus._on("pagechanging", this.onPageChanging.bind(this), { + signal + }); + eventBus._on("scalechanging", this.onScaleChanging.bind(this), { + signal + }); + eventBus._on("rotationchanging", this.onRotationChanging.bind(this), { + signal + }); + eventBus._on("setpreference", this.onSetPreference.bind(this), { + signal + }); + eventBus._on("switchannotationeditorparams", evt => this.updateParams(evt.type, evt.value), { + signal + }); + window.addEventListener("pointerdown", () => { + this.#isPointerDown = true; + }, { + capture: true, + signal + }); + window.addEventListener("pointerup", () => { + this.#isPointerDown = false; + }, { + capture: true, + signal + }); + window.addEventListener("beforeunload", this.#beforeUnload.bind(this), { + capture: true, + signal + }); + this.#addSelectionListener(); + this.#addDragAndDropListeners(); + this.#addKeyboardManager(); + this.#annotationStorage = pdfDocument.annotationStorage; + this.#filterFactory = pdfDocument.filterFactory; + this.#pageColors = pageColors; + this.#highlightColors = highlightColors || null; + this.#enableHighlightFloatingButton = enableHighlightFloatingButton; + this.#enableUpdatedAddImage = enableUpdatedAddImage; + this.#enableNewAltTextWhenAddingImage = enableNewAltTextWhenAddingImage; + this.#mlManager = mlManager || null; + this.viewParameters = { + realScale: PixelsPerInch.PDF_TO_CSS_UNITS, + rotation: 0 + }; + this.isShiftKeyDown = false; + this._editorUndoBar = editorUndoBar || null; + this._supportsPinchToZoom = supportsPinchToZoom !== false; + commentManager?.setSidebarUiManager(this); + } + destroy() { + this.#updateModeCapability?.resolve(); + this.#updateModeCapability = null; + this.#abortController?.abort(); + this.#abortController = null; + this._signal = null; + for (const layer of this.#allLayers.values()) { + layer.destroy(); + } + this.#allLayers.clear(); + this.#allEditors.clear(); + this.#editorsToRescale.clear(); + this.#missingCanvases?.clear(); + this.#activeEditor = null; + this.#selectedEditors.clear(); + this.#commandManager.destroy(); + this.#altTextManager?.destroy(); + this.#commentManager?.destroy(); + this.#signatureManager?.destroy(); + this.#floatingToolbar?.hide(); + this.#floatingToolbar = null; + this.#mainHighlightColorPicker?.destroy(); + this.#mainHighlightColorPicker = null; + this.#allEditableAnnotations = null; + if (this.#focusMainContainerTimeoutId) { + clearTimeout(this.#focusMainContainerTimeoutId); + this.#focusMainContainerTimeoutId = null; + } + if (this.#translationTimeoutId) { + clearTimeout(this.#translationTimeoutId); + this.#translationTimeoutId = null; + } + this._editorUndoBar?.destroy(); + this.#pdfDocument = null; + } + combinedSignal(ac) { + return AbortSignal.any([this._signal, ac.signal]); + } + get mlManager() { + return this.#mlManager; + } + get useNewAltTextFlow() { + return this.#enableUpdatedAddImage; + } + get useNewAltTextWhenAddingImage() { + return this.#enableNewAltTextWhenAddingImage; + } + get hcmFilter() { + return shadow(this, "hcmFilter", this.#pageColors ? this.#filterFactory.addHCMFilter(this.#pageColors.foreground, this.#pageColors.background) : "none"); + } + get direction() { + return shadow(this, "direction", getComputedStyle(this.#container).direction); + } + get _highlightColors() { + return shadow(this, "_highlightColors", this.#highlightColors ? new Map(this.#highlightColors.split(",").map(pair => { + pair = pair.split("=").map(x => x.trim()); + pair[1] = pair[1].toUpperCase(); + return pair; + })) : null); + } + get highlightColors() { + const { + _highlightColors + } = this; + if (!_highlightColors) { + return shadow(this, "highlightColors", null); + } + const map = new Map(); + const hasHCM = !!this.#pageColors; + for (const [name, color] of _highlightColors) { + const isNameForHCM = name.endsWith("_HCM"); + if (hasHCM && isNameForHCM) { + map.set(name.replace("_HCM", ""), color); + continue; + } + if (!hasHCM && !isNameForHCM) { + map.set(name, color); + } + } + return shadow(this, "highlightColors", map); + } + get highlightColorNames() { + return shadow(this, "highlightColorNames", this.highlightColors ? new Map(Array.from(this.highlightColors, e => e.reverse())) : null); + } + getNonHCMColor(color) { + if (!this._highlightColors) { + return color; + } + const colorName = this.highlightColorNames.get(color); + return this._highlightColors.get(colorName) || color; + } + getNonHCMColorName(color) { + return this.highlightColorNames.get(color) || color; + } + setCurrentDrawingSession(layer) { + if (layer) { + this.unselectAll(); + this.disableUserSelect(true); + } else { + this.disableUserSelect(false); + } + this.#currentDrawingSession = layer; + } + setMainHighlightColorPicker(colorPicker) { + this.#mainHighlightColorPicker = colorPicker; + } + editAltText(editor, firstTime = false) { + this.#altTextManager?.editAltText(this, editor, firstTime); + } + hasCommentManager() { + return !!this.#commentManager; + } + editComment(editor, posX, posY, options) { + this.#commentManager?.showDialog(this, editor, posX, posY, options); + } + selectComment(pageIndex, uid) { + const layer = this.#allLayers.get(pageIndex); + const editor = layer?.getEditorByUID(uid); + editor?.toggleComment(true, true); + } + updateComment(editor) { + this.#commentManager?.updateComment(editor.getData()); + } + updatePopupColor(editor) { + this.#commentManager?.updatePopupColor(editor); + } + removeComment(editor) { + this.#commentManager?.removeComments([editor.uid]); + } + deleteComment(editor, savedData) { + const undo = () => { + editor.comment = savedData; + }; + const cmd = () => { + this._editorUndoBar?.show(undo, "comment"); + this.toggleComment(null); + editor.comment = null; + }; + this.addCommands({ + cmd, + undo, + mustExec: true + }); + } + toggleComment(editor, isSelected, visibility = undefined) { + this.#commentManager?.toggleCommentPopup(editor, isSelected, visibility); + } + makeCommentColor(color, opacity) { + return color && this.#commentManager?.makeCommentColor(color, opacity) || null; + } + getCommentDialogElement() { + return this.#commentManager?.dialogElement || null; + } + async waitForEditorsRendered(pageNumber) { + if (this.#allLayers.has(pageNumber - 1)) { + return; + } + const { + resolve, + promise + } = Promise.withResolvers(); + const onEditorsRendered = evt => { + if (evt.pageNumber === pageNumber) { + this._eventBus._off("editorsrendered", onEditorsRendered); + resolve(); + } + }; + this._eventBus.on("editorsrendered", onEditorsRendered); + await promise; + } + getSignature(editor) { + this.#signatureManager?.getSignature({ + uiManager: this, + editor + }); + } + get signatureManager() { + return this.#signatureManager; + } + switchToMode(mode, callback) { + this._eventBus.on("annotationeditormodechanged", callback, { + once: true, + signal: this._signal + }); + this._eventBus.dispatch("showannotationeditorui", { + source: this, + mode + }); + } + setPreference(name, value) { + this._eventBus.dispatch("setpreference", { + source: this, + name, + value + }); + } + onSetPreference({ + name, + value + }) { + switch (name) { + case "enableNewAltTextWhenAddingImage": + this.#enableNewAltTextWhenAddingImage = value; + break; + } + } + onPageChanging({ + pageNumber + }) { + this.#currentPageIndex = pageNumber - 1; + } + deletePage(id) { + for (const editor of this.getEditors(id)) { + editor.remove(); + } + this.#allLayers.delete(id); + if (this.#currentPageIndex === id) { + this.#currentPageIndex = 0; + } + } + focusMainContainer() { + this.#container.focus(); + } + findParent(x, y) { + for (const layer of this.#allLayers.values()) { + const { + x: layerX, + y: layerY, + width, + height + } = layer.div.getBoundingClientRect(); + if (x >= layerX && x <= layerX + width && y >= layerY && y <= layerY + height) { + return layer; + } + } + return null; + } + disableUserSelect(value = false) { + this.#viewer.classList.toggle("noUserSelect", value); + } + addShouldRescale(editor) { + this.#editorsToRescale.add(editor); + } + removeShouldRescale(editor) { + this.#editorsToRescale.delete(editor); + } + onScaleChanging({ + scale + }) { + this.commitOrRemove(); + this.viewParameters.realScale = scale * PixelsPerInch.PDF_TO_CSS_UNITS; + for (const editor of this.#editorsToRescale) { + editor.onScaleChanging(); + } + this.#currentDrawingSession?.onScaleChanging(); + } + onRotationChanging({ + pagesRotation + }) { + this.commitOrRemove(); + this.viewParameters.rotation = pagesRotation; + } + #getAnchorElementForSelection({ + anchorNode + }) { + return anchorNode.nodeType === Node.TEXT_NODE ? anchorNode.parentElement : anchorNode; + } + #getLayerForTextLayer(textLayer) { + const { + currentLayer + } = this; + if (currentLayer.hasTextLayer(textLayer)) { + return currentLayer; + } + for (const layer of this.#allLayers.values()) { + if (layer.hasTextLayer(textLayer)) { + return layer; + } + } + return null; + } + highlightSelection(methodOfCreation = "", comment = false) { + const selection = document.getSelection(); + if (!selection || selection.isCollapsed) { + return; + } + const { + anchorNode, + anchorOffset, + focusNode, + focusOffset + } = selection; + const text = selection.toString(); + const anchorElement = this.#getAnchorElementForSelection(selection); + const textLayer = anchorElement.closest(".textLayer"); + const boxes = this.getSelectionBoxes(textLayer); + if (!boxes) { + return; + } + selection.empty(); + const layer = this.#getLayerForTextLayer(textLayer); + const isNoneMode = this.#mode === AnnotationEditorType.NONE; + const callback = () => { + const editor = layer?.createAndAddNewEditor({ + x: 0, + y: 0 + }, false, { + methodOfCreation, + boxes, + anchorNode, + anchorOffset, + focusNode, + focusOffset, + text + }); + if (isNoneMode) { + this.showAllEditors("highlight", true, true); + } + if (comment) { + editor?.editComment(); + } + }; + if (isNoneMode) { + this.switchToMode(AnnotationEditorType.HIGHLIGHT, callback); + return; + } + callback(); + } + commentSelection(methodOfCreation = "") { + this.highlightSelection(methodOfCreation, true); + } + #beforeUnload(e) { + this.commitOrRemove(); + this.currentLayer?.endDrawingSession(false); + } + #displayFloatingToolbar() { + const selection = document.getSelection(); + if (!selection || selection.isCollapsed) { + return; + } + const anchorElement = this.#getAnchorElementForSelection(selection); + const textLayer = anchorElement.closest(".textLayer"); + const boxes = this.getSelectionBoxes(textLayer); + if (!boxes) { + return; + } + this.#floatingToolbar ||= new FloatingToolbar(this); + this.#floatingToolbar.show(textLayer, boxes, this.direction === "ltr"); + } + getAndRemoveDataFromAnnotationStorage(annotationId) { + if (!this.#annotationStorage) { + return null; + } + const key = `${AnnotationEditorPrefix}${annotationId}`; + const storedValue = this.#annotationStorage.getRawValue(key); + if (storedValue) { + this.#annotationStorage.remove(key); + } + return storedValue; + } + addToAnnotationStorage(editor) { + if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) { + this.#annotationStorage.setValue(editor.id, editor); + } + } + a11yAlert(messageId, args = null) { + const viewerAlert = this.#viewerAlert; + if (!viewerAlert) { + return; + } + viewerAlert.setAttribute("data-l10n-id", messageId); + if (args) { + viewerAlert.setAttribute("data-l10n-args", JSON.stringify(args)); + } else { + viewerAlert.removeAttribute("data-l10n-args"); + } + } + #selectionChange() { + const selection = document.getSelection(); + if (!selection || selection.isCollapsed) { + if (this.#selectedTextNode) { + this.#floatingToolbar?.hide(); + this.#selectedTextNode = null; + this.#dispatchUpdateStates({ + hasSelectedText: false + }); + } + return; + } + const { + anchorNode + } = selection; + if (anchorNode === this.#selectedTextNode) { + return; + } + const anchorElement = this.#getAnchorElementForSelection(selection); + const textLayer = anchorElement.closest(".textLayer"); + if (!textLayer) { + if (this.#selectedTextNode) { + this.#floatingToolbar?.hide(); + this.#selectedTextNode = null; + this.#dispatchUpdateStates({ + hasSelectedText: false + }); + } + return; + } + this.#floatingToolbar?.hide(); + this.#selectedTextNode = anchorNode; + this.#dispatchUpdateStates({ + hasSelectedText: true + }); + if (this.#mode !== AnnotationEditorType.HIGHLIGHT && this.#mode !== AnnotationEditorType.NONE) { + return; + } + if (this.#mode === AnnotationEditorType.HIGHLIGHT) { + this.showAllEditors("highlight", true, true); + } + this.#highlightWhenShiftUp = this.isShiftKeyDown; + if (!this.isShiftKeyDown) { + const activeLayer = this.#mode === AnnotationEditorType.HIGHLIGHT ? this.#getLayerForTextLayer(textLayer) : null; + activeLayer?.toggleDrawing(); + if (this.#isPointerDown) { + const ac = new AbortController(); + const signal = this.combinedSignal(ac); + const pointerup = e => { + if (e.type === "pointerup" && e.button !== 0) { + return; + } + ac.abort(); + activeLayer?.toggleDrawing(true); + if (e.type === "pointerup") { + this.#onSelectEnd("main_toolbar"); + } + }; + window.addEventListener("pointerup", pointerup, { + signal + }); + window.addEventListener("blur", pointerup, { + signal + }); + } else { + activeLayer?.toggleDrawing(true); + this.#onSelectEnd("main_toolbar"); + } + } + } + #onSelectEnd(methodOfCreation = "") { + if (this.#mode === AnnotationEditorType.HIGHLIGHT) { + this.highlightSelection(methodOfCreation); + } else if (this.#enableHighlightFloatingButton) { + this.#displayFloatingToolbar(); + } + } + #addSelectionListener() { + document.addEventListener("selectionchange", this.#selectionChange.bind(this), { + signal: this._signal + }); + } + #addFocusManager() { + if (this.#focusManagerAC) { + return; + } + this.#focusManagerAC = new AbortController(); + const signal = this.combinedSignal(this.#focusManagerAC); + window.addEventListener("focus", this.focus.bind(this), { + signal + }); + window.addEventListener("blur", this.blur.bind(this), { + signal + }); + } + #removeFocusManager() { + this.#focusManagerAC?.abort(); + this.#focusManagerAC = null; + } + blur() { + this.isShiftKeyDown = false; + if (this.#highlightWhenShiftUp) { + this.#highlightWhenShiftUp = false; + this.#onSelectEnd("main_toolbar"); + } + if (!this.hasSelection) { + return; + } + const { + activeElement + } = document; + for (const editor of this.#selectedEditors) { + if (editor.div.contains(activeElement)) { + this.#lastActiveElement = [editor, activeElement]; + editor._focusEventsAllowed = false; + break; + } + } + } + focus() { + if (!this.#lastActiveElement) { + return; + } + const [lastEditor, lastActiveElement] = this.#lastActiveElement; + this.#lastActiveElement = null; + lastActiveElement.addEventListener("focusin", () => { + lastEditor._focusEventsAllowed = true; + }, { + once: true, + signal: this._signal + }); + lastActiveElement.focus(); + } + #addKeyboardManager() { + if (this.#keyboardManagerAC) { + return; + } + this.#keyboardManagerAC = new AbortController(); + const signal = this.combinedSignal(this.#keyboardManagerAC); + window.addEventListener("keydown", this.keydown.bind(this), { + signal + }); + window.addEventListener("keyup", this.keyup.bind(this), { + signal + }); + } + #removeKeyboardManager() { + this.#keyboardManagerAC?.abort(); + this.#keyboardManagerAC = null; + } + #addCopyPasteListeners() { + if (this.#copyPasteAC) { + return; + } + this.#copyPasteAC = new AbortController(); + const signal = this.combinedSignal(this.#copyPasteAC); + document.addEventListener("copy", this.copy.bind(this), { + signal + }); + document.addEventListener("cut", this.cut.bind(this), { + signal + }); + document.addEventListener("paste", this.paste.bind(this), { + signal + }); + } + #removeCopyPasteListeners() { + this.#copyPasteAC?.abort(); + this.#copyPasteAC = null; + } + #addDragAndDropListeners() { + const signal = this._signal; + document.addEventListener("dragover", this.dragOver.bind(this), { + signal + }); + document.addEventListener("drop", this.drop.bind(this), { + signal + }); + } + addEditListeners() { + this.#addKeyboardManager(); + this.setEditingState(true); + } + removeEditListeners() { + this.#removeKeyboardManager(); + this.setEditingState(false); + } + dragOver(event) { + for (const { + type + } of event.dataTransfer.items) { + for (const editorType of this.#editorTypes) { + if (editorType.isHandlingMimeForPasting(type)) { + event.dataTransfer.dropEffect = "copy"; + event.preventDefault(); + return; + } + } + } + } + drop(event) { + for (const item of event.dataTransfer.items) { + for (const editorType of this.#editorTypes) { + if (editorType.isHandlingMimeForPasting(item.type)) { + editorType.paste(item, this.currentLayer); + event.preventDefault(); + return; + } + } + } + } + copy(event) { + event.preventDefault(); + this.#activeEditor?.commitOrRemove(); + if (!this.hasSelection) { + return; + } + const editors = []; + for (const editor of this.#selectedEditors) { + const serialized = editor.serialize(true); + if (serialized) { + editors.push(serialized); + } + } + if (editors.length === 0) { + return; + } + event.clipboardData.setData("application/pdfjs", JSON.stringify(editors)); + } + cut(event) { + this.copy(event); + this.delete(); + } + async paste(event) { + event.preventDefault(); + const { + clipboardData + } = event; + for (const item of clipboardData.items) { + for (const editorType of this.#editorTypes) { + if (editorType.isHandlingMimeForPasting(item.type)) { + editorType.paste(item, this.currentLayer); + return; + } + } + } + let data = clipboardData.getData("application/pdfjs"); + if (!data) { + return; + } + try { + data = JSON.parse(data); + } catch (ex) { + warn(`paste: "${ex.message}".`); + return; + } + if (!Array.isArray(data)) { + return; + } + this.unselectAll(); + const layer = this.currentLayer; + try { + const newEditors = []; + for (const editor of data) { + const deserializedEditor = await layer.deserialize(editor); + if (!deserializedEditor) { + return; + } + newEditors.push(deserializedEditor); + } + const cmd = () => { + for (const editor of newEditors) { + this.#addEditorToLayer(editor); + } + this.#selectEditors(newEditors); + }; + const undo = () => { + for (const editor of newEditors) { + editor.remove(); + } + }; + this.addCommands({ + cmd, + undo, + mustExec: true + }); + } catch (ex) { + warn(`paste: "${ex.message}".`); + } + } + keydown(event) { + if (!this.isShiftKeyDown && event.key === "Shift") { + this.isShiftKeyDown = true; + } + if (this.#mode !== AnnotationEditorType.NONE && !this.isEditorHandlingKeyboard) { + AnnotationEditorUIManager._keyboardManager.exec(this, event); + } + } + keyup(event) { + if (this.isShiftKeyDown && event.key === "Shift") { + this.isShiftKeyDown = false; + if (this.#highlightWhenShiftUp) { + this.#highlightWhenShiftUp = false; + this.#onSelectEnd("main_toolbar"); + } + } + } + onEditingAction({ + name + }) { + switch (name) { + case "undo": + case "redo": + case "delete": + case "selectAll": + this[name](); + break; + case "highlightSelection": + this.highlightSelection("context_menu"); + break; + case "commentSelection": + this.commentSelection("context_menu"); + break; + } + } + #dispatchUpdateStates(details) { + const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value); + if (hasChanged) { + this._eventBus.dispatch("annotationeditorstateschanged", { + source: this, + details: Object.assign(this.#previousStates, details) + }); + if (this.#mode === AnnotationEditorType.HIGHLIGHT && details.hasSelectedEditor === false) { + this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_FREE, true]]); + } + } + } + #dispatchUpdateUI(details) { + this._eventBus.dispatch("annotationeditorparamschanged", { + source: this, + details + }); + } + setEditingState(isEditing) { + if (isEditing) { + this.#addFocusManager(); + this.#addCopyPasteListeners(); + this.#dispatchUpdateStates({ + isEditing: this.#mode !== AnnotationEditorType.NONE, + isEmpty: this.#isEmpty(), + hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(), + hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(), + hasSelectedEditor: false + }); + } else { + this.#removeFocusManager(); + this.#removeCopyPasteListeners(); + this.#dispatchUpdateStates({ + isEditing: false + }); + this.disableUserSelect(false); + } + } + registerEditorTypes(types) { + if (this.#editorTypes) { + return; + } + this.#editorTypes = types; + for (const editorType of this.#editorTypes) { + this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate); + } + } + getId() { + return this.#idManager.id; + } + get currentLayer() { + return this.#allLayers.get(this.#currentPageIndex); + } + getLayer(pageIndex) { + return this.#allLayers.get(pageIndex); + } + get currentPageIndex() { + return this.#currentPageIndex; + } + addLayer(layer) { + this.#allLayers.set(layer.pageIndex, layer); + if (this.#isEnabled) { + layer.enable(); + } else { + layer.disable(); + } + } + removeLayer(layer) { + this.#allLayers.delete(layer.pageIndex); + } + async updateMode(mode, editId = null, isFromUser = false, isFromKeyboard = false, mustEnterInEditMode = false, editComment = false) { + if (this.#mode === mode) { + return; + } + if (this.#updateModeCapability) { + await this.#updateModeCapability.promise; + if (!this.#updateModeCapability) { + return; + } + } + this.#updateModeCapability = Promise.withResolvers(); + this.#currentDrawingSession?.commitOrRemove(); + if (this.#mode === AnnotationEditorType.POPUP) { + this.#commentManager?.hideSidebar(); + } + this.#commentManager?.destroyPopup(); + this.#mode = mode; + if (mode === AnnotationEditorType.NONE) { + this.setEditingState(false); + this.#disableAll(); + for (const editor of this.#allEditors.values()) { + editor.hideStandaloneCommentButton(); + } + this._editorUndoBar?.hide(); + this.toggleComment(null); + this.#updateModeCapability.resolve(); + return; + } + for (const editor of this.#allEditors.values()) { + editor.addStandaloneCommentButton(); + } + if (mode === AnnotationEditorType.SIGNATURE) { + await this.#signatureManager?.loadSignatures(); + } + if (isFromUser) { + CurrentPointers.clearPointerType(); + } + this.setEditingState(true); + await this.#enableAll(); + this.unselectAll(); + for (const layer of this.#allLayers.values()) { + layer.updateMode(mode); + } + if (mode === AnnotationEditorType.POPUP) { + this.#allEditableAnnotations ||= await this.#pdfDocument.getAnnotationsByType(new Set(this.#editorTypes.map(editorClass => editorClass._editorType))); + const elementIds = new Set(); + const allComments = []; + for (const editor of this.#allEditors.values()) { + const { + annotationElementId, + hasComment, + deleted + } = editor; + if (annotationElementId) { + elementIds.add(annotationElementId); + } + if (hasComment && !deleted) { + allComments.push(editor.getData()); + } + } + for (const annotation of this.#allEditableAnnotations) { + const { + id, + popupRef, + contentsObj + } = annotation; + if (popupRef && contentsObj?.str && !elementIds.has(id) && !this.#deletedAnnotationsElementIds.has(id)) { + allComments.push(annotation); + } + } + this.#commentManager?.showSidebar(allComments); + } + if (!editId) { + if (isFromKeyboard) { + this.addNewEditorFromKeyboard(); + } + this.#updateModeCapability.resolve(); + return; + } + for (const editor of this.#allEditors.values()) { + if (editor.uid === editId) { + this.setSelected(editor); + if (editComment) { + editor.editComment(); + } else if (mustEnterInEditMode) { + editor.enterInEditMode(); + } else { + editor.focus(); + } + } else { + editor.unselect(); + } + } + this.#updateModeCapability.resolve(); + } + addNewEditorFromKeyboard() { + if (this.currentLayer.canCreateNewEmptyEditor()) { + this.currentLayer.addNewEditor(); + } + } + updateToolbar(options) { + if (options.mode === this.#mode) { + return; + } + this._eventBus.dispatch("switchannotationeditormode", { + source: this, + ...options + }); + } + updateParams(type, value) { + if (!this.#editorTypes) { + return; + } + switch (type) { + case AnnotationEditorParamsType.CREATE: + this.currentLayer.addNewEditor(value); + return; + case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL: + this._eventBus.dispatch("reporttelemetry", { + source: this, + details: { + type: "editing", + data: { + type: "highlight", + action: "toggle_visibility" + } + } + }); + (this.#showAllStates ||= new Map()).set(type, value); + this.showAllEditors("highlight", value); + break; + } + if (this.hasSelection) { + for (const editor of this.#selectedEditors) { + editor.updateParams(type, value); + } + } else { + for (const editorType of this.#editorTypes) { + editorType.updateDefaultParams(type, value); + } + } + } + showAllEditors(type, visible, updateButton = false) { + for (const editor of this.#allEditors.values()) { + if (editor.editorType === type) { + editor.show(visible); + } + } + const state = this.#showAllStates?.get(AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL) ?? true; + if (state !== visible) { + this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL, visible]]); + } + } + enableWaiting(mustWait = false) { + if (this.#isWaiting === mustWait) { + return; + } + this.#isWaiting = mustWait; + for (const layer of this.#allLayers.values()) { + if (mustWait) { + layer.disableClick(); + } else { + layer.enableClick(); + } + layer.div.classList.toggle("waiting", mustWait); + } + } + async #enableAll() { + if (!this.#isEnabled) { + this.#isEnabled = true; + const promises = []; + for (const layer of this.#allLayers.values()) { + promises.push(layer.enable()); + } + await Promise.all(promises); + for (const editor of this.#allEditors.values()) { + editor.enable(); + } + } + } + #disableAll() { + this.unselectAll(); + if (this.#isEnabled) { + this.#isEnabled = false; + for (const layer of this.#allLayers.values()) { + layer.disable(); + } + for (const editor of this.#allEditors.values()) { + editor.disable(); + } + } + } + *getEditors(pageIndex) { + for (const editor of this.#allEditors.values()) { + if (editor.pageIndex === pageIndex) { + yield editor; + } + } + } + getEditor(id) { + return this.#allEditors.get(id); + } + addEditor(editor) { + this.#allEditors.set(editor.id, editor); + } + removeEditor(editor) { + if (editor.div.contains(document.activeElement)) { + if (this.#focusMainContainerTimeoutId) { + clearTimeout(this.#focusMainContainerTimeoutId); + } + this.#focusMainContainerTimeoutId = setTimeout(() => { + this.focusMainContainer(); + this.#focusMainContainerTimeoutId = null; + }, 0); + } + this.#allEditors.delete(editor.id); + if (editor.annotationElementId) { + this.#missingCanvases?.delete(editor.annotationElementId); + } + this.unselect(editor); + if (!editor.annotationElementId || !this.#deletedAnnotationsElementIds.has(editor.annotationElementId)) { + this.#annotationStorage?.remove(editor.id); + } + } + addDeletedAnnotationElement(editor) { + this.#deletedAnnotationsElementIds.add(editor.annotationElementId); + this.addChangedExistingAnnotation(editor); + editor.deleted = true; + } + isDeletedAnnotationElement(annotationElementId) { + return this.#deletedAnnotationsElementIds.has(annotationElementId); + } + removeDeletedAnnotationElement(editor) { + this.#deletedAnnotationsElementIds.delete(editor.annotationElementId); + this.removeChangedExistingAnnotation(editor); + editor.deleted = false; + } + #addEditorToLayer(editor) { + const layer = this.#allLayers.get(editor.pageIndex); + if (layer) { + layer.addOrRebuild(editor); + } else { + this.addEditor(editor); + this.addToAnnotationStorage(editor); + } + } + setActiveEditor(editor) { + if (this.#activeEditor === editor) { + return; + } + this.#activeEditor = editor; + if (editor) { + this.#dispatchUpdateUI(editor.propertiesToUpdate); + } + } + get #lastSelectedEditor() { + let ed = null; + for (ed of this.#selectedEditors) {} + return ed; + } + updateUI(editor) { + if (this.#lastSelectedEditor === editor) { + this.#dispatchUpdateUI(editor.propertiesToUpdate); + } + } + updateUIForDefaultProperties(editorType) { + this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate); + } + toggleSelected(editor) { + if (this.#selectedEditors.has(editor)) { + this.#selectedEditors.delete(editor); + editor.unselect(); + this.#dispatchUpdateStates({ + hasSelectedEditor: this.hasSelection + }); + return; + } + this.#selectedEditors.add(editor); + editor.select(); + this.#dispatchUpdateUI(editor.propertiesToUpdate); + this.#dispatchUpdateStates({ + hasSelectedEditor: true + }); + } + setSelected(editor) { + this.updateToolbar({ + mode: editor.mode, + editId: editor.uid + }); + this.#currentDrawingSession?.commitOrRemove(); + for (const ed of this.#selectedEditors) { + if (ed !== editor) { + ed.unselect(); + } + } + this.#selectedEditors.clear(); + this.#selectedEditors.add(editor); + editor.select(); + this.#dispatchUpdateUI(editor.propertiesToUpdate); + this.#dispatchUpdateStates({ + hasSelectedEditor: true + }); + } + isSelected(editor) { + return this.#selectedEditors.has(editor); + } + get firstSelectedEditor() { + return this.#selectedEditors.values().next().value; + } + unselect(editor) { + editor.unselect(); + this.#selectedEditors.delete(editor); + this.#dispatchUpdateStates({ + hasSelectedEditor: this.hasSelection + }); + } + get hasSelection() { + return this.#selectedEditors.size !== 0; + } + get isEnterHandled() { + return this.#selectedEditors.size === 1 && this.firstSelectedEditor.isEnterHandled; + } + undo() { + this.#commandManager.undo(); + this.#dispatchUpdateStates({ + hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(), + hasSomethingToRedo: true, + isEmpty: this.#isEmpty() + }); + this._editorUndoBar?.hide(); + } + redo() { + this.#commandManager.redo(); + this.#dispatchUpdateStates({ + hasSomethingToUndo: true, + hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(), + isEmpty: this.#isEmpty() + }); + } + addCommands(params) { + this.#commandManager.add(params); + this.#dispatchUpdateStates({ + hasSomethingToUndo: true, + hasSomethingToRedo: false, + isEmpty: this.#isEmpty() + }); + } + cleanUndoStack(type) { + this.#commandManager.cleanType(type); + } + #isEmpty() { + if (this.#allEditors.size === 0) { + return true; + } + if (this.#allEditors.size === 1) { + for (const editor of this.#allEditors.values()) { + return editor.isEmpty(); + } + } + return false; + } + delete() { + this.commitOrRemove(); + const drawingEditor = this.currentLayer?.endDrawingSession(true); + if (!this.hasSelection && !drawingEditor) { + return; + } + const editors = drawingEditor ? [drawingEditor] : [...this.#selectedEditors]; + const cmd = () => { + this._editorUndoBar?.show(undo, editors.length === 1 ? editors[0].editorType : editors.length); + for (const editor of editors) { + editor.remove(); + } + }; + const undo = () => { + for (const editor of editors) { + this.#addEditorToLayer(editor); + } + }; + this.addCommands({ + cmd, + undo, + mustExec: true + }); + } + commitOrRemove() { + this.#activeEditor?.commitOrRemove(); + } + hasSomethingToControl() { + return this.#activeEditor || this.hasSelection; + } + #selectEditors(editors) { + for (const editor of this.#selectedEditors) { + editor.unselect(); + } + this.#selectedEditors.clear(); + for (const editor of editors) { + if (editor.isEmpty()) { + continue; + } + this.#selectedEditors.add(editor); + editor.select(); + } + this.#dispatchUpdateStates({ + hasSelectedEditor: this.hasSelection + }); + } + selectAll() { + for (const editor of this.#selectedEditors) { + editor.commit(); + } + this.#selectEditors(this.#allEditors.values()); + } + unselectAll() { + if (this.#activeEditor) { + this.#activeEditor.commitOrRemove(); + if (this.#mode !== AnnotationEditorType.NONE) { + return; + } + } + if (this.#currentDrawingSession?.commitOrRemove()) { + return; + } + if (!this.hasSelection) { + return; + } + for (const editor of this.#selectedEditors) { + editor.unselect(); + } + this.#selectedEditors.clear(); + this.#dispatchUpdateStates({ + hasSelectedEditor: false + }); + } + translateSelectedEditors(x, y, noCommit = false) { + if (!noCommit) { + this.commitOrRemove(); + } + if (!this.hasSelection) { + return; + } + this.#translation[0] += x; + this.#translation[1] += y; + const [totalX, totalY] = this.#translation; + const editors = [...this.#selectedEditors]; + const TIME_TO_WAIT = 1000; + if (this.#translationTimeoutId) { + clearTimeout(this.#translationTimeoutId); + } + this.#translationTimeoutId = setTimeout(() => { + this.#translationTimeoutId = null; + this.#translation[0] = this.#translation[1] = 0; + this.addCommands({ + cmd: () => { + for (const editor of editors) { + if (this.#allEditors.has(editor.id)) { + editor.translateInPage(totalX, totalY); + editor.translationDone(); + } + } + }, + undo: () => { + for (const editor of editors) { + if (this.#allEditors.has(editor.id)) { + editor.translateInPage(-totalX, -totalY); + editor.translationDone(); + } + } + }, + mustExec: false + }); + }, TIME_TO_WAIT); + for (const editor of editors) { + editor.translateInPage(x, y); + editor.translationDone(); + } + } + setUpDragSession() { + if (!this.hasSelection) { + return; + } + this.disableUserSelect(true); + this.#draggingEditors = new Map(); + for (const editor of this.#selectedEditors) { + this.#draggingEditors.set(editor, { + savedX: editor.x, + savedY: editor.y, + savedPageIndex: editor.pageIndex, + newX: 0, + newY: 0, + newPageIndex: -1 + }); + } + } + endDragSession() { + if (!this.#draggingEditors) { + return false; + } + this.disableUserSelect(false); + const map = this.#draggingEditors; + this.#draggingEditors = null; + let mustBeAddedInUndoStack = false; + for (const [{ + x, + y, + pageIndex + }, value] of map) { + value.newX = x; + value.newY = y; + value.newPageIndex = pageIndex; + mustBeAddedInUndoStack ||= x !== value.savedX || y !== value.savedY || pageIndex !== value.savedPageIndex; + } + if (!mustBeAddedInUndoStack) { + return false; + } + const move = (editor, x, y, pageIndex) => { + if (this.#allEditors.has(editor.id)) { + const parent = this.#allLayers.get(pageIndex); + if (parent) { + editor._setParentAndPosition(parent, x, y); + } else { + editor.pageIndex = pageIndex; + editor.x = x; + editor.y = y; + } + } + }; + this.addCommands({ + cmd: () => { + for (const [editor, { + newX, + newY, + newPageIndex + }] of map) { + move(editor, newX, newY, newPageIndex); + } + }, + undo: () => { + for (const [editor, { + savedX, + savedY, + savedPageIndex + }] of map) { + move(editor, savedX, savedY, savedPageIndex); + } + }, + mustExec: true + }); + return true; + } + dragSelectedEditors(tx, ty) { + if (!this.#draggingEditors) { + return; + } + for (const editor of this.#draggingEditors.keys()) { + editor.drag(tx, ty); + } + } + rebuild(editor) { + if (editor.parent === null) { + const parent = this.getLayer(editor.pageIndex); + if (parent) { + parent.changeParent(editor); + parent.addOrRebuild(editor); + } else { + this.addEditor(editor); + this.addToAnnotationStorage(editor); + editor.rebuild(); + } + } else { + editor.parent.addOrRebuild(editor); + } + } + get isEditorHandlingKeyboard() { + return this.getActive()?.shouldGetKeyboardEvents() || this.#selectedEditors.size === 1 && this.firstSelectedEditor.shouldGetKeyboardEvents(); + } + isActive(editor) { + return this.#activeEditor === editor; + } + getActive() { + return this.#activeEditor; + } + getMode() { + return this.#mode; + } + isEditingMode() { + return this.#mode !== AnnotationEditorType.NONE; + } + get imageManager() { + return shadow(this, "imageManager", new ImageManager()); + } + getSelectionBoxes(textLayer) { + if (!textLayer) { + return null; + } + const selection = document.getSelection(); + for (let i = 0, ii = selection.rangeCount; i < ii; i++) { + if (!textLayer.contains(selection.getRangeAt(i).commonAncestorContainer)) { + return null; + } + } + const { + x: layerX, + y: layerY, + width: parentWidth, + height: parentHeight + } = textLayer.getBoundingClientRect(); + let rotator; + switch (textLayer.getAttribute("data-main-rotation")) { + case "90": + rotator = (x, y, w, h) => ({ + x: (y - layerY) / parentHeight, + y: 1 - (x + w - layerX) / parentWidth, + width: h / parentHeight, + height: w / parentWidth + }); + break; + case "180": + rotator = (x, y, w, h) => ({ + x: 1 - (x + w - layerX) / parentWidth, + y: 1 - (y + h - layerY) / parentHeight, + width: w / parentWidth, + height: h / parentHeight + }); + break; + case "270": + rotator = (x, y, w, h) => ({ + x: 1 - (y + h - layerY) / parentHeight, + y: (x - layerX) / parentWidth, + width: h / parentHeight, + height: w / parentWidth + }); + break; + default: + rotator = (x, y, w, h) => ({ + x: (x - layerX) / parentWidth, + y: (y - layerY) / parentHeight, + width: w / parentWidth, + height: h / parentHeight + }); + break; + } + const boxes = []; + for (let i = 0, ii = selection.rangeCount; i < ii; i++) { + const range = selection.getRangeAt(i); + if (range.collapsed) { + continue; + } + for (const { + x, + y, + width, + height + } of range.getClientRects()) { + if (width === 0 || height === 0) { + continue; + } + boxes.push(rotator(x, y, width, height)); + } + } + return boxes.length === 0 ? null : boxes; + } + addChangedExistingAnnotation({ + annotationElementId, + id + }) { + (this.#changedExistingAnnotations ||= new Map()).set(annotationElementId, id); + } + removeChangedExistingAnnotation({ + annotationElementId + }) { + this.#changedExistingAnnotations?.delete(annotationElementId); + } + renderAnnotationElement(annotation) { + const editorId = this.#changedExistingAnnotations?.get(annotation.data.id); + if (!editorId) { + return; + } + const editor = this.#annotationStorage.getRawValue(editorId); + if (!editor) { + return; + } + if (this.#mode === AnnotationEditorType.NONE && !editor.hasBeenModified) { + return; + } + editor.renderAnnotationElement(annotation); + } + setMissingCanvas(annotationId, annotationElementId, canvas) { + const editor = this.#missingCanvases?.get(annotationId); + if (!editor) { + return; + } + editor.setCanvas(annotationElementId, canvas); + this.#missingCanvases.delete(annotationId); + } + addMissingCanvas(annotationId, editor) { + (this.#missingCanvases ||= new Map()).set(annotationId, editor); + } +} + +;// ./src/display/editor/alt_text.js + +class AltText { + #altText = null; + #altTextDecorative = false; + #altTextButton = null; + #altTextButtonLabel = null; + #altTextTooltip = null; + #altTextTooltipTimeout = null; + #altTextWasFromKeyBoard = false; + #badge = null; + #editor = null; + #guessedText = null; + #textWithDisclaimer = null; + #useNewAltTextFlow = false; + static #l10nNewButton = null; + static _l10n = null; + constructor(editor) { + this.#editor = editor; + this.#useNewAltTextFlow = editor._uiManager.useNewAltTextFlow; + AltText.#l10nNewButton ||= Object.freeze({ + added: "pdfjs-editor-new-alt-text-added-button", + "added-label": "pdfjs-editor-new-alt-text-added-button-label", + missing: "pdfjs-editor-new-alt-text-missing-button", + "missing-label": "pdfjs-editor-new-alt-text-missing-button-label", + review: "pdfjs-editor-new-alt-text-to-review-button", + "review-label": "pdfjs-editor-new-alt-text-to-review-button-label" + }); + } + static initialize(l10n) { + AltText._l10n ??= l10n; + } + async render() { + const altText = this.#altTextButton = document.createElement("button"); + altText.className = "altText"; + altText.tabIndex = "0"; + const label = this.#altTextButtonLabel = document.createElement("span"); + altText.append(label); + if (this.#useNewAltTextFlow) { + altText.classList.add("new"); + altText.setAttribute("data-l10n-id", AltText.#l10nNewButton.missing); + label.setAttribute("data-l10n-id", AltText.#l10nNewButton["missing-label"]); + } else { + altText.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button"); + label.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button-label"); + } + const signal = this.#editor._uiManager._signal; + altText.addEventListener("contextmenu", noContextMenu, { + signal + }); + altText.addEventListener("pointerdown", event => event.stopPropagation(), { + signal + }); + const onClick = event => { + event.preventDefault(); + this.#editor._uiManager.editAltText(this.#editor); + if (this.#useNewAltTextFlow) { + this.#editor._reportTelemetry({ + action: "pdfjs.image.alt_text.image_status_label_clicked", + data: { + label: this.#label + } + }); + } + }; + altText.addEventListener("click", onClick, { + capture: true, + signal + }); + altText.addEventListener("keydown", event => { + if (event.target === altText && event.key === "Enter") { + this.#altTextWasFromKeyBoard = true; + onClick(event); + } + }, { + signal + }); + await this.#setState(); + return altText; + } + get #label() { + return this.#altText && "added" || this.#altText === null && this.guessedText && "review" || "missing"; + } + finish() { + if (!this.#altTextButton) { + return; + } + this.#altTextButton.focus({ + focusVisible: this.#altTextWasFromKeyBoard + }); + this.#altTextWasFromKeyBoard = false; + } + isEmpty() { + if (this.#useNewAltTextFlow) { + return this.#altText === null; + } + return !this.#altText && !this.#altTextDecorative; + } + hasData() { + if (this.#useNewAltTextFlow) { + return this.#altText !== null || !!this.#guessedText; + } + return this.isEmpty(); + } + get guessedText() { + return this.#guessedText; + } + async setGuessedText(guessedText) { + if (this.#altText !== null) { + return; + } + this.#guessedText = guessedText; + this.#textWithDisclaimer = await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer", { + generatedAltText: guessedText + }); + this.#setState(); + } + toggleAltTextBadge(visibility = false) { + if (!this.#useNewAltTextFlow || this.#altText) { + this.#badge?.remove(); + this.#badge = null; + return; + } + if (!this.#badge) { + const badge = this.#badge = document.createElement("div"); + badge.className = "noAltTextBadge"; + this.#editor.div.append(badge); + } + this.#badge.classList.toggle("hidden", !visibility); + } + serialize(isForCopying) { + let altText = this.#altText; + if (!isForCopying && this.#guessedText === altText) { + altText = this.#textWithDisclaimer; + } + return { + altText, + decorative: this.#altTextDecorative, + guessedText: this.#guessedText, + textWithDisclaimer: this.#textWithDisclaimer + }; + } + get data() { + return { + altText: this.#altText, + decorative: this.#altTextDecorative + }; + } + set data({ + altText, + decorative, + guessedText, + textWithDisclaimer, + cancel = false + }) { + if (guessedText) { + this.#guessedText = guessedText; + this.#textWithDisclaimer = textWithDisclaimer; + } + if (this.#altText === altText && this.#altTextDecorative === decorative) { + return; + } + if (!cancel) { + this.#altText = altText; + this.#altTextDecorative = decorative; + } + this.#setState(); + } + toggle(enabled = false) { + if (!this.#altTextButton) { + return; + } + if (!enabled && this.#altTextTooltipTimeout) { + clearTimeout(this.#altTextTooltipTimeout); + this.#altTextTooltipTimeout = null; + } + this.#altTextButton.disabled = !enabled; + } + shown() { + this.#editor._reportTelemetry({ + action: "pdfjs.image.alt_text.image_status_label_displayed", + data: { + label: this.#label + } + }); + } + destroy() { + this.#altTextButton?.remove(); + this.#altTextButton = null; + this.#altTextButtonLabel = null; + this.#altTextTooltip = null; + this.#badge?.remove(); + this.#badge = null; + } + async #setState() { + const button = this.#altTextButton; + if (!button) { + return; + } + if (this.#useNewAltTextFlow) { + button.classList.toggle("done", !!this.#altText); + button.setAttribute("data-l10n-id", AltText.#l10nNewButton[this.#label]); + this.#altTextButtonLabel?.setAttribute("data-l10n-id", AltText.#l10nNewButton[`${this.#label}-label`]); + if (!this.#altText) { + this.#altTextTooltip?.remove(); + return; + } + } else { + if (!this.#altText && !this.#altTextDecorative) { + button.classList.remove("done"); + this.#altTextTooltip?.remove(); + return; + } + button.classList.add("done"); + button.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-edit-button"); + } + let tooltip = this.#altTextTooltip; + if (!tooltip) { + this.#altTextTooltip = tooltip = document.createElement("span"); + tooltip.className = "tooltip"; + tooltip.setAttribute("role", "tooltip"); + tooltip.id = `alt-text-tooltip-${this.#editor.id}`; + const DELAY_TO_SHOW_TOOLTIP = 100; + const signal = this.#editor._uiManager._signal; + signal.addEventListener("abort", () => { + clearTimeout(this.#altTextTooltipTimeout); + this.#altTextTooltipTimeout = null; + }, { + once: true + }); + button.addEventListener("mouseenter", () => { + this.#altTextTooltipTimeout = setTimeout(() => { + this.#altTextTooltipTimeout = null; + this.#altTextTooltip.classList.add("show"); + this.#editor._reportTelemetry({ + action: "alt_text_tooltip" + }); + }, DELAY_TO_SHOW_TOOLTIP); + }, { + signal + }); + button.addEventListener("mouseleave", () => { + if (this.#altTextTooltipTimeout) { + clearTimeout(this.#altTextTooltipTimeout); + this.#altTextTooltipTimeout = null; + } + this.#altTextTooltip?.classList.remove("show"); + }, { + signal + }); + } + if (this.#altTextDecorative) { + tooltip.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-decorative-tooltip"); + } else { + tooltip.removeAttribute("data-l10n-id"); + tooltip.textContent = this.#altText; + } + if (!tooltip.parentNode) { + button.append(tooltip); + } + const element = this.#editor.getElementForAltText(); + element?.setAttribute("aria-describedby", tooltip.id); + } +} + +;// ./src/display/editor/comment.js + +class Comment { + #commentStandaloneButton = null; + #commentToolbarButton = null; + #commentWasFromKeyBoard = false; + #editor = null; + #initialText = null; + #richText = null; + #text = null; + #date = null; + #deleted = false; + #popupPosition = null; + constructor(editor) { + this.#editor = editor; + } + renderForToolbar() { + const button = this.#commentToolbarButton = document.createElement("button"); + button.className = "comment"; + return this.#render(button, false); + } + renderForStandalone() { + const button = this.#commentStandaloneButton = document.createElement("button"); + button.className = "annotationCommentButton"; + const position = this.#editor.commentButtonPosition; + if (position) { + const { + style + } = button; + style.insetInlineEnd = `calc(${100 * (this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0])}% - var(--comment-button-dim))`; + style.top = `calc(${100 * position[1]}% - var(--comment-button-dim))`; + const color = this.#editor.commentButtonColor; + if (color) { + style.backgroundColor = color; + } + } + return this.#render(button, true); + } + focusButton() { + setTimeout(() => { + (this.#commentStandaloneButton ?? this.#commentToolbarButton)?.focus(); + }, 0); + } + onUpdatedColor() { + if (!this.#commentStandaloneButton) { + return; + } + const color = this.#editor.commentButtonColor; + if (color) { + this.#commentStandaloneButton.style.backgroundColor = color; + } + this.#editor._uiManager.updatePopupColor(this.#editor); + } + get commentButtonWidth() { + return (this.#commentStandaloneButton?.getBoundingClientRect().width ?? 0) / this.#editor.parent.boundingClientRect.width; + } + get commentPopupPositionInLayer() { + if (this.#popupPosition) { + return this.#popupPosition; + } + if (!this.#commentStandaloneButton) { + return null; + } + const { + x, + y, + height + } = this.#commentStandaloneButton.getBoundingClientRect(); + const { + x: parentX, + y: parentY, + width: parentWidth, + height: parentHeight + } = this.#editor.parent.boundingClientRect; + return [(x - parentX) / parentWidth, (y + height - parentY) / parentHeight]; + } + set commentPopupPositionInLayer(pos) { + this.#popupPosition = pos; + } + hasDefaultPopupPosition() { + return this.#popupPosition === null; + } + removeStandaloneCommentButton() { + this.#commentStandaloneButton?.remove(); + this.#commentStandaloneButton = null; + } + removeToolbarCommentButton() { + this.#commentToolbarButton?.remove(); + this.#commentToolbarButton = null; + } + setCommentButtonStates({ + selected, + hasPopup + }) { + if (!this.#commentStandaloneButton) { + return; + } + this.#commentStandaloneButton.classList.toggle("selected", selected); + this.#commentStandaloneButton.ariaExpanded = hasPopup; + } + #render(comment, isStandalone) { + if (!this.#editor._uiManager.hasCommentManager()) { + return null; + } + comment.tabIndex = "0"; + comment.ariaHasPopup = "dialog"; + if (isStandalone) { + comment.ariaControls = "commentPopup"; + comment.setAttribute("data-l10n-id", "pdfjs-show-comment-button"); + } else { + comment.ariaControlsElements = [this.#editor._uiManager.getCommentDialogElement()]; + comment.setAttribute("data-l10n-id", "pdfjs-editor-add-comment-button"); + } + const signal = this.#editor._uiManager._signal; + if (!(signal instanceof AbortSignal) || signal.aborted) { + return comment; + } + comment.addEventListener("contextmenu", noContextMenu, { + signal + }); + if (isStandalone) { + comment.addEventListener("focusin", e => { + this.#editor._focusEventsAllowed = false; + stopEvent(e); + }, { + capture: true, + signal + }); + comment.addEventListener("focusout", e => { + this.#editor._focusEventsAllowed = true; + stopEvent(e); + }, { + capture: true, + signal + }); + } + comment.addEventListener("pointerdown", event => event.stopPropagation(), { + signal + }); + const onClick = event => { + event.preventDefault(); + if (comment === this.#commentToolbarButton) { + this.edit(); + } else { + this.#editor.toggleComment(true); + } + }; + comment.addEventListener("click", onClick, { + capture: true, + signal + }); + comment.addEventListener("keydown", event => { + if (event.target === comment && event.key === "Enter") { + this.#commentWasFromKeyBoard = true; + onClick(event); + } + }, { + signal + }); + comment.addEventListener("pointerenter", () => { + this.#editor.toggleComment(false, true); + }, { + signal + }); + comment.addEventListener("pointerleave", () => { + this.#editor.toggleComment(false, false); + }, { + signal + }); + return comment; + } + edit(options) { + const position = this.commentPopupPositionInLayer; + let posX, posY; + if (position) { + [posX, posY] = position; + } else { + [posX, posY] = this.#editor.commentButtonPosition; + const { + width, + height, + x, + y + } = this.#editor; + posX = x + posX * width; + posY = y + posY * height; + } + const parentDimensions = this.#editor.parent.boundingClientRect; + const { + x: parentX, + y: parentY, + width: parentWidth, + height: parentHeight + } = parentDimensions; + this.#editor._uiManager.editComment(this.#editor, parentX + posX * parentWidth, parentY + posY * parentHeight, { + ...options, + parentDimensions + }); + } + finish() { + if (!this.#commentToolbarButton) { + return; + } + this.#commentToolbarButton.focus({ + focusVisible: this.#commentWasFromKeyBoard + }); + this.#commentWasFromKeyBoard = false; + } + isDeleted() { + return this.#deleted || this.#text === ""; + } + isEmpty() { + return this.#text === null; + } + hasBeenEdited() { + return this.isDeleted() || this.#text !== this.#initialText; + } + serialize() { + return this.data; + } + get data() { + return { + text: this.#text, + richText: this.#richText, + date: this.#date, + deleted: this.isDeleted() + }; + } + set data(text) { + if (text !== this.#text) { + this.#richText = null; + } + if (text === null) { + this.#text = ""; + this.#deleted = true; + return; + } + this.#text = text; + this.#date = new Date(); + this.#deleted = false; + } + restoreData({ + text, + richText, + date + }) { + this.#text = text; + this.#richText = richText; + this.#date = date; + this.#deleted = false; + } + setInitialText(text, richText = null) { + this.#initialText = text; + this.data = text; + this.#date = null; + this.#richText = richText; + } + shown() {} + destroy() { + this.#commentToolbarButton?.remove(); + this.#commentToolbarButton = null; + this.#commentStandaloneButton?.remove(); + this.#commentStandaloneButton = null; + this.#text = ""; + this.#richText = null; + this.#date = null; + this.#editor = null; + this.#commentWasFromKeyBoard = false; + this.#deleted = false; + } +} + +;// ./src/display/touch_manager.js + +class TouchManager { + #container; + #isPinching = false; + #isPinchingStopped = null; + #isPinchingDisabled; + #onPinchStart; + #onPinching; + #onPinchEnd; + #pointerDownAC = null; + #signal; + #touchInfo = null; + #touchManagerAC; + #touchMoveAC = null; + constructor({ + container, + isPinchingDisabled = null, + isPinchingStopped = null, + onPinchStart = null, + onPinching = null, + onPinchEnd = null, + signal + }) { + this.#container = container; + this.#isPinchingStopped = isPinchingStopped; + this.#isPinchingDisabled = isPinchingDisabled; + this.#onPinchStart = onPinchStart; + this.#onPinching = onPinching; + this.#onPinchEnd = onPinchEnd; + this.#touchManagerAC = new AbortController(); + this.#signal = AbortSignal.any([signal, this.#touchManagerAC.signal]); + container.addEventListener("touchstart", this.#onTouchStart.bind(this), { + passive: false, + signal: this.#signal + }); + } + get MIN_TOUCH_DISTANCE_TO_PINCH() { + return 35 / OutputScale.pixelRatio; + } + #onTouchStart(evt) { + if (this.#isPinchingDisabled?.()) { + return; + } + if (evt.touches.length === 1) { + if (this.#pointerDownAC) { + return; + } + const pointerDownAC = this.#pointerDownAC = new AbortController(); + const signal = AbortSignal.any([this.#signal, pointerDownAC.signal]); + const container = this.#container; + const opts = { + capture: true, + signal, + passive: false + }; + const cancelPointerDown = e => { + if (e.pointerType === "touch") { + this.#pointerDownAC?.abort(); + this.#pointerDownAC = null; + } + }; + container.addEventListener("pointerdown", e => { + if (e.pointerType === "touch") { + stopEvent(e); + cancelPointerDown(e); + } + }, opts); + container.addEventListener("pointerup", cancelPointerDown, opts); + container.addEventListener("pointercancel", cancelPointerDown, opts); + return; + } + if (!this.#touchMoveAC) { + this.#touchMoveAC = new AbortController(); + const signal = AbortSignal.any([this.#signal, this.#touchMoveAC.signal]); + const container = this.#container; + const opt = { + signal, + capture: false, + passive: false + }; + container.addEventListener("touchmove", this.#onTouchMove.bind(this), opt); + const onTouchEnd = this.#onTouchEnd.bind(this); + container.addEventListener("touchend", onTouchEnd, opt); + container.addEventListener("touchcancel", onTouchEnd, opt); + opt.capture = true; + container.addEventListener("pointerdown", stopEvent, opt); + container.addEventListener("pointermove", stopEvent, opt); + container.addEventListener("pointercancel", stopEvent, opt); + container.addEventListener("pointerup", stopEvent, opt); + this.#onPinchStart?.(); + } + stopEvent(evt); + if (evt.touches.length !== 2 || this.#isPinchingStopped?.()) { + this.#touchInfo = null; + return; + } + let [touch0, touch1] = evt.touches; + if (touch0.identifier > touch1.identifier) { + [touch0, touch1] = [touch1, touch0]; + } + this.#touchInfo = { + touch0X: touch0.screenX, + touch0Y: touch0.screenY, + touch1X: touch1.screenX, + touch1Y: touch1.screenY + }; + } + #onTouchMove(evt) { + if (!this.#touchInfo || evt.touches.length !== 2) { + return; + } + stopEvent(evt); + let [touch0, touch1] = evt.touches; + if (touch0.identifier > touch1.identifier) { + [touch0, touch1] = [touch1, touch0]; + } + const { + screenX: screen0X, + screenY: screen0Y + } = touch0; + const { + screenX: screen1X, + screenY: screen1Y + } = touch1; + const touchInfo = this.#touchInfo; + const { + touch0X: pTouch0X, + touch0Y: pTouch0Y, + touch1X: pTouch1X, + touch1Y: pTouch1Y + } = touchInfo; + const prevGapX = pTouch1X - pTouch0X; + const prevGapY = pTouch1Y - pTouch0Y; + const currGapX = screen1X - screen0X; + const currGapY = screen1Y - screen0Y; + const distance = Math.hypot(currGapX, currGapY) || 1; + const pDistance = Math.hypot(prevGapX, prevGapY) || 1; + if (!this.#isPinching && Math.abs(pDistance - distance) <= TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH) { + return; + } + touchInfo.touch0X = screen0X; + touchInfo.touch0Y = screen0Y; + touchInfo.touch1X = screen1X; + touchInfo.touch1Y = screen1Y; + if (!this.#isPinching) { + this.#isPinching = true; + return; + } + const origin = [(screen0X + screen1X) / 2, (screen0Y + screen1Y) / 2]; + this.#onPinching?.(origin, pDistance, distance); + } + #onTouchEnd(evt) { + if (evt.touches.length >= 2) { + return; + } + if (this.#touchMoveAC) { + this.#touchMoveAC.abort(); + this.#touchMoveAC = null; + this.#onPinchEnd?.(); + } + if (!this.#touchInfo) { + return; + } + stopEvent(evt); + this.#touchInfo = null; + this.#isPinching = false; + } + destroy() { + this.#touchManagerAC?.abort(); + this.#touchManagerAC = null; + this.#pointerDownAC?.abort(); + this.#pointerDownAC = null; + } +} + +;// ./src/display/editor/editor.js + + + + + + + +class AnnotationEditor { + #accessibilityData = null; + #allResizerDivs = null; + #altText = null; + #comment = null; + #commentStandaloneButton = null; + #disabled = false; + #dragPointerId = null; + #dragPointerType = ""; + #resizersDiv = null; + #lastPointerCoords = null; + #savedDimensions = null; + #fakeAnnotation = null; + #focusAC = null; + #focusedResizerName = ""; + #hasBeenClicked = false; + #initialRect = null; + #isEditing = false; + #isInEditMode = false; + #isResizerEnabledForKeyboard = false; + #moveInDOMTimeout = null; + #prevDragX = 0; + #prevDragY = 0; + #telemetryTimeouts = null; + #touchManager = null; + isSelected = false; + _isCopy = false; + _editToolbar = null; + _initialOptions = Object.create(null); + _initialData = null; + _isVisible = true; + _uiManager = null; + _focusEventsAllowed = true; + static _l10n = null; + static _l10nResizer = null; + #isDraggable = false; + #zIndex = AnnotationEditor._zIndex++; + static _borderLineWidth = -1; + static _colorManager = new ColorManager(); + static _zIndex = 1; + static _telemetryTimeout = 1000; + static get _resizerKeyboardManager() { + const resize = AnnotationEditor.prototype._resizeWithKeyboard; + const small = AnnotationEditorUIManager.TRANSLATE_SMALL; + const big = AnnotationEditorUIManager.TRANSLATE_BIG; + return shadow(this, "_resizerKeyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], resize, { + args: [-small, 0] + }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], resize, { + args: [-big, 0] + }], [["ArrowRight", "mac+ArrowRight"], resize, { + args: [small, 0] + }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], resize, { + args: [big, 0] + }], [["ArrowUp", "mac+ArrowUp"], resize, { + args: [0, -small] + }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], resize, { + args: [0, -big] + }], [["ArrowDown", "mac+ArrowDown"], resize, { + args: [0, small] + }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], resize, { + args: [0, big] + }], [["Escape", "mac+Escape"], AnnotationEditor.prototype._stopResizingWithKeyboard]])); + } + constructor(parameters) { + this.parent = parameters.parent; + this.id = parameters.id; + this.width = this.height = null; + this.pageIndex = parameters.parent.pageIndex; + this.name = parameters.name; + this.div = null; + this._uiManager = parameters.uiManager; + this.annotationElementId = null; + this._willKeepAspectRatio = false; + this._initialOptions.isCentered = parameters.isCentered; + this._structTreeParentId = null; + this.annotationElementId = parameters.annotationElementId || null; + this.creationDate = parameters.creationDate || new Date(); + this.modificationDate = parameters.modificationDate || null; + this.canAddComment = true; + const { + rotation, + rawDims: { + pageWidth, + pageHeight, + pageX, + pageY + } + } = this.parent.viewport; + this.rotation = rotation; + this.pageRotation = (360 + rotation - this._uiManager.viewParameters.rotation) % 360; + this.pageDimensions = [pageWidth, pageHeight]; + this.pageTranslation = [pageX, pageY]; + const [width, height] = this.parentDimensions; + this.x = parameters.x / width; + this.y = parameters.y / height; + this.isAttachedToDOM = false; + this.deleted = false; + } + updatePageIndex(newPageIndex) { + this.pageIndex = newPageIndex; + } + get editorType() { + return Object.getPrototypeOf(this).constructor._type; + } + get mode() { + return Object.getPrototypeOf(this).constructor._editorType; + } + static get isDrawer() { + return false; + } + static get _defaultLineColor() { + return shadow(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText")); + } + static deleteAnnotationElement(editor) { + const fakeEditor = new FakeEditor({ + id: editor.parent.getNextId(), + parent: editor.parent, + uiManager: editor._uiManager + }); + fakeEditor.annotationElementId = editor.annotationElementId; + fakeEditor.deleted = true; + fakeEditor._uiManager.addToAnnotationStorage(fakeEditor); + } + static initialize(l10n, _uiManager) { + AnnotationEditor._l10n ??= l10n; + AnnotationEditor._l10nResizer ||= Object.freeze({ + topLeft: "pdfjs-editor-resizer-top-left", + topMiddle: "pdfjs-editor-resizer-top-middle", + topRight: "pdfjs-editor-resizer-top-right", + middleRight: "pdfjs-editor-resizer-middle-right", + bottomRight: "pdfjs-editor-resizer-bottom-right", + bottomMiddle: "pdfjs-editor-resizer-bottom-middle", + bottomLeft: "pdfjs-editor-resizer-bottom-left", + middleLeft: "pdfjs-editor-resizer-middle-left" + }); + if (AnnotationEditor._borderLineWidth !== -1) { + return; + } + const style = getComputedStyle(document.documentElement); + AnnotationEditor._borderLineWidth = parseFloat(style.getPropertyValue("--outline-width")) || 0; + } + static updateDefaultParams(_type, _value) {} + static get defaultPropertiesToUpdate() { + return []; + } + static isHandlingMimeForPasting(mime) { + return false; + } + static paste(item, parent) { + unreachable("Not implemented"); + } + get propertiesToUpdate() { + return []; + } + get _isDraggable() { + return this.#isDraggable; + } + set _isDraggable(value) { + this.#isDraggable = value; + this.div?.classList.toggle("draggable", value); + } + get uid() { + return this.annotationElementId || this.id; + } + get isEnterHandled() { + return true; + } + center() { + const [pageWidth, pageHeight] = this.pageDimensions; + switch (this.parentRotation) { + case 90: + this.x -= this.height * pageHeight / (pageWidth * 2); + this.y += this.width * pageWidth / (pageHeight * 2); + break; + case 180: + this.x += this.width / 2; + this.y += this.height / 2; + break; + case 270: + this.x += this.height * pageHeight / (pageWidth * 2); + this.y -= this.width * pageWidth / (pageHeight * 2); + break; + default: + this.x -= this.width / 2; + this.y -= this.height / 2; + break; + } + this.fixAndSetPosition(); + } + addCommands(params) { + this._uiManager.addCommands(params); + } + get currentLayer() { + return this._uiManager.currentLayer; + } + setInBackground() { + this.div.style.zIndex = 0; + } + setInForeground() { + this.div.style.zIndex = this.#zIndex; + } + setParent(parent) { + if (parent !== null) { + this.pageIndex = parent.pageIndex; + this.pageDimensions = parent.pageDimensions; + } else { + this.#stopResizing(); + this.#fakeAnnotation?.remove(); + this.#fakeAnnotation = null; + } + this.parent = parent; + } + focusin(event) { + if (!this._focusEventsAllowed) { + return; + } + if (!this.#hasBeenClicked) { + this.parent.setSelected(this); + } else { + this.#hasBeenClicked = false; + } + } + focusout(event) { + if (!this._focusEventsAllowed) { + return; + } + if (!this.isAttachedToDOM) { + return; + } + const target = event.relatedTarget; + if (target?.closest(`#${this.id}`)) { + return; + } + event.preventDefault(); + if (!this.parent?.isMultipleSelection) { + this.commitOrRemove(); + } + } + commitOrRemove() { + if (this.isEmpty()) { + this.remove(); + } else { + this.commit(); + } + } + commit() { + if (!this.isInEditMode()) { + return; + } + this.addToAnnotationStorage(); + } + addToAnnotationStorage() { + this._uiManager.addToAnnotationStorage(this); + } + setAt(x, y, tx, ty) { + const [width, height] = this.parentDimensions; + [tx, ty] = this.screenToPageTranslation(tx, ty); + this.x = (x + tx) / width; + this.y = (y + ty) / height; + this.fixAndSetPosition(); + } + _moveAfterPaste(baseX, baseY) { + const [parentWidth, parentHeight] = this.parentDimensions; + this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight); + this._onTranslated(); + } + #translate([width, height], x, y) { + [x, y] = this.screenToPageTranslation(x, y); + this.x += x / width; + this.y += y / height; + this._onTranslating(this.x, this.y); + this.fixAndSetPosition(); + } + translate(x, y) { + this.#translate(this.parentDimensions, x, y); + } + translateInPage(x, y) { + this.#initialRect ||= [this.x, this.y, this.width, this.height]; + this.#translate(this.pageDimensions, x, y); + this.div.scrollIntoView({ + block: "nearest" + }); + } + translationDone() { + this._onTranslated(this.x, this.y); + } + drag(tx, ty) { + this.#initialRect ||= [this.x, this.y, this.width, this.height]; + const { + div, + parentDimensions: [parentWidth, parentHeight] + } = this; + this.x += tx / parentWidth; + this.y += ty / parentHeight; + if (this.parent && (this.x < 0 || this.x > 1 || this.y < 0 || this.y > 1)) { + const { + x, + y + } = this.div.getBoundingClientRect(); + if (this.parent.findNewParent(this, x, y)) { + this.x -= Math.floor(this.x); + this.y -= Math.floor(this.y); + } + } + let { + x, + y + } = this; + const [bx, by] = this.getBaseTranslation(); + x += bx; + y += by; + const { + style + } = div; + style.left = `${(100 * x).toFixed(2)}%`; + style.top = `${(100 * y).toFixed(2)}%`; + this._onTranslating(x, y); + div.scrollIntoView({ + block: "nearest" + }); + } + _onTranslating(x, y) {} + _onTranslated(x, y) {} + get _hasBeenMoved() { + return !!this.#initialRect && (this.#initialRect[0] !== this.x || this.#initialRect[1] !== this.y); + } + get _hasBeenResized() { + return !!this.#initialRect && (this.#initialRect[2] !== this.width || this.#initialRect[3] !== this.height); + } + getBaseTranslation() { + const [parentWidth, parentHeight] = this.parentDimensions; + const { + _borderLineWidth + } = AnnotationEditor; + const x = _borderLineWidth / parentWidth; + const y = _borderLineWidth / parentHeight; + switch (this.rotation) { + case 90: + return [-x, y]; + case 180: + return [x, y]; + case 270: + return [x, -y]; + default: + return [-x, -y]; + } + } + get _mustFixPosition() { + return true; + } + fixAndSetPosition(rotation = this.rotation) { + const { + div: { + style + }, + pageDimensions: [pageWidth, pageHeight] + } = this; + let { + x, + y, + width, + height + } = this; + width *= pageWidth; + height *= pageHeight; + x *= pageWidth; + y *= pageHeight; + if (this._mustFixPosition) { + switch (rotation) { + case 0: + x = MathClamp(x, 0, pageWidth - width); + y = MathClamp(y, 0, pageHeight - height); + break; + case 90: + x = MathClamp(x, 0, pageWidth - height); + y = MathClamp(y, width, pageHeight); + break; + case 180: + x = MathClamp(x, width, pageWidth); + y = MathClamp(y, height, pageHeight); + break; + case 270: + x = MathClamp(x, height, pageWidth); + y = MathClamp(y, 0, pageHeight - width); + break; + } + } + this.x = x /= pageWidth; + this.y = y /= pageHeight; + const [bx, by] = this.getBaseTranslation(); + x += bx; + y += by; + style.left = `${(100 * x).toFixed(2)}%`; + style.top = `${(100 * y).toFixed(2)}%`; + this.moveInDOM(); + } + static #rotatePoint(x, y, angle) { + switch (angle) { + case 90: + return [y, -x]; + case 180: + return [-x, -y]; + case 270: + return [-y, x]; + default: + return [x, y]; + } + } + screenToPageTranslation(x, y) { + return AnnotationEditor.#rotatePoint(x, y, this.parentRotation); + } + pageTranslationToScreen(x, y) { + return AnnotationEditor.#rotatePoint(x, y, 360 - this.parentRotation); + } + #getRotationMatrix(rotation) { + switch (rotation) { + case 90: + { + const [pageWidth, pageHeight] = this.pageDimensions; + return [0, -pageWidth / pageHeight, pageHeight / pageWidth, 0]; + } + case 180: + return [-1, 0, 0, -1]; + case 270: + { + const [pageWidth, pageHeight] = this.pageDimensions; + return [0, pageWidth / pageHeight, -pageHeight / pageWidth, 0]; + } + default: + return [1, 0, 0, 1]; + } + } + get parentScale() { + return this._uiManager.viewParameters.realScale; + } + get parentRotation() { + return (this._uiManager.viewParameters.rotation + this.pageRotation) % 360; + } + get parentDimensions() { + const { + parentScale, + pageDimensions: [pageWidth, pageHeight] + } = this; + return [pageWidth * parentScale, pageHeight * parentScale]; + } + setDims() { + const { + div: { + style + }, + width, + height + } = this; + style.width = `${(100 * width).toFixed(2)}%`; + style.height = `${(100 * height).toFixed(2)}%`; + } + getInitialTranslation() { + return [0, 0]; + } + #createResizers() { + if (this.#resizersDiv) { + return; + } + this.#resizersDiv = document.createElement("div"); + this.#resizersDiv.classList.add("resizers"); + const classes = this._willKeepAspectRatio ? ["topLeft", "topRight", "bottomRight", "bottomLeft"] : ["topLeft", "topMiddle", "topRight", "middleRight", "bottomRight", "bottomMiddle", "bottomLeft", "middleLeft"]; + const signal = this._uiManager._signal; + for (const name of classes) { + const div = document.createElement("div"); + this.#resizersDiv.append(div); + div.classList.add("resizer", name); + div.setAttribute("data-resizer-name", name); + div.addEventListener("pointerdown", this.#resizerPointerdown.bind(this, name), { + signal + }); + div.addEventListener("contextmenu", noContextMenu, { + signal + }); + div.tabIndex = -1; + } + this.div.prepend(this.#resizersDiv); + } + #resizerPointerdown(name, event) { + event.preventDefault(); + const { + isMac + } = FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + return; + } + this.#altText?.toggle(false); + const savedDraggable = this._isDraggable; + this._isDraggable = false; + this.#lastPointerCoords = [event.screenX, event.screenY]; + const ac = new AbortController(); + const signal = this._uiManager.combinedSignal(ac); + this.parent.togglePointerEvents(false); + window.addEventListener("pointermove", this.#resizerPointermove.bind(this, name), { + passive: true, + capture: true, + signal + }); + window.addEventListener("touchmove", stopEvent, { + passive: false, + signal + }); + window.addEventListener("contextmenu", noContextMenu, { + signal + }); + this.#savedDimensions = { + savedX: this.x, + savedY: this.y, + savedWidth: this.width, + savedHeight: this.height + }; + const savedParentCursor = this.parent.div.style.cursor; + const savedCursor = this.div.style.cursor; + this.div.style.cursor = this.parent.div.style.cursor = window.getComputedStyle(event.target).cursor; + const pointerUpCallback = () => { + ac.abort(); + this.parent.togglePointerEvents(true); + this.#altText?.toggle(true); + this._isDraggable = savedDraggable; + this.parent.div.style.cursor = savedParentCursor; + this.div.style.cursor = savedCursor; + this.#addResizeToUndoStack(); + }; + window.addEventListener("pointerup", pointerUpCallback, { + signal + }); + window.addEventListener("blur", pointerUpCallback, { + signal + }); + } + #resize(x, y, width, height) { + this.width = width; + this.height = height; + this.x = x; + this.y = y; + this.setDims(); + this.fixAndSetPosition(); + this._onResized(); + } + _onResized() {} + #addResizeToUndoStack() { + if (!this.#savedDimensions) { + return; + } + const { + savedX, + savedY, + savedWidth, + savedHeight + } = this.#savedDimensions; + this.#savedDimensions = null; + const newX = this.x; + const newY = this.y; + const newWidth = this.width; + const newHeight = this.height; + if (newX === savedX && newY === savedY && newWidth === savedWidth && newHeight === savedHeight) { + return; + } + this.addCommands({ + cmd: this.#resize.bind(this, newX, newY, newWidth, newHeight), + undo: this.#resize.bind(this, savedX, savedY, savedWidth, savedHeight), + mustExec: true + }); + } + static _round(x) { + return Math.round(x * 10000) / 10000; + } + #resizerPointermove(name, event) { + const [parentWidth, parentHeight] = this.parentDimensions; + const savedX = this.x; + const savedY = this.y; + const savedWidth = this.width; + const savedHeight = this.height; + const minWidth = AnnotationEditor.MIN_SIZE / parentWidth; + const minHeight = AnnotationEditor.MIN_SIZE / parentHeight; + const rotationMatrix = this.#getRotationMatrix(this.rotation); + const transf = (x, y) => [rotationMatrix[0] * x + rotationMatrix[2] * y, rotationMatrix[1] * x + rotationMatrix[3] * y]; + const invRotationMatrix = this.#getRotationMatrix(360 - this.rotation); + const invTransf = (x, y) => [invRotationMatrix[0] * x + invRotationMatrix[2] * y, invRotationMatrix[1] * x + invRotationMatrix[3] * y]; + let getPoint; + let getOpposite; + let isDiagonal = false; + let isHorizontal = false; + switch (name) { + case "topLeft": + isDiagonal = true; + getPoint = (w, h) => [0, 0]; + getOpposite = (w, h) => [w, h]; + break; + case "topMiddle": + getPoint = (w, h) => [w / 2, 0]; + getOpposite = (w, h) => [w / 2, h]; + break; + case "topRight": + isDiagonal = true; + getPoint = (w, h) => [w, 0]; + getOpposite = (w, h) => [0, h]; + break; + case "middleRight": + isHorizontal = true; + getPoint = (w, h) => [w, h / 2]; + getOpposite = (w, h) => [0, h / 2]; + break; + case "bottomRight": + isDiagonal = true; + getPoint = (w, h) => [w, h]; + getOpposite = (w, h) => [0, 0]; + break; + case "bottomMiddle": + getPoint = (w, h) => [w / 2, h]; + getOpposite = (w, h) => [w / 2, 0]; + break; + case "bottomLeft": + isDiagonal = true; + getPoint = (w, h) => [0, h]; + getOpposite = (w, h) => [w, 0]; + break; + case "middleLeft": + isHorizontal = true; + getPoint = (w, h) => [0, h / 2]; + getOpposite = (w, h) => [w, h / 2]; + break; + } + const point = getPoint(savedWidth, savedHeight); + const oppositePoint = getOpposite(savedWidth, savedHeight); + let transfOppositePoint = transf(...oppositePoint); + const oppositeX = AnnotationEditor._round(savedX + transfOppositePoint[0]); + const oppositeY = AnnotationEditor._round(savedY + transfOppositePoint[1]); + let ratioX = 1; + let ratioY = 1; + let deltaX, deltaY; + if (!event.fromKeyboard) { + const { + screenX, + screenY + } = event; + const [lastScreenX, lastScreenY] = this.#lastPointerCoords; + [deltaX, deltaY] = this.screenToPageTranslation(screenX - lastScreenX, screenY - lastScreenY); + this.#lastPointerCoords[0] = screenX; + this.#lastPointerCoords[1] = screenY; + } else { + ({ + deltaX, + deltaY + } = event); + } + [deltaX, deltaY] = invTransf(deltaX / parentWidth, deltaY / parentHeight); + if (isDiagonal) { + const oldDiag = Math.hypot(savedWidth, savedHeight); + ratioX = ratioY = Math.max(Math.min(Math.hypot(oppositePoint[0] - point[0] - deltaX, oppositePoint[1] - point[1] - deltaY) / oldDiag, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight); + } else if (isHorizontal) { + ratioX = MathClamp(Math.abs(oppositePoint[0] - point[0] - deltaX), minWidth, 1) / savedWidth; + } else { + ratioY = MathClamp(Math.abs(oppositePoint[1] - point[1] - deltaY), minHeight, 1) / savedHeight; + } + const newWidth = AnnotationEditor._round(savedWidth * ratioX); + const newHeight = AnnotationEditor._round(savedHeight * ratioY); + transfOppositePoint = transf(...getOpposite(newWidth, newHeight)); + const newX = oppositeX - transfOppositePoint[0]; + const newY = oppositeY - transfOppositePoint[1]; + this.#initialRect ||= [this.x, this.y, this.width, this.height]; + this.width = newWidth; + this.height = newHeight; + this.x = newX; + this.y = newY; + this.setDims(); + this.fixAndSetPosition(); + this._onResizing(); + } + _onResizing() {} + altTextFinish() { + this.#altText?.finish(); + } + get toolbarButtons() { + return null; + } + async addEditToolbar() { + if (this._editToolbar || this.#isInEditMode) { + return this._editToolbar; + } + this._editToolbar = new EditorToolbar(this); + this.div.append(this._editToolbar.render()); + const { + toolbarButtons + } = this; + if (toolbarButtons) { + for (const [name, tool] of toolbarButtons) { + await this._editToolbar.addButton(name, tool); + } + } + if (!this.hasComment) { + this._editToolbar.addButton("comment", this.addCommentButton()); + } + this._editToolbar.addButton("delete"); + return this._editToolbar; + } + addCommentButtonInToolbar() { + this._editToolbar?.addButtonBefore("comment", this.addCommentButton(), ".deleteButton"); + } + removeCommentButtonFromToolbar() { + this._editToolbar?.removeButton("comment"); + } + removeEditToolbar() { + this._editToolbar?.remove(); + this._editToolbar = null; + this.#altText?.destroy(); + } + addContainer(container) { + const editToolbarDiv = this._editToolbar?.div; + if (editToolbarDiv) { + editToolbarDiv.before(container); + } else { + this.div.append(container); + } + } + getClientDimensions() { + return this.div.getBoundingClientRect(); + } + createAltText() { + if (!this.#altText) { + AltText.initialize(AnnotationEditor._l10n); + this.#altText = new AltText(this); + if (this.#accessibilityData) { + this.#altText.data = this.#accessibilityData; + this.#accessibilityData = null; + } + } + return this.#altText; + } + get altTextData() { + return this.#altText?.data; + } + set altTextData(data) { + if (!this.#altText) { + return; + } + this.#altText.data = data; + } + get guessedAltText() { + return this.#altText?.guessedText; + } + async setGuessedAltText(text) { + await this.#altText?.setGuessedText(text); + } + serializeAltText(isForCopying) { + return this.#altText?.serialize(isForCopying); + } + hasAltText() { + return !!this.#altText && !this.#altText.isEmpty(); + } + hasAltTextData() { + return this.#altText?.hasData() ?? false; + } + focusCommentButton() { + this.#comment?.focusButton(); + } + addCommentButton() { + return this.canAddComment ? this.#comment ||= new Comment(this) : null; + } + addStandaloneCommentButton() { + if (!this._uiManager.hasCommentManager()) { + return; + } + if (this.#commentStandaloneButton) { + if (this._uiManager.isEditingMode()) { + this.#commentStandaloneButton.classList.remove("hidden"); + } + return; + } + if (!this.hasComment) { + return; + } + this.#commentStandaloneButton = this.#comment.renderForStandalone(); + this.div.append(this.#commentStandaloneButton); + } + removeStandaloneCommentButton() { + this.#comment.removeStandaloneCommentButton(); + this.#commentStandaloneButton = null; + } + hideStandaloneCommentButton() { + this.#commentStandaloneButton?.classList.add("hidden"); + } + get comment() { + if (!this.#comment) { + return null; + } + const { + data: { + richText, + text, + date, + deleted + } + } = this.#comment; + return { + text, + richText, + date, + deleted, + color: this.getNonHCMColor(), + opacity: this.opacity ?? 1 + }; + } + set comment(value) { + this.#comment ||= new Comment(this); + if (typeof value === "object" && value !== null) { + this.#comment.restoreData(value); + } else { + this.#comment.data = value; + } + if (this.hasComment) { + this.removeCommentButtonFromToolbar(); + this.addStandaloneCommentButton(); + this._uiManager.updateComment(this); + } else { + this.addCommentButtonInToolbar(); + this.removeStandaloneCommentButton(); + this._uiManager.removeComment(this); + } + } + setCommentData({ + comment, + popupRef, + richText + }) { + if (!popupRef) { + return; + } + this.#comment ||= new Comment(this); + this.#comment.setInitialText(comment, richText); + if (!this.annotationElementId) { + return; + } + const storedData = this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId); + if (storedData) { + this.updateFromAnnotationLayer(storedData); + } + } + get hasEditedComment() { + return this.#comment?.hasBeenEdited(); + } + get hasDeletedComment() { + return this.#comment?.isDeleted(); + } + get hasComment() { + return !!this.#comment && !this.#comment.isEmpty() && !this.#comment.isDeleted(); + } + async editComment(options) { + this.#comment ||= new Comment(this); + this.#comment.edit(options); + } + toggleComment(isSelected, visibility = undefined) { + if (this.hasComment) { + this._uiManager.toggleComment(this, isSelected, visibility); + } + } + setSelectedCommentButton(selected) { + this.#comment.setSelectedButton(selected); + } + addComment(serialized) { + if (this.hasEditedComment) { + const DEFAULT_POPUP_WIDTH = 180; + const DEFAULT_POPUP_HEIGHT = 100; + const [,,, trY] = serialized.rect; + const [pageWidth] = this.pageDimensions; + const [pageX] = this.pageTranslation; + const blX = pageX + pageWidth + 1; + const blY = trY - DEFAULT_POPUP_HEIGHT; + const trX = blX + DEFAULT_POPUP_WIDTH; + serialized.popup = { + contents: this.comment.text, + deleted: this.comment.deleted, + rect: [blX, blY, trX, trY] + }; + } + } + updateFromAnnotationLayer({ + popup: { + contents, + deleted + } + }) { + this.#comment.data = deleted ? null : contents; + } + get parentBoundingClientRect() { + return this.parent.boundingClientRect; + } + render() { + const div = this.div = document.createElement("div"); + div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360); + div.className = this.name; + div.setAttribute("id", this.id); + div.tabIndex = this.#disabled ? -1 : 0; + div.setAttribute("role", "application"); + if (this.defaultL10nId) { + div.setAttribute("data-l10n-id", this.defaultL10nId); + } + if (!this._isVisible) { + div.classList.add("hidden"); + } + this.setInForeground(); + this.#addFocusListeners(); + const [parentWidth, parentHeight] = this.parentDimensions; + if (this.parentRotation % 180 !== 0) { + div.style.maxWidth = `${(100 * parentHeight / parentWidth).toFixed(2)}%`; + div.style.maxHeight = `${(100 * parentWidth / parentHeight).toFixed(2)}%`; + } + const [tx, ty] = this.getInitialTranslation(); + this.translate(tx, ty); + bindEvents(this, div, ["keydown", "pointerdown", "dblclick"]); + if (this.isResizable && this._uiManager._supportsPinchToZoom) { + this.#touchManager ||= new TouchManager({ + container: div, + isPinchingDisabled: () => !this.isSelected, + onPinchStart: this.#touchPinchStartCallback.bind(this), + onPinching: this.#touchPinchCallback.bind(this), + onPinchEnd: this.#touchPinchEndCallback.bind(this), + signal: this._uiManager._signal + }); + } + this.addStandaloneCommentButton(); + this._uiManager._editorUndoBar?.hide(); + return div; + } + #touchPinchStartCallback() { + this.#savedDimensions = { + savedX: this.x, + savedY: this.y, + savedWidth: this.width, + savedHeight: this.height + }; + this.#altText?.toggle(false); + this.parent.togglePointerEvents(false); + } + #touchPinchCallback(_origin, prevDistance, distance) { + const slowDownFactor = 0.7; + let factor = slowDownFactor * (distance / prevDistance) + 1 - slowDownFactor; + if (factor === 1) { + return; + } + const rotationMatrix = this.#getRotationMatrix(this.rotation); + const transf = (x, y) => [rotationMatrix[0] * x + rotationMatrix[2] * y, rotationMatrix[1] * x + rotationMatrix[3] * y]; + const [parentWidth, parentHeight] = this.parentDimensions; + const savedX = this.x; + const savedY = this.y; + const savedWidth = this.width; + const savedHeight = this.height; + const minWidth = AnnotationEditor.MIN_SIZE / parentWidth; + const minHeight = AnnotationEditor.MIN_SIZE / parentHeight; + factor = Math.max(Math.min(factor, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight); + const newWidth = AnnotationEditor._round(savedWidth * factor); + const newHeight = AnnotationEditor._round(savedHeight * factor); + if (newWidth === savedWidth && newHeight === savedHeight) { + return; + } + this.#initialRect ||= [savedX, savedY, savedWidth, savedHeight]; + const transfCenterPoint = transf(savedWidth / 2, savedHeight / 2); + const centerX = AnnotationEditor._round(savedX + transfCenterPoint[0]); + const centerY = AnnotationEditor._round(savedY + transfCenterPoint[1]); + const newTransfCenterPoint = transf(newWidth / 2, newHeight / 2); + this.x = centerX - newTransfCenterPoint[0]; + this.y = centerY - newTransfCenterPoint[1]; + this.width = newWidth; + this.height = newHeight; + this.setDims(); + this.fixAndSetPosition(); + this._onResizing(); + } + #touchPinchEndCallback() { + this.#altText?.toggle(true); + this.parent.togglePointerEvents(true); + this.#addResizeToUndoStack(); + } + pointerdown(event) { + const { + isMac + } = FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + event.preventDefault(); + return; + } + this.#hasBeenClicked = true; + if (this._isDraggable) { + this.#setUpDragSession(event); + return; + } + this.#selectOnPointerEvent(event); + } + #selectOnPointerEvent(event) { + const { + isMac + } = FeatureTest.platform; + if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) { + this.parent.toggleSelected(this); + } else { + this.parent.setSelected(this); + } + } + #setUpDragSession(event) { + const { + isSelected + } = this; + this._uiManager.setUpDragSession(); + let hasDraggingStarted = false; + const ac = new AbortController(); + const signal = this._uiManager.combinedSignal(ac); + const opts = { + capture: true, + passive: false, + signal + }; + const cancelDrag = e => { + ac.abort(); + this.#dragPointerId = null; + this.#hasBeenClicked = false; + if (!this._uiManager.endDragSession()) { + this.#selectOnPointerEvent(e); + } + if (hasDraggingStarted) { + this._onStopDragging(); + } + }; + if (isSelected) { + this.#prevDragX = event.clientX; + this.#prevDragY = event.clientY; + this.#dragPointerId = event.pointerId; + this.#dragPointerType = event.pointerType; + window.addEventListener("pointermove", e => { + if (!hasDraggingStarted) { + hasDraggingStarted = true; + this._uiManager.toggleComment(this, true, false); + this._onStartDragging(); + } + const { + clientX: x, + clientY: y, + pointerId + } = e; + if (pointerId !== this.#dragPointerId) { + stopEvent(e); + return; + } + const [tx, ty] = this.screenToPageTranslation(x - this.#prevDragX, y - this.#prevDragY); + this.#prevDragX = x; + this.#prevDragY = y; + this._uiManager.dragSelectedEditors(tx, ty); + }, opts); + window.addEventListener("touchmove", stopEvent, opts); + window.addEventListener("pointerdown", e => { + if (e.pointerType === this.#dragPointerType) { + if (this.#touchManager || e.isPrimary) { + cancelDrag(e); + } + } + stopEvent(e); + }, opts); + } + const pointerUpCallback = e => { + if (!this.#dragPointerId || this.#dragPointerId === e.pointerId) { + cancelDrag(e); + return; + } + stopEvent(e); + }; + window.addEventListener("pointerup", pointerUpCallback, { + signal + }); + window.addEventListener("blur", pointerUpCallback, { + signal + }); + } + _onStartDragging() {} + _onStopDragging() {} + moveInDOM() { + if (this.#moveInDOMTimeout) { + clearTimeout(this.#moveInDOMTimeout); + } + this.#moveInDOMTimeout = setTimeout(() => { + this.#moveInDOMTimeout = null; + this.parent?.moveEditorInDOM(this); + }, 0); + } + _setParentAndPosition(parent, x, y) { + parent.changeParent(this); + this.x = x; + this.y = y; + this.fixAndSetPosition(); + this._onTranslated(); + } + getRect(tx, ty, rotation = this.rotation) { + const scale = this.parentScale; + const [pageWidth, pageHeight] = this.pageDimensions; + const [pageX, pageY] = this.pageTranslation; + const shiftX = tx / scale; + const shiftY = ty / scale; + const x = this.x * pageWidth; + const y = this.y * pageHeight; + const width = this.width * pageWidth; + const height = this.height * pageHeight; + switch (rotation) { + case 0: + return [x + shiftX + pageX, pageHeight - y - shiftY - height + pageY, x + shiftX + width + pageX, pageHeight - y - shiftY + pageY]; + case 90: + return [x + shiftY + pageX, pageHeight - y + shiftX + pageY, x + shiftY + height + pageX, pageHeight - y + shiftX + width + pageY]; + case 180: + return [x - shiftX - width + pageX, pageHeight - y + shiftY + pageY, x - shiftX + pageX, pageHeight - y + shiftY + height + pageY]; + case 270: + return [x - shiftY - height + pageX, pageHeight - y - shiftX - width + pageY, x - shiftY + pageX, pageHeight - y - shiftX + pageY]; + default: + throw new Error("Invalid rotation"); + } + } + getRectInCurrentCoords(rect, pageHeight) { + const [x1, y1, x2, y2] = rect; + const width = x2 - x1; + const height = y2 - y1; + switch (this.rotation) { + case 0: + return [x1, pageHeight - y2, width, height]; + case 90: + return [x1, pageHeight - y1, height, width]; + case 180: + return [x2, pageHeight - y1, width, height]; + case 270: + return [x2, pageHeight - y2, height, width]; + default: + throw new Error("Invalid rotation"); + } + } + getPDFRect() { + return this.getRect(0, 0); + } + getNonHCMColor() { + return this.color && AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color)); + } + onUpdatedColor() { + this.#comment?.onUpdatedColor(); + } + getData() { + const { + comment: { + text: str, + color, + date, + opacity, + deleted, + richText + }, + uid: id, + pageIndex, + creationDate, + modificationDate + } = this; + return { + id, + pageIndex, + rect: this.getPDFRect(), + richText, + contentsObj: { + str + }, + creationDate, + modificationDate: date || modificationDate, + popupRef: !deleted, + color, + opacity + }; + } + onceAdded(focus) {} + isEmpty() { + return false; + } + enableEditMode() { + if (this.isInEditMode()) { + return false; + } + this.parent.setEditingState(false); + this.#isInEditMode = true; + return true; + } + disableEditMode() { + if (!this.isInEditMode()) { + return false; + } + this.parent.setEditingState(true); + this.#isInEditMode = false; + return true; + } + isInEditMode() { + return this.#isInEditMode; + } + shouldGetKeyboardEvents() { + return this.#isResizerEnabledForKeyboard; + } + needsToBeRebuilt() { + return this.div && !this.isAttachedToDOM; + } + get isOnScreen() { + const { + top, + left, + bottom, + right + } = this.getClientDimensions(); + const { + innerHeight, + innerWidth + } = window; + return left < innerWidth && right > 0 && top < innerHeight && bottom > 0; + } + #addFocusListeners() { + if (this.#focusAC || !this.div) { + return; + } + this.#focusAC = new AbortController(); + const signal = this._uiManager.combinedSignal(this.#focusAC); + this.div.addEventListener("focusin", this.focusin.bind(this), { + signal + }); + this.div.addEventListener("focusout", this.focusout.bind(this), { + signal + }); + } + rebuild() { + this.#addFocusListeners(); + } + rotate(_angle) {} + resize() {} + serializeDeleted() { + return { + id: this.annotationElementId, + deleted: true, + pageIndex: this.pageIndex, + popupRef: this._initialData?.popupRef || "" + }; + } + serialize(isForCopying = false, context = null) { + return { + annotationType: this.mode, + pageIndex: this.pageIndex, + rect: this.getPDFRect(), + rotation: this.rotation, + structTreeParentId: this._structTreeParentId, + popupRef: this._initialData?.popupRef || "" + }; + } + static async deserialize(data, parent, uiManager) { + const editor = new this.prototype.constructor({ + parent, + id: parent.getNextId(), + uiManager, + annotationElementId: data.annotationElementId, + creationDate: data.creationDate, + modificationDate: data.modificationDate + }); + editor.rotation = data.rotation; + editor.#accessibilityData = data.accessibilityData; + editor._isCopy = data.isCopy || false; + const [pageWidth, pageHeight] = editor.pageDimensions; + const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight); + editor.x = x / pageWidth; + editor.y = y / pageHeight; + editor.width = width / pageWidth; + editor.height = height / pageHeight; + return editor; + } + get hasBeenModified() { + return !!this.annotationElementId && (this.deleted || this.serialize() !== null); + } + remove() { + this.#focusAC?.abort(); + this.#focusAC = null; + if (!this.isEmpty()) { + this.commit(); + } + if (this.parent) { + this.parent.remove(this); + } else { + this._uiManager.removeEditor(this); + } + this.hideCommentPopup(); + if (this.#moveInDOMTimeout) { + clearTimeout(this.#moveInDOMTimeout); + this.#moveInDOMTimeout = null; + } + this.#stopResizing(); + this.removeEditToolbar(); + if (this.#telemetryTimeouts) { + for (const timeout of this.#telemetryTimeouts.values()) { + clearTimeout(timeout); + } + this.#telemetryTimeouts = null; + } + this.parent = null; + this.#touchManager?.destroy(); + this.#touchManager = null; + this.#fakeAnnotation?.remove(); + this.#fakeAnnotation = null; + } + get isResizable() { + return false; + } + makeResizable() { + if (this.isResizable) { + this.#createResizers(); + this.#resizersDiv.classList.remove("hidden"); + } + } + get toolbarPosition() { + return null; + } + get commentButtonPosition() { + return this._uiManager.direction === "ltr" ? [1, 0] : [0, 0]; + } + get commentButtonPositionInPage() { + const { + commentButtonPosition: [posX, posY] + } = this; + const [blX, blY, trX, trY] = this.getPDFRect(); + return [AnnotationEditor._round(blX + (trX - blX) * posX), AnnotationEditor._round(blY + (trY - blY) * (1 - posY))]; + } + get commentButtonColor() { + return this._uiManager.makeCommentColor(this.getNonHCMColor(), this.opacity); + } + get commentPopupPosition() { + return this.#comment.commentPopupPositionInLayer; + } + set commentPopupPosition(pos) { + this.#comment.commentPopupPositionInLayer = pos; + } + hasDefaultPopupPosition() { + return this.#comment.hasDefaultPopupPosition(); + } + get commentButtonWidth() { + return this.#comment.commentButtonWidth; + } + get elementBeforePopup() { + return this.div; + } + setCommentButtonStates(options) { + this.#comment?.setCommentButtonStates(options); + } + keydown(event) { + if (!this.isResizable || event.target !== this.div || event.key !== "Enter") { + return; + } + this._uiManager.setSelected(this); + this.#savedDimensions = { + savedX: this.x, + savedY: this.y, + savedWidth: this.width, + savedHeight: this.height + }; + const children = this.#resizersDiv.children; + if (!this.#allResizerDivs) { + this.#allResizerDivs = Array.from(children); + const boundResizerKeydown = this.#resizerKeydown.bind(this); + const boundResizerBlur = this.#resizerBlur.bind(this); + const signal = this._uiManager._signal; + for (const div of this.#allResizerDivs) { + const name = div.getAttribute("data-resizer-name"); + div.setAttribute("role", "spinbutton"); + div.addEventListener("keydown", boundResizerKeydown, { + signal + }); + div.addEventListener("blur", boundResizerBlur, { + signal + }); + div.addEventListener("focus", this.#resizerFocus.bind(this, name), { + signal + }); + div.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]); + } + } + const first = this.#allResizerDivs[0]; + let firstPosition = 0; + for (const div of children) { + if (div === first) { + break; + } + firstPosition++; + } + const nextFirstPosition = (360 - this.rotation + this.parentRotation) % 360 / 90 * (this.#allResizerDivs.length / 4); + if (nextFirstPosition !== firstPosition) { + if (nextFirstPosition < firstPosition) { + for (let i = 0; i < firstPosition - nextFirstPosition; i++) { + this.#resizersDiv.append(this.#resizersDiv.firstElementChild); + } + } else if (nextFirstPosition > firstPosition) { + for (let i = 0; i < nextFirstPosition - firstPosition; i++) { + this.#resizersDiv.firstElementChild.before(this.#resizersDiv.lastElementChild); + } + } + let i = 0; + for (const child of children) { + const div = this.#allResizerDivs[i++]; + const name = div.getAttribute("data-resizer-name"); + child.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]); + } + } + this.#setResizerTabIndex(0); + this.#isResizerEnabledForKeyboard = true; + this.#resizersDiv.firstElementChild.focus({ + focusVisible: true + }); + event.preventDefault(); + event.stopImmediatePropagation(); + } + #resizerKeydown(event) { + AnnotationEditor._resizerKeyboardManager.exec(this, event); + } + #resizerBlur(event) { + if (this.#isResizerEnabledForKeyboard && event.relatedTarget?.parentNode !== this.#resizersDiv) { + this.#stopResizing(); + } + } + #resizerFocus(name) { + this.#focusedResizerName = this.#isResizerEnabledForKeyboard ? name : ""; + } + #setResizerTabIndex(value) { + if (!this.#allResizerDivs) { + return; + } + for (const div of this.#allResizerDivs) { + div.tabIndex = value; + } + } + _resizeWithKeyboard(x, y) { + if (!this.#isResizerEnabledForKeyboard) { + return; + } + this.#resizerPointermove(this.#focusedResizerName, { + deltaX: x, + deltaY: y, + fromKeyboard: true + }); + } + #stopResizing() { + this.#isResizerEnabledForKeyboard = false; + this.#setResizerTabIndex(-1); + this.#addResizeToUndoStack(); + } + _stopResizingWithKeyboard() { + this.#stopResizing(); + this.div.focus(); + } + select() { + if (this.isSelected && this._editToolbar) { + this._editToolbar.show(); + return; + } + this.isSelected = true; + this.makeResizable(); + this.div?.classList.add("selectedEditor"); + if (!this._editToolbar) { + this.addEditToolbar().then(() => { + if (this.div?.classList.contains("selectedEditor")) { + this._editToolbar?.show(); + } + }); + return; + } + this._editToolbar?.show(); + this.#altText?.toggleAltTextBadge(false); + } + focus() { + if (this.div && !this.div.contains(document.activeElement)) { + setTimeout(() => this.div?.focus({ + preventScroll: true + }), 0); + } + } + unselect() { + if (!this.isSelected) { + return; + } + this.isSelected = false; + this.#resizersDiv?.classList.add("hidden"); + this.div?.classList.remove("selectedEditor"); + if (this.div?.contains(document.activeElement)) { + this._uiManager.currentLayer.div.focus({ + preventScroll: true + }); + } + this._editToolbar?.hide(); + this.#altText?.toggleAltTextBadge(true); + this.hideCommentPopup(); + } + hideCommentPopup() { + if (this.hasComment) { + this._uiManager.toggleComment(null); + } + } + updateParams(type, value) {} + disableEditing() {} + enableEditing() {} + get canChangeContent() { + return false; + } + enterInEditMode() { + if (!this.canChangeContent) { + return; + } + this.enableEditMode(); + this.div.focus(); + } + dblclick(event) { + if (event.target.nodeName === "BUTTON") { + return; + } + this.enterInEditMode(); + this.parent.updateToolbar({ + mode: this.constructor._editorType, + editId: this.uid + }); + } + getElementForAltText() { + return this.div; + } + get contentDiv() { + return this.div; + } + get isEditing() { + return this.#isEditing; + } + set isEditing(value) { + this.#isEditing = value; + if (!this.parent) { + return; + } + if (value) { + this.parent.setSelected(this); + this.parent.setActiveEditor(this); + } else { + this.parent.setActiveEditor(null); + } + } + static get MIN_SIZE() { + return 16; + } + static canCreateNewEmptyEditor() { + return true; + } + get telemetryInitialData() { + return { + action: "added" + }; + } + get telemetryFinalData() { + return null; + } + _reportTelemetry(data, mustWait = false) { + if (mustWait) { + this.#telemetryTimeouts ||= new Map(); + const { + action + } = data; + let timeout = this.#telemetryTimeouts.get(action); + if (timeout) { + clearTimeout(timeout); + } + timeout = setTimeout(() => { + this._reportTelemetry(data); + this.#telemetryTimeouts.delete(action); + if (this.#telemetryTimeouts.size === 0) { + this.#telemetryTimeouts = null; + } + }, AnnotationEditor._telemetryTimeout); + this.#telemetryTimeouts.set(action, timeout); + return; + } + data.type ||= this.editorType; + this._uiManager._eventBus.dispatch("reporttelemetry", { + source: this, + details: { + type: "editing", + data + } + }); + } + show(visible = this._isVisible) { + this.div.classList.toggle("hidden", !visible); + this._isVisible = visible; + } + enable() { + if (this.div) { + this.div.tabIndex = 0; + } + this.#disabled = false; + } + disable() { + if (this.div) { + this.div.tabIndex = -1; + } + this.#disabled = true; + } + updateFakeAnnotationElement(annotationLayer) { + if (!this.#fakeAnnotation && !this.deleted) { + this.#fakeAnnotation = annotationLayer.addFakeAnnotation(this); + return; + } + if (this.deleted) { + this.#fakeAnnotation.remove(); + this.#fakeAnnotation = null; + return; + } + if (this.hasEditedComment || this._hasBeenMoved || this._hasBeenResized) { + this.#fakeAnnotation.updateEdited({ + rect: this.getPDFRect(), + popup: this.comment + }); + } + } + renderAnnotationElement(annotation) { + if (this.deleted) { + annotation.hide(); + return null; + } + let content = annotation.container.querySelector(".annotationContent"); + if (!content) { + content = document.createElement("div"); + content.classList.add("annotationContent", this.editorType); + annotation.container.prepend(content); + } else if (content.nodeName === "CANVAS") { + const canvas = content; + content = document.createElement("div"); + content.classList.add("annotationContent", this.editorType); + canvas.before(content); + } + return content; + } + resetAnnotationElement(annotation) { + const { + firstElementChild + } = annotation.container; + if (firstElementChild?.nodeName === "DIV" && firstElementChild.classList.contains("annotationContent")) { + firstElementChild.remove(); + } + } +} +class FakeEditor extends AnnotationEditor { + constructor(params) { + super(params); + this.annotationElementId = params.annotationElementId; + this.deleted = true; + } + serialize() { + return this.serializeDeleted(); + } +} + +;// ./src/shared/murmurhash3.js +const SEED = 0xc3d2e1f0; +const MASK_HIGH = 0xffff0000; +const MASK_LOW = 0xffff; +class MurmurHash3_64 { + constructor(seed) { + this.h1 = seed ? seed & 0xffffffff : SEED; + this.h2 = seed ? seed & 0xffffffff : SEED; + } + update(input) { + let data, length; + if (typeof input === "string") { + data = new Uint8Array(input.length * 2); + length = 0; + for (let i = 0, ii = input.length; i < ii; i++) { + const code = input.charCodeAt(i); + if (code <= 0xff) { + data[length++] = code; + } else { + data[length++] = code >>> 8; + data[length++] = code & 0xff; + } + } + } else if (ArrayBuffer.isView(input)) { + data = input.slice(); + length = data.byteLength; + } else { + throw new Error("Invalid data format, must be a string or TypedArray."); + } + const blockCounts = length >> 2; + const tailLength = length - blockCounts * 4; + const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts); + let k1 = 0, + k2 = 0; + let h1 = this.h1, + h2 = this.h2; + const C1 = 0xcc9e2d51, + C2 = 0x1b873593; + const C1_LOW = C1 & MASK_LOW, + C2_LOW = C2 & MASK_LOW; + for (let i = 0; i < blockCounts; i++) { + if (i & 1) { + k1 = dataUint32[i]; + k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW; + k1 = k1 << 15 | k1 >>> 17; + k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW; + h1 ^= k1; + h1 = h1 << 13 | h1 >>> 19; + h1 = h1 * 5 + 0xe6546b64; + } else { + k2 = dataUint32[i]; + k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW; + k2 = k2 << 15 | k2 >>> 17; + k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW; + h2 ^= k2; + h2 = h2 << 13 | h2 >>> 19; + h2 = h2 * 5 + 0xe6546b64; + } + } + k1 = 0; + switch (tailLength) { + case 3: + k1 ^= data[blockCounts * 4 + 2] << 16; + case 2: + k1 ^= data[blockCounts * 4 + 1] << 8; + case 1: + k1 ^= data[blockCounts * 4]; + k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW; + k1 = k1 << 15 | k1 >>> 17; + k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW; + if (blockCounts & 1) { + h1 ^= k1; + } else { + h2 ^= k1; + } + } + this.h1 = h1; + this.h2 = h2; + } + hexdigest() { + let h1 = this.h1, + h2 = this.h2; + h1 ^= h2 >>> 1; + h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW; + h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16; + h1 ^= h2 >>> 1; + h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW; + h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16; + h1 ^= h2 >>> 1; + return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0"); + } +} + +;// ./src/display/annotation_storage.js + + + +const SerializableEmpty = Object.freeze({ + map: null, + hash: "", + transfer: undefined +}); +class AnnotationStorage { + #modified = false; + #modifiedIds = null; + #editorsMap = null; + #storage = new Map(); + onSetModified = null; + onResetModified = null; + onAnnotationEditor = null; + getValue(key, defaultValue) { + const value = this.#storage.get(key); + if (value === undefined) { + return defaultValue; + } + return Object.assign(defaultValue, value); + } + getRawValue(key) { + return this.#storage.get(key); + } + remove(key) { + const storedValue = this.#storage.get(key); + if (storedValue === undefined) { + return; + } + if (storedValue instanceof AnnotationEditor) { + this.#editorsMap.delete(storedValue.annotationElementId); + } + this.#storage.delete(key); + if (this.#storage.size === 0) { + this.resetModified(); + } + if (typeof this.onAnnotationEditor === "function") { + for (const value of this.#storage.values()) { + if (value instanceof AnnotationEditor) { + return; + } + } + this.onAnnotationEditor(null); + } + } + setValue(key, value) { + const obj = this.#storage.get(key); + let modified = false; + if (obj !== undefined) { + for (const [entry, val] of Object.entries(value)) { + if (obj[entry] !== val) { + modified = true; + obj[entry] = val; + } + } + } else { + modified = true; + this.#storage.set(key, value); + } + if (modified) { + this.#setModified(); + } + if (value instanceof AnnotationEditor) { + (this.#editorsMap ||= new Map()).set(value.annotationElementId, value); + if (typeof this.onAnnotationEditor === "function") { + this.onAnnotationEditor(value.constructor._type); + } + } + } + has(key) { + return this.#storage.has(key); + } + get size() { + return this.#storage.size; + } + #setModified() { + if (!this.#modified) { + this.#modified = true; + if (typeof this.onSetModified === "function") { + this.onSetModified(); + } + } + } + resetModified() { + if (this.#modified) { + this.#modified = false; + if (typeof this.onResetModified === "function") { + this.onResetModified(); + } + } + } + get print() { + return new PrintAnnotationStorage(this); + } + get serializable() { + if (this.#storage.size === 0) { + return SerializableEmpty; + } + const map = new Map(), + hash = new MurmurHash3_64(), + transfer = []; + const context = Object.create(null); + let hasBitmap = false; + for (const [key, val] of this.#storage) { + const serialized = val instanceof AnnotationEditor ? val.serialize(false, context) : val; + if (val.page) { + val.pageIndex = val.page._pageIndex; + delete val.page; + } + if (serialized) { + map.set(key, serialized); + hash.update(`${key}:${JSON.stringify(serialized)}`); + hasBitmap ||= !!serialized.bitmap; + } + } + if (hasBitmap) { + for (const value of map.values()) { + if (value.bitmap) { + transfer.push(value.bitmap); + } + } + } + return map.size > 0 ? { + map, + hash: hash.hexdigest(), + transfer + } : SerializableEmpty; + } + get editorStats() { + let stats = null; + const typeToEditor = new Map(); + let numberOfEditedComments = 0; + let numberOfDeletedComments = 0; + for (const value of this.#storage.values()) { + if (!(value instanceof AnnotationEditor)) { + if (value.popup) { + if (value.popup.deleted) { + numberOfDeletedComments += 1; + } else { + numberOfEditedComments += 1; + } + } + continue; + } + if (value.isCommentDeleted) { + numberOfDeletedComments += 1; + } else if (value.hasEditedComment) { + numberOfEditedComments += 1; + } + const editorStats = value.telemetryFinalData; + if (!editorStats) { + continue; + } + const { + type + } = editorStats; + if (!typeToEditor.has(type)) { + typeToEditor.set(type, Object.getPrototypeOf(value).constructor); + } + stats ||= Object.create(null); + const map = stats[type] ||= new Map(); + for (const [key, val] of Object.entries(editorStats)) { + if (key === "type") { + continue; + } + const counters = map.getOrInsertComputed(key, makeMap); + counters.set(val, (counters.get(val) ?? 0) + 1); + } + } + if (numberOfDeletedComments > 0 || numberOfEditedComments > 0) { + stats ||= Object.create(null); + stats.comments = { + deleted: numberOfDeletedComments, + edited: numberOfEditedComments + }; + } + if (!stats) { + return null; + } + for (const [type, editor] of typeToEditor) { + stats[type] = editor.computeTelemetryFinalData(stats[type]); + } + return stats; + } + resetModifiedIds() { + this.#modifiedIds = null; + } + updateEditor(annotationId, data) { + const value = this.#editorsMap?.get(annotationId); + if (value) { + value.updateFromAnnotationLayer(data); + return true; + } + return false; + } + getEditor(annotationId) { + return this.#editorsMap?.get(annotationId) || null; + } + get modifiedIds() { + if (this.#modifiedIds) { + return this.#modifiedIds; + } + const ids = []; + if (this.#editorsMap) { + for (const value of this.#editorsMap.values()) { + if (!value.serialize()) { + continue; + } + ids.push(value.annotationElementId); + } + } + return this.#modifiedIds = { + ids: new Set(ids), + hash: ids.join(",") + }; + } + [Symbol.iterator]() { + return this.#storage.entries(); + } +} +class PrintAnnotationStorage extends AnnotationStorage { + #serializable = SerializableEmpty; + constructor(parent) { + super(); + const { + serializable + } = parent; + if (serializable === SerializableEmpty) { + return; + } + const { + map, + hash, + transfer + } = serializable; + const clone = structuredClone(map, transfer ? { + transfer + } : null); + this.#serializable = { + map: clone, + hash, + transfer: [] + }; + } + get print() { + unreachable("Should not call PrintAnnotationStorage.print"); + } + get serializable() { + return this.#serializable; + } + get modifiedIds() { + return shadow(this, "modifiedIds", { + ids: new Set(), + hash: "" + }); + } +} + +;// ./src/display/font_loader.js + + +class FontLoader { + #systemFonts = new Set(); + constructor({ + ownerDocument = globalThis.document, + styleElement = null + }) { + this._document = ownerDocument; + this.nativeFontFaces = new Set(); + this.styleElement = null; + this.loadingRequests = []; + this.loadTestFontId = 0; + } + addNativeFontFace(nativeFontFace) { + this.nativeFontFaces.add(nativeFontFace); + this._document.fonts.add(nativeFontFace); + } + removeNativeFontFace(nativeFontFace) { + this.nativeFontFaces.delete(nativeFontFace); + this._document.fonts.delete(nativeFontFace); + } + insertRule(rule) { + if (!this.styleElement) { + this.styleElement = this._document.createElement("style"); + this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement); + } + const styleSheet = this.styleElement.sheet; + styleSheet.insertRule(rule, styleSheet.cssRules.length); + } + clear() { + for (const nativeFontFace of this.nativeFontFaces) { + this._document.fonts.delete(nativeFontFace); + } + this.nativeFontFaces.clear(); + this.#systemFonts.clear(); + if (this.styleElement) { + this.styleElement.remove(); + this.styleElement = null; + } + } + async loadSystemFont({ + systemFontInfo: info, + disableFontFace, + _inspectFont + }) { + if (!info || this.#systemFonts.has(info.loadedName)) { + return; + } + assert(!disableFontFace, "loadSystemFont shouldn't be called when `disableFontFace` is set."); + if (this.isFontLoadingAPISupported) { + const { + loadedName, + src, + style + } = info; + const fontFace = new FontFace(loadedName, src, style); + this.addNativeFontFace(fontFace); + try { + await fontFace.load(); + this.#systemFonts.add(loadedName); + _inspectFont?.(info); + } catch { + warn(`Cannot load system font: ${info.baseFontName}, installing it could help to improve PDF rendering.`); + this.removeNativeFontFace(fontFace); + } + return; + } + unreachable("Not implemented: loadSystemFont without the Font Loading API."); + } + async bind(font) { + if (font.attached || font.missingFile && !font.systemFontInfo) { + return; + } + font.attached = true; + if (font.systemFontInfo) { + await this.loadSystemFont(font); + return; + } + if (this.isFontLoadingAPISupported) { + const nativeFontFace = font.createNativeFontFace(); + if (nativeFontFace) { + this.addNativeFontFace(nativeFontFace); + try { + await nativeFontFace.loaded; + } catch (ex) { + warn(`Failed to load font '${nativeFontFace.family}': '${ex}'.`); + font.disableFontFace = true; + throw ex; + } + } + return; + } + const rule = font.createFontFaceRule(); + if (rule) { + this.insertRule(rule); + if (this.isSyncFontLoadingSupported) { + return; + } + await new Promise(resolve => { + const request = this._queueLoadingCallback(resolve); + this._prepareFontLoadEvent(font, request); + }); + } + } + get isFontLoadingAPISupported() { + const hasFonts = !!this._document?.fonts; + return shadow(this, "isFontLoadingAPISupported", hasFonts); + } + get isSyncFontLoadingSupported() { + return shadow(this, "isSyncFontLoadingSupported", isNodeJS || FeatureTest.platform.isFirefox); + } + _queueLoadingCallback(callback) { + function completeRequest() { + assert(!request.done, "completeRequest() cannot be called twice."); + request.done = true; + while (loadingRequests.length > 0 && loadingRequests[0].done) { + const otherRequest = loadingRequests.shift(); + setTimeout(otherRequest.callback, 0); + } + } + const { + loadingRequests + } = this; + const request = { + done: false, + complete: completeRequest, + callback + }; + loadingRequests.push(request); + return request; + } + get _loadTestFont() { + const testFont = atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQA" + "FQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAA" + "ALwAAAA2aGhlYQdkA+oAAAD0AAAAJGh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AAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAA" + "AAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQAC" + "AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3" + "Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj" + "FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="); + return shadow(this, "_loadTestFont", testFont); + } + _prepareFontLoadEvent(font, request) { + function int32(data, offset) { + return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff; + } + function spliceString(s, offset, remove, insert) { + const chunk1 = s.substring(0, offset); + const chunk2 = s.substring(offset + remove); + return chunk1 + insert + chunk2; + } + let i, ii; + const canvas = this._document.createElement("canvas"); + canvas.width = 1; + canvas.height = 1; + const ctx = canvas.getContext("2d"); + let called = 0; + function isFontReady(name, callback) { + if (++called > 30) { + warn("Load test font never loaded."); + callback(); + return; + } + ctx.font = "30px " + name; + ctx.fillText(".", 0, 20); + const imageData = ctx.getImageData(0, 0, 1, 1); + if (imageData.data[3] > 0) { + callback(); + return; + } + setTimeout(isFontReady.bind(null, name, callback)); + } + const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`; + let data = this._loadTestFont; + const COMMENT_OFFSET = 976; + data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId); + const CFF_CHECKSUM_OFFSET = 16; + const XXXX_VALUE = 0x58585858; + let checksum = int32(data, CFF_CHECKSUM_OFFSET); + for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) { + checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0; + } + if (i < loadTestFontId.length) { + checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0; + } + data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum)); + const url = `url(data:font/opentype;base64,${btoa(data)});`; + const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`; + this.insertRule(rule); + const div = this._document.createElement("div"); + div.style.visibility = "hidden"; + div.style.width = div.style.height = "10px"; + div.style.position = "absolute"; + div.style.top = div.style.left = "0px"; + for (const name of [font.loadedName, loadTestFontId]) { + const span = this._document.createElement("span"); + span.textContent = "Hi"; + span.style.fontFamily = name; + div.append(span); + } + this._document.body.append(div); + isFontReady(loadTestFontId, () => { + div.remove(); + request.complete(); + }); + } +} +class FontFaceObject { + #fontData; + constructor(translatedData, inspectFont = null, extra, charProcOperatorList) { + this.compiledGlyphs = Object.create(null); + this.#fontData = translatedData; + this._inspectFont = inspectFont; + if (extra) { + Object.assign(this, extra); + } + if (charProcOperatorList) { + this.charProcOperatorList = charProcOperatorList; + } + } + createNativeFontFace() { + if (!this.data || this.disableFontFace) { + return null; + } + let nativeFontFace; + if (!this.cssFontInfo) { + nativeFontFace = new FontFace(this.loadedName, this.data, {}); + } else { + const css = { + weight: this.cssFontInfo.fontWeight + }; + if (this.cssFontInfo.italicAngle) { + css.style = `oblique ${this.cssFontInfo.italicAngle}deg`; + } + nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css); + } + this._inspectFont?.(this); + return nativeFontFace; + } + createFontFaceRule() { + if (!this.data || this.disableFontFace) { + return null; + } + const url = `url(data:${this.mimetype};base64,${this.data.toBase64()});`; + let rule; + if (!this.cssFontInfo) { + rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`; + } else { + let css = `font-weight: ${this.cssFontInfo.fontWeight};`; + if (this.cssFontInfo.italicAngle) { + css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`; + } + rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`; + } + this._inspectFont?.(this, url); + return rule; + } + getPathGenerator(objs, character) { + if (this.compiledGlyphs[character] !== undefined) { + return this.compiledGlyphs[character]; + } + const objId = this.loadedName + "_path_" + character; + let cmds; + try { + cmds = objs.get(objId); + } catch (ex) { + warn(`getPathGenerator - ignoring character: "${ex}".`); + } + const path = makePathFromDrawOPS(cmds?.path); + if (!this.fontExtraProperties) { + objs.delete(objId); + } + return this.compiledGlyphs[character] = path; + } + get black() { + return this.#fontData.black; + } + get bold() { + return this.#fontData.bold; + } + get disableFontFace() { + return this.#fontData.disableFontFace ?? false; + } + set disableFontFace(value) { + shadow(this, "disableFontFace", !!value); + } + get fontExtraProperties() { + return this.#fontData.fontExtraProperties ?? false; + } + get isInvalidPDFjsFont() { + return this.#fontData.isInvalidPDFjsFont; + } + get isType3Font() { + return this.#fontData.isType3Font; + } + get italic() { + return this.#fontData.italic; + } + get missingFile() { + return this.#fontData.missingFile; + } + get remeasure() { + return this.#fontData.remeasure; + } + get vertical() { + return this.#fontData.vertical; + } + get ascent() { + return this.#fontData.ascent; + } + get defaultWidth() { + return this.#fontData.defaultWidth; + } + get descent() { + return this.#fontData.descent; + } + get bbox() { + return this.#fontData.bbox; + } + set bbox(bbox) { + shadow(this, "bbox", bbox); + } + get fontMatrix() { + return this.#fontData.fontMatrix; + } + get fallbackName() { + return this.#fontData.fallbackName; + } + get loadedName() { + return this.#fontData.loadedName; + } + get mimetype() { + return this.#fontData.mimetype; + } + get name() { + return this.#fontData.name; + } + get data() { + return this.#fontData.data; + } + clearData() { + this.#fontData.clearData(); + } + get cssFontInfo() { + return this.#fontData.cssFontInfo; + } + get systemFontInfo() { + return this.#fontData.systemFontInfo; + } + get defaultVMetrics() { + return this.#fontData.defaultVMetrics; + } +} + +;// ./src/shared/obj-bin-transform.js + +class CssFontInfo { + #buffer; + #view; + #decoder; + static strings = ["fontFamily", "fontWeight", "italicAngle"]; + static write(info) { + const encoder = new TextEncoder(); + const encodedStrings = {}; + let stringsLength = 0; + for (const prop of CssFontInfo.strings) { + const encoded = encoder.encode(info[prop]); + encodedStrings[prop] = encoded; + stringsLength += 4 + encoded.length; + } + const buffer = new ArrayBuffer(stringsLength); + const data = new Uint8Array(buffer); + const view = new DataView(buffer); + let offset = 0; + for (const prop of CssFontInfo.strings) { + const encoded = encodedStrings[prop]; + const length = encoded.length; + view.setUint32(offset, length); + data.set(encoded, offset + 4); + offset += 4 + length; + } + assert(offset === buffer.byteLength, "CssFontInfo.write: Buffer overflow"); + return buffer; + } + constructor(buffer) { + this.#buffer = buffer; + this.#view = new DataView(this.#buffer); + this.#decoder = new TextDecoder(); + } + #readString(index) { + assert(index < CssFontInfo.strings.length, "Invalid string index"); + let offset = 0; + for (let i = 0; i < index; i++) { + offset += this.#view.getUint32(offset) + 4; + } + const length = this.#view.getUint32(offset); + return this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, length)); + } + get fontFamily() { + return this.#readString(0); + } + get fontWeight() { + return this.#readString(1); + } + get italicAngle() { + return this.#readString(2); + } +} +class SystemFontInfo { + #buffer; + #view; + #decoder; + static strings = ["css", "loadedName", "baseFontName", "src"]; + static write(info) { + const encoder = new TextEncoder(); + const encodedStrings = {}; + let stringsLength = 0; + for (const prop of SystemFontInfo.strings) { + const encoded = encoder.encode(info[prop]); + encodedStrings[prop] = encoded; + stringsLength += 4 + encoded.length; + } + stringsLength += 4; + let encodedStyleStyle, + encodedStyleWeight, + lengthEstimate = 1 + stringsLength; + if (info.style) { + encodedStyleStyle = encoder.encode(info.style.style); + encodedStyleWeight = encoder.encode(info.style.weight); + lengthEstimate += 4 + encodedStyleStyle.length + 4 + encodedStyleWeight.length; + } + const buffer = new ArrayBuffer(lengthEstimate); + const data = new Uint8Array(buffer); + const view = new DataView(buffer); + let offset = 0; + view.setUint8(offset++, info.guessFallback ? 1 : 0); + view.setUint32(offset, 0); + offset += 4; + stringsLength = 0; + for (const prop of SystemFontInfo.strings) { + const encoded = encodedStrings[prop]; + const length = encoded.length; + stringsLength += 4 + length; + view.setUint32(offset, length); + data.set(encoded, offset + 4); + offset += 4 + length; + } + view.setUint32(offset - stringsLength - 4, stringsLength); + if (info.style) { + view.setUint32(offset, encodedStyleStyle.length); + data.set(encodedStyleStyle, offset + 4); + offset += 4 + encodedStyleStyle.length; + view.setUint32(offset, encodedStyleWeight.length); + data.set(encodedStyleWeight, offset + 4); + offset += 4 + encodedStyleWeight.length; + } + assert(offset <= buffer.byteLength, "SubstitionInfo.write: Buffer overflow"); + return buffer.transferToFixedLength(offset); + } + constructor(buffer) { + this.#buffer = buffer; + this.#view = new DataView(this.#buffer); + this.#decoder = new TextDecoder(); + } + get guessFallback() { + return this.#view.getUint8(0) !== 0; + } + #readString(index) { + assert(index < SystemFontInfo.strings.length, "Invalid string index"); + let offset = 5; + for (let i = 0; i < index; i++) { + offset += this.#view.getUint32(offset) + 4; + } + const length = this.#view.getUint32(offset); + return this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, length)); + } + get css() { + return this.#readString(0); + } + get loadedName() { + return this.#readString(1); + } + get baseFontName() { + return this.#readString(2); + } + get src() { + return this.#readString(3); + } + get style() { + let offset = 1; + offset += 4 + this.#view.getUint32(offset); + const styleLength = this.#view.getUint32(offset); + const style = this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, styleLength)); + offset += 4 + styleLength; + const weightLength = this.#view.getUint32(offset); + const weight = this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, weightLength)); + return { + style, + weight + }; + } +} +class FontInfo { + static bools = ["black", "bold", "disableFontFace", "fontExtraProperties", "isInvalidPDFjsFont", "isType3Font", "italic", "missingFile", "remeasure", "vertical"]; + static numbers = ["ascent", "defaultWidth", "descent"]; + static strings = ["fallbackName", "loadedName", "mimetype", "name"]; + static #OFFSET_NUMBERS = Math.ceil(this.bools.length * 2 / 8); + static #OFFSET_BBOX = this.#OFFSET_NUMBERS + this.numbers.length * 8; + static #OFFSET_FONT_MATRIX = this.#OFFSET_BBOX + 1 + 2 * 4; + static #OFFSET_DEFAULT_VMETRICS = this.#OFFSET_FONT_MATRIX + 1 + 8 * 6; + static #OFFSET_STRINGS = this.#OFFSET_DEFAULT_VMETRICS + 1 + 2 * 3; + #buffer; + #decoder; + #view; + constructor({ + data, + extra + }) { + this.#buffer = data; + this.#decoder = new TextDecoder(); + this.#view = new DataView(this.#buffer); + if (extra) { + Object.assign(this, extra); + } + } + #readBoolean(index) { + assert(index < FontInfo.bools.length, "Invalid boolean index"); + const byteOffset = Math.floor(index / 4); + const bitOffset = index * 2 % 8; + const value = this.#view.getUint8(byteOffset) >> bitOffset & 0x03; + return value === 0x00 ? undefined : value === 0x02; + } + get black() { + return this.#readBoolean(0); + } + get bold() { + return this.#readBoolean(1); + } + get disableFontFace() { + return this.#readBoolean(2); + } + get fontExtraProperties() { + return this.#readBoolean(3); + } + get isInvalidPDFjsFont() { + return this.#readBoolean(4); + } + get isType3Font() { + return this.#readBoolean(5); + } + get italic() { + return this.#readBoolean(6); + } + get missingFile() { + return this.#readBoolean(7); + } + get remeasure() { + return this.#readBoolean(8); + } + get vertical() { + return this.#readBoolean(9); + } + #readNumber(index) { + assert(index < FontInfo.numbers.length, "Invalid number index"); + return this.#view.getFloat64(FontInfo.#OFFSET_NUMBERS + index * 8); + } + get ascent() { + return this.#readNumber(0); + } + get defaultWidth() { + return this.#readNumber(1); + } + get descent() { + return this.#readNumber(2); + } + get bbox() { + let offset = FontInfo.#OFFSET_BBOX; + const numCoords = this.#view.getUint8(offset); + if (numCoords === 0) { + return undefined; + } + offset += 1; + const bbox = []; + for (let i = 0; i < 4; i++) { + bbox.push(this.#view.getInt16(offset, true)); + offset += 2; + } + return bbox; + } + get fontMatrix() { + let offset = FontInfo.#OFFSET_FONT_MATRIX; + const numPoints = this.#view.getUint8(offset); + if (numPoints === 0) { + return undefined; + } + offset += 1; + const fontMatrix = []; + for (let i = 0; i < 6; i++) { + fontMatrix.push(this.#view.getFloat64(offset, true)); + offset += 8; + } + return fontMatrix; + } + get defaultVMetrics() { + let offset = FontInfo.#OFFSET_DEFAULT_VMETRICS; + const numMetrics = this.#view.getUint8(offset); + if (numMetrics === 0) { + return undefined; + } + offset += 1; + const defaultVMetrics = []; + for (let i = 0; i < 3; i++) { + defaultVMetrics.push(this.#view.getInt16(offset, true)); + offset += 2; + } + return defaultVMetrics; + } + #readString(index) { + assert(index < FontInfo.strings.length, "Invalid string index"); + let offset = FontInfo.#OFFSET_STRINGS + 4; + for (let i = 0; i < index; i++) { + offset += this.#view.getUint32(offset) + 4; + } + const length = this.#view.getUint32(offset); + const stringData = new Uint8Array(length); + stringData.set(new Uint8Array(this.#buffer, offset + 4, length)); + return this.#decoder.decode(stringData); + } + get fallbackName() { + return this.#readString(0); + } + get loadedName() { + return this.#readString(1); + } + get mimetype() { + return this.#readString(2); + } + get name() { + return this.#readString(3); + } + get data() { + let offset = FontInfo.#OFFSET_STRINGS; + const stringsLength = this.#view.getUint32(offset); + offset += 4 + stringsLength; + const systemFontInfoLength = this.#view.getUint32(offset); + offset += 4 + systemFontInfoLength; + const cssFontInfoLength = this.#view.getUint32(offset); + offset += 4 + cssFontInfoLength; + const length = this.#view.getUint32(offset); + if (length === 0) { + return undefined; + } + return new Uint8Array(this.#buffer, offset + 4, length); + } + clearData() { + let offset = FontInfo.#OFFSET_STRINGS; + const stringsLength = this.#view.getUint32(offset); + offset += 4 + stringsLength; + const systemFontInfoLength = this.#view.getUint32(offset); + offset += 4 + systemFontInfoLength; + const cssFontInfoLength = this.#view.getUint32(offset); + offset += 4 + cssFontInfoLength; + const length = this.#view.getUint32(offset); + const data = new Uint8Array(this.#buffer, offset + 4, length); + data.fill(0); + this.#view.setUint32(offset, 0); + } + get cssFontInfo() { + let offset = FontInfo.#OFFSET_STRINGS; + const stringsLength = this.#view.getUint32(offset); + offset += 4 + stringsLength; + const systemFontInfoLength = this.#view.getUint32(offset); + offset += 4 + systemFontInfoLength; + const cssFontInfoLength = this.#view.getUint32(offset); + if (cssFontInfoLength === 0) { + return null; + } + const cssFontInfoData = new Uint8Array(cssFontInfoLength); + cssFontInfoData.set(new Uint8Array(this.#buffer, offset + 4, cssFontInfoLength)); + return new CssFontInfo(cssFontInfoData.buffer); + } + get systemFontInfo() { + let offset = FontInfo.#OFFSET_STRINGS; + const stringsLength = this.#view.getUint32(offset); + offset += 4 + stringsLength; + const systemFontInfoLength = this.#view.getUint32(offset); + if (systemFontInfoLength === 0) { + return null; + } + const systemFontInfoData = new Uint8Array(systemFontInfoLength); + systemFontInfoData.set(new Uint8Array(this.#buffer, offset + 4, systemFontInfoLength)); + return new SystemFontInfo(systemFontInfoData.buffer); + } + static write(font) { + const systemFontInfoBuffer = font.systemFontInfo ? SystemFontInfo.write(font.systemFontInfo) : null; + const cssFontInfoBuffer = font.cssFontInfo ? CssFontInfo.write(font.cssFontInfo) : null; + const encoder = new TextEncoder(); + const encodedStrings = {}; + let stringsLength = 0; + for (const prop of FontInfo.strings) { + encodedStrings[prop] = encoder.encode(font[prop]); + stringsLength += 4 + encodedStrings[prop].length; + } + const lengthEstimate = FontInfo.#OFFSET_STRINGS + 4 + stringsLength + 4 + (systemFontInfoBuffer ? systemFontInfoBuffer.byteLength : 0) + 4 + (cssFontInfoBuffer ? cssFontInfoBuffer.byteLength : 0) + 4 + (font.data ? font.data.length : 0); + const buffer = new ArrayBuffer(lengthEstimate); + const data = new Uint8Array(buffer); + const view = new DataView(buffer); + let offset = 0; + const numBools = FontInfo.bools.length; + let boolByte = 0, + boolBit = 0; + for (let i = 0; i < numBools; i++) { + const value = font[FontInfo.bools[i]]; + const bits = value === undefined ? 0x00 : value ? 0x02 : 0x01; + boolByte |= bits << boolBit; + boolBit += 2; + if (boolBit === 8 || i === numBools - 1) { + view.setUint8(offset++, boolByte); + boolByte = 0; + boolBit = 0; + } + } + assert(offset === FontInfo.#OFFSET_NUMBERS, "FontInfo.write: Boolean properties offset mismatch"); + for (const prop of FontInfo.numbers) { + view.setFloat64(offset, font[prop]); + offset += 8; + } + assert(offset === FontInfo.#OFFSET_BBOX, "FontInfo.write: Number properties offset mismatch"); + if (font.bbox) { + view.setUint8(offset++, 4); + for (const coord of font.bbox) { + view.setInt16(offset, coord, true); + offset += 2; + } + } else { + view.setUint8(offset++, 0); + offset += 2 * 4; + } + assert(offset === FontInfo.#OFFSET_FONT_MATRIX, "FontInfo.write: BBox properties offset mismatch"); + if (font.fontMatrix) { + view.setUint8(offset++, 6); + for (const point of font.fontMatrix) { + view.setFloat64(offset, point, true); + offset += 8; + } + } else { + view.setUint8(offset++, 0); + offset += 8 * 6; + } + assert(offset === FontInfo.#OFFSET_DEFAULT_VMETRICS, "FontInfo.write: FontMatrix properties offset mismatch"); + if (font.defaultVMetrics) { + view.setUint8(offset++, 1); + for (const metric of font.defaultVMetrics) { + view.setInt16(offset, metric, true); + offset += 2; + } + } else { + view.setUint8(offset++, 0); + offset += 3 * 2; + } + assert(offset === FontInfo.#OFFSET_STRINGS, "FontInfo.write: DefaultVMetrics properties offset mismatch"); + view.setUint32(FontInfo.#OFFSET_STRINGS, 0); + offset += 4; + for (const prop of FontInfo.strings) { + const encoded = encodedStrings[prop]; + const length = encoded.length; + view.setUint32(offset, length); + data.set(encoded, offset + 4); + offset += 4 + length; + } + view.setUint32(FontInfo.#OFFSET_STRINGS, offset - FontInfo.#OFFSET_STRINGS - 4); + if (!systemFontInfoBuffer) { + view.setUint32(offset, 0); + offset += 4; + } else { + const length = systemFontInfoBuffer.byteLength; + view.setUint32(offset, length); + assert(offset + 4 + length <= buffer.byteLength, "FontInfo.write: Buffer overflow at systemFontInfo"); + data.set(new Uint8Array(systemFontInfoBuffer), offset + 4); + offset += 4 + length; + } + if (!cssFontInfoBuffer) { + view.setUint32(offset, 0); + offset += 4; + } else { + const length = cssFontInfoBuffer.byteLength; + view.setUint32(offset, length); + assert(offset + 4 + length <= buffer.byteLength, "FontInfo.write: Buffer overflow at cssFontInfo"); + data.set(new Uint8Array(cssFontInfoBuffer), offset + 4); + offset += 4 + length; + } + if (font.data === undefined) { + view.setUint32(offset, 0); + offset += 4; + } else { + view.setUint32(offset, font.data.length); + data.set(font.data, offset + 4); + offset += 4 + font.data.length; + } + assert(offset <= buffer.byteLength, "FontInfo.write: Buffer overflow"); + return buffer.transferToFixedLength(offset); + } +} +class PatternInfo { + static #KIND = 0; + static #HAS_BBOX = 1; + static #HAS_BACKGROUND = 2; + static #SHADING_TYPE = 3; + static #N_COORD = 4; + static #N_COLOR = 8; + static #N_STOP = 12; + static #N_FIGURES = 16; + constructor(buffer) { + this.buffer = buffer; + this.view = new DataView(buffer); + this.data = new Uint8Array(buffer); + } + static write(ir) { + let kind, + bbox = null, + coords = [], + colors = [], + colorStops = [], + figures = [], + shadingType = null, + background = null; + switch (ir[0]) { + case "RadialAxial": + kind = ir[1] === "axial" ? 1 : 2; + bbox = ir[2]; + colorStops = ir[3]; + if (kind === 1) { + coords.push(...ir[4], ...ir[5]); + } else { + coords.push(ir[4][0], ir[4][1], ir[6], ir[5][0], ir[5][1], ir[7]); + } + break; + case "Mesh": + kind = 3; + shadingType = ir[1]; + coords = ir[2]; + colors = ir[3]; + figures = ir[4] || []; + bbox = ir[6]; + background = ir[7]; + break; + default: + throw new Error(`Unsupported pattern type: ${ir[0]}`); + } + const nCoord = Math.floor(coords.length / 2); + const nColor = Math.floor(colors.length / 3); + const nStop = colorStops.length; + const nFigures = figures.length; + let figuresSize = 0; + for (const figure of figures) { + figuresSize += 1; + figuresSize = Math.ceil(figuresSize / 4) * 4; + figuresSize += 4 + figure.coords.length * 4; + figuresSize += 4 + figure.colors.length * 4; + if (figure.verticesPerRow !== undefined) { + figuresSize += 4; + } + } + const byteLen = 20 + nCoord * 8 + nColor * 3 + nStop * 8 + (bbox ? 16 : 0) + (background ? 3 : 0) + figuresSize; + const buffer = new ArrayBuffer(byteLen); + const dataView = new DataView(buffer); + const u8data = new Uint8Array(buffer); + dataView.setUint8(PatternInfo.#KIND, kind); + dataView.setUint8(PatternInfo.#HAS_BBOX, bbox ? 1 : 0); + dataView.setUint8(PatternInfo.#HAS_BACKGROUND, background ? 1 : 0); + dataView.setUint8(PatternInfo.#SHADING_TYPE, shadingType); + dataView.setUint32(PatternInfo.#N_COORD, nCoord, true); + dataView.setUint32(PatternInfo.#N_COLOR, nColor, true); + dataView.setUint32(PatternInfo.#N_STOP, nStop, true); + dataView.setUint32(PatternInfo.#N_FIGURES, nFigures, true); + let offset = 20; + const coordsView = new Float32Array(buffer, offset, nCoord * 2); + coordsView.set(coords); + offset += nCoord * 8; + u8data.set(colors, offset); + offset += nColor * 3; + for (const [pos, hex] of colorStops) { + dataView.setFloat32(offset, pos, true); + offset += 4; + dataView.setUint32(offset, parseInt(hex.slice(1), 16), true); + offset += 4; + } + if (bbox) { + for (const v of bbox) { + dataView.setFloat32(offset, v, true); + offset += 4; + } + } + if (background) { + u8data.set(background, offset); + offset += 3; + } + for (let i = 0; i < figures.length; i++) { + const figure = figures[i]; + dataView.setUint8(offset, figure.type); + offset += 1; + offset = Math.ceil(offset / 4) * 4; + dataView.setUint32(offset, figure.coords.length, true); + offset += 4; + const figureCoordsView = new Int32Array(buffer, offset, figure.coords.length); + figureCoordsView.set(figure.coords); + offset += figure.coords.length * 4; + dataView.setUint32(offset, figure.colors.length, true); + offset += 4; + const colorsView = new Int32Array(buffer, offset, figure.colors.length); + colorsView.set(figure.colors); + offset += figure.colors.length * 4; + if (figure.verticesPerRow !== undefined) { + dataView.setUint32(offset, figure.verticesPerRow, true); + offset += 4; + } + } + return buffer; + } + getIR() { + const dataView = this.view; + const kind = this.data[PatternInfo.#KIND]; + const hasBBox = !!this.data[PatternInfo.#HAS_BBOX]; + const hasBackground = !!this.data[PatternInfo.#HAS_BACKGROUND]; + const nCoord = dataView.getUint32(PatternInfo.#N_COORD, true); + const nColor = dataView.getUint32(PatternInfo.#N_COLOR, true); + const nStop = dataView.getUint32(PatternInfo.#N_STOP, true); + const nFigures = dataView.getUint32(PatternInfo.#N_FIGURES, true); + let offset = 20; + const coords = new Float32Array(this.buffer, offset, nCoord * 2); + offset += nCoord * 8; + const colors = new Uint8Array(this.buffer, offset, nColor * 3); + offset += nColor * 3; + const stops = []; + for (let i = 0; i < nStop; ++i) { + const p = dataView.getFloat32(offset, true); + offset += 4; + const rgb = dataView.getUint32(offset, true); + offset += 4; + stops.push([p, `#${rgb.toString(16).padStart(6, "0")}`]); + } + let bbox = null; + if (hasBBox) { + bbox = []; + for (let i = 0; i < 4; ++i) { + bbox.push(dataView.getFloat32(offset, true)); + offset += 4; + } + } + let background = null; + if (hasBackground) { + background = new Uint8Array(this.buffer, offset, 3); + offset += 3; + } + const figures = []; + for (let i = 0; i < nFigures; ++i) { + const type = dataView.getUint8(offset); + offset += 1; + offset = Math.ceil(offset / 4) * 4; + const coordsLength = dataView.getUint32(offset, true); + offset += 4; + const figureCoords = new Int32Array(this.buffer, offset, coordsLength); + offset += coordsLength * 4; + const colorsLength = dataView.getUint32(offset, true); + offset += 4; + const figureColors = new Int32Array(this.buffer, offset, colorsLength); + offset += colorsLength * 4; + const figure = { + type, + coords: figureCoords, + colors: figureColors + }; + if (type === MeshFigureType.LATTICE) { + figure.verticesPerRow = dataView.getUint32(offset, true); + offset += 4; + } + figures.push(figure); + } + if (kind === 1) { + return ["RadialAxial", "axial", bbox, stops, Array.from(coords.slice(0, 2)), Array.from(coords.slice(2, 4)), null, null]; + } + if (kind === 2) { + return ["RadialAxial", "radial", bbox, stops, [coords[0], coords[1]], [coords[3], coords[4]], coords[2], coords[5]]; + } + if (kind === 3) { + const shadingType = this.data[PatternInfo.#SHADING_TYPE]; + let bounds = null; + if (coords.length > 0) { + let minX = coords[0], + maxX = coords[0]; + let minY = coords[1], + maxY = coords[1]; + for (let i = 0; i < coords.length; i += 2) { + const x = coords[i], + y = coords[i + 1]; + minX = minX > x ? x : minX; + minY = minY > y ? y : minY; + maxX = maxX < x ? x : maxX; + maxY = maxY < y ? y : maxY; + } + bounds = [minX, minY, maxX, maxY]; + } + return ["Mesh", shadingType, coords, colors, figures, bounds, bbox, background]; + } + throw new Error(`Unsupported pattern kind: ${kind}`); + } +} +class FontPathInfo { + static write(path) { + let data; + let buffer; + if (FeatureTest.isFloat16ArraySupported) { + buffer = new ArrayBuffer(path.length * 2); + data = new Float16Array(buffer); + } else { + buffer = new ArrayBuffer(path.length * 4); + data = new Float32Array(buffer); + } + data.set(path); + return buffer; + } + #buffer; + constructor(buffer) { + this.#buffer = buffer; + } + get path() { + if (FeatureTest.isFloat16ArraySupported) { + return new Float16Array(this.#buffer); + } + return new Float32Array(this.#buffer); + } +} + +;// ./src/display/api_utils.js + +function getUrlProp(val) { + if (val instanceof URL) { + return val; + } + if (typeof val === "string") { + if (isNodeJS) { + if (/^[a-z][a-z0-9\-+.]+:/i.test(val)) { + return new URL(val); + } + const url = process.getBuiltinModule("url"); + return new URL(url.pathToFileURL(val)); + } + const url = URL.parse(val, window.location); + if (url) { + return url; + } + } + throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property."); +} +function getDataProp(val) { + if (isNodeJS && typeof Buffer !== "undefined" && val instanceof Buffer) { + throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`."); + } + if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) { + return val; + } + if (typeof val === "string") { + return stringToBytes(val); + } + if (val instanceof ArrayBuffer || ArrayBuffer.isView(val) || typeof val === "object" && !isNaN(val?.length)) { + return new Uint8Array(val); + } + throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property."); +} +function getFactoryUrlProp(val) { + if (typeof val !== "string") { + return null; + } + if (val.endsWith("/")) { + return val; + } + throw new Error(`Invalid factory url: "${val}" must include trailing slash.`); +} +const isRefProxy = v => typeof v === "object" && Number.isInteger(v?.num) && v.num >= 0 && Number.isInteger(v?.gen) && v.gen >= 0; +const isNameProxy = v => typeof v === "object" && typeof v?.name === "string"; +const isValidExplicitDest = _isValidExplicitDest.bind(null, isRefProxy, isNameProxy); +class LoopbackPort { + #listeners = new Map(); + #deferred = Promise.resolve(); + postMessage(obj, transfer) { + const event = { + data: structuredClone(obj, transfer ? { + transfer + } : null) + }; + this.#deferred.then(() => { + for (const [listener] of this.#listeners) { + listener.call(this, event); + } + }); + } + addEventListener(name, listener, options = null) { + let rmAbort = null; + if (options?.signal instanceof AbortSignal) { + const { + signal + } = options; + if (signal.aborted) { + warn("LoopbackPort - cannot use an `aborted` signal."); + return; + } + const onAbort = () => this.removeEventListener(name, listener); + rmAbort = () => signal.removeEventListener("abort", onAbort); + signal.addEventListener("abort", onAbort); + } + this.#listeners.set(listener, rmAbort); + } + removeEventListener(name, listener) { + const rmAbort = this.#listeners.get(listener); + rmAbort?.(); + this.#listeners.delete(listener); + } + terminate() { + for (const [, rmAbort] of this.#listeners) { + rmAbort?.(); + } + this.#listeners.clear(); + } +} + +;// ./src/shared/message_handler.js + +const CallbackKind = { + DATA: 1, + ERROR: 2 +}; +const StreamKind = { + CANCEL: 1, + CANCEL_COMPLETE: 2, + CLOSE: 3, + ENQUEUE: 4, + ERROR: 5, + PULL: 6, + PULL_COMPLETE: 7, + START_COMPLETE: 8 +}; +function onFn() {} +function wrapReason(ex) { + if (ex instanceof AbortException || ex instanceof InvalidPDFException || ex instanceof PasswordException || ex instanceof ResponseException || ex instanceof UnknownErrorException) { + return ex; + } + if (!(ex instanceof Error || typeof ex === "object" && ex !== null)) { + unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.'); + } + switch (ex.name) { + case "AbortException": + return new AbortException(ex.message); + case "InvalidPDFException": + return new InvalidPDFException(ex.message); + case "PasswordException": + return new PasswordException(ex.message, ex.code); + case "ResponseException": + return new ResponseException(ex.message, ex.status, ex.missing); + case "UnknownErrorException": + return new UnknownErrorException(ex.message, ex.details); + } + return new UnknownErrorException(ex.message, ex.toString()); +} +class MessageHandler { + #messageAC = new AbortController(); + constructor(sourceName, targetName, comObj) { + this.sourceName = sourceName; + this.targetName = targetName; + this.comObj = comObj; + this.callbackId = 1; + this.streamId = 1; + this.streamSinks = Object.create(null); + this.streamControllers = Object.create(null); + this.callbackCapabilities = Object.create(null); + this.actionHandler = Object.create(null); + comObj.addEventListener("message", this.#onMessage.bind(this), { + signal: this.#messageAC.signal + }); + } + #onMessage({ + data + }) { + if (data.targetName !== this.sourceName) { + return; + } + if (data.stream) { + this.#processStreamMessage(data); + return; + } + if (data.callback) { + const callbackId = data.callbackId; + const capability = this.callbackCapabilities[callbackId]; + if (!capability) { + throw new Error(`Cannot resolve callback ${callbackId}`); + } + delete this.callbackCapabilities[callbackId]; + if (data.callback === CallbackKind.DATA) { + capability.resolve(data.data); + } else if (data.callback === CallbackKind.ERROR) { + capability.reject(wrapReason(data.reason)); + } else { + throw new Error("Unexpected callback case"); + } + return; + } + const action = this.actionHandler[data.action]; + if (!action) { + throw new Error(`Unknown action from worker: ${data.action}`); + } + if (data.callbackId) { + const sourceName = this.sourceName, + targetName = data.sourceName, + comObj = this.comObj; + Promise.try(action, data.data).then(function (result) { + comObj.postMessage({ + sourceName, + targetName, + callback: CallbackKind.DATA, + callbackId: data.callbackId, + data: result + }); + }, function (reason) { + comObj.postMessage({ + sourceName, + targetName, + callback: CallbackKind.ERROR, + callbackId: data.callbackId, + reason: wrapReason(reason) + }); + }); + return; + } + if (data.streamId) { + this.#createStreamSink(data); + return; + } + action(data.data); + } + on(actionName, handler) { + const ah = this.actionHandler; + if (ah[actionName]) { + throw new Error(`There is already an actionName called "${actionName}"`); + } + ah[actionName] = handler; + } + send(actionName, data, transfers) { + this.comObj.postMessage({ + sourceName: this.sourceName, + targetName: this.targetName, + action: actionName, + data + }, transfers); + } + sendWithPromise(actionName, data, transfers) { + const callbackId = this.callbackId++; + const capability = Promise.withResolvers(); + this.callbackCapabilities[callbackId] = capability; + try { + this.comObj.postMessage({ + sourceName: this.sourceName, + targetName: this.targetName, + action: actionName, + callbackId, + data + }, transfers); + } catch (ex) { + capability.reject(ex); + } + return capability.promise; + } + sendWithStream(actionName, data, queueingStrategy, transfers) { + const streamId = this.streamId++, + sourceName = this.sourceName, + targetName = this.targetName, + comObj = this.comObj; + return new ReadableStream({ + start: controller => { + const startCapability = Promise.withResolvers(); + this.streamControllers[streamId] = { + controller, + startCall: startCapability, + pullCall: null, + cancelCall: null, + isClosed: false + }; + comObj.postMessage({ + sourceName, + targetName, + action: actionName, + streamId, + data, + desiredSize: controller.desiredSize + }, transfers); + return startCapability.promise; + }, + pull: controller => { + const pullCapability = Promise.withResolvers(); + this.streamControllers[streamId].pullCall = pullCapability; + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.PULL, + streamId, + desiredSize: controller.desiredSize + }); + return pullCapability.promise; + }, + cancel: reason => { + assert(reason instanceof Error, "cancel must have a valid reason"); + const cancelCapability = Promise.withResolvers(); + this.streamControllers[streamId].cancelCall = cancelCapability; + this.streamControllers[streamId].isClosed = true; + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.CANCEL, + streamId, + reason: wrapReason(reason) + }); + return cancelCapability.promise; + } + }, queueingStrategy); + } + #createStreamSink(data) { + const streamId = data.streamId, + sourceName = this.sourceName, + targetName = data.sourceName, + comObj = this.comObj; + const self = this, + action = this.actionHandler[data.action]; + const streamSink = { + enqueue(chunk, size = 1, transfers) { + if (this.isCancelled) { + return; + } + const lastDesiredSize = this.desiredSize; + this.desiredSize -= size; + if (lastDesiredSize > 0 && this.desiredSize <= 0) { + this.sinkCapability = Promise.withResolvers(); + this.ready = this.sinkCapability.promise; + } + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.ENQUEUE, + streamId, + chunk + }, transfers); + }, + close() { + if (this.isCancelled) { + return; + } + this.isCancelled = true; + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.CLOSE, + streamId + }); + delete self.streamSinks[streamId]; + }, + error(reason) { + assert(reason instanceof Error, "error must have a valid reason"); + if (this.isCancelled) { + return; + } + this.isCancelled = true; + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.ERROR, + streamId, + reason: wrapReason(reason) + }); + }, + sinkCapability: Promise.withResolvers(), + onPull: null, + onCancel: null, + isCancelled: false, + desiredSize: data.desiredSize, + ready: null + }; + streamSink.sinkCapability.resolve(); + streamSink.ready = streamSink.sinkCapability.promise; + this.streamSinks[streamId] = streamSink; + Promise.try(action, data.data, streamSink).then(function () { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.START_COMPLETE, + streamId, + success: true + }); + }, function (reason) { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.START_COMPLETE, + streamId, + reason: wrapReason(reason) + }); + }); + } + #processStreamMessage(data) { + const streamId = data.streamId, + sourceName = this.sourceName, + targetName = data.sourceName, + comObj = this.comObj; + const streamController = this.streamControllers[streamId], + streamSink = this.streamSinks[streamId]; + switch (data.stream) { + case StreamKind.START_COMPLETE: + if (data.success) { + streamController.startCall.resolve(); + } else { + streamController.startCall.reject(wrapReason(data.reason)); + } + break; + case StreamKind.PULL_COMPLETE: + if (data.success) { + streamController.pullCall.resolve(); + } else { + streamController.pullCall.reject(wrapReason(data.reason)); + } + break; + case StreamKind.PULL: + if (!streamSink) { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.PULL_COMPLETE, + streamId, + success: true + }); + break; + } + if (streamSink.desiredSize <= 0 && data.desiredSize > 0) { + streamSink.sinkCapability.resolve(); + } + streamSink.desiredSize = data.desiredSize; + Promise.try(streamSink.onPull || onFn).then(function () { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.PULL_COMPLETE, + streamId, + success: true + }); + }, function (reason) { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.PULL_COMPLETE, + streamId, + reason: wrapReason(reason) + }); + }); + break; + case StreamKind.ENQUEUE: + assert(streamController, "enqueue should have stream controller"); + if (streamController.isClosed) { + break; + } + streamController.controller.enqueue(data.chunk); + break; + case StreamKind.CLOSE: + assert(streamController, "close should have stream controller"); + if (streamController.isClosed) { + break; + } + streamController.isClosed = true; + streamController.controller.close(); + this.#deleteStreamController(streamController, streamId); + break; + case StreamKind.ERROR: + assert(streamController, "error should have stream controller"); + streamController.controller.error(wrapReason(data.reason)); + this.#deleteStreamController(streamController, streamId); + break; + case StreamKind.CANCEL_COMPLETE: + if (data.success) { + streamController.cancelCall.resolve(); + } else { + streamController.cancelCall.reject(wrapReason(data.reason)); + } + this.#deleteStreamController(streamController, streamId); + break; + case StreamKind.CANCEL: + if (!streamSink) { + break; + } + const dataReason = wrapReason(data.reason); + Promise.try(streamSink.onCancel || onFn, dataReason).then(function () { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.CANCEL_COMPLETE, + streamId, + success: true + }); + }, function (reason) { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.CANCEL_COMPLETE, + streamId, + reason: wrapReason(reason) + }); + }); + streamSink.sinkCapability.reject(dataReason); + streamSink.isCancelled = true; + delete this.streamSinks[streamId]; + break; + default: + throw new Error("Unexpected stream case"); + } + } + async #deleteStreamController(streamController, streamId) { + await Promise.allSettled([streamController.startCall?.promise, streamController.pullCall?.promise, streamController.cancelCall?.promise]); + delete this.streamControllers[streamId]; + } + destroy() { + this.#messageAC?.abort(); + this.#messageAC = null; + } +} + +;// ./src/display/canvas_factory.js + +class BaseCanvasFactory { + #enableHWA = false; + constructor({ + enableHWA = false + }) { + this.#enableHWA = enableHWA; + } + create(width, height) { + if (width <= 0 || height <= 0) { + throw new Error("Invalid canvas size"); + } + const canvas = this._createCanvas(width, height); + return { + canvas, + context: canvas.getContext("2d", { + willReadFrequently: !this.#enableHWA + }) + }; + } + reset(canvasAndContext, width, height) { + if (!canvasAndContext.canvas) { + throw new Error("Canvas is not specified"); + } + if (width <= 0 || height <= 0) { + throw new Error("Invalid canvas size"); + } + canvasAndContext.canvas.width = width; + canvasAndContext.canvas.height = height; + } + destroy(canvasAndContext) { + if (!canvasAndContext.canvas) { + throw new Error("Canvas is not specified"); + } + canvasAndContext.canvas.width = 0; + canvasAndContext.canvas.height = 0; + canvasAndContext.canvas = null; + canvasAndContext.context = null; + } + _createCanvas(width, height) { + unreachable("Abstract method `_createCanvas` called."); + } +} +class DOMCanvasFactory extends BaseCanvasFactory { + constructor({ + ownerDocument = globalThis.document, + enableHWA = false + }) { + super({ + enableHWA + }); + this._document = ownerDocument; + } + _createCanvas(width, height) { + const canvas = this._document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + return canvas; + } +} + +;// ./src/display/cmap_reader_factory.js + + +class BaseCMapReaderFactory { + constructor({ + baseUrl = null, + isCompressed = true + }) { + this.baseUrl = baseUrl; + this.isCompressed = isCompressed; + } + async fetch({ + name + }) { + if (!this.baseUrl) { + throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided."); + } + if (!name) { + throw new Error("CMap name must be specified."); + } + const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : ""); + return this._fetch(url).then(cMapData => ({ + cMapData, + isCompressed: this.isCompressed + })).catch(reason => { + throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`); + }); + } + async _fetch(url) { + unreachable("Abstract method `_fetch` called."); + } +} +class DOMCMapReaderFactory extends BaseCMapReaderFactory { + async _fetch(url) { + const data = await fetchData(url, this.isCompressed ? "bytes" : "text"); + return data instanceof Uint8Array ? data : stringToBytes(data); + } +} + +;// ./src/display/filter_factory.js + + +class BaseFilterFactory { + addFilter(maps) { + return "none"; + } + addHCMFilter(fgColor, bgColor) { + return "none"; + } + addAlphaFilter(map) { + return "none"; + } + addLuminosityFilter(map) { + return "none"; + } + addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) { + return "none"; + } + destroy(keepHCM = false) {} +} +class DOMFilterFactory extends BaseFilterFactory { + #baseUrl; + #_cache; + #_defs; + #docId; + #document; + #_hcmCache; + #id = 0; + constructor({ + docId, + ownerDocument = globalThis.document + }) { + super(); + this.#docId = docId; + this.#document = ownerDocument; + } + get #cache() { + return this.#_cache ||= new Map(); + } + get #hcmCache() { + return this.#_hcmCache ||= new Map(); + } + get #defs() { + if (!this.#_defs) { + const div = this.#document.createElement("div"); + const { + style + } = div; + style.visibility = "hidden"; + style.contain = "strict"; + style.width = style.height = 0; + style.position = "absolute"; + style.top = style.left = 0; + style.zIndex = -1; + const svg = this.#document.createElementNS(SVG_NS, "svg"); + svg.setAttribute("width", 0); + svg.setAttribute("height", 0); + this.#_defs = this.#document.createElementNS(SVG_NS, "defs"); + div.append(svg); + svg.append(this.#_defs); + this.#document.body.append(div); + } + return this.#_defs; + } + #createTables(maps) { + if (maps.length === 1) { + const mapR = maps[0]; + const buffer = new Array(256); + for (let i = 0; i < 256; i++) { + buffer[i] = mapR[i] / 255; + } + const table = buffer.join(","); + return [table, table, table]; + } + const [mapR, mapG, mapB] = maps; + const bufferR = new Array(256); + const bufferG = new Array(256); + const bufferB = new Array(256); + for (let i = 0; i < 256; i++) { + bufferR[i] = mapR[i] / 255; + bufferG[i] = mapG[i] / 255; + bufferB[i] = mapB[i] / 255; + } + return [bufferR.join(","), bufferG.join(","), bufferB.join(",")]; + } + #createUrl(id) { + if (this.#baseUrl === undefined) { + this.#baseUrl = ""; + const url = this.#document.URL; + if (url !== this.#document.baseURI) { + if (isDataScheme(url)) { + warn('#createUrl: ignore "data:"-URL for performance reasons.'); + } else { + this.#baseUrl = updateUrlHash(url, ""); + } + } + } + return `url(${this.#baseUrl}#${id})`; + } + addFilter(maps) { + if (!maps) { + return "none"; + } + let value = this.#cache.get(maps); + if (value) { + return value; + } + const [tableR, tableG, tableB] = this.#createTables(maps); + const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`; + value = this.#cache.get(key); + if (value) { + this.#cache.set(maps, value); + return value; + } + const id = `g_${this.#docId}_transfer_map_${this.#id++}`; + const url = this.#createUrl(id); + this.#cache.set(maps, url); + this.#cache.set(key, url); + const filter = this.#createFilter(id); + this.#addTransferMapConversion(tableR, tableG, tableB, filter); + return url; + } + addHCMFilter(fgColor, bgColor) { + const key = `${fgColor}-${bgColor}`; + const filterName = "base"; + let info = this.#hcmCache.get(filterName); + if (info?.key === key) { + return info.url; + } + if (info) { + info.filter?.remove(); + info.key = key; + info.url = "none"; + info.filter = null; + } else { + info = { + key, + url: "none", + filter: null + }; + this.#hcmCache.set(filterName, info); + } + if (!fgColor || !bgColor) { + return info.url; + } + const fgRGB = this.#getRGB(fgColor); + fgColor = Util.makeHexColor(...fgRGB); + const bgRGB = this.#getRGB(bgColor); + bgColor = Util.makeHexColor(...bgRGB); + this.#defs.style.color = ""; + if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) { + return info.url; + } + const map = new Array(256); + for (let i = 0; i <= 255; i++) { + const x = i / 255; + map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4; + } + const table = map.join(","); + const id = `g_${this.#docId}_hcm_filter`; + const filter = info.filter = this.#createFilter(id); + this.#addTransferMapConversion(table, table, table, filter); + this.#addGrayConversion(filter); + const getSteps = (c, n) => { + const start = fgRGB[c] / 255; + const end = bgRGB[c] / 255; + const arr = new Array(n + 1); + for (let i = 0; i <= n; i++) { + arr[i] = start + i / n * (end - start); + } + return arr.join(","); + }; + this.#addTransferMapConversion(getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter); + info.url = this.#createUrl(id); + return info.url; + } + addAlphaFilter(map) { + let value = this.#cache.get(map); + if (value) { + return value; + } + const [tableA] = this.#createTables([map]); + const key = `alpha_${tableA}`; + value = this.#cache.get(key); + if (value) { + this.#cache.set(map, value); + return value; + } + const id = `g_${this.#docId}_alpha_map_${this.#id++}`; + const url = this.#createUrl(id); + this.#cache.set(map, url); + this.#cache.set(key, url); + const filter = this.#createFilter(id); + this.#addTransferMapAlphaConversion(tableA, filter); + return url; + } + addLuminosityFilter(map) { + let value = this.#cache.get(map || "luminosity"); + if (value) { + return value; + } + let tableA, key; + if (map) { + [tableA] = this.#createTables([map]); + key = `luminosity_${tableA}`; + } else { + key = "luminosity"; + } + value = this.#cache.get(key); + if (value) { + this.#cache.set(map, value); + return value; + } + const id = `g_${this.#docId}_luminosity_map_${this.#id++}`; + const url = this.#createUrl(id); + this.#cache.set(map, url); + this.#cache.set(key, url); + const filter = this.#createFilter(id); + this.#addLuminosityConversion(filter); + if (map) { + this.#addTransferMapAlphaConversion(tableA, filter); + } + return url; + } + addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) { + const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`; + let info = this.#hcmCache.get(filterName); + if (info?.key === key) { + return info.url; + } + if (info) { + info.filter?.remove(); + info.key = key; + info.url = "none"; + info.filter = null; + } else { + info = { + key, + url: "none", + filter: null + }; + this.#hcmCache.set(filterName, info); + } + if (!fgColor || !bgColor) { + return info.url; + } + const [fgRGB, bgRGB] = [fgColor, bgColor].map(this.#getRGB.bind(this)); + let fgGray = Math.round(0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]); + let bgGray = Math.round(0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]); + let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(this.#getRGB.bind(this)); + if (bgGray < fgGray) { + [fgGray, bgGray, newFgRGB, newBgRGB] = [bgGray, fgGray, newBgRGB, newFgRGB]; + } + this.#defs.style.color = ""; + const getSteps = (fg, bg, n) => { + const arr = new Array(256); + const step = (bgGray - fgGray) / n; + const newStart = fg / 255; + const newStep = (bg - fg) / (255 * n); + let prev = 0; + for (let i = 0; i <= n; i++) { + const k = Math.round(fgGray + i * step); + const value = newStart + i * newStep; + for (let j = prev; j <= k; j++) { + arr[j] = value; + } + prev = k + 1; + } + for (let i = prev; i < 256; i++) { + arr[i] = arr[prev - 1]; + } + return arr.join(","); + }; + const id = `g_${this.#docId}_hcm_${filterName}_filter`; + const filter = info.filter = this.#createFilter(id); + this.#addGrayConversion(filter); + this.#addTransferMapConversion(getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter); + info.url = this.#createUrl(id); + return info.url; + } + destroy(keepHCM = false) { + if (keepHCM && this.#_hcmCache?.size) { + return; + } + this.#_defs?.parentNode.parentNode.remove(); + this.#_defs = null; + this.#_cache?.clear(); + this.#_cache = null; + this.#_hcmCache?.clear(); + this.#_hcmCache = null; + this.#id = 0; + } + #addLuminosityConversion(filter) { + const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix"); + feColorMatrix.setAttribute("type", "matrix"); + feColorMatrix.setAttribute("values", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"); + filter.append(feColorMatrix); + } + #addGrayConversion(filter) { + const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix"); + feColorMatrix.setAttribute("type", "matrix"); + feColorMatrix.setAttribute("values", "0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"); + filter.append(feColorMatrix); + } + #createFilter(id) { + const filter = this.#document.createElementNS(SVG_NS, "filter"); + filter.setAttribute("color-interpolation-filters", "sRGB"); + filter.setAttribute("id", id); + this.#defs.append(filter); + return filter; + } + #appendFeFunc(feComponentTransfer, func, table) { + const feFunc = this.#document.createElementNS(SVG_NS, func); + feFunc.setAttribute("type", "discrete"); + feFunc.setAttribute("tableValues", table); + feComponentTransfer.append(feFunc); + } + #addTransferMapConversion(rTable, gTable, bTable, filter) { + const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer"); + filter.append(feComponentTransfer); + this.#appendFeFunc(feComponentTransfer, "feFuncR", rTable); + this.#appendFeFunc(feComponentTransfer, "feFuncG", gTable); + this.#appendFeFunc(feComponentTransfer, "feFuncB", bTable); + } + #addTransferMapAlphaConversion(aTable, filter) { + const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer"); + filter.append(feComponentTransfer); + this.#appendFeFunc(feComponentTransfer, "feFuncA", aTable); + } + #getRGB(color) { + this.#defs.style.color = color; + return getRGB(getComputedStyle(this.#defs).getPropertyValue("color")); + } +} + +;// ./src/display/standard_fontdata_factory.js + + +class BaseStandardFontDataFactory { + constructor({ + baseUrl = null + }) { + this.baseUrl = baseUrl; + } + async fetch({ + filename + }) { + if (!this.baseUrl) { + throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided."); + } + if (!filename) { + throw new Error("Font filename must be specified."); + } + const url = `${this.baseUrl}${filename}`; + return this._fetch(url).catch(reason => { + throw new Error(`Unable to load font data at: ${url}`); + }); + } + async _fetch(url) { + unreachable("Abstract method `_fetch` called."); + } +} +class DOMStandardFontDataFactory extends BaseStandardFontDataFactory { + async _fetch(url) { + return fetchData(url, "bytes"); + } +} + +;// ./src/display/wasm_factory.js + + +class BaseWasmFactory { + constructor({ + baseUrl = null + }) { + this.baseUrl = baseUrl; + } + async fetch({ + filename + }) { + if (!this.baseUrl) { + throw new Error("Ensure that the `wasmUrl` API parameter is provided."); + } + if (!filename) { + throw new Error("Wasm filename must be specified."); + } + const url = `${this.baseUrl}${filename}`; + return this._fetch(url).catch(reason => { + throw new Error(`Unable to load wasm data at: ${url}`); + }); + } + async _fetch(url) { + unreachable("Abstract method `_fetch` called."); + } +} +class DOMWasmFactory extends BaseWasmFactory { + async _fetch(url) { + return fetchData(url, "bytes"); + } +} + +;// ./src/display/node_utils.js + + + + + + +if (isNodeJS) { + warn("Please use the `legacy` build in Node.js environments."); +} +async function node_utils_fetchData(url) { + const fs = process.getBuiltinModule("fs"); + const data = await fs.promises.readFile(url); + return new Uint8Array(data); +} +class NodeFilterFactory extends BaseFilterFactory {} +class NodeCanvasFactory extends BaseCanvasFactory { + _createCanvas(width, height) { + const require = process.getBuiltinModule("module").createRequire(import.meta.url); + const canvas = require("@napi-rs/canvas"); + return canvas.createCanvas(width, height); + } +} +class NodeCMapReaderFactory extends BaseCMapReaderFactory { + async _fetch(url) { + return node_utils_fetchData(url); + } +} +class NodeStandardFontDataFactory extends BaseStandardFontDataFactory { + async _fetch(url) { + return node_utils_fetchData(url); + } +} +class NodeWasmFactory extends BaseWasmFactory { + async _fetch(url) { + return node_utils_fetchData(url); + } +} + +;// ./src/display/canvas_dependency_tracker.js + +const FORCED_DEPENDENCY_LABEL = "__forcedDependency"; +const { + floor, + ceil +} = Math; +function expandBBox(array, index, minX, minY, maxX, maxY) { + array[index * 4 + 0] = Math.min(array[index * 4 + 0], minX); + array[index * 4 + 1] = Math.min(array[index * 4 + 1], minY); + array[index * 4 + 2] = Math.max(array[index * 4 + 2], maxX); + array[index * 4 + 3] = Math.max(array[index * 4 + 3], maxY); +} +const EMPTY_BBOX = new Uint32Array(new Uint8Array([255, 255, 0, 0]).buffer)[0]; +class BBoxReader { + #bboxes; + #coords; + constructor(bboxes, coords) { + this.#bboxes = bboxes; + this.#coords = coords; + } + get length() { + return this.#bboxes.length; + } + isEmpty(i) { + return this.#bboxes[i] === EMPTY_BBOX; + } + minX(i) { + return this.#coords[i * 4 + 0] / 256; + } + minY(i) { + return this.#coords[i * 4 + 1] / 256; + } + maxX(i) { + return (this.#coords[i * 4 + 2] + 1) / 256; + } + maxY(i) { + return (this.#coords[i * 4 + 3] + 1) / 256; + } +} +const ensureDebugMetadata = (map, key) => map?.getOrInsertComputed(key, () => ({ + dependencies: new Set(), + isRenderingOperation: false +})); +class CanvasDependencyTracker { + #simple = { + __proto__: null + }; + #incremental = { + __proto__: null, + transform: [], + moveText: [], + sameLineText: [], + [FORCED_DEPENDENCY_LABEL]: [] + }; + #namedDependencies = new Map(); + #savesStack = []; + #markedContentStack = []; + #baseTransformStack = [[1, 0, 0, 1, 0, 0]]; + #clipBox = [-Infinity, -Infinity, Infinity, Infinity]; + #pendingBBox = new Float64Array([Infinity, Infinity, -Infinity, -Infinity]); + #pendingBBoxIdx = -1; + #pendingDependencies = new Set(); + #operations = new Map(); + #fontBBoxTrustworthy = new Map(); + #canvasWidth; + #canvasHeight; + #bboxesCoords; + #bboxes; + #debugMetadata; + constructor(canvas, operationsCount, recordDebugMetadata = false) { + this.#canvasWidth = canvas.width; + this.#canvasHeight = canvas.height; + this.#initializeBBoxes(operationsCount); + if (recordDebugMetadata) { + this.#debugMetadata = new Map(); + } + } + growOperationsCount(operationsCount) { + if (operationsCount >= this.#bboxes.length) { + this.#initializeBBoxes(operationsCount, this.#bboxes); + } + } + #initializeBBoxes(operationsCount, oldBBoxes) { + const buffer = new ArrayBuffer(operationsCount * 4); + this.#bboxesCoords = new Uint8ClampedArray(buffer); + this.#bboxes = new Uint32Array(buffer); + if (oldBBoxes && oldBBoxes.length > 0) { + this.#bboxes.set(oldBBoxes); + this.#bboxes.fill(EMPTY_BBOX, oldBBoxes.length); + } else { + this.#bboxes.fill(EMPTY_BBOX); + } + } + save(opIdx) { + this.#simple = { + __proto__: this.#simple + }; + this.#incremental = { + __proto__: this.#incremental, + transform: { + __proto__: this.#incremental.transform + }, + moveText: { + __proto__: this.#incremental.moveText + }, + sameLineText: { + __proto__: this.#incremental.sameLineText + }, + [FORCED_DEPENDENCY_LABEL]: { + __proto__: this.#incremental[FORCED_DEPENDENCY_LABEL] + } + }; + this.#clipBox = { + __proto__: this.#clipBox + }; + this.#savesStack.push(opIdx); + return this; + } + restore(opIdx) { + const previous = Object.getPrototypeOf(this.#simple); + if (previous === null) { + return this; + } + this.#simple = previous; + this.#incremental = Object.getPrototypeOf(this.#incremental); + this.#clipBox = Object.getPrototypeOf(this.#clipBox); + const lastSave = this.#savesStack.pop(); + if (lastSave !== undefined) { + ensureDebugMetadata(this.#debugMetadata, opIdx)?.dependencies.add(lastSave); + this.#bboxes[opIdx] = this.#bboxes[lastSave]; + } + return this; + } + recordOpenMarker(idx) { + this.#savesStack.push(idx); + return this; + } + getOpenMarker() { + if (this.#savesStack.length === 0) { + return null; + } + return this.#savesStack.at(-1); + } + recordCloseMarker(opIdx) { + const lastSave = this.#savesStack.pop(); + if (lastSave !== undefined) { + ensureDebugMetadata(this.#debugMetadata, opIdx)?.dependencies.add(lastSave); + this.#bboxes[opIdx] = this.#bboxes[lastSave]; + } + return this; + } + beginMarkedContent(opIdx) { + this.#markedContentStack.push(opIdx); + return this; + } + endMarkedContent(opIdx) { + const lastSave = this.#markedContentStack.pop(); + if (lastSave !== undefined) { + ensureDebugMetadata(this.#debugMetadata, opIdx)?.dependencies.add(lastSave); + this.#bboxes[opIdx] = this.#bboxes[lastSave]; + } + return this; + } + pushBaseTransform(ctx) { + this.#baseTransformStack.push(Util.multiplyByDOMMatrix(this.#baseTransformStack.at(-1), ctx.getTransform())); + return this; + } + popBaseTransform() { + if (this.#baseTransformStack.length > 1) { + this.#baseTransformStack.pop(); + } + return this; + } + recordSimpleData(name, idx) { + this.#simple[name] = idx; + return this; + } + recordIncrementalData(name, idx) { + this.#incremental[name].push(idx); + return this; + } + resetIncrementalData(name, idx) { + this.#incremental[name].length = 0; + return this; + } + recordNamedData(name, idx) { + this.#namedDependencies.set(name, idx); + return this; + } + recordSimpleDataFromNamed(name, depName, fallbackIdx) { + this.#simple[name] = this.#namedDependencies.get(depName) ?? fallbackIdx; + } + recordFutureForcedDependency(name, idx) { + this.recordIncrementalData(FORCED_DEPENDENCY_LABEL, idx); + return this; + } + inheritSimpleDataAsFutureForcedDependencies(names) { + for (const name of names) { + if (name in this.#simple) { + this.recordFutureForcedDependency(name, this.#simple[name]); + } + } + return this; + } + inheritPendingDependenciesAsFutureForcedDependencies() { + for (const dep of this.#pendingDependencies) { + this.recordFutureForcedDependency(FORCED_DEPENDENCY_LABEL, dep); + } + return this; + } + resetBBox(idx) { + if (this.#pendingBBoxIdx !== idx) { + this.#pendingBBoxIdx = idx; + this.#pendingBBox[0] = Infinity; + this.#pendingBBox[1] = Infinity; + this.#pendingBBox[2] = -Infinity; + this.#pendingBBox[3] = -Infinity; + } + return this; + } + recordClipBox(idx, ctx, minX, maxX, minY, maxY) { + const transform = Util.multiplyByDOMMatrix(this.#baseTransformStack.at(-1), ctx.getTransform()); + const clipBox = [Infinity, Infinity, -Infinity, -Infinity]; + Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, clipBox); + const intersection = Util.intersect(this.#clipBox, clipBox); + if (intersection) { + this.#clipBox[0] = intersection[0]; + this.#clipBox[1] = intersection[1]; + this.#clipBox[2] = intersection[2]; + this.#clipBox[3] = intersection[3]; + } else { + this.#clipBox[0] = this.#clipBox[1] = Infinity; + this.#clipBox[2] = this.#clipBox[3] = -Infinity; + } + return this; + } + recordBBox(idx, ctx, minX, maxX, minY, maxY) { + const clipBox = this.#clipBox; + if (clipBox[0] === Infinity) { + return this; + } + const transform = Util.multiplyByDOMMatrix(this.#baseTransformStack.at(-1), ctx.getTransform()); + if (clipBox[0] === -Infinity) { + Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, this.#pendingBBox); + return this; + } + const bbox = [Infinity, Infinity, -Infinity, -Infinity]; + Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, bbox); + this.#pendingBBox[0] = Math.min(this.#pendingBBox[0], Math.max(bbox[0], clipBox[0])); + this.#pendingBBox[1] = Math.min(this.#pendingBBox[1], Math.max(bbox[1], clipBox[1])); + this.#pendingBBox[2] = Math.max(this.#pendingBBox[2], Math.min(bbox[2], clipBox[2])); + this.#pendingBBox[3] = Math.max(this.#pendingBBox[3], Math.min(bbox[3], clipBox[3])); + return this; + } + recordCharacterBBox(idx, ctx, font, scale = 1, x = 0, y = 0, getMeasure) { + const fontBBox = font.bbox; + let isBBoxTrustworthy; + let computedBBox; + if (fontBBox) { + isBBoxTrustworthy = fontBBox[2] !== fontBBox[0] && fontBBox[3] !== fontBBox[1] && this.#fontBBoxTrustworthy.get(font); + if (isBBoxTrustworthy !== false) { + computedBBox = [0, 0, 0, 0]; + Util.axialAlignedBoundingBox(fontBBox, font.fontMatrix, computedBBox); + if (scale !== 1 || x !== 0 || y !== 0) { + Util.scaleMinMax([scale, 0, 0, -scale, x, y], computedBBox); + } + if (isBBoxTrustworthy) { + return this.recordBBox(idx, ctx, computedBBox[0], computedBBox[2], computedBBox[1], computedBBox[3]); + } + } + } + if (!getMeasure) { + return this.recordFullPageBBox(idx); + } + const measure = getMeasure(); + if (fontBBox && computedBBox && isBBoxTrustworthy === undefined) { + isBBoxTrustworthy = computedBBox[0] <= x - measure.actualBoundingBoxLeft && computedBBox[2] >= x + measure.actualBoundingBoxRight && computedBBox[1] <= y - measure.actualBoundingBoxAscent && computedBBox[3] >= y + measure.actualBoundingBoxDescent; + this.#fontBBoxTrustworthy.set(font, isBBoxTrustworthy); + if (isBBoxTrustworthy) { + return this.recordBBox(idx, ctx, computedBBox[0], computedBBox[2], computedBBox[1], computedBBox[3]); + } + } + return this.recordBBox(idx, ctx, x - measure.actualBoundingBoxLeft, x + measure.actualBoundingBoxRight, y - measure.actualBoundingBoxAscent, y + measure.actualBoundingBoxDescent); + } + recordFullPageBBox(idx) { + this.#pendingBBox[0] = Math.max(0, this.#clipBox[0]); + this.#pendingBBox[1] = Math.max(0, this.#clipBox[1]); + this.#pendingBBox[2] = Math.min(this.#canvasWidth, this.#clipBox[2]); + this.#pendingBBox[3] = Math.min(this.#canvasHeight, this.#clipBox[3]); + return this; + } + getSimpleIndex(dependencyName) { + return this.#simple[dependencyName]; + } + recordDependencies(idx, dependencyNames) { + const pendingDependencies = this.#pendingDependencies; + const simple = this.#simple; + const incremental = this.#incremental; + for (const name of dependencyNames) { + if (name in this.#simple) { + pendingDependencies.add(simple[name]); + } else if (name in incremental) { + incremental[name].forEach(pendingDependencies.add, pendingDependencies); + } + } + return this; + } + recordNamedDependency(idx, name) { + if (this.#namedDependencies.has(name)) { + this.#pendingDependencies.add(this.#namedDependencies.get(name)); + } + return this; + } + recordOperation(idx, preserve = false) { + this.recordDependencies(idx, [FORCED_DEPENDENCY_LABEL]); + if (this.#debugMetadata) { + const metadata = ensureDebugMetadata(this.#debugMetadata, idx); + const { + dependencies + } = metadata; + this.#pendingDependencies.forEach(dependencies.add, dependencies); + this.#savesStack.forEach(dependencies.add, dependencies); + this.#markedContentStack.forEach(dependencies.add, dependencies); + dependencies.delete(idx); + metadata.isRenderingOperation = true; + } + if (this.#pendingBBoxIdx === idx) { + const minX = floor(this.#pendingBBox[0] * 256 / this.#canvasWidth); + const minY = floor(this.#pendingBBox[1] * 256 / this.#canvasHeight); + const maxX = ceil(this.#pendingBBox[2] * 256 / this.#canvasWidth); + const maxY = ceil(this.#pendingBBox[3] * 256 / this.#canvasHeight); + expandBBox(this.#bboxesCoords, idx, minX, minY, maxX, maxY); + for (const depIdx of this.#pendingDependencies) { + if (depIdx !== idx) { + expandBBox(this.#bboxesCoords, depIdx, minX, minY, maxX, maxY); + } + } + for (const saveIdx of this.#savesStack) { + if (saveIdx !== idx) { + expandBBox(this.#bboxesCoords, saveIdx, minX, minY, maxX, maxY); + } + } + for (const saveIdx of this.#markedContentStack) { + if (saveIdx !== idx) { + expandBBox(this.#bboxesCoords, saveIdx, minX, minY, maxX, maxY); + } + } + if (!preserve) { + this.#pendingDependencies.clear(); + this.#pendingBBoxIdx = -1; + } + } + return this; + } + recordShowTextOperation(idx, preserve = false) { + const deps = Array.from(this.#pendingDependencies); + this.recordOperation(idx, preserve); + this.recordIncrementalData("sameLineText", idx); + for (const dep of deps) { + this.recordIncrementalData("sameLineText", dep); + } + return this; + } + bboxToClipBoxDropOperation(idx, preserve = false) { + if (this.#pendingBBoxIdx === idx) { + this.#pendingBBoxIdx = -1; + this.#clipBox[0] = Math.max(this.#clipBox[0], this.#pendingBBox[0]); + this.#clipBox[1] = Math.max(this.#clipBox[1], this.#pendingBBox[1]); + this.#clipBox[2] = Math.min(this.#clipBox[2], this.#pendingBBox[2]); + this.#clipBox[3] = Math.min(this.#clipBox[3], this.#pendingBBox[3]); + if (!preserve) { + this.#pendingDependencies.clear(); + } + } + return this; + } + _takePendingDependencies() { + const pendingDependencies = this.#pendingDependencies; + this.#pendingDependencies = new Set(); + return pendingDependencies; + } + _extractOperation(idx) { + const operation = this.#operations.get(idx); + this.#operations.delete(idx); + return operation; + } + _pushPendingDependencies(dependencies) { + for (const dep of dependencies) { + this.#pendingDependencies.add(dep); + } + } + take() { + this.#fontBBoxTrustworthy.clear(); + return new BBoxReader(this.#bboxes, this.#bboxesCoords); + } + takeDebugMetadata() { + return this.#debugMetadata; + } +} +class CanvasNestedDependencyTracker { + #dependencyTracker; + #opIdx; + #ignoreBBoxes; + #nestingLevel = 0; + #savesLevel = 0; + constructor(dependencyTracker, opIdx, ignoreBBoxes) { + if (dependencyTracker instanceof CanvasNestedDependencyTracker && dependencyTracker.#ignoreBBoxes === !!ignoreBBoxes) { + return dependencyTracker; + } + this.#dependencyTracker = dependencyTracker; + this.#opIdx = opIdx; + this.#ignoreBBoxes = !!ignoreBBoxes; + } + growOperationsCount() { + throw new Error("Unreachable"); + } + save(opIdx) { + this.#savesLevel++; + this.#dependencyTracker.save(this.#opIdx); + return this; + } + restore(opIdx) { + if (this.#savesLevel > 0) { + this.#dependencyTracker.restore(this.#opIdx); + this.#savesLevel--; + } + return this; + } + recordOpenMarker(idx) { + this.#nestingLevel++; + return this; + } + getOpenMarker() { + return this.#nestingLevel > 0 ? this.#opIdx : this.#dependencyTracker.getOpenMarker(); + } + recordCloseMarker(idx) { + this.#nestingLevel--; + return this; + } + beginMarkedContent(opIdx) { + return this; + } + endMarkedContent(opIdx) { + return this; + } + pushBaseTransform(ctx) { + this.#dependencyTracker.pushBaseTransform(ctx); + return this; + } + popBaseTransform() { + this.#dependencyTracker.popBaseTransform(); + return this; + } + recordSimpleData(name, idx) { + this.#dependencyTracker.recordSimpleData(name, this.#opIdx); + return this; + } + recordIncrementalData(name, idx) { + this.#dependencyTracker.recordIncrementalData(name, this.#opIdx); + return this; + } + resetIncrementalData(name, idx) { + this.#dependencyTracker.resetIncrementalData(name, this.#opIdx); + return this; + } + recordNamedData(name, idx) { + return this; + } + recordSimpleDataFromNamed(name, depName, fallbackIdx) { + this.#dependencyTracker.recordSimpleDataFromNamed(name, depName, this.#opIdx); + return this; + } + recordFutureForcedDependency(name, idx) { + this.#dependencyTracker.recordFutureForcedDependency(name, this.#opIdx); + return this; + } + inheritSimpleDataAsFutureForcedDependencies(names) { + this.#dependencyTracker.inheritSimpleDataAsFutureForcedDependencies(names); + return this; + } + inheritPendingDependenciesAsFutureForcedDependencies() { + this.#dependencyTracker.inheritPendingDependenciesAsFutureForcedDependencies(); + return this; + } + resetBBox(idx) { + if (!this.#ignoreBBoxes) { + this.#dependencyTracker.resetBBox(this.#opIdx); + } + return this; + } + recordClipBox(idx, ctx, minX, maxX, minY, maxY) { + if (!this.#ignoreBBoxes) { + this.#dependencyTracker.recordClipBox(this.#opIdx, ctx, minX, maxX, minY, maxY); + } + return this; + } + recordBBox(idx, ctx, minX, maxX, minY, maxY) { + if (!this.#ignoreBBoxes) { + this.#dependencyTracker.recordBBox(this.#opIdx, ctx, minX, maxX, minY, maxY); + } + return this; + } + recordCharacterBBox(idx, ctx, font, scale, x, y, getMeasure) { + if (!this.#ignoreBBoxes) { + this.#dependencyTracker.recordCharacterBBox(this.#opIdx, ctx, font, scale, x, y, getMeasure); + } + return this; + } + recordFullPageBBox(idx) { + if (!this.#ignoreBBoxes) { + this.#dependencyTracker.recordFullPageBBox(this.#opIdx); + } + return this; + } + getSimpleIndex(dependencyName) { + return this.#dependencyTracker.getSimpleIndex(dependencyName); + } + recordDependencies(idx, dependencyNames) { + this.#dependencyTracker.recordDependencies(this.#opIdx, dependencyNames); + return this; + } + recordNamedDependency(idx, name) { + this.#dependencyTracker.recordNamedDependency(this.#opIdx, name); + return this; + } + recordOperation(idx) { + this.#dependencyTracker.recordOperation(this.#opIdx, true); + return this; + } + recordShowTextOperation(idx) { + this.#dependencyTracker.recordShowTextOperation(this.#opIdx, true); + return this; + } + bboxToClipBoxDropOperation(idx) { + if (!this.#ignoreBBoxes) { + this.#dependencyTracker.bboxToClipBoxDropOperation(this.#opIdx, true); + } + return this; + } + take() { + throw new Error("Unreachable"); + } + takeDebugMetadata() { + throw new Error("Unreachable"); + } +} +const Dependencies = { + stroke: ["path", "transform", "filter", "strokeColor", "strokeAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "dash"], + fill: ["path", "transform", "filter", "fillColor", "fillAlpha", "globalCompositeOperation", "SMask"], + imageXObject: ["transform", "SMask", "filter", "fillAlpha", "strokeAlpha", "globalCompositeOperation"], + rawFillPath: ["filter", "fillColor", "fillAlpha"], + showText: ["transform", "leading", "charSpacing", "wordSpacing", "hScale", "textRise", "moveText", "textMatrix", "font", "fontObj", "filter", "fillColor", "textRenderingMode", "SMask", "fillAlpha", "strokeAlpha", "globalCompositeOperation", "sameLineText"], + transform: ["transform"], + transformAndFill: ["transform", "fillColor"] +}; + +;// ./src/display/pattern_helper.js + + +const PathType = { + FILL: "Fill", + STROKE: "Stroke", + SHADING: "Shading" +}; +function applyBoundingBox(ctx, bbox) { + if (!bbox) { + return; + } + const width = bbox[2] - bbox[0]; + const height = bbox[3] - bbox[1]; + const region = new Path2D(); + region.rect(bbox[0], bbox[1], width, height); + ctx.clip(region); +} +class BaseShadingPattern { + isModifyingCurrentTransform() { + return false; + } + getPattern() { + unreachable("Abstract method `getPattern` called."); + } +} +class RadialAxialShadingPattern extends BaseShadingPattern { + constructor(IR) { + super(); + this._type = IR[1]; + this._bbox = IR[2]; + this._colorStops = IR[3]; + this._p0 = IR[4]; + this._p1 = IR[5]; + this._r0 = IR[6]; + this._r1 = IR[7]; + this.matrix = null; + } + isOriginBased() { + return this._p0[0] === 0 && this._p0[1] === 0 && (!this.isRadial() || this._p1[0] === 0 && this._p1[1] === 0); + } + isRadial() { + return this._type === "radial"; + } + _createGradient(ctx, transform = null) { + let grad; + let firstPoint = this._p0; + let secondPoint = this._p1; + if (transform) { + firstPoint = firstPoint.slice(); + secondPoint = secondPoint.slice(); + Util.applyTransform(firstPoint, transform); + Util.applyTransform(secondPoint, transform); + } + if (this._type === "axial") { + grad = ctx.createLinearGradient(firstPoint[0], firstPoint[1], secondPoint[0], secondPoint[1]); + } else if (this._type === "radial") { + let r0 = this._r0; + let r1 = this._r1; + if (transform) { + const scale = new Float32Array(2); + Util.singularValueDecompose2dScale(transform, scale); + r0 *= scale[0]; + r1 *= scale[0]; + } + grad = ctx.createRadialGradient(firstPoint[0], firstPoint[1], r0, secondPoint[0], secondPoint[1], r1); + } + for (const colorStop of this._colorStops) { + grad.addColorStop(colorStop[0], colorStop[1]); + } + return grad; + } + getPattern(ctx, owner, inverse, pathType) { + let pattern; + if (pathType === PathType.STROKE || pathType === PathType.FILL) { + if (this.isOriginBased()) { + let transf = Util.transform(inverse, owner.baseTransform); + if (this.matrix) { + transf = Util.transform(transf, this.matrix); + } + const precision = 1e-3; + const n1 = Math.hypot(transf[0], transf[1]); + const n2 = Math.hypot(transf[2], transf[3]); + const ps = (transf[0] * transf[2] + transf[1] * transf[3]) / (n1 * n2); + if (Math.abs(ps) < precision) { + if (this.isRadial()) { + if (Math.abs(n1 - n2) < precision) { + return this._createGradient(ctx, transf); + } + } else { + return this._createGradient(ctx, transf); + } + } + } + const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, getCurrentTransform(ctx)) || [0, 0, 0, 0]; + const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1; + const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1; + const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height); + const tmpCtx = tmpCanvas.context; + tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height); + tmpCtx.beginPath(); + tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height); + tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]); + inverse = Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]); + tmpCtx.transform(...owner.baseTransform); + if (this.matrix) { + tmpCtx.transform(...this.matrix); + } + applyBoundingBox(tmpCtx, this._bbox); + tmpCtx.fillStyle = this._createGradient(tmpCtx); + tmpCtx.fill(); + pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat"); + const domMatrix = new DOMMatrix(inverse); + pattern.setTransform(domMatrix); + } else { + applyBoundingBox(ctx, this._bbox); + pattern = this._createGradient(ctx); + } + return pattern; + } +} +function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) { + const coords = context.coords, + colors = context.colors; + const bytes = data.data, + rowSize = data.width * 4; + let tmp; + if (coords[p1 + 1] > coords[p2 + 1]) { + tmp = p1; + p1 = p2; + p2 = tmp; + tmp = c1; + c1 = c2; + c2 = tmp; + } + if (coords[p2 + 1] > coords[p3 + 1]) { + tmp = p2; + p2 = p3; + p3 = tmp; + tmp = c2; + c2 = c3; + c3 = tmp; + } + if (coords[p1 + 1] > coords[p2 + 1]) { + tmp = p1; + p1 = p2; + p2 = tmp; + tmp = c1; + c1 = c2; + c2 = tmp; + } + const x1 = (coords[p1] + context.offsetX) * context.scaleX; + const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY; + const x2 = (coords[p2] + context.offsetX) * context.scaleX; + const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY; + const x3 = (coords[p3] + context.offsetX) * context.scaleX; + const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY; + if (y1 >= y3) { + return; + } + const c1r = colors[c1], + c1g = colors[c1 + 1], + c1b = colors[c1 + 2]; + const c2r = colors[c2], + c2g = colors[c2 + 1], + c2b = colors[c2 + 2]; + const c3r = colors[c3], + c3g = colors[c3 + 1], + c3b = colors[c3 + 2]; + const minY = Math.round(y1), + maxY = Math.round(y3); + let xa, car, cag, cab; + let xb, cbr, cbg, cbb; + for (let y = minY; y <= maxY; y++) { + if (y < y2) { + const k = y < y1 ? 0 : (y1 - y) / (y1 - y2); + xa = x1 - (x1 - x2) * k; + car = c1r - (c1r - c2r) * k; + cag = c1g - (c1g - c2g) * k; + cab = c1b - (c1b - c2b) * k; + } else { + let k; + if (y > y3) { + k = 1; + } else if (y2 === y3) { + k = 0; + } else { + k = (y2 - y) / (y2 - y3); + } + xa = x2 - (x2 - x3) * k; + car = c2r - (c2r - c3r) * k; + cag = c2g - (c2g - c3g) * k; + cab = c2b - (c2b - c3b) * k; + } + let k; + if (y < y1) { + k = 0; + } else if (y > y3) { + k = 1; + } else { + k = (y1 - y) / (y1 - y3); + } + xb = x1 - (x1 - x3) * k; + cbr = c1r - (c1r - c3r) * k; + cbg = c1g - (c1g - c3g) * k; + cbb = c1b - (c1b - c3b) * k; + const x1_ = Math.round(Math.min(xa, xb)); + const x2_ = Math.round(Math.max(xa, xb)); + let j = rowSize * y + x1_ * 4; + for (let x = x1_; x <= x2_; x++) { + k = (xa - x) / (xa - xb); + if (k < 0) { + k = 0; + } else if (k > 1) { + k = 1; + } + bytes[j++] = car - (car - cbr) * k | 0; + bytes[j++] = cag - (cag - cbg) * k | 0; + bytes[j++] = cab - (cab - cbb) * k | 0; + bytes[j++] = 255; + } + } +} +function drawFigure(data, figure, context) { + const ps = figure.coords; + const cs = figure.colors; + let i, ii; + switch (figure.type) { + case MeshFigureType.LATTICE: + const verticesPerRow = figure.verticesPerRow; + const rows = Math.floor(ps.length / verticesPerRow) - 1; + const cols = verticesPerRow - 1; + for (i = 0; i < rows; i++) { + let q = i * verticesPerRow; + for (let j = 0; j < cols; j++, q++) { + drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]); + drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]); + } + } + break; + case MeshFigureType.TRIANGLES: + for (i = 0, ii = ps.length; i < ii; i += 3) { + drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]); + } + break; + default: + throw new Error("illegal figure"); + } +} +class MeshShadingPattern extends BaseShadingPattern { + constructor(IR) { + super(); + this._coords = IR[2]; + this._colors = IR[3]; + this._figures = IR[4]; + this._bounds = IR[5]; + this._bbox = IR[6]; + this._background = IR[7]; + this.matrix = null; + } + _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) { + const EXPECTED_SCALE = 1.1; + const MAX_PATTERN_SIZE = 3000; + const BORDER_SIZE = 2; + const offsetX = Math.floor(this._bounds[0]); + const offsetY = Math.floor(this._bounds[1]); + const boundsWidth = Math.ceil(this._bounds[2]) - offsetX; + const boundsHeight = Math.ceil(this._bounds[3]) - offsetY; + const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); + const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); + const scaleX = boundsWidth / width; + const scaleY = boundsHeight / height; + const context = { + coords: this._coords, + colors: this._colors, + offsetX: -offsetX, + offsetY: -offsetY, + scaleX: 1 / scaleX, + scaleY: 1 / scaleY + }; + const paddedWidth = width + BORDER_SIZE * 2; + const paddedHeight = height + BORDER_SIZE * 2; + const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight); + const tmpCtx = tmpCanvas.context; + const data = tmpCtx.createImageData(width, height); + if (backgroundColor) { + const bytes = data.data; + for (let i = 0, ii = bytes.length; i < ii; i += 4) { + bytes[i] = backgroundColor[0]; + bytes[i + 1] = backgroundColor[1]; + bytes[i + 2] = backgroundColor[2]; + bytes[i + 3] = 255; + } + } + for (const figure of this._figures) { + drawFigure(data, figure, context); + } + tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE); + const canvas = tmpCanvas.canvas; + return { + canvas, + offsetX: offsetX - BORDER_SIZE * scaleX, + offsetY: offsetY - BORDER_SIZE * scaleY, + scaleX, + scaleY + }; + } + isModifyingCurrentTransform() { + return true; + } + getPattern(ctx, owner, inverse, pathType) { + applyBoundingBox(ctx, this._bbox); + const scale = new Float32Array(2); + if (pathType === PathType.SHADING) { + Util.singularValueDecompose2dScale(getCurrentTransform(ctx), scale); + } else if (this.matrix) { + Util.singularValueDecompose2dScale(this.matrix, scale); + const [matrixScaleX, matrixScaleY] = scale; + Util.singularValueDecompose2dScale(owner.baseTransform, scale); + scale[0] *= matrixScaleX; + scale[1] *= matrixScaleY; + } else { + Util.singularValueDecompose2dScale(owner.baseTransform, scale); + } + const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases); + if (pathType !== PathType.SHADING) { + ctx.setTransform(...owner.baseTransform); + if (this.matrix) { + ctx.transform(...this.matrix); + } + } + ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); + ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY); + return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat"); + } +} +class DummyShadingPattern extends BaseShadingPattern { + getPattern() { + return "hotpink"; + } +} +function getShadingPattern(IR) { + switch (IR[0]) { + case "RadialAxial": + return new RadialAxialShadingPattern(IR); + case "Mesh": + return new MeshShadingPattern(IR); + case "Dummy": + return new DummyShadingPattern(); + } + throw new Error(`Unknown IR type: ${IR[0]}`); +} +const PaintType = { + COLORED: 1, + UNCOLORED: 2 +}; +class TilingPattern { + static MAX_PATTERN_SIZE = 3000; + constructor(IR, ctx, canvasGraphicsFactory, baseTransform) { + this.color = IR[1]; + this.operatorList = IR[2]; + this.matrix = IR[3]; + this.bbox = IR[4]; + this.xstep = IR[5]; + this.ystep = IR[6]; + this.paintType = IR[7]; + this.tilingType = IR[8]; + this.ctx = ctx; + this.canvasGraphicsFactory = canvasGraphicsFactory; + this.baseTransform = baseTransform; + } + createPatternCanvas(owner, opIdx) { + const { + bbox, + operatorList, + paintType, + tilingType, + color, + canvasGraphicsFactory + } = this; + let { + xstep, + ystep + } = this; + xstep = Math.abs(xstep); + ystep = Math.abs(ystep); + info("TilingType: " + tilingType); + const x0 = bbox[0], + y0 = bbox[1], + x1 = bbox[2], + y1 = bbox[3]; + const width = x1 - x0; + const height = y1 - y0; + const scale = new Float32Array(2); + Util.singularValueDecompose2dScale(this.matrix, scale); + const [matrixScaleX, matrixScaleY] = scale; + Util.singularValueDecompose2dScale(this.baseTransform, scale); + const combinedScaleX = matrixScaleX * scale[0]; + const combinedScaleY = matrixScaleY * scale[1]; + let canvasWidth = width, + canvasHeight = height, + redrawHorizontally = false, + redrawVertically = false; + const xScaledStep = Math.ceil(xstep * combinedScaleX); + const yScaledStep = Math.ceil(ystep * combinedScaleY); + const xScaledWidth = Math.ceil(width * combinedScaleX); + const yScaledHeight = Math.ceil(height * combinedScaleY); + if (xScaledStep >= xScaledWidth) { + canvasWidth = xstep; + } else { + redrawHorizontally = true; + } + if (yScaledStep >= yScaledHeight) { + canvasHeight = ystep; + } else { + redrawVertically = true; + } + const dimx = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX); + const dimy = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY); + const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size); + const tmpCtx = tmpCanvas.context; + const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx, opIdx); + graphics.groupLevel = owner.groupLevel; + this.setFillAndStrokeStyleToContext(graphics, paintType, color); + tmpCtx.translate(-dimx.scale * x0, -dimy.scale * y0); + graphics.transform(0, dimx.scale, 0, 0, dimy.scale, 0, 0); + tmpCtx.save(); + graphics.dependencyTracker?.save(); + this.clipBbox(graphics, x0, y0, x1, y1); + graphics.baseTransform = getCurrentTransform(graphics.ctx); + graphics.executeOperatorList(operatorList); + graphics.endDrawing(); + graphics.dependencyTracker?.restore(); + tmpCtx.restore(); + if (redrawHorizontally || redrawVertically) { + const image = tmpCanvas.canvas; + if (redrawHorizontally) { + canvasWidth = xstep; + } + if (redrawVertically) { + canvasHeight = ystep; + } + const dimx2 = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX); + const dimy2 = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY); + const xSize = dimx2.size; + const ySize = dimy2.size; + const tmpCanvas2 = owner.cachedCanvases.getCanvas("pattern-workaround", xSize, ySize); + const tmpCtx2 = tmpCanvas2.context; + const ii = redrawHorizontally ? Math.floor(width / xstep) : 0; + const jj = redrawVertically ? Math.floor(height / ystep) : 0; + for (let i = 0; i <= ii; i++) { + for (let j = 0; j <= jj; j++) { + tmpCtx2.drawImage(image, xSize * i, ySize * j, xSize, ySize, 0, 0, xSize, ySize); + } + } + return { + canvas: tmpCanvas2.canvas, + scaleX: dimx2.scale, + scaleY: dimy2.scale, + offsetX: x0, + offsetY: y0 + }; + } + return { + canvas: tmpCanvas.canvas, + scaleX: dimx.scale, + scaleY: dimy.scale, + offsetX: x0, + offsetY: y0 + }; + } + getSizeAndScale(step, realOutputSize, scale) { + const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize); + let size = Math.ceil(step * scale); + if (size >= maxSize) { + size = maxSize; + } else { + scale = size / step; + } + return { + scale, + size + }; + } + clipBbox(graphics, x0, y0, x1, y1) { + const bboxWidth = x1 - x0; + const bboxHeight = y1 - y0; + graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight); + Util.axialAlignedBoundingBox([x0, y0, x1, y1], getCurrentTransform(graphics.ctx), graphics.current.minMax); + graphics.clip(); + graphics.endPath(); + } + setFillAndStrokeStyleToContext(graphics, paintType, color) { + const context = graphics.ctx, + current = graphics.current; + switch (paintType) { + case PaintType.COLORED: + const { + fillStyle, + strokeStyle + } = this.ctx; + context.fillStyle = current.fillColor = fillStyle; + context.strokeStyle = current.strokeColor = strokeStyle; + break; + case PaintType.UNCOLORED: + context.fillStyle = context.strokeStyle = color; + current.fillColor = current.strokeColor = color; + break; + default: + throw new FormatError(`Unsupported paint type: ${paintType}`); + } + } + isModifyingCurrentTransform() { + return false; + } + getPattern(ctx, owner, inverse, pathType, opIdx) { + let matrix = inverse; + if (pathType !== PathType.SHADING) { + matrix = Util.transform(matrix, owner.baseTransform); + if (this.matrix) { + matrix = Util.transform(matrix, this.matrix); + } + } + const temporaryPatternCanvas = this.createPatternCanvas(owner, opIdx); + let domMatrix = new DOMMatrix(matrix); + domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); + domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY); + const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat"); + pattern.setTransform(domMatrix); + return pattern; + } +} + +;// ./src/shared/image_utils.js +/* unused harmony import specifier */ var image_utils_ImageKind; +/* unused harmony import specifier */ var image_utils_FeatureTest; + +function convertToRGBA(params) { + switch (params.kind) { + case image_utils_ImageKind.GRAYSCALE_1BPP: + return convertBlackAndWhiteToRGBA(params); + case image_utils_ImageKind.RGB_24BPP: + return convertRGBToRGBA(params); + } + return null; +} +function convertBlackAndWhiteToRGBA({ + src, + srcPos = 0, + dest, + width, + height, + nonBlackColor = 0xffffffff, + inverseDecode = false +}) { + const black = FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff; + const [zeroMapping, oneMapping] = inverseDecode ? [nonBlackColor, black] : [black, nonBlackColor]; + const widthInSource = width >> 3; + const widthRemainder = width & 7; + const xorMask = zeroMapping ^ oneMapping; + const srcLength = src.length; + dest = new Uint32Array(dest.buffer); + let destPos = 0; + for (let i = 0; i < height; ++i) { + for (const max = srcPos + widthInSource; srcPos < max; ++srcPos, destPos += 8) { + const elem = src[srcPos]; + dest[destPos] = zeroMapping ^ -(elem >> 7 & 1) & xorMask; + dest[destPos + 1] = zeroMapping ^ -(elem >> 6 & 1) & xorMask; + dest[destPos + 2] = zeroMapping ^ -(elem >> 5 & 1) & xorMask; + dest[destPos + 3] = zeroMapping ^ -(elem >> 4 & 1) & xorMask; + dest[destPos + 4] = zeroMapping ^ -(elem >> 3 & 1) & xorMask; + dest[destPos + 5] = zeroMapping ^ -(elem >> 2 & 1) & xorMask; + dest[destPos + 6] = zeroMapping ^ -(elem >> 1 & 1) & xorMask; + dest[destPos + 7] = zeroMapping ^ -(elem & 1) & xorMask; + } + if (widthRemainder === 0) { + continue; + } + const elem = srcPos < srcLength ? src[srcPos++] : 255; + for (let j = 0; j < widthRemainder; ++j, ++destPos) { + dest[destPos] = zeroMapping ^ -(elem >> 7 - j & 1) & xorMask; + } + } + return { + srcPos, + destPos + }; +} +function convertRGBToRGBA({ + src, + srcPos = 0, + dest, + destPos = 0, + width, + height +}) { + let i = 0; + const len = width * height * 3; + const len32 = len >> 2; + const src32 = new Uint32Array(src.buffer, srcPos, len32); + const alphaMask = image_utils_FeatureTest.isLittleEndian ? 0xff000000 : 0xff; + if (image_utils_FeatureTest.isLittleEndian) { + for (; i < len32 - 2; i += 3, destPos += 4) { + const s1 = src32[i], + s2 = src32[i + 1], + s3 = src32[i + 2]; + dest[destPos] = s1 | alphaMask; + dest[destPos + 1] = s1 >>> 24 | s2 << 8 | alphaMask; + dest[destPos + 2] = s2 >>> 16 | s3 << 16 | alphaMask; + dest[destPos + 3] = s3 >>> 8 | alphaMask; + } + for (let j = i * 4, jj = srcPos + len; j < jj; j += 3) { + dest[destPos++] = src[j] | src[j + 1] << 8 | src[j + 2] << 16 | alphaMask; + } + } else { + for (; i < len32 - 2; i += 3, destPos += 4) { + const s1 = src32[i], + s2 = src32[i + 1], + s3 = src32[i + 2]; + dest[destPos] = s1 | alphaMask; + dest[destPos + 1] = s1 << 24 | s2 >>> 8 | alphaMask; + dest[destPos + 2] = s2 << 16 | s3 >>> 16 | alphaMask; + dest[destPos + 3] = s3 << 8 | alphaMask; + } + for (let j = i * 4, jj = srcPos + len; j < jj; j += 3) { + dest[destPos++] = src[j] << 24 | src[j + 1] << 16 | src[j + 2] << 8 | alphaMask; + } + } + return { + srcPos: srcPos + len, + destPos + }; +} +function grayToRGBA(src, dest) { + if (image_utils_FeatureTest.isLittleEndian) { + for (let i = 0, ii = src.length; i < ii; i++) { + dest[i] = src[i] * 0x10101 | 0xff000000; + } + } else { + for (let i = 0, ii = src.length; i < ii; i++) { + dest[i] = src[i] * 0x1010100 | 0x000000ff; + } + } +} + +;// ./src/display/canvas.js + + + + + +const MIN_FONT_SIZE = 16; +const MAX_FONT_SIZE = 100; +const EXECUTION_TIME = 15; +const EXECUTION_STEPS = 10; +const FULL_CHUNK_HEIGHT = 16; +const SCALE_MATRIX = new DOMMatrix(); +const XY = new Float32Array(2); +const MIN_MAX_INIT = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]); +function mirrorContextOperations(ctx, destCtx) { + if (ctx._removeMirroring) { + throw new Error("Context is already forwarding operations."); + } + ctx.__originalSave = ctx.save; + ctx.__originalRestore = ctx.restore; + ctx.__originalRotate = ctx.rotate; + ctx.__originalScale = ctx.scale; + ctx.__originalTranslate = ctx.translate; + ctx.__originalTransform = ctx.transform; + ctx.__originalSetTransform = ctx.setTransform; + ctx.__originalResetTransform = ctx.resetTransform; + ctx.__originalClip = ctx.clip; + ctx.__originalMoveTo = ctx.moveTo; + ctx.__originalLineTo = ctx.lineTo; + ctx.__originalBezierCurveTo = ctx.bezierCurveTo; + ctx.__originalRect = ctx.rect; + ctx.__originalClosePath = ctx.closePath; + ctx.__originalBeginPath = ctx.beginPath; + ctx._removeMirroring = () => { + ctx.save = ctx.__originalSave; + ctx.restore = ctx.__originalRestore; + ctx.rotate = ctx.__originalRotate; + ctx.scale = ctx.__originalScale; + ctx.translate = ctx.__originalTranslate; + ctx.transform = ctx.__originalTransform; + ctx.setTransform = ctx.__originalSetTransform; + ctx.resetTransform = ctx.__originalResetTransform; + ctx.clip = ctx.__originalClip; + ctx.moveTo = ctx.__originalMoveTo; + ctx.lineTo = ctx.__originalLineTo; + ctx.bezierCurveTo = ctx.__originalBezierCurveTo; + ctx.rect = ctx.__originalRect; + ctx.closePath = ctx.__originalClosePath; + ctx.beginPath = ctx.__originalBeginPath; + delete ctx._removeMirroring; + }; + ctx.save = function () { + destCtx.save(); + this.__originalSave(); + }; + ctx.restore = function () { + destCtx.restore(); + this.__originalRestore(); + }; + ctx.translate = function (x, y) { + destCtx.translate(x, y); + this.__originalTranslate(x, y); + }; + ctx.scale = function (x, y) { + destCtx.scale(x, y); + this.__originalScale(x, y); + }; + ctx.transform = function (a, b, c, d, e, f) { + destCtx.transform(a, b, c, d, e, f); + this.__originalTransform(a, b, c, d, e, f); + }; + ctx.setTransform = function (a, b, c, d, e, f) { + destCtx.setTransform(a, b, c, d, e, f); + this.__originalSetTransform(a, b, c, d, e, f); + }; + ctx.resetTransform = function () { + destCtx.resetTransform(); + this.__originalResetTransform(); + }; + ctx.rotate = function (angle) { + destCtx.rotate(angle); + this.__originalRotate(angle); + }; + ctx.clip = function (rule) { + destCtx.clip(rule); + this.__originalClip(rule); + }; + ctx.moveTo = function (x, y) { + destCtx.moveTo(x, y); + this.__originalMoveTo(x, y); + }; + ctx.lineTo = function (x, y) { + destCtx.lineTo(x, y); + this.__originalLineTo(x, y); + }; + ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) { + destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y); + this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y); + }; + ctx.rect = function (x, y, width, height) { + destCtx.rect(x, y, width, height); + this.__originalRect(x, y, width, height); + }; + ctx.closePath = function () { + destCtx.closePath(); + this.__originalClosePath(); + }; + ctx.beginPath = function () { + destCtx.beginPath(); + this.__originalBeginPath(); + }; +} +class CachedCanvases { + constructor(canvasFactory) { + this.canvasFactory = canvasFactory; + this.cache = Object.create(null); + } + getCanvas(id, width, height) { + let canvasEntry; + if (this.cache[id] !== undefined) { + canvasEntry = this.cache[id]; + this.canvasFactory.reset(canvasEntry, width, height); + } else { + canvasEntry = this.canvasFactory.create(width, height); + this.cache[id] = canvasEntry; + } + return canvasEntry; + } + delete(id) { + delete this.cache[id]; + } + clear() { + for (const id in this.cache) { + const canvasEntry = this.cache[id]; + this.canvasFactory.destroy(canvasEntry); + delete this.cache[id]; + } + } +} +function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) { + const [a, b, c, d, tx, ty] = getCurrentTransform(ctx); + if (b === 0 && c === 0) { + const tlX = destX * a + tx; + const rTlX = Math.round(tlX); + const tlY = destY * d + ty; + const rTlY = Math.round(tlY); + const brX = (destX + destW) * a + tx; + const rWidth = Math.abs(Math.round(brX) - rTlX) || 1; + const brY = (destY + destH) * d + ty; + const rHeight = Math.abs(Math.round(brY) - rTlY) || 1; + ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY); + ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight); + ctx.setTransform(a, b, c, d, tx, ty); + return [rWidth, rHeight]; + } + if (a === 0 && d === 0) { + const tlX = destY * c + tx; + const rTlX = Math.round(tlX); + const tlY = destX * b + ty; + const rTlY = Math.round(tlY); + const brX = (destY + destH) * c + tx; + const rWidth = Math.abs(Math.round(brX) - rTlX) || 1; + const brY = (destX + destW) * b + ty; + const rHeight = Math.abs(Math.round(brY) - rTlY) || 1; + ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY); + ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth); + ctx.setTransform(a, b, c, d, tx, ty); + return [rHeight, rWidth]; + } + ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH); + const scaleX = Math.hypot(a, b); + const scaleY = Math.hypot(c, d); + return [scaleX * destW, scaleY * destH]; +} +class CanvasExtraState { + alphaIsShape = false; + fontSize = 0; + fontSizeScale = 1; + textMatrix = null; + textMatrixScale = 1; + fontMatrix = FONT_IDENTITY_MATRIX; + leading = 0; + x = 0; + y = 0; + lineX = 0; + lineY = 0; + charSpacing = 0; + wordSpacing = 0; + textHScale = 1; + textRenderingMode = TextRenderingMode.FILL; + textRise = 0; + fillColor = "#000000"; + strokeColor = "#000000"; + patternFill = false; + patternStroke = false; + fillAlpha = 1; + strokeAlpha = 1; + lineWidth = 1; + activeSMask = null; + transferMaps = "none"; + constructor(width, height, preInit) { + preInit?.(this); + this.clipBox = new Float32Array([0, 0, width, height]); + this.minMax = MIN_MAX_INIT.slice(); + } + clone() { + const clone = Object.create(this); + clone.clipBox = this.clipBox.slice(); + clone.minMax = this.minMax.slice(); + return clone; + } + getPathBoundingBox(pathType = PathType.FILL, transform = null) { + const box = this.minMax.slice(); + if (pathType === PathType.STROKE) { + if (!transform) { + unreachable("Stroke bounding box must include transform."); + } + Util.singularValueDecompose2dScale(transform, XY); + const xStrokePad = XY[0] * this.lineWidth / 2; + const yStrokePad = XY[1] * this.lineWidth / 2; + box[0] -= xStrokePad; + box[1] -= yStrokePad; + box[2] += xStrokePad; + box[3] += yStrokePad; + } + return box; + } + updateClipFromPath() { + const intersect = Util.intersect(this.clipBox, this.getPathBoundingBox()); + this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]); + } + isEmptyClip() { + return this.minMax[0] === Infinity; + } + startNewPathAndClipBox(box) { + this.clipBox.set(box, 0); + this.minMax.set(MIN_MAX_INIT, 0); + } + getClippedPathBoundingBox(pathType = PathType.FILL, transform = null) { + return Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform)); + } +} +function putBinaryImageData(ctx, imgData) { + if (imgData instanceof ImageData) { + ctx.putImageData(imgData, 0, 0); + return; + } + const height = imgData.height, + width = imgData.width; + const partialChunkHeight = height % FULL_CHUNK_HEIGHT; + const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; + const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; + const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); + let srcPos = 0, + destPos; + const src = imgData.data; + const dest = chunkImgData.data; + let i, j, thisChunkHeight, elemsInThisChunk; + if (imgData.kind === ImageKind.GRAYSCALE_1BPP) { + const srcLength = src.byteLength; + const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2); + const dest32DataLength = dest32.length; + const fullSrcDiff = width + 7 >> 3; + const white = 0xffffffff; + const black = FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff; + for (i = 0; i < totalChunks; i++) { + thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight; + destPos = 0; + for (j = 0; j < thisChunkHeight; j++) { + const srcDiff = srcLength - srcPos; + let k = 0; + const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7; + const kEndUnrolled = kEnd & ~7; + let mask = 0; + let srcByte = 0; + for (; k < kEndUnrolled; k += 8) { + srcByte = src[srcPos++]; + dest32[destPos++] = srcByte & 128 ? white : black; + dest32[destPos++] = srcByte & 64 ? white : black; + dest32[destPos++] = srcByte & 32 ? white : black; + dest32[destPos++] = srcByte & 16 ? white : black; + dest32[destPos++] = srcByte & 8 ? white : black; + dest32[destPos++] = srcByte & 4 ? white : black; + dest32[destPos++] = srcByte & 2 ? white : black; + dest32[destPos++] = srcByte & 1 ? white : black; + } + for (; k < kEnd; k++) { + if (mask === 0) { + srcByte = src[srcPos++]; + mask = 128; + } + dest32[destPos++] = srcByte & mask ? white : black; + mask >>= 1; + } + } + while (destPos < dest32DataLength) { + dest32[destPos++] = 0; + } + ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); + } + } else if (imgData.kind === ImageKind.RGBA_32BPP) { + j = 0; + elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4; + for (i = 0; i < fullChunks; i++) { + dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); + srcPos += elemsInThisChunk; + ctx.putImageData(chunkImgData, 0, j); + j += FULL_CHUNK_HEIGHT; + } + if (i < totalChunks) { + elemsInThisChunk = width * partialChunkHeight * 4; + dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); + ctx.putImageData(chunkImgData, 0, j); + } + } else if (imgData.kind === ImageKind.RGB_24BPP) { + thisChunkHeight = FULL_CHUNK_HEIGHT; + elemsInThisChunk = width * thisChunkHeight; + for (i = 0; i < totalChunks; i++) { + if (i >= fullChunks) { + thisChunkHeight = partialChunkHeight; + elemsInThisChunk = width * thisChunkHeight; + } + destPos = 0; + for (j = elemsInThisChunk; j--;) { + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = 255; + } + ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); + } + } else { + throw new Error(`bad image kind: ${imgData.kind}`); + } +} +function putBinaryImageMask(ctx, imgData) { + if (imgData.bitmap) { + ctx.drawImage(imgData.bitmap, 0, 0); + return; + } + const height = imgData.height, + width = imgData.width; + const partialChunkHeight = height % FULL_CHUNK_HEIGHT; + const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; + const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; + const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); + let srcPos = 0; + const src = imgData.data; + const dest = chunkImgData.data; + for (let i = 0; i < totalChunks; i++) { + const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight; + ({ + srcPos + } = convertBlackAndWhiteToRGBA({ + src, + srcPos, + dest, + width, + height: thisChunkHeight, + nonBlackColor: 0 + })); + ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); + } +} +function copyCtxState(sourceCtx, destCtx) { + const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font", "filter"]; + for (const property of properties) { + if (sourceCtx[property] !== undefined) { + destCtx[property] = sourceCtx[property]; + } + } + if (sourceCtx.setLineDash !== undefined) { + destCtx.setLineDash(sourceCtx.getLineDash()); + destCtx.lineDashOffset = sourceCtx.lineDashOffset; + } +} +function resetCtxToDefault(ctx) { + ctx.strokeStyle = ctx.fillStyle = "#000000"; + ctx.fillRule = "nonzero"; + ctx.globalAlpha = 1; + ctx.lineWidth = 1; + ctx.lineCap = "butt"; + ctx.lineJoin = "miter"; + ctx.miterLimit = 10; + ctx.globalCompositeOperation = "source-over"; + ctx.font = "10px sans-serif"; + if (ctx.setLineDash !== undefined) { + ctx.setLineDash([]); + ctx.lineDashOffset = 0; + } + const { + filter + } = ctx; + if (filter !== "none" && filter !== "") { + ctx.filter = "none"; + } +} +function getImageSmoothingEnabled(transform, interpolate) { + if (interpolate) { + return true; + } + Util.singularValueDecompose2dScale(transform, XY); + const actualScale = Math.fround(OutputScale.pixelRatio * PixelsPerInch.PDF_TO_CSS_UNITS); + return XY[0] <= actualScale && XY[1] <= actualScale; +} +const LINE_CAP_STYLES = ["butt", "round", "square"]; +const LINE_JOIN_STYLES = ["miter", "round", "bevel"]; +const NORMAL_CLIP = {}; +const EO_CLIP = {}; +class CanvasGraphics { + constructor(canvasCtx, commonObjs, objs, canvasFactory, filterFactory, { + optionalContentConfig, + markedContentStack = null + }, annotationCanvasMap, pageColors, dependencyTracker) { + this.ctx = canvasCtx; + this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height); + this.stateStack = []; + this.pendingClip = null; + this.pendingEOFill = false; + this.commonObjs = commonObjs; + this.objs = objs; + this.canvasFactory = canvasFactory; + this.filterFactory = filterFactory; + this.groupStack = []; + this.baseTransform = null; + this.baseTransformStack = []; + this.groupLevel = 0; + this.smaskStack = []; + this.smaskCounter = 0; + this.tempSMask = null; + this.suspendedCtx = null; + this.contentVisible = true; + this.markedContentStack = markedContentStack || []; + this.optionalContentConfig = optionalContentConfig; + this.cachedCanvases = new CachedCanvases(this.canvasFactory); + this.cachedPatterns = new Map(); + this.annotationCanvasMap = annotationCanvasMap; + this.viewportScale = 1; + this.outputScaleX = 1; + this.outputScaleY = 1; + this.pageColors = pageColors; + this._cachedScaleForStroking = [-1, 0]; + this._cachedGetSinglePixelWidth = null; + this._cachedBitmapsMap = new Map(); + this.dependencyTracker = dependencyTracker ?? null; + } + getObject(opIdx, data, fallback = null) { + if (typeof data === "string") { + this.dependencyTracker?.recordNamedDependency(opIdx, data); + return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data); + } + return fallback; + } + beginDrawing({ + transform, + viewport, + transparency = false, + background = null + }) { + const width = this.ctx.canvas.width; + const height = this.ctx.canvas.height; + const savedFillStyle = this.ctx.fillStyle; + this.ctx.fillStyle = background || "#ffffff"; + this.ctx.fillRect(0, 0, width, height); + this.ctx.fillStyle = savedFillStyle; + if (transparency) { + const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height); + this.compositeCtx = this.ctx; + this.transparentCanvas = transparentCanvas.canvas; + this.ctx = transparentCanvas.context; + this.ctx.save(); + this.ctx.transform(...getCurrentTransform(this.compositeCtx)); + } + this.ctx.save(); + resetCtxToDefault(this.ctx); + if (transform) { + this.ctx.transform(...transform); + this.outputScaleX = transform[0]; + this.outputScaleY = transform[0]; + } + this.ctx.transform(...viewport.transform); + this.viewportScale = viewport.scale; + this.baseTransform = getCurrentTransform(this.ctx); + } + executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper, operationsFilter) { + const argsArray = operatorList.argsArray; + const fnArray = operatorList.fnArray; + let i = executionStartIdx || 0; + const argsArrayLen = argsArray.length; + if (argsArrayLen === i) { + return i; + } + const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function"; + const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0; + let steps = 0; + const commonObjs = this.commonObjs; + const objs = this.objs; + let fnId, fnArgs; + while (true) { + if (stepper !== undefined && i === stepper.nextBreakPoint) { + stepper.breakIt(i, continueCallback); + return i; + } + if (!operationsFilter || operationsFilter(i)) { + fnId = fnArray[i]; + fnArgs = argsArray[i] ?? null; + if (fnId !== OPS.dependency) { + if (fnArgs === null) { + this[fnId](i); + } else { + this[fnId](i, ...fnArgs); + } + } else { + for (const depObjId of fnArgs) { + this.dependencyTracker?.recordNamedData(depObjId, i); + const objsPool = depObjId.startsWith("g_") ? commonObjs : objs; + if (!objsPool.has(depObjId)) { + objsPool.get(depObjId, continueCallback); + return i; + } + } + } + } + i++; + if (i === argsArrayLen) { + return i; + } + if (chunkOperations && ++steps > EXECUTION_STEPS) { + if (Date.now() > endTime) { + continueCallback(); + return i; + } + steps = 0; + } + } + } + #restoreInitialState() { + while (this.stateStack.length || this.inSMaskMode) { + this.restore(); + } + this.current.activeSMask = null; + this.ctx.restore(); + if (this.transparentCanvas) { + this.ctx = this.compositeCtx; + this.ctx.save(); + this.ctx.setTransform(1, 0, 0, 1, 0, 0); + this.ctx.drawImage(this.transparentCanvas, 0, 0); + this.ctx.restore(); + this.transparentCanvas = null; + } + } + endDrawing() { + this.#restoreInitialState(); + this.cachedCanvases.clear(); + this.cachedPatterns.clear(); + for (const cache of this._cachedBitmapsMap.values()) { + for (const canvas of cache.values()) { + if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) { + canvas.width = canvas.height = 0; + } + } + cache.clear(); + } + this._cachedBitmapsMap.clear(); + this.#drawFilter(); + } + #drawFilter() { + if (this.pageColors) { + const hcmFilterId = this.filterFactory.addHCMFilter(this.pageColors.foreground, this.pageColors.background); + if (hcmFilterId !== "none") { + const savedFilter = this.ctx.filter; + this.ctx.filter = hcmFilterId; + this.ctx.drawImage(this.ctx.canvas, 0, 0); + this.ctx.filter = savedFilter; + } + } + } + _scaleImage(img, inverseTransform) { + const width = img.width ?? img.displayWidth; + const height = img.height ?? img.displayHeight; + let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1); + let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1); + let paintWidth = width, + paintHeight = height; + let tmpCanvasId = "prescale1"; + let tmpCanvas, tmpCtx; + while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) { + let newWidth = paintWidth, + newHeight = paintHeight; + if (widthScale > 2 && paintWidth > 1) { + newWidth = paintWidth >= 16384 ? Math.floor(paintWidth / 2) - 1 || 1 : Math.ceil(paintWidth / 2); + widthScale /= paintWidth / newWidth; + } + if (heightScale > 2 && paintHeight > 1) { + newHeight = paintHeight >= 16384 ? Math.floor(paintHeight / 2) - 1 || 1 : Math.ceil(paintHeight) / 2; + heightScale /= paintHeight / newHeight; + } + tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight); + tmpCtx = tmpCanvas.context; + tmpCtx.clearRect(0, 0, newWidth, newHeight); + tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight); + img = tmpCanvas.canvas; + paintWidth = newWidth; + paintHeight = newHeight; + tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1"; + } + return { + img, + paintWidth, + paintHeight + }; + } + _createMaskCanvas(opIdx, img) { + const ctx = this.ctx; + const { + width, + height + } = img; + const fillColor = this.current.fillColor; + const isPatternFill = this.current.patternFill; + const currentTransform = getCurrentTransform(ctx); + let cache, cacheKey, scaled, maskCanvas; + if ((img.bitmap || img.data) && img.count > 1) { + const mainKey = img.bitmap || img.data.buffer; + cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]); + cache = this._cachedBitmapsMap.getOrInsertComputed(mainKey, makeMap); + const cachedImage = cache.get(cacheKey); + if (cachedImage && !isPatternFill) { + const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]); + const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]); + this.dependencyTracker?.recordDependencies(opIdx, Dependencies.transformAndFill); + return { + canvas: cachedImage, + offsetX, + offsetY + }; + } + scaled = cachedImage; + } + if (!scaled) { + maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height); + putBinaryImageMask(maskCanvas.context, img); + } + let maskToCanvas = Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]); + maskToCanvas = Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]); + const minMax = MIN_MAX_INIT.slice(); + Util.axialAlignedBoundingBox([0, 0, width, height], maskToCanvas, minMax); + const [minX, minY, maxX, maxY] = minMax; + const drawnWidth = Math.round(maxX - minX) || 1; + const drawnHeight = Math.round(maxY - minY) || 1; + const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight); + const fillCtx = fillCanvas.context; + const offsetX = minX; + const offsetY = minY; + fillCtx.translate(-offsetX, -offsetY); + fillCtx.transform(...maskToCanvas); + if (!scaled) { + scaled = this._scaleImage(maskCanvas.canvas, getCurrentTransformInverse(fillCtx)); + scaled = scaled.img; + if (cache && isPatternFill) { + cache.set(cacheKey, scaled); + } + } + fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(fillCtx), img.interpolate); + drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height); + fillCtx.globalCompositeOperation = "source-in"; + const inverse = Util.transform(getCurrentTransformInverse(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]); + fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, PathType.FILL, opIdx) : fillColor; + fillCtx.fillRect(0, 0, width, height); + if (cache && !isPatternFill) { + this.cachedCanvases.delete("fillCanvas"); + cache.set(cacheKey, fillCanvas.canvas); + } + this.dependencyTracker?.recordDependencies(opIdx, Dependencies.transformAndFill); + return { + canvas: fillCanvas.canvas, + offsetX: Math.round(offsetX), + offsetY: Math.round(offsetY) + }; + } + setLineWidth(opIdx, width) { + this.dependencyTracker?.recordSimpleData("lineWidth", opIdx); + if (width !== this.current.lineWidth) { + this._cachedScaleForStroking[0] = -1; + } + this.current.lineWidth = width; + this.ctx.lineWidth = width; + } + setLineCap(opIdx, style) { + this.dependencyTracker?.recordSimpleData("lineCap", opIdx); + this.ctx.lineCap = LINE_CAP_STYLES[style]; + } + setLineJoin(opIdx, style) { + this.dependencyTracker?.recordSimpleData("lineJoin", opIdx); + this.ctx.lineJoin = LINE_JOIN_STYLES[style]; + } + setMiterLimit(opIdx, limit) { + this.dependencyTracker?.recordSimpleData("miterLimit", opIdx); + this.ctx.miterLimit = limit; + } + setDash(opIdx, dashArray, dashPhase) { + this.dependencyTracker?.recordSimpleData("dash", opIdx); + const ctx = this.ctx; + if (ctx.setLineDash !== undefined) { + ctx.setLineDash(dashArray); + ctx.lineDashOffset = dashPhase; + } + } + setRenderingIntent(opIdx, intent) {} + setFlatness(opIdx, flatness) {} + setGState(opIdx, states) { + for (const [key, value] of states) { + switch (key) { + case "LW": + this.setLineWidth(opIdx, value); + break; + case "LC": + this.setLineCap(opIdx, value); + break; + case "LJ": + this.setLineJoin(opIdx, value); + break; + case "ML": + this.setMiterLimit(opIdx, value); + break; + case "D": + this.setDash(opIdx, value[0], value[1]); + break; + case "RI": + this.setRenderingIntent(opIdx, value); + break; + case "FL": + this.setFlatness(opIdx, value); + break; + case "Font": + this.setFont(opIdx, value[0], value[1]); + break; + case "CA": + this.dependencyTracker?.recordSimpleData("strokeAlpha", opIdx); + this.current.strokeAlpha = value; + break; + case "ca": + this.dependencyTracker?.recordSimpleData("fillAlpha", opIdx); + this.ctx.globalAlpha = this.current.fillAlpha = value; + break; + case "BM": + this.dependencyTracker?.recordSimpleData("globalCompositeOperation", opIdx); + this.ctx.globalCompositeOperation = value; + break; + case "SMask": + this.dependencyTracker?.recordSimpleData("SMask", opIdx); + this.current.activeSMask = value ? this.tempSMask : null; + this.tempSMask = null; + this.checkSMaskState(); + break; + case "TR": + this.dependencyTracker?.recordSimpleData("filter", opIdx); + this.ctx.filter = this.current.transferMaps = this.filterFactory.addFilter(value); + break; + } + } + } + get inSMaskMode() { + return !!this.suspendedCtx; + } + checkSMaskState() { + const inSMaskMode = this.inSMaskMode; + if (this.current.activeSMask && !inSMaskMode) { + this.beginSMaskMode(); + } else if (!this.current.activeSMask && inSMaskMode) { + this.endSMaskMode(); + } + } + beginSMaskMode(opIdx) { + if (this.inSMaskMode) { + throw new Error("beginSMaskMode called while already in smask mode"); + } + const drawnWidth = this.ctx.canvas.width; + const drawnHeight = this.ctx.canvas.height; + const cacheId = "smaskGroupAt" + this.groupLevel; + const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight); + this.suspendedCtx = this.ctx; + const ctx = this.ctx = scratchCanvas.context; + ctx.setTransform(this.suspendedCtx.getTransform()); + copyCtxState(this.suspendedCtx, ctx); + mirrorContextOperations(ctx, this.suspendedCtx); + this.setGState(opIdx, [["BM", "source-over"]]); + } + endSMaskMode() { + if (!this.inSMaskMode) { + throw new Error("endSMaskMode called while not in smask mode"); + } + this.ctx._removeMirroring(); + copyCtxState(this.ctx, this.suspendedCtx); + this.ctx = this.suspendedCtx; + this.suspendedCtx = null; + } + compose(dirtyBox) { + if (!this.current.activeSMask) { + return; + } + if (!dirtyBox) { + dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height]; + } else { + dirtyBox[0] = Math.floor(dirtyBox[0]); + dirtyBox[1] = Math.floor(dirtyBox[1]); + dirtyBox[2] = Math.ceil(dirtyBox[2]); + dirtyBox[3] = Math.ceil(dirtyBox[3]); + } + const smask = this.current.activeSMask; + const suspendedCtx = this.suspendedCtx; + this.composeSMask(suspendedCtx, smask, this.ctx, dirtyBox); + this.ctx.save(); + this.ctx.setTransform(1, 0, 0, 1, 0, 0); + this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height); + this.ctx.restore(); + } + composeSMask(ctx, smask, layerCtx, layerBox) { + const layerOffsetX = layerBox[0]; + const layerOffsetY = layerBox[1]; + const layerWidth = layerBox[2] - layerOffsetX; + const layerHeight = layerBox[3] - layerOffsetY; + if (layerWidth === 0 || layerHeight === 0) { + return; + } + this.genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY); + ctx.save(); + ctx.globalAlpha = 1; + ctx.globalCompositeOperation = "source-over"; + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.drawImage(layerCtx.canvas, 0, 0); + ctx.restore(); + } + genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) { + let maskCanvas = maskCtx.canvas; + let maskX = layerOffsetX - maskOffsetX; + let maskY = layerOffsetY - maskOffsetY; + if (backdrop) { + if (maskX < 0 || maskY < 0 || maskX + width > maskCanvas.width || maskY + height > maskCanvas.height) { + const canvas = this.cachedCanvases.getCanvas("maskExtension", width, height); + const ctx = canvas.context; + ctx.drawImage(maskCanvas, -maskX, -maskY); + ctx.globalCompositeOperation = "destination-atop"; + ctx.fillStyle = backdrop; + ctx.fillRect(0, 0, width, height); + ctx.globalCompositeOperation = "source-over"; + maskCanvas = canvas.canvas; + maskX = maskY = 0; + } else { + maskCtx.save(); + maskCtx.globalAlpha = 1; + maskCtx.setTransform(1, 0, 0, 1, 0, 0); + const clip = new Path2D(); + clip.rect(maskX, maskY, width, height); + maskCtx.clip(clip); + maskCtx.globalCompositeOperation = "destination-atop"; + maskCtx.fillStyle = backdrop; + maskCtx.fillRect(maskX, maskY, width, height); + maskCtx.restore(); + } + } + layerCtx.save(); + layerCtx.globalAlpha = 1; + layerCtx.setTransform(1, 0, 0, 1, 0, 0); + if (subtype === "Alpha" && transferMap) { + layerCtx.filter = this.filterFactory.addAlphaFilter(transferMap); + } else if (subtype === "Luminosity") { + layerCtx.filter = this.filterFactory.addLuminosityFilter(transferMap); + } + const clip = new Path2D(); + clip.rect(layerOffsetX, layerOffsetY, width, height); + layerCtx.clip(clip); + layerCtx.globalCompositeOperation = "destination-in"; + layerCtx.drawImage(maskCanvas, maskX, maskY, width, height, layerOffsetX, layerOffsetY, width, height); + layerCtx.restore(); + } + save(opIdx) { + if (this.inSMaskMode) { + copyCtxState(this.ctx, this.suspendedCtx); + } + this.ctx.save(); + const old = this.current; + this.stateStack.push(old); + this.current = old.clone(); + this.dependencyTracker?.save(opIdx); + } + restore(opIdx) { + this.dependencyTracker?.restore(opIdx); + if (this.stateStack.length === 0) { + if (this.inSMaskMode) { + this.endSMaskMode(); + } + return; + } + this.current = this.stateStack.pop(); + this.ctx.restore(); + if (this.inSMaskMode) { + copyCtxState(this.suspendedCtx, this.ctx); + } + this.checkSMaskState(); + this.pendingClip = null; + this._cachedScaleForStroking[0] = -1; + this._cachedGetSinglePixelWidth = null; + } + transform(opIdx, a, b, c, d, e, f) { + this.dependencyTracker?.recordIncrementalData("transform", opIdx); + this.ctx.transform(a, b, c, d, e, f); + this._cachedScaleForStroking[0] = -1; + this._cachedGetSinglePixelWidth = null; + } + constructPath(opIdx, op, data, minMax) { + let [path] = data; + if (!minMax) { + path ||= data[0] = new Path2D(); + this[op](opIdx, path); + return; + } + if (this.dependencyTracker !== null) { + const outerExtraSize = op === OPS.stroke ? this.current.lineWidth / 2 : 0; + this.dependencyTracker.resetBBox(opIdx).recordBBox(opIdx, this.ctx, minMax[0] - outerExtraSize, minMax[2] + outerExtraSize, minMax[1] - outerExtraSize, minMax[3] + outerExtraSize).recordDependencies(opIdx, ["transform"]); + } + if (!(path instanceof Path2D)) { + path = data[0] = makePathFromDrawOPS(path); + } + Util.axialAlignedBoundingBox(minMax, getCurrentTransform(this.ctx), this.current.minMax); + this[op](opIdx, path); + this._pathStartIdx = opIdx; + } + closePath(opIdx) { + this.ctx.closePath(); + } + stroke(opIdx, path, consumePath = true) { + const ctx = this.ctx; + const strokeColor = this.current.strokeColor; + ctx.globalAlpha = this.current.strokeAlpha; + if (this.contentVisible) { + if (typeof strokeColor === "object" && strokeColor?.getPattern) { + const baseTransform = strokeColor.isModifyingCurrentTransform() ? ctx.getTransform() : null; + ctx.save(); + ctx.strokeStyle = strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE, opIdx); + if (baseTransform) { + const newPath = new Path2D(); + newPath.addPath(path, ctx.getTransform().invertSelf().multiplySelf(baseTransform)); + path = newPath; + } + this.rescaleAndStroke(path, false); + ctx.restore(); + } else { + this.rescaleAndStroke(path, true); + } + } + this.dependencyTracker?.recordDependencies(opIdx, Dependencies.stroke); + if (consumePath) { + this.consumePath(opIdx, path, this.current.getClippedPathBoundingBox(PathType.STROKE, getCurrentTransform(this.ctx))); + } + ctx.globalAlpha = this.current.fillAlpha; + } + closeStroke(opIdx, path) { + this.stroke(opIdx, path); + } + fill(opIdx, path, consumePath = true) { + const ctx = this.ctx; + const fillColor = this.current.fillColor; + const isPatternFill = this.current.patternFill; + let needRestore = false; + if (isPatternFill) { + const baseTransform = fillColor.isModifyingCurrentTransform() ? ctx.getTransform() : null; + this.dependencyTracker?.save(opIdx); + ctx.save(); + ctx.fillStyle = fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL, opIdx); + if (baseTransform) { + const newPath = new Path2D(); + newPath.addPath(path, ctx.getTransform().invertSelf().multiplySelf(baseTransform)); + path = newPath; + } + needRestore = true; + } + const intersect = this.current.getClippedPathBoundingBox(); + if (this.contentVisible && intersect !== null) { + if (this.pendingEOFill) { + ctx.fill(path, "evenodd"); + this.pendingEOFill = false; + } else { + ctx.fill(path); + } + } + this.dependencyTracker?.recordDependencies(opIdx, Dependencies.fill); + if (needRestore) { + ctx.restore(); + this.dependencyTracker?.restore(opIdx); + } + if (consumePath) { + this.consumePath(opIdx, path, intersect); + } + } + eoFill(opIdx, path) { + this.pendingEOFill = true; + this.fill(opIdx, path); + } + fillStroke(opIdx, path) { + this.fill(opIdx, path, false); + this.stroke(opIdx, path, false); + this.consumePath(opIdx, path); + } + eoFillStroke(opIdx, path) { + this.pendingEOFill = true; + this.fillStroke(opIdx, path); + } + closeFillStroke(opIdx, path) { + this.fillStroke(opIdx, path); + } + closeEOFillStroke(opIdx, path) { + this.pendingEOFill = true; + this.fillStroke(opIdx, path); + } + endPath(opIdx, path) { + this.consumePath(opIdx, path); + } + rawFillPath(opIdx, path) { + this.ctx.fill(path); + this.dependencyTracker?.recordDependencies(opIdx, Dependencies.rawFillPath).recordOperation(opIdx); + } + clip(opIdx) { + this.dependencyTracker?.recordFutureForcedDependency("clipMode", opIdx); + this.pendingClip = NORMAL_CLIP; + } + eoClip(opIdx) { + this.dependencyTracker?.recordFutureForcedDependency("clipMode", opIdx); + this.pendingClip = EO_CLIP; + } + beginText(opIdx) { + this.current.textMatrix = null; + this.current.textMatrixScale = 1; + this.current.x = this.current.lineX = 0; + this.current.y = this.current.lineY = 0; + this.dependencyTracker?.recordOpenMarker(opIdx).resetIncrementalData("sameLineText").resetIncrementalData("moveText", opIdx); + } + endText(opIdx) { + const paths = this.pendingTextPaths; + const ctx = this.ctx; + if (this.dependencyTracker) { + const { + dependencyTracker + } = this; + if (paths !== undefined) { + dependencyTracker.recordFutureForcedDependency("textClip", dependencyTracker.getOpenMarker()).recordFutureForcedDependency("textClip", opIdx); + } + dependencyTracker.recordCloseMarker(opIdx); + } + if (paths !== undefined) { + const newPath = new Path2D(); + const invTransf = ctx.getTransform().invertSelf(); + for (const { + transform, + x, + y, + fontSize, + path + } of paths) { + if (!path) { + continue; + } + newPath.addPath(path, new DOMMatrix(transform).preMultiplySelf(invTransf).translate(x, y).scale(fontSize, -fontSize)); + } + ctx.clip(newPath); + } + delete this.pendingTextPaths; + } + setCharSpacing(opIdx, spacing) { + this.dependencyTracker?.recordSimpleData("charSpacing", opIdx); + this.current.charSpacing = spacing; + } + setWordSpacing(opIdx, spacing) { + this.dependencyTracker?.recordSimpleData("wordSpacing", opIdx); + this.current.wordSpacing = spacing; + } + setHScale(opIdx, scale) { + this.dependencyTracker?.recordSimpleData("hScale", opIdx); + this.current.textHScale = scale / 100; + } + setLeading(opIdx, leading) { + this.dependencyTracker?.recordSimpleData("leading", opIdx); + this.current.leading = -leading; + } + setFont(opIdx, fontRefName, size) { + this.dependencyTracker?.recordSimpleData("font", opIdx).recordSimpleDataFromNamed("fontObj", fontRefName, opIdx); + const fontObj = this.commonObjs.get(fontRefName); + const current = this.current; + if (!fontObj) { + throw new Error(`Can't find font for ${fontRefName}`); + } + current.fontMatrix = fontObj.fontMatrix || FONT_IDENTITY_MATRIX; + if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) { + warn("Invalid font matrix for font " + fontRefName); + } + if (size < 0) { + size = -size; + current.fontDirection = -1; + } else { + current.fontDirection = 1; + } + this.current.font = fontObj; + this.current.fontSize = size; + if (fontObj.isType3Font) { + return; + } + const name = fontObj.loadedName || "sans-serif"; + const typeface = fontObj.systemFontInfo?.css || `"${name}", ${fontObj.fallbackName}`; + let bold = "normal"; + if (fontObj.black) { + bold = "900"; + } else if (fontObj.bold) { + bold = "bold"; + } + const italic = fontObj.italic ? "italic" : "normal"; + let browserFontSize = size; + if (size < MIN_FONT_SIZE) { + browserFontSize = MIN_FONT_SIZE; + } else if (size > MAX_FONT_SIZE) { + browserFontSize = MAX_FONT_SIZE; + } + this.current.fontSizeScale = size / browserFontSize; + this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`; + } + setTextRenderingMode(opIdx, mode) { + this.dependencyTracker?.recordSimpleData("textRenderingMode", opIdx); + this.current.textRenderingMode = mode; + } + setTextRise(opIdx, rise) { + this.dependencyTracker?.recordSimpleData("textRise", opIdx); + this.current.textRise = rise; + } + moveText(opIdx, x, y) { + this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText", opIdx); + this.current.x = this.current.lineX += x; + this.current.y = this.current.lineY += y; + } + setLeadingMoveText(opIdx, x, y) { + this.setLeading(opIdx, -y); + this.moveText(opIdx, x, y); + } + setTextMatrix(opIdx, matrix) { + this.dependencyTracker?.resetIncrementalData("sameLineText").recordSimpleData("textMatrix", opIdx); + const { + current + } = this; + current.textMatrix = matrix; + current.textMatrixScale = Math.hypot(matrix[0], matrix[1]); + current.x = current.lineX = 0; + current.y = current.lineY = 0; + } + nextLine(opIdx) { + this.moveText(opIdx, 0, this.current.leading); + this.dependencyTracker?.recordIncrementalData("moveText", this.dependencyTracker.getSimpleIndex("leading") ?? opIdx); + } + #getScaledPath(path, currentTransform, transform) { + const newPath = new Path2D(); + newPath.addPath(path, new DOMMatrix(transform).invertSelf().multiplySelf(currentTransform)); + return newPath; + } + paintChar(opIdx, character, x, y, patternFillTransform, patternStrokeTransform) { + const ctx = this.ctx; + const current = this.current; + const font = current.font; + const textRenderingMode = current.textRenderingMode; + const fontSize = current.fontSize / current.fontSizeScale; + const fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; + const isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG); + const patternFill = current.patternFill && !font.missingFile; + const patternStroke = current.patternStroke && !font.missingFile; + let path; + if ((font.disableFontFace || isAddToPathSet || patternFill || patternStroke) && !font.missingFile) { + path = font.getPathGenerator(this.commonObjs, character); + } + if (path && (font.disableFontFace || patternFill || patternStroke)) { + ctx.save(); + ctx.translate(x, y); + ctx.scale(fontSize, -fontSize); + this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font); + let currentTransform; + if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + if (patternFillTransform) { + currentTransform = ctx.getTransform(); + ctx.setTransform(...patternFillTransform); + const scaledPath = this.#getScaledPath(path, currentTransform, patternFillTransform); + ctx.fill(scaledPath); + } else { + ctx.fill(path); + } + } + if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + if (patternStrokeTransform) { + currentTransform ||= ctx.getTransform(); + ctx.setTransform(...patternStrokeTransform); + const { + a, + b, + c, + d + } = currentTransform; + const invPatternTransform = Util.inverseTransform(patternStrokeTransform); + const transf = Util.transform([a, b, c, d, 0, 0], invPatternTransform); + Util.singularValueDecompose2dScale(transf, XY); + ctx.lineWidth *= Math.max(XY[0], XY[1]) / fontSize; + ctx.stroke(this.#getScaledPath(path, currentTransform, patternStrokeTransform)); + } else { + ctx.lineWidth /= fontSize; + ctx.stroke(path); + } + } + ctx.restore(); + } else { + if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + ctx.fillText(character, x, y); + this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x, y, () => ctx.measureText(character)); + } + if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + if (this.dependencyTracker) { + this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x, y, () => ctx.measureText(character)).recordDependencies(opIdx, Dependencies.stroke); + } + ctx.strokeText(character, x, y); + } + } + if (isAddToPathSet) { + const paths = this.pendingTextPaths ||= []; + paths.push({ + transform: getCurrentTransform(ctx), + x, + y, + fontSize, + path + }); + this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x, y); + } + } + get isFontSubpixelAAEnabled() { + const { + context: ctx + } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10); + ctx.scale(1.5, 1); + ctx.fillText("I", 0, 10); + const data = ctx.getImageData(0, 0, 10, 10).data; + let enabled = false; + for (let i = 3; i < data.length; i += 4) { + if (data[i] > 0 && data[i] < 255) { + enabled = true; + break; + } + } + return shadow(this, "isFontSubpixelAAEnabled", enabled); + } + showText(opIdx, glyphs) { + if (this.dependencyTracker) { + this.dependencyTracker.recordDependencies(opIdx, Dependencies.showText).resetBBox(opIdx); + if (this.current.textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG) { + this.dependencyTracker.recordFutureForcedDependency("textClip", opIdx).inheritPendingDependenciesAsFutureForcedDependencies(); + } + } + const current = this.current; + const font = current.font; + if (font.isType3Font) { + this.showType3Text(opIdx, glyphs); + this.dependencyTracker?.recordShowTextOperation(opIdx); + return undefined; + } + const fontSize = current.fontSize; + if (fontSize === 0) { + this.dependencyTracker?.recordOperation(opIdx); + return undefined; + } + const ctx = this.ctx; + const fontSizeScale = current.fontSizeScale; + const charSpacing = current.charSpacing; + const wordSpacing = current.wordSpacing; + const fontDirection = current.fontDirection; + const textHScale = current.textHScale * fontDirection; + const glyphsLength = glyphs.length; + const vertical = font.vertical; + const spacingDir = vertical ? 1 : -1; + const defaultVMetrics = font.defaultVMetrics; + const widthAdvanceScale = fontSize * current.fontMatrix[0]; + const simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill; + ctx.save(); + if (current.textMatrix) { + ctx.transform(...current.textMatrix); + } + ctx.translate(current.x, current.y + current.textRise); + if (fontDirection > 0) { + ctx.scale(textHScale, -1); + } else { + ctx.scale(textHScale, 1); + } + let patternFillTransform, patternStrokeTransform; + const fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; + const needsFill = fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE; + const needsStroke = fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE; + if (needsFill && current.patternFill) { + ctx.save(); + const pattern = current.fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL, opIdx); + patternFillTransform = getCurrentTransform(ctx); + ctx.restore(); + ctx.fillStyle = pattern; + } + if (needsStroke && current.patternStroke) { + ctx.save(); + const pattern = current.strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE, opIdx); + patternStrokeTransform = getCurrentTransform(ctx); + ctx.restore(); + ctx.strokeStyle = pattern; + } + let lineWidth = current.lineWidth; + const scale = current.textMatrixScale; + if (scale === 0 || lineWidth === 0) { + if (needsStroke) { + lineWidth = this.getSinglePixelWidth(); + } + } else { + lineWidth /= scale; + } + if (fontSizeScale !== 1.0) { + ctx.scale(fontSizeScale, fontSizeScale); + lineWidth /= fontSizeScale; + } + ctx.lineWidth = lineWidth; + if (font.isInvalidPDFjsFont) { + const chars = []; + let width = 0; + for (const glyph of glyphs) { + chars.push(glyph.unicode); + width += glyph.width; + } + const joinedChars = chars.join(""); + ctx.fillText(joinedChars, 0, 0); + if (this.dependencyTracker !== null) { + const measure = ctx.measureText(joinedChars); + this.dependencyTracker.recordBBox(opIdx, this.ctx, -measure.actualBoundingBoxLeft, measure.actualBoundingBoxRight, -measure.actualBoundingBoxAscent, measure.actualBoundingBoxDescent).recordShowTextOperation(opIdx); + } + current.x += width * widthAdvanceScale * textHScale; + ctx.restore(); + this.compose(); + return undefined; + } + let x = 0, + i; + for (i = 0; i < glyphsLength; ++i) { + const glyph = glyphs[i]; + if (typeof glyph === "number") { + x += spacingDir * glyph * fontSize / 1000; + continue; + } + let restoreNeeded = false; + const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; + const character = glyph.fontChar; + const accent = glyph.accent; + let scaledX, scaledY; + let width = glyph.width; + if (vertical) { + const vmetric = glyph.vmetric || defaultVMetrics; + const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale; + const vy = vmetric[2] * widthAdvanceScale; + width = vmetric ? -vmetric[0] : width; + scaledX = vx / fontSizeScale; + scaledY = (x + vy) / fontSizeScale; + } else { + scaledX = x / fontSizeScale; + scaledY = 0; + } + let measure; + if (font.remeasure && width > 0) { + measure = ctx.measureText(character); + const measuredWidth = measure.width * 1000 / fontSize * fontSizeScale; + if (width < measuredWidth && this.isFontSubpixelAAEnabled) { + const characterScaleX = width / measuredWidth; + restoreNeeded = true; + ctx.save(); + ctx.scale(characterScaleX, 1); + scaledX /= characterScaleX; + } else if (width !== measuredWidth) { + scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale; + } + } + if (this.contentVisible && (glyph.isInFont || font.missingFile)) { + if (simpleFillText && !accent) { + ctx.fillText(character, scaledX, scaledY); + this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, measure ? { + bbox: null + } : font, fontSize / fontSizeScale, scaledX, scaledY, () => measure ?? ctx.measureText(character)); + } else { + this.paintChar(opIdx, character, scaledX, scaledY, patternFillTransform, patternStrokeTransform); + if (accent) { + const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale; + const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale; + this.paintChar(opIdx, accent.fontChar, scaledAccentX, scaledAccentY, patternFillTransform, patternStrokeTransform); + } + } + } + const charWidth = vertical ? width * widthAdvanceScale - spacing * fontDirection : width * widthAdvanceScale + spacing * fontDirection; + x += charWidth; + if (restoreNeeded) { + ctx.restore(); + } + } + if (vertical) { + current.y -= x; + } else { + current.x += x * textHScale; + } + ctx.restore(); + this.compose(); + this.dependencyTracker?.recordShowTextOperation(opIdx); + return undefined; + } + showType3Text(opIdx, glyphs) { + const ctx = this.ctx; + const current = this.current; + const font = current.font; + const fontSize = current.fontSize; + const fontDirection = current.fontDirection; + const spacingDir = font.vertical ? 1 : -1; + const charSpacing = current.charSpacing; + const wordSpacing = current.wordSpacing; + const textHScale = current.textHScale * fontDirection; + const fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX; + const glyphsLength = glyphs.length; + const isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE; + let i, glyph, width, spacingLength; + if (isTextInvisible || fontSize === 0) { + return; + } + this._cachedScaleForStroking[0] = -1; + this._cachedGetSinglePixelWidth = null; + ctx.save(); + if (current.textMatrix) { + ctx.transform(...current.textMatrix); + } + ctx.translate(current.x, current.y + current.textRise); + ctx.scale(textHScale, fontDirection); + const dependencyTracker = this.dependencyTracker; + this.dependencyTracker = dependencyTracker ? new CanvasNestedDependencyTracker(dependencyTracker, opIdx) : null; + for (i = 0; i < glyphsLength; ++i) { + glyph = glyphs[i]; + if (typeof glyph === "number") { + spacingLength = spacingDir * glyph * fontSize / 1000; + this.ctx.translate(spacingLength, 0); + current.x += spacingLength * textHScale; + continue; + } + const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; + const operatorList = font.charProcOperatorList[glyph.operatorListId]; + if (!operatorList) { + warn(`Type3 character "${glyph.operatorListId}" is not available.`); + } else if (this.contentVisible) { + this.save(); + ctx.scale(fontSize, fontSize); + ctx.transform(...fontMatrix); + this.executeOperatorList(operatorList); + this.restore(); + } + const p = [glyph.width, 0]; + Util.applyTransform(p, fontMatrix); + width = p[0] * fontSize + spacing; + ctx.translate(width, 0); + current.x += width * textHScale; + } + ctx.restore(); + if (dependencyTracker) { + this.dependencyTracker = dependencyTracker; + } + } + setCharWidth(opIdx, xWidth, yWidth) {} + setCharWidthAndBounds(opIdx, xWidth, yWidth, llx, lly, urx, ury) { + const clip = new Path2D(); + clip.rect(llx, lly, urx - llx, ury - lly); + this.ctx.clip(clip); + this.dependencyTracker?.recordBBox(opIdx, this.ctx, llx, urx, lly, ury).recordClipBox(opIdx, this.ctx, llx, urx, lly, ury); + this.endPath(opIdx); + } + getColorN_Pattern(opIdx, IR) { + let pattern; + if (IR[0] === "TilingPattern") { + const baseTransform = this.baseTransform || getCurrentTransform(this.ctx); + const canvasGraphicsFactory = { + createCanvasGraphics: (ctx, renderingOpIdx) => new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, { + optionalContentConfig: this.optionalContentConfig, + markedContentStack: this.markedContentStack + }, undefined, undefined, this.dependencyTracker ? new CanvasNestedDependencyTracker(this.dependencyTracker, renderingOpIdx, true) : null) + }; + pattern = new TilingPattern(IR, this.ctx, canvasGraphicsFactory, baseTransform); + } else { + pattern = this._getPattern(opIdx, IR[1], IR[2]); + } + return pattern; + } + setStrokeColorN(opIdx, ...args) { + this.dependencyTracker?.recordSimpleData("strokeColor", opIdx); + this.current.strokeColor = this.getColorN_Pattern(opIdx, args); + this.current.patternStroke = true; + } + setFillColorN(opIdx, ...args) { + this.dependencyTracker?.recordSimpleData("fillColor", opIdx); + this.current.fillColor = this.getColorN_Pattern(opIdx, args); + this.current.patternFill = true; + } + setStrokeRGBColor(opIdx, color) { + this.dependencyTracker?.recordSimpleData("strokeColor", opIdx); + this.ctx.strokeStyle = this.current.strokeColor = color; + this.current.patternStroke = false; + } + setStrokeTransparent(opIdx) { + this.dependencyTracker?.recordSimpleData("strokeColor", opIdx); + this.ctx.strokeStyle = this.current.strokeColor = "transparent"; + this.current.patternStroke = false; + } + setFillRGBColor(opIdx, color) { + this.dependencyTracker?.recordSimpleData("fillColor", opIdx); + this.ctx.fillStyle = this.current.fillColor = color; + this.current.patternFill = false; + } + setFillTransparent(opIdx) { + this.dependencyTracker?.recordSimpleData("fillColor", opIdx); + this.ctx.fillStyle = this.current.fillColor = "transparent"; + this.current.patternFill = false; + } + _getPattern(opIdx, objId, matrix = null) { + let pattern; + if (this.cachedPatterns.has(objId)) { + pattern = this.cachedPatterns.get(objId); + } else { + pattern = getShadingPattern(this.getObject(opIdx, objId)); + this.cachedPatterns.set(objId, pattern); + } + if (matrix) { + pattern.matrix = matrix; + } + return pattern; + } + shadingFill(opIdx, objId) { + if (!this.contentVisible) { + return; + } + const ctx = this.ctx; + this.save(opIdx); + const pattern = this._getPattern(opIdx, objId); + ctx.fillStyle = pattern.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.SHADING, opIdx); + const inv = getCurrentTransformInverse(ctx); + if (inv) { + const { + width, + height + } = ctx.canvas; + const minMax = MIN_MAX_INIT.slice(); + Util.axialAlignedBoundingBox([0, 0, width, height], inv, minMax); + const [x0, y0, x1, y1] = minMax; + this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0); + } else { + this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10); + } + this.dependencyTracker?.resetBBox(opIdx).recordFullPageBBox(opIdx).recordDependencies(opIdx, Dependencies.transform).recordDependencies(opIdx, Dependencies.fill).recordOperation(opIdx); + this.compose(this.current.getClippedPathBoundingBox()); + this.restore(opIdx); + } + beginInlineImage() { + unreachable("Should not call beginInlineImage"); + } + beginImageData() { + unreachable("Should not call beginImageData"); + } + paintFormXObjectBegin(opIdx, matrix, bbox) { + if (!this.contentVisible) { + return; + } + this.save(opIdx); + this.baseTransformStack.push(this.baseTransform); + if (matrix) { + this.transform(opIdx, ...matrix); + } + this.baseTransform = getCurrentTransform(this.ctx); + if (bbox) { + Util.axialAlignedBoundingBox(bbox, this.baseTransform, this.current.minMax); + const [x0, y0, x1, y1] = bbox; + const clip = new Path2D(); + clip.rect(x0, y0, x1 - x0, y1 - y0); + this.ctx.clip(clip); + this.dependencyTracker?.recordClipBox(opIdx, this.ctx, x0, x1, y0, y1); + this.endPath(opIdx); + } + } + paintFormXObjectEnd(opIdx) { + if (!this.contentVisible) { + return; + } + this.restore(opIdx); + this.baseTransform = this.baseTransformStack.pop(); + } + beginGroup(opIdx, group) { + if (!this.contentVisible) { + return; + } + this.save(opIdx); + if (this.inSMaskMode) { + this.endSMaskMode(); + this.current.activeSMask = null; + } + const currentCtx = this.ctx; + if (!group.isolated) { + info("TODO: Support non-isolated groups."); + } + if (group.knockout) { + warn("Knockout groups not supported."); + } + const currentTransform = getCurrentTransform(currentCtx); + if (group.matrix) { + currentCtx.transform(...group.matrix); + } + if (!group.bbox) { + throw new Error("Bounding box is required."); + } + let bounds = MIN_MAX_INIT.slice(); + Util.axialAlignedBoundingBox(group.bbox, getCurrentTransform(currentCtx), bounds); + const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height]; + bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0]; + const offsetX = Math.floor(bounds[0]); + const offsetY = Math.floor(bounds[1]); + const drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1); + const drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1); + this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]); + let cacheId = "groupAt" + this.groupLevel; + if (group.smask) { + cacheId += "_smask_" + this.smaskCounter++ % 2; + } + const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight); + const groupCtx = scratchCanvas.context; + groupCtx.translate(-offsetX, -offsetY); + groupCtx.transform(...currentTransform); + let clip = new Path2D(); + const [x0, y0, x1, y1] = group.bbox; + clip.rect(x0, y0, x1 - x0, y1 - y0); + if (group.matrix) { + const path = new Path2D(); + path.addPath(clip, new DOMMatrix(group.matrix)); + clip = path; + } + groupCtx.clip(clip); + if (group.smask) { + this.smaskStack.push({ + canvas: scratchCanvas.canvas, + context: groupCtx, + offsetX, + offsetY, + subtype: group.smask.subtype, + backdrop: group.smask.backdrop, + transferMap: group.smask.transferMap || null, + startTransformInverse: null + }); + } + if (!group.smask || this.dependencyTracker) { + currentCtx.setTransform(1, 0, 0, 1, 0, 0); + currentCtx.translate(offsetX, offsetY); + currentCtx.save(); + } + copyCtxState(currentCtx, groupCtx); + this.ctx = groupCtx; + this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha", "strokeAlpha", "globalCompositeOperation"]).pushBaseTransform(currentCtx); + this.setGState(opIdx, [["BM", "source-over"], ["ca", 1], ["CA", 1], ["TR", null]]); + this.groupStack.push(currentCtx); + this.groupLevel++; + } + endGroup(opIdx, group) { + if (!this.contentVisible) { + return; + } + this.groupLevel--; + const groupCtx = this.ctx; + const ctx = this.groupStack.pop(); + this.ctx = ctx; + this.ctx.imageSmoothingEnabled = false; + this.dependencyTracker?.popBaseTransform(); + if (group.smask) { + this.tempSMask = this.smaskStack.pop(); + this.restore(opIdx); + if (this.dependencyTracker) { + this.ctx.restore(); + } + } else { + this.ctx.restore(); + const currentMtx = getCurrentTransform(this.ctx); + this.restore(opIdx); + this.ctx.save(); + this.ctx.setTransform(...currentMtx); + const dirtyBox = MIN_MAX_INIT.slice(); + Util.axialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx, dirtyBox); + this.ctx.drawImage(groupCtx.canvas, 0, 0); + this.ctx.restore(); + this.compose(dirtyBox); + } + } + beginAnnotation(opIdx, id, rect, transform, matrix, hasOwnCanvas) { + this.#restoreInitialState(); + resetCtxToDefault(this.ctx); + this.ctx.save(); + this.save(opIdx); + if (this.baseTransform) { + this.ctx.setTransform(...this.baseTransform); + } + if (rect) { + const width = rect[2] - rect[0]; + const height = rect[3] - rect[1]; + if (hasOwnCanvas && this.annotationCanvasMap) { + transform = transform.slice(); + transform[4] -= rect[0]; + transform[5] -= rect[1]; + rect = rect.slice(); + rect[0] = rect[1] = 0; + rect[2] = width; + rect[3] = height; + Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx), XY); + const { + viewportScale + } = this; + const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale); + const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale); + this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight); + const { + canvas, + context + } = this.annotationCanvas; + this.annotationCanvasMap.set(id, canvas); + this.annotationCanvas.savedCtx = this.ctx; + this.ctx = context; + this.ctx.save(); + this.ctx.setTransform(XY[0], 0, 0, -XY[1], 0, height * XY[1]); + resetCtxToDefault(this.ctx); + } else { + resetCtxToDefault(this.ctx); + this.endPath(opIdx); + const clip = new Path2D(); + clip.rect(rect[0], rect[1], width, height); + this.ctx.clip(clip); + } + } + this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height); + this.transform(opIdx, ...transform); + this.transform(opIdx, ...matrix); + } + endAnnotation(opIdx) { + if (this.annotationCanvas) { + this.ctx.restore(); + this.#drawFilter(); + this.ctx = this.annotationCanvas.savedCtx; + delete this.annotationCanvas.savedCtx; + delete this.annotationCanvas; + } + } + paintImageMaskXObject(opIdx, img) { + if (!this.contentVisible) { + return; + } + const count = img.count; + img = this.getObject(opIdx, img.data, img); + img.count = count; + const ctx = this.ctx; + const mask = this._createMaskCanvas(opIdx, img); + const maskCanvas = mask.canvas; + ctx.save(); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY); + this.dependencyTracker?.resetBBox(opIdx).recordBBox(opIdx, this.ctx, mask.offsetX, mask.offsetX + maskCanvas.width, mask.offsetY, mask.offsetY + maskCanvas.height).recordOperation(opIdx); + ctx.restore(); + this.compose(); + } + paintImageMaskXObjectRepeat(opIdx, img, scaleX, skewX = 0, skewY = 0, scaleY, positions) { + if (!this.contentVisible) { + return; + } + img = this.getObject(opIdx, img.data, img); + const ctx = this.ctx; + ctx.save(); + const currentTransform = getCurrentTransform(ctx); + ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0); + const mask = this._createMaskCanvas(opIdx, img); + ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]); + this.dependencyTracker?.resetBBox(opIdx); + for (let i = 0, ii = positions.length; i < ii; i += 2) { + const trans = Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]); + ctx.drawImage(mask.canvas, trans[4], trans[5]); + this.dependencyTracker?.recordBBox(opIdx, this.ctx, trans[4], trans[4] + mask.canvas.width, trans[5], trans[5] + mask.canvas.height); + } + ctx.restore(); + this.compose(); + this.dependencyTracker?.recordOperation(opIdx); + } + paintImageMaskXObjectGroup(opIdx, images) { + if (!this.contentVisible) { + return; + } + const ctx = this.ctx; + const fillColor = this.current.fillColor; + const isPatternFill = this.current.patternFill; + this.dependencyTracker?.resetBBox(opIdx).recordDependencies(opIdx, Dependencies.transformAndFill); + for (const image of images) { + const { + data, + width, + height, + transform + } = image; + const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height); + const maskCtx = maskCanvas.context; + maskCtx.save(); + const img = this.getObject(opIdx, data, image); + putBinaryImageMask(maskCtx, img); + maskCtx.globalCompositeOperation = "source-in"; + maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, getCurrentTransformInverse(ctx), PathType.FILL, opIdx) : fillColor; + maskCtx.fillRect(0, 0, width, height); + maskCtx.restore(); + ctx.save(); + ctx.transform(...transform); + ctx.scale(1, -1); + drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); + this.dependencyTracker?.recordBBox(opIdx, ctx, 0, width, 0, height); + ctx.restore(); + } + this.compose(); + this.dependencyTracker?.recordOperation(opIdx); + } + paintImageXObject(opIdx, objId) { + if (!this.contentVisible) { + return; + } + const imgData = this.getObject(opIdx, objId); + if (!imgData) { + warn("Dependent image isn't ready yet"); + return; + } + this.paintInlineImageXObject(opIdx, imgData); + } + paintImageXObjectRepeat(opIdx, objId, scaleX, scaleY, positions) { + if (!this.contentVisible) { + return; + } + const imgData = this.getObject(opIdx, objId); + if (!imgData) { + warn("Dependent image isn't ready yet"); + return; + } + const width = imgData.width; + const height = imgData.height; + const map = []; + for (let i = 0, ii = positions.length; i < ii; i += 2) { + map.push({ + transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]], + x: 0, + y: 0, + w: width, + h: height + }); + } + this.paintInlineImageXObjectGroup(opIdx, imgData, map); + } + applyTransferMapsToCanvas(ctx) { + if (this.current.transferMaps !== "none") { + ctx.filter = this.current.transferMaps; + ctx.drawImage(ctx.canvas, 0, 0); + ctx.filter = "none"; + } + return ctx.canvas; + } + applyTransferMapsToBitmap(imgData) { + if (this.current.transferMaps === "none") { + return imgData.bitmap; + } + const { + bitmap, + width, + height + } = imgData; + const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height); + const tmpCtx = tmpCanvas.context; + tmpCtx.filter = this.current.transferMaps; + tmpCtx.drawImage(bitmap, 0, 0); + tmpCtx.filter = "none"; + return tmpCanvas.canvas; + } + paintInlineImageXObject(opIdx, imgData) { + if (!this.contentVisible) { + return; + } + const width = imgData.width; + const height = imgData.height; + const ctx = this.ctx; + this.save(opIdx); + const { + filter + } = ctx; + if (filter !== "none" && filter !== "") { + ctx.filter = "none"; + } + ctx.scale(1 / width, -1 / height); + let imgToPaint; + if (imgData.bitmap) { + imgToPaint = this.applyTransferMapsToBitmap(imgData); + } else if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) { + imgToPaint = imgData; + } else { + const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height); + const tmpCtx = tmpCanvas.context; + putBinaryImageData(tmpCtx, imgData); + imgToPaint = this.applyTransferMapsToCanvas(tmpCtx); + } + const scaled = this._scaleImage(imgToPaint, getCurrentTransformInverse(ctx)); + ctx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(ctx), imgData.interpolate); + this.dependencyTracker?.resetBBox(opIdx).recordBBox(opIdx, ctx, 0, width, -height, 0).recordDependencies(opIdx, Dependencies.imageXObject).recordOperation(opIdx); + drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height); + this.compose(); + this.restore(opIdx); + } + paintInlineImageXObjectGroup(opIdx, imgData, map) { + if (!this.contentVisible) { + return; + } + const ctx = this.ctx; + let imgToPaint; + if (imgData.bitmap) { + imgToPaint = imgData.bitmap; + } else { + const w = imgData.width; + const h = imgData.height; + const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h); + const tmpCtx = tmpCanvas.context; + putBinaryImageData(tmpCtx, imgData); + imgToPaint = this.applyTransferMapsToCanvas(tmpCtx); + } + this.dependencyTracker?.resetBBox(opIdx); + for (const entry of map) { + ctx.save(); + ctx.transform(...entry.transform); + ctx.scale(1, -1); + drawImageAtIntegerCoords(ctx, imgToPaint, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1); + this.dependencyTracker?.recordBBox(opIdx, ctx, 0, 1, -1, 0); + ctx.restore(); + } + this.dependencyTracker?.recordOperation(opIdx); + this.compose(); + } + paintSolidColorImageMask(opIdx) { + if (!this.contentVisible) { + return; + } + this.dependencyTracker?.resetBBox(opIdx).recordBBox(opIdx, this.ctx, 0, 1, 0, 1).recordDependencies(opIdx, Dependencies.fill).recordOperation(opIdx); + this.ctx.fillRect(0, 0, 1, 1); + this.compose(); + } + markPoint(opIdx, tag) {} + markPointProps(opIdx, tag, properties) {} + beginMarkedContent(opIdx, tag) { + this.dependencyTracker?.beginMarkedContent(opIdx); + this.markedContentStack.push({ + visible: true + }); + } + beginMarkedContentProps(opIdx, tag, properties) { + this.dependencyTracker?.beginMarkedContent(opIdx); + if (tag === "OC") { + this.markedContentStack.push({ + visible: this.optionalContentConfig.isVisible(properties) + }); + } else { + this.markedContentStack.push({ + visible: true + }); + } + this.contentVisible = this.isContentVisible(); + } + endMarkedContent(opIdx) { + this.dependencyTracker?.endMarkedContent(opIdx); + this.markedContentStack.pop(); + this.contentVisible = this.isContentVisible(); + } + beginCompat(opIdx) {} + endCompat(opIdx) {} + consumePath(opIdx, path, clipBox) { + const isEmpty = this.current.isEmptyClip(); + if (this.pendingClip) { + this.current.updateClipFromPath(); + } + if (!this.pendingClip) { + this.compose(clipBox); + } + const ctx = this.ctx; + if (this.pendingClip) { + if (!isEmpty) { + if (this.pendingClip === EO_CLIP) { + ctx.clip(path, "evenodd"); + } else { + ctx.clip(path); + } + } + this.pendingClip = null; + this.dependencyTracker?.bboxToClipBoxDropOperation(opIdx).recordFutureForcedDependency("clipPath", opIdx); + } else { + this.dependencyTracker?.recordOperation(opIdx); + } + this.current.startNewPathAndClipBox(this.current.clipBox); + } + getSinglePixelWidth() { + if (!this._cachedGetSinglePixelWidth) { + const m = getCurrentTransform(this.ctx); + if (m[1] === 0 && m[2] === 0) { + this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3])); + } else { + const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]); + const normX = Math.hypot(m[0], m[2]); + const normY = Math.hypot(m[1], m[3]); + this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet; + } + } + return this._cachedGetSinglePixelWidth; + } + getScaleForStroking() { + if (this._cachedScaleForStroking[0] === -1) { + const { + lineWidth + } = this.current; + const { + a, + b, + c, + d + } = this.ctx.getTransform(); + let scaleX, scaleY; + if (b === 0 && c === 0) { + const normX = Math.abs(a); + const normY = Math.abs(d); + if (normX === normY) { + if (lineWidth === 0) { + scaleX = scaleY = 1 / normX; + } else { + const scaledLineWidth = normX * lineWidth; + scaleX = scaleY = scaledLineWidth < 1 ? 1 / scaledLineWidth : 1; + } + } else if (lineWidth === 0) { + scaleX = 1 / normX; + scaleY = 1 / normY; + } else { + const scaledXLineWidth = normX * lineWidth; + const scaledYLineWidth = normY * lineWidth; + scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1; + scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1; + } + } else { + const absDet = Math.abs(a * d - b * c); + const normX = Math.hypot(a, b); + const normY = Math.hypot(c, d); + if (lineWidth === 0) { + scaleX = normY / absDet; + scaleY = normX / absDet; + } else { + const baseArea = lineWidth * absDet; + scaleX = normY > baseArea ? normY / baseArea : 1; + scaleY = normX > baseArea ? normX / baseArea : 1; + } + } + this._cachedScaleForStroking[0] = scaleX; + this._cachedScaleForStroking[1] = scaleY; + } + return this._cachedScaleForStroking; + } + rescaleAndStroke(path, saveRestore) { + const { + ctx, + current: { + lineWidth + } + } = this; + const [scaleX, scaleY] = this.getScaleForStroking(); + if (scaleX === scaleY) { + ctx.lineWidth = (lineWidth || 1) * scaleX; + ctx.stroke(path); + return; + } + const dashes = ctx.getLineDash(); + if (saveRestore) { + ctx.save(); + } + ctx.scale(scaleX, scaleY); + SCALE_MATRIX.a = 1 / scaleX; + SCALE_MATRIX.d = 1 / scaleY; + const newPath = new Path2D(); + newPath.addPath(path, SCALE_MATRIX); + if (dashes.length > 0) { + const scale = Math.max(scaleX, scaleY); + ctx.setLineDash(dashes.map(x => x / scale)); + ctx.lineDashOffset /= scale; + } + ctx.lineWidth = lineWidth || 1; + ctx.stroke(newPath); + if (saveRestore) { + ctx.restore(); + } + } + isContentVisible() { + for (let i = this.markedContentStack.length - 1; i >= 0; i--) { + if (!this.markedContentStack[i].visible) { + return false; + } + } + return true; + } +} +for (const op in OPS) { + if (CanvasGraphics.prototype[op] !== undefined) { + CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op]; + } +} + +;// ./src/display/worker_options.js +class GlobalWorkerOptions { + static #port = null; + static #src = ""; + static get workerPort() { + return this.#port; + } + static set workerPort(val) { + if (!(typeof Worker !== "undefined" && val instanceof Worker) && val !== null) { + throw new Error("Invalid `workerPort` type."); + } + this.#port = val; + } + static get workerSrc() { + return this.#src; + } + static set workerSrc(val) { + if (typeof val !== "string") { + throw new Error("Invalid `workerSrc` type."); + } + this.#src = val; + } +} + +;// ./src/display/metadata.js +class Metadata { + #map; + #data; + constructor({ + parsedData, + rawData + }) { + this.#map = parsedData; + this.#data = rawData; + } + getRaw() { + return this.#data; + } + get(name) { + return this.#map.get(name) ?? null; + } + [Symbol.iterator]() { + return this.#map.entries(); + } +} + +;// ./src/display/optional_content_config.js + + +const INTERNAL = Symbol("INTERNAL"); +class OptionalContentGroup { + #isDisplay = false; + #isPrint = false; + #userSet = false; + #visible = true; + constructor(renderingIntent, { + name, + intent, + usage, + rbGroups + }) { + this.#isDisplay = !!(renderingIntent & RenderingIntentFlag.DISPLAY); + this.#isPrint = !!(renderingIntent & RenderingIntentFlag.PRINT); + this.name = name; + this.intent = intent; + this.usage = usage; + this.rbGroups = rbGroups; + } + get visible() { + if (this.#userSet) { + return this.#visible; + } + if (!this.#visible) { + return false; + } + const { + print, + view + } = this.usage; + if (this.#isDisplay) { + return view?.viewState !== "OFF"; + } else if (this.#isPrint) { + return print?.printState !== "OFF"; + } + return true; + } + _setVisible(internal, visible, userSet = false) { + if (internal !== INTERNAL) { + unreachable("Internal method `_setVisible` called."); + } + this.#userSet = userSet; + this.#visible = visible; + } +} +class OptionalContentConfig { + #cachedGetHash = null; + #groups = new Map(); + #initialHash = null; + #order = null; + constructor(data, renderingIntent = RenderingIntentFlag.DISPLAY) { + this.renderingIntent = renderingIntent; + this.name = null; + this.creator = null; + if (data === null) { + return; + } + this.name = data.name; + this.creator = data.creator; + this.#order = data.order; + for (const group of data.groups) { + this.#groups.set(group.id, new OptionalContentGroup(renderingIntent, group)); + } + if (data.baseState === "OFF") { + for (const group of this.#groups.values()) { + group._setVisible(INTERNAL, false); + } + } + for (const on of data.on) { + this.#groups.get(on)._setVisible(INTERNAL, true); + } + for (const off of data.off) { + this.#groups.get(off)._setVisible(INTERNAL, false); + } + this.#initialHash = this.getHash(); + } + #evaluateVisibilityExpression(array) { + const length = array.length; + if (length < 2) { + return true; + } + const operator = array[0]; + for (let i = 1; i < length; i++) { + const element = array[i]; + let state; + if (Array.isArray(element)) { + state = this.#evaluateVisibilityExpression(element); + } else if (this.#groups.has(element)) { + state = this.#groups.get(element).visible; + } else { + warn(`Optional content group not found: ${element}`); + return true; + } + switch (operator) { + case "And": + if (!state) { + return false; + } + break; + case "Or": + if (state) { + return true; + } + break; + case "Not": + return !state; + default: + return true; + } + } + return operator === "And"; + } + isVisible(group) { + if (this.#groups.size === 0) { + return true; + } + if (!group) { + info("Optional content group not defined."); + return true; + } + if (group.type === "OCG") { + if (!this.#groups.has(group.id)) { + warn(`Optional content group not found: ${group.id}`); + return true; + } + return this.#groups.get(group.id).visible; + } else if (group.type === "OCMD") { + if (group.expression) { + return this.#evaluateVisibilityExpression(group.expression); + } + if (!group.policy || group.policy === "AnyOn") { + for (const id of group.ids) { + if (!this.#groups.has(id)) { + warn(`Optional content group not found: ${id}`); + return true; + } + if (this.#groups.get(id).visible) { + return true; + } + } + return false; + } else if (group.policy === "AllOn") { + for (const id of group.ids) { + if (!this.#groups.has(id)) { + warn(`Optional content group not found: ${id}`); + return true; + } + if (!this.#groups.get(id).visible) { + return false; + } + } + return true; + } else if (group.policy === "AnyOff") { + for (const id of group.ids) { + if (!this.#groups.has(id)) { + warn(`Optional content group not found: ${id}`); + return true; + } + if (!this.#groups.get(id).visible) { + return true; + } + } + return false; + } else if (group.policy === "AllOff") { + for (const id of group.ids) { + if (!this.#groups.has(id)) { + warn(`Optional content group not found: ${id}`); + return true; + } + if (this.#groups.get(id).visible) { + return false; + } + } + return true; + } + warn(`Unknown optional content policy ${group.policy}.`); + return true; + } + warn(`Unknown group type ${group.type}.`); + return true; + } + setVisibility(id, visible = true, preserveRB = true) { + const group = this.#groups.get(id); + if (!group) { + warn(`Optional content group not found: ${id}`); + return; + } + if (preserveRB && visible && group.rbGroups.length) { + for (const rbGroup of group.rbGroups) { + for (const otherId of rbGroup) { + if (otherId !== id) { + this.#groups.get(otherId)?._setVisible(INTERNAL, false, true); + } + } + } + } + group._setVisible(INTERNAL, !!visible, true); + this.#cachedGetHash = null; + } + setOCGState({ + state, + preserveRB + }) { + let operator; + for (const elem of state) { + switch (elem) { + case "ON": + case "OFF": + case "Toggle": + operator = elem; + continue; + } + const group = this.#groups.get(elem); + if (!group) { + continue; + } + switch (operator) { + case "ON": + this.setVisibility(elem, true, preserveRB); + break; + case "OFF": + this.setVisibility(elem, false, preserveRB); + break; + case "Toggle": + this.setVisibility(elem, !group.visible, preserveRB); + break; + } + } + this.#cachedGetHash = null; + } + get hasInitialVisibility() { + return this.#initialHash === null || this.getHash() === this.#initialHash; + } + getOrder() { + if (!this.#groups.size) { + return null; + } + if (this.#order) { + return this.#order.slice(); + } + return [...this.#groups.keys()]; + } + getGroup(id) { + return this.#groups.get(id) || null; + } + getHash() { + if (this.#cachedGetHash !== null) { + return this.#cachedGetHash; + } + const hash = new MurmurHash3_64(); + for (const [id, group] of this.#groups) { + hash.update(`${id}:${group.visible}`); + } + return this.#cachedGetHash = hash.hexdigest(); + } + [Symbol.iterator]() { + return this.#groups.entries(); + } +} + +;// ./src/shared/base_pdf_stream.js + +class BasePDFStream { + #PDFStreamReader = null; + #PDFStreamRangeReader = null; + _fullReader = null; + _rangeReaders = new Set(); + _source = null; + constructor(source, PDFStreamReader, PDFStreamRangeReader) { + this._source = source; + this.#PDFStreamReader = PDFStreamReader; + this.#PDFStreamRangeReader = PDFStreamRangeReader; + } + get _progressiveDataLength() { + return this._fullReader?._loaded ?? 0; + } + getFullReader() { + assert(!this._fullReader, "BasePDFStream.getFullReader can only be called once."); + return this._fullReader = new this.#PDFStreamReader(this); + } + getRangeReader(begin, end) { + if (end <= this._progressiveDataLength) { + return null; + } + const reader = new this.#PDFStreamRangeReader(this, begin, end); + this._rangeReaders.add(reader); + return reader; + } + cancelAllRequests(reason) { + this._fullReader?.cancel(reason); + for (const reader of new Set(this._rangeReaders)) { + reader.cancel(reason); + } + } +} +class BasePDFStreamReader { + onProgress = null; + _contentLength = 0; + _filename = null; + _headersCapability = Promise.withResolvers(); + _isRangeSupported = false; + _isStreamingSupported = false; + _loaded = 0; + _stream = null; + constructor(stream) { + this._stream = stream; + } + _callOnProgress() { + this.onProgress?.({ + loaded: this._loaded, + total: this._contentLength + }); + } + get headersReady() { + return this._headersCapability.promise; + } + get filename() { + return this._filename; + } + get contentLength() { + return this._contentLength; + } + get isRangeSupported() { + return this._isRangeSupported; + } + get isStreamingSupported() { + return this._isStreamingSupported; + } + async read() { + unreachable("Abstract method `read` called"); + } + cancel(reason) { + unreachable("Abstract method `cancel` called"); + } +} +class BasePDFStreamRangeReader { + _stream = null; + constructor(stream, begin, end) { + this._stream = stream; + } + async read() { + unreachable("Abstract method `read` called"); + } + cancel(reason) { + unreachable("Abstract method `cancel` called"); + } +} + +;// ./src/display/transport_stream.js + + + +function getArrayBuffer(val) { + return val instanceof Uint8Array && val.byteLength === val.buffer.byteLength ? val.buffer : new Uint8Array(val).buffer; +} +function endRequests() { + for (const capability of this._requests) { + capability.resolve({ + value: undefined, + done: true + }); + } + this._requests.length = 0; +} +class PDFDataTransportStream extends BasePDFStream { + _progressiveDone = false; + _queuedChunks = []; + constructor(source) { + super(source, PDFDataTransportStreamReader, PDFDataTransportStreamRangeReader); + const { + pdfDataRangeTransport + } = source; + const { + initialData, + progressiveDone + } = pdfDataRangeTransport; + if (initialData?.length > 0) { + const buffer = getArrayBuffer(initialData); + this._queuedChunks.push(buffer); + } + this._progressiveDone = progressiveDone; + pdfDataRangeTransport.addRangeListener((begin, chunk) => { + this.#onReceiveData(begin, chunk); + }); + pdfDataRangeTransport.addProgressiveReadListener(chunk => { + this.#onReceiveData(undefined, chunk); + }); + pdfDataRangeTransport.addProgressiveDoneListener(() => { + this._fullReader?.progressiveDone(); + this._progressiveDone = true; + }); + pdfDataRangeTransport.transportReady(); + } + #onReceiveData(begin, chunk) { + const buffer = getArrayBuffer(chunk); + if (begin === undefined) { + if (this._fullReader) { + this._fullReader._enqueue(buffer); + } else { + this._queuedChunks.push(buffer); + } + } else { + const rangeReader = this._rangeReaders.keys().find(r => r._begin === begin); + assert(rangeReader, "#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."); + rangeReader._enqueue(buffer); + } + } + getFullReader() { + const reader = super.getFullReader(); + this._queuedChunks = null; + return reader; + } + getRangeReader(begin, end) { + const reader = super.getRangeReader(begin, end); + if (reader) { + reader.onDone = () => this._rangeReaders.delete(reader); + this._source.pdfDataRangeTransport.requestDataRange(begin, end); + } + return reader; + } + cancelAllRequests(reason) { + super.cancelAllRequests(reason); + this._source.pdfDataRangeTransport.abort(); + } +} +class PDFDataTransportStreamReader extends BasePDFStreamReader { + #endRequests = endRequests.bind(this); + _done = false; + _queuedChunks = null; + _requests = []; + constructor(stream) { + super(stream); + const { + pdfDataRangeTransport, + disableRange, + disableStream + } = stream._source; + const { + length, + contentDispositionFilename + } = pdfDataRangeTransport; + this._queuedChunks = stream._queuedChunks || []; + for (const chunk of this._queuedChunks) { + this._loaded += chunk.byteLength; + } + this._done = stream._progressiveDone; + this._contentLength = length; + this._isStreamingSupported = !disableStream; + this._isRangeSupported = !disableRange; + if (isPdfFile(contentDispositionFilename)) { + this._filename = contentDispositionFilename; + } + this._headersCapability.resolve(); + const loaded = this._loaded; + Promise.resolve().then(() => { + if (loaded > 0 && this._loaded === loaded) { + this._callOnProgress(); + } + }); + } + _enqueue(chunk) { + if (this._done) { + return; + } + if (this._requests.length > 0) { + const capability = this._requests.shift(); + capability.resolve({ + value: chunk, + done: false + }); + } else { + this._queuedChunks.push(chunk); + } + this._loaded += chunk.byteLength; + this._callOnProgress(); + } + async read() { + if (this._queuedChunks.length > 0) { + const chunk = this._queuedChunks.shift(); + return { + value: chunk, + done: false + }; + } + if (this._done) { + return { + value: undefined, + done: true + }; + } + const capability = Promise.withResolvers(); + this._requests.push(capability); + return capability.promise; + } + cancel(reason) { + this._done = true; + this.#endRequests(); + } + progressiveDone() { + this._done ||= true; + if (this._queuedChunks.length === 0) { + this.#endRequests(); + } + } +} +class PDFDataTransportStreamRangeReader extends BasePDFStreamRangeReader { + #endRequests = endRequests.bind(this); + onDone = null; + _begin = -1; + _done = false; + _queuedChunk = null; + _requests = []; + constructor(stream, begin, end) { + super(stream, begin, end); + this._begin = begin; + } + _enqueue(chunk) { + if (this._done) { + return; + } + if (this._requests.length === 0) { + this._queuedChunk = chunk; + } else { + const capability = this._requests.shift(); + capability.resolve({ + value: chunk, + done: false + }); + this.#endRequests(); + } + this._done = true; + this.onDone?.(); + } + async read() { + if (this._queuedChunk) { + const chunk = this._queuedChunk; + this._queuedChunk = null; + return { + value: chunk, + done: false + }; + } + if (this._done) { + return { + value: undefined, + done: true + }; + } + const capability = Promise.withResolvers(); + this._requests.push(capability); + return capability.promise; + } + cancel(reason) { + this._done = true; + this.#endRequests(); + this.onDone?.(); + } +} + +;// ./src/display/content_disposition.js + +function getFilenameFromContentDispositionHeader(contentDisposition) { + let needsEncodingFixup = true; + let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition); + if (tmp) { + tmp = tmp[1]; + let filename = rfc2616unquote(tmp); + filename = unescape(filename); + filename = rfc5987decode(filename); + filename = rfc2047decode(filename); + return fixupEncoding(filename); + } + tmp = rfc2231getparam(contentDisposition); + if (tmp) { + const filename = rfc2047decode(tmp); + return fixupEncoding(filename); + } + tmp = toParamRegExp("filename", "i").exec(contentDisposition); + if (tmp) { + tmp = tmp[1]; + let filename = rfc2616unquote(tmp); + filename = rfc2047decode(filename); + return fixupEncoding(filename); + } + function toParamRegExp(attributePattern, flags) { + return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags); + } + function textdecode(encoding, value) { + if (encoding) { + if (!/^[\x00-\xFF]+$/.test(value)) { + return value; + } + try { + const decoder = new TextDecoder(encoding, { + fatal: true + }); + const buffer = stringToBytes(value); + value = decoder.decode(buffer); + needsEncodingFixup = false; + } catch {} + } + return value; + } + function fixupEncoding(value) { + if (needsEncodingFixup && /[\x80-\xff]/.test(value)) { + value = textdecode("utf-8", value); + if (needsEncodingFixup) { + value = textdecode("iso-8859-1", value); + } + } + return value; + } + function rfc2231getparam(contentDispositionStr) { + const matches = []; + let match; + const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig"); + while ((match = iter.exec(contentDispositionStr)) !== null) { + let [, n, quot, part] = match; + n = parseInt(n, 10); + if (n in matches) { + if (n === 0) { + break; + } + continue; + } + matches[n] = [quot, part]; + } + const parts = []; + for (let n = 0; n < matches.length; ++n) { + if (!(n in matches)) { + break; + } + let [quot, part] = matches[n]; + part = rfc2616unquote(part); + if (quot) { + part = unescape(part); + if (n === 0) { + part = rfc5987decode(part); + } + } + parts.push(part); + } + return parts.join(""); + } + function rfc2616unquote(value) { + if (value.startsWith('"')) { + const parts = value.slice(1).split('\\"'); + for (let i = 0; i < parts.length; ++i) { + const quotindex = parts[i].indexOf('"'); + if (quotindex !== -1) { + parts[i] = parts[i].slice(0, quotindex); + parts.length = i + 1; + } + parts[i] = parts[i].replaceAll(/\\(.)/g, "$1"); + } + value = parts.join('"'); + } + return value; + } + function rfc5987decode(extvalue) { + const encodingend = extvalue.indexOf("'"); + if (encodingend === -1) { + return extvalue; + } + const encoding = extvalue.slice(0, encodingend); + const langvalue = extvalue.slice(encodingend + 1); + const value = langvalue.replace(/^[^']*'/, ""); + return textdecode(encoding, value); + } + function rfc2047decode(value) { + if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) { + return value; + } + return value.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) { + if (encoding === "q" || encoding === "Q") { + text = text.replaceAll("_", " "); + text = text.replaceAll(/=([0-9a-fA-F]{2})/g, function (match, hex) { + return String.fromCharCode(parseInt(hex, 16)); + }); + return textdecode(charset, text); + } + try { + text = atob(text); + } catch {} + return textdecode(charset, text); + }); + } + return ""; +} + +;// ./src/display/network_utils.js + + + +function createHeaders(isHttp, httpHeaders) { + const headers = new Headers(); + if (!isHttp || !httpHeaders || typeof httpHeaders !== "object") { + return headers; + } + for (const key in httpHeaders) { + const val = httpHeaders[key]; + if (val !== undefined) { + headers.append(key, val); + } + } + return headers; +} +function getResponseOrigin(url) { + return URL.parse(url)?.origin ?? null; +} +function validateRangeRequestCapabilities({ + responseHeaders, + isHttp, + rangeChunkSize, + disableRange +}) { + const returnValues = { + allowRangeRequests: false, + suggestedLength: undefined + }; + const length = parseInt(responseHeaders.get("Content-Length"), 10); + if (!Number.isInteger(length)) { + return returnValues; + } + returnValues.suggestedLength = length; + if (length <= 2 * rangeChunkSize) { + return returnValues; + } + if (disableRange || !isHttp) { + return returnValues; + } + if (responseHeaders.get("Accept-Ranges") !== "bytes") { + return returnValues; + } + const contentEncoding = responseHeaders.get("Content-Encoding") || "identity"; + if (contentEncoding !== "identity") { + return returnValues; + } + returnValues.allowRangeRequests = true; + return returnValues; +} +function extractFilenameFromHeader(responseHeaders) { + const contentDisposition = responseHeaders.get("Content-Disposition"); + if (contentDisposition) { + let filename = getFilenameFromContentDispositionHeader(contentDisposition); + if (filename.includes("%")) { + try { + filename = decodeURIComponent(filename); + } catch {} + } + if (isPdfFile(filename)) { + return filename; + } + } + return null; +} +function createResponseError(status, url) { + return new ResponseException(`Unexpected server response (${status}) while retrieving PDF "${url.href}".`, status, status === 404 || status === 0 && url.protocol === "file:"); +} +function ensureResponseOrigin(rangeOrigin, origin) { + if (rangeOrigin !== origin) { + throw new Error(`Expected range response-origin "${rangeOrigin}" to match "${origin}".`); + } +} + +;// ./src/display/fetch_stream.js + + + +function fetchUrl(url, headers, withCredentials, abortController) { + return fetch(url, { + method: "GET", + headers, + signal: abortController.signal, + mode: "cors", + credentials: withCredentials ? "include" : "same-origin", + redirect: "follow" + }); +} +function ensureResponseStatus(status, url) { + if (status !== 200 && status !== 206) { + throw createResponseError(status, url); + } +} +function fetch_stream_getArrayBuffer(val) { + if (val instanceof Uint8Array) { + return val.buffer; + } + if (val instanceof ArrayBuffer) { + return val; + } + throw new Error(`getArrayBuffer - unexpected data: ${val}`); +} +class PDFFetchStream extends BasePDFStream { + _responseOrigin = null; + constructor(source) { + super(source, PDFFetchStreamReader, PDFFetchStreamRangeReader); + const { + httpHeaders, + url + } = source; + assert(/https?:/.test(url.protocol), "PDFFetchStream only supports http(s):// URLs."); + this.headers = createHeaders(true, httpHeaders); + } +} +class PDFFetchStreamReader extends BasePDFStreamReader { + _abortController = new AbortController(); + _reader = null; + constructor(stream) { + super(stream); + const { + disableRange, + disableStream, + length, + rangeChunkSize, + url, + withCredentials + } = stream._source; + this._contentLength = length; + this._isStreamingSupported = !disableStream; + this._isRangeSupported = !disableRange; + const headers = new Headers(stream.headers); + fetchUrl(url, headers, withCredentials, this._abortController).then(response => { + stream._responseOrigin = getResponseOrigin(response.url); + ensureResponseStatus(response.status, url); + this._reader = response.body.getReader(); + const responseHeaders = response.headers; + const { + allowRangeRequests, + suggestedLength + } = validateRangeRequestCapabilities({ + responseHeaders, + isHttp: true, + rangeChunkSize, + disableRange + }); + this._isRangeSupported = allowRangeRequests; + this._contentLength = suggestedLength || this._contentLength; + this._filename = extractFilenameFromHeader(responseHeaders); + if (!this._isStreamingSupported && this._isRangeSupported) { + this.cancel(new AbortException("Streaming is disabled.")); + } + this._headersCapability.resolve(); + }).catch(this._headersCapability.reject); + } + async read() { + await this._headersCapability.promise; + const { + value, + done + } = await this._reader.read(); + if (done) { + return { + value, + done + }; + } + this._loaded += value.byteLength; + this._callOnProgress(); + return { + value: fetch_stream_getArrayBuffer(value), + done: false + }; + } + cancel(reason) { + this._reader?.cancel(reason); + this._abortController.abort(); + } +} +class PDFFetchStreamRangeReader extends BasePDFStreamRangeReader { + _abortController = new AbortController(); + _readCapability = Promise.withResolvers(); + _reader = null; + constructor(stream, begin, end) { + super(stream, begin, end); + const { + url, + withCredentials + } = stream._source; + const headers = new Headers(stream.headers); + headers.append("Range", `bytes=${begin}-${end - 1}`); + fetchUrl(url, headers, withCredentials, this._abortController).then(response => { + const responseOrigin = getResponseOrigin(response.url); + ensureResponseOrigin(responseOrigin, stream._responseOrigin); + ensureResponseStatus(response.status, url); + this._reader = response.body.getReader(); + this._readCapability.resolve(); + }).catch(this._readCapability.reject); + } + async read() { + await this._readCapability.promise; + const { + value, + done + } = await this._reader.read(); + if (done) { + return { + value, + done + }; + } + return { + value: fetch_stream_getArrayBuffer(value), + done: false + }; + } + cancel(reason) { + this._reader?.cancel(reason); + this._abortController.abort(); + } +} + +;// ./src/display/network.js + + + + +const OK_RESPONSE = 200; +const PARTIAL_CONTENT_RESPONSE = 206; +function network_getArrayBuffer(val) { + return typeof val !== "string" ? val : stringToBytes(val).buffer; +} +class PDFNetworkStream extends BasePDFStream { + #pendingRequests = new WeakMap(); + _responseOrigin = null; + constructor(source) { + super(source, PDFNetworkStreamReader, PDFNetworkStreamRangeReader); + const { + httpHeaders, + url + } = source; + this.url = url; + this.isHttp = /https?:/.test(url.protocol); + this.headers = createHeaders(this.isHttp, httpHeaders); + } + _request(args) { + const xhr = new XMLHttpRequest(); + const pendingRequest = { + validateStatus: null, + onHeadersReceived: args.onHeadersReceived, + onDone: args.onDone, + onError: args.onError, + onProgress: args.onProgress + }; + this.#pendingRequests.set(xhr, pendingRequest); + xhr.open("GET", this.url); + xhr.withCredentials = this._source.withCredentials; + for (const [key, val] of this.headers) { + xhr.setRequestHeader(key, val); + } + if (this.isHttp && "begin" in args && "end" in args) { + xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`); + pendingRequest.validateStatus = status => status === PARTIAL_CONTENT_RESPONSE || status === OK_RESPONSE; + } else { + pendingRequest.validateStatus = status => status === OK_RESPONSE; + } + xhr.responseType = "arraybuffer"; + assert(args.onError, "Expected `onError` callback to be provided."); + xhr.onerror = () => args.onError(xhr.status); + xhr.onreadystatechange = this.#onStateChange.bind(this, xhr); + xhr.onprogress = this.#onProgress.bind(this, xhr); + xhr.send(null); + return xhr; + } + #onProgress(xhr, evt) { + const pendingRequest = this.#pendingRequests.get(xhr); + pendingRequest?.onProgress?.(evt); + } + #onStateChange(xhr, evt) { + const pendingRequest = this.#pendingRequests.get(xhr); + if (!pendingRequest) { + return; + } + if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) { + pendingRequest.onHeadersReceived(); + delete pendingRequest.onHeadersReceived; + } + if (xhr.readyState !== 4) { + return; + } + if (!this.#pendingRequests.has(xhr)) { + return; + } + this.#pendingRequests.delete(xhr); + if (xhr.status === 0 && this.isHttp) { + pendingRequest.onError(xhr.status); + return; + } + const xhrStatus = xhr.status || OK_RESPONSE; + if (!pendingRequest.validateStatus(xhrStatus)) { + pendingRequest.onError(xhr.status); + return; + } + const chunk = network_getArrayBuffer(xhr.response); + if (xhrStatus === PARTIAL_CONTENT_RESPONSE) { + const rangeHeader = xhr.getResponseHeader("Content-Range"); + if (/bytes (\d+)-(\d+)\/(\d+)/.test(rangeHeader)) { + pendingRequest.onDone(chunk); + } else { + warn(`Missing or invalid "Content-Range" header.`); + pendingRequest.onError(0); + } + } else if (chunk) { + pendingRequest.onDone(chunk); + } else { + pendingRequest.onError(xhr.status); + } + } + _abortRequest(xhr) { + if (this.#pendingRequests.has(xhr)) { + this.#pendingRequests.delete(xhr); + xhr.abort(); + } + } + getRangeReader(begin, end) { + const reader = super.getRangeReader(begin, end); + if (reader) { + reader.onClosed = () => this._rangeReaders.delete(reader); + } + return reader; + } +} +class PDFNetworkStreamReader extends BasePDFStreamReader { + #endRequests = endRequests.bind(this); + _cachedChunks = []; + _done = false; + _requests = []; + _storedError = null; + constructor(stream) { + super(stream); + const { + length + } = stream._source; + this._contentLength = length; + this._fullRequestXhr = stream._request({ + onHeadersReceived: this.#onHeadersReceived.bind(this), + onDone: this.#onDone.bind(this), + onError: this.#onError.bind(this), + onProgress: this.#onProgress.bind(this) + }); + } + #onHeadersReceived() { + const stream = this._stream; + const { + disableRange, + rangeChunkSize + } = stream._source; + const fullRequestXhr = this._fullRequestXhr; + stream._responseOrigin = getResponseOrigin(fullRequestXhr.responseURL); + const rawResponseHeaders = fullRequestXhr.getAllResponseHeaders(); + const responseHeaders = new Headers(rawResponseHeaders ? rawResponseHeaders.trimStart().replace(/[^\S ]+$/, "").split(/[\r\n]+/).map(x => { + const [key, ...val] = x.split(": "); + return [key, val.join(": ")]; + }) : []); + const { + allowRangeRequests, + suggestedLength + } = validateRangeRequestCapabilities({ + responseHeaders, + isHttp: stream.isHttp, + rangeChunkSize, + disableRange + }); + if (allowRangeRequests) { + this._isRangeSupported = true; + } + this._contentLength = suggestedLength || this._contentLength; + this._filename = extractFilenameFromHeader(responseHeaders); + if (this._isRangeSupported) { + stream._abortRequest(fullRequestXhr); + } + this._headersCapability.resolve(); + } + #onDone(chunk) { + if (this._requests.length > 0) { + const capability = this._requests.shift(); + capability.resolve({ + value: chunk, + done: false + }); + } else { + this._cachedChunks.push(chunk); + } + this._done = true; + if (this._cachedChunks.length === 0) { + this.#endRequests(); + } + } + #onError(status) { + this._storedError = createResponseError(status, this._stream.url); + this._headersCapability.reject(this._storedError); + for (const capability of this._requests) { + capability.reject(this._storedError); + } + this._requests.length = 0; + this._cachedChunks.length = 0; + } + #onProgress(evt) { + this.onProgress?.({ + loaded: evt.loaded, + total: evt.lengthComputable ? evt.total : this._contentLength + }); + } + async read() { + await this._headersCapability.promise; + if (this._storedError) { + throw this._storedError; + } + if (this._cachedChunks.length > 0) { + const chunk = this._cachedChunks.shift(); + return { + value: chunk, + done: false + }; + } + if (this._done) { + return { + value: undefined, + done: true + }; + } + const capability = Promise.withResolvers(); + this._requests.push(capability); + return capability.promise; + } + cancel(reason) { + this._done = true; + this._headersCapability.reject(reason); + this.#endRequests(); + this._stream._abortRequest(this._fullRequestXhr); + this._fullRequestXhr = null; + } +} +class PDFNetworkStreamRangeReader extends BasePDFStreamRangeReader { + #endRequests = endRequests.bind(this); + onClosed = null; + _done = false; + _queuedChunk = null; + _requests = []; + _storedError = null; + constructor(stream, begin, end) { + super(stream, begin, end); + this._requestXhr = stream._request({ + begin, + end, + onHeadersReceived: this.#onHeadersReceived.bind(this), + onDone: this.#onDone.bind(this), + onError: this.#onError.bind(this), + onProgress: null + }); + } + #onHeadersReceived() { + const responseOrigin = getResponseOrigin(this._requestXhr?.responseURL); + try { + ensureResponseOrigin(responseOrigin, this._stream._responseOrigin); + } catch (ex) { + this._storedError = ex; + this.#onError(0); + } + } + #onDone(chunk) { + if (this._requests.length > 0) { + const capability = this._requests.shift(); + capability.resolve({ + value: chunk, + done: false + }); + } else { + this._queuedChunk = chunk; + } + this._done = true; + this.#endRequests(); + this.onClosed?.(); + } + #onError(status) { + this._storedError ??= createResponseError(status, this._stream.url); + for (const capability of this._requests) { + capability.reject(this._storedError); + } + this._requests.length = 0; + this._queuedChunk = null; + } + async read() { + if (this._storedError) { + throw this._storedError; + } + if (this._queuedChunk !== null) { + const chunk = this._queuedChunk; + this._queuedChunk = null; + return { + value: chunk, + done: false + }; + } + if (this._done) { + return { + value: undefined, + done: true + }; + } + const capability = Promise.withResolvers(); + this._requests.push(capability); + return capability.promise; + } + cancel(reason) { + this._done = true; + this.#endRequests(); + this._stream._abortRequest(this._requestXhr); + this.onClosed?.(); + } +} + +;// ./src/display/node_stream.js + + + + +function getReadableStream(readStream) { + const { + Readable + } = process.getBuiltinModule("stream"); + if (typeof Readable.toWeb === "function") { + return Readable.toWeb(readStream); + } + const require = process.getBuiltinModule("module").createRequire(import.meta.url); + const polyfill = require("node-readable-to-web-readable-stream"); + return polyfill.makeDefaultReadableStreamFromNodeReadable(readStream); +} +class PDFNodeStream extends BasePDFStream { + constructor(source) { + super(source, PDFNodeStreamReader, PDFNodeStreamRangeReader); + const { + url + } = source; + assert(url.protocol === "file:", "PDFNodeStream only supports file:// URLs."); + } +} +class PDFNodeStreamReader extends BasePDFStreamReader { + _reader = null; + constructor(stream) { + super(stream); + const { + disableRange, + disableStream, + length, + rangeChunkSize, + url + } = stream._source; + this._contentLength = length; + this._isStreamingSupported = !disableStream; + this._isRangeSupported = !disableRange; + const fs = process.getBuiltinModule("fs"); + fs.promises.lstat(url).then(stat => { + const readStream = fs.createReadStream(url); + const readableStream = getReadableStream(readStream); + this._reader = readableStream.getReader(); + const { + size + } = stat; + if (size <= 2 * rangeChunkSize) { + this._isRangeSupported = false; + } + this._contentLength = size; + if (!this._isStreamingSupported && this._isRangeSupported) { + this.cancel(new AbortException("Streaming is disabled.")); + } + this._headersCapability.resolve(); + }).catch(error => { + if (error.code === "ENOENT") { + error = createResponseError(0, url); + } + this._headersCapability.reject(error); + }); + } + async read() { + await this._headersCapability.promise; + const { + value, + done + } = await this._reader.read(); + if (done) { + return { + value, + done + }; + } + this._loaded += value.byteLength; + this._callOnProgress(); + return { + value: fetch_stream_getArrayBuffer(value), + done: false + }; + } + cancel(reason) { + this._reader?.cancel(reason); + } +} +class PDFNodeStreamRangeReader extends BasePDFStreamRangeReader { + _readCapability = Promise.withResolvers(); + _reader = null; + constructor(stream, begin, end) { + super(stream, begin, end); + const { + url + } = stream._source; + const fs = process.getBuiltinModule("fs"); + try { + const readStream = fs.createReadStream(url, { + start: begin, + end: end - 1 + }); + const readableStream = getReadableStream(readStream); + this._reader = readableStream.getReader(); + this._readCapability.resolve(); + } catch (error) { + this._readCapability.reject(error); + } + } + async read() { + await this._readCapability.promise; + const { + value, + done + } = await this._reader.read(); + if (done) { + return { + value, + done + }; + } + return { + value: fetch_stream_getArrayBuffer(value), + done: false + }; + } + cancel(reason) { + this._reader?.cancel(reason); + } +} + +;// ./src/display/pdf_objects.js +const INITIAL_DATA = Symbol("INITIAL_DATA"); +const dataObj = () => ({ + ...Promise.withResolvers(), + data: INITIAL_DATA +}); +class PDFObjects { + #objs = new Map(); + #ensureObj(objId) { + return this.#objs.getOrInsertComputed(objId, dataObj); + } + get(objId, callback = null) { + if (callback) { + const obj = this.#ensureObj(objId); + obj.promise.then(() => callback(obj.data)); + return null; + } + const obj = this.#objs.get(objId); + if (!obj || obj.data === INITIAL_DATA) { + throw new Error(`Requesting object that isn't resolved yet ${objId}.`); + } + return obj.data; + } + has(objId) { + const obj = this.#objs.get(objId); + return !!obj && obj.data !== INITIAL_DATA; + } + delete(objId) { + const obj = this.#objs.get(objId); + if (!obj || obj.data === INITIAL_DATA) { + return false; + } + this.#objs.delete(objId); + return true; + } + resolve(objId, data = null) { + const obj = this.#ensureObj(objId); + obj.data = data; + obj.resolve(); + } + clear() { + for (const { + data + } of this.#objs.values()) { + data?.bitmap?.close(); + } + this.#objs.clear(); + } + *[Symbol.iterator]() { + for (const [objId, { + data + }] of this.#objs) { + if (data !== INITIAL_DATA) { + yield [objId, data]; + } + } + } +} + +;// ./src/display/text_layer.js + + +const MAX_TEXT_DIVS_TO_RENDER = 100000; +const DEFAULT_FONT_SIZE = 30; +class TextLayer { + #capability = Promise.withResolvers(); + #container = null; + #disableProcessItems = false; + #fontInspectorEnabled = !!globalThis.FontInspector?.enabled; + #lang = null; + #layoutTextParams = null; + #pageHeight = 0; + #pageWidth = 0; + #reader = null; + #rootContainer = null; + #rotation = 0; + #scale = 0; + #styleCache = Object.create(null); + #textContentItemsStr = []; + #textContentSource = null; + #textDivs = []; + #textDivProperties = new WeakMap(); + #transform = null; + static #ascentCache = new Map(); + static #canvasContexts = new Map(); + static #canvasCtxFonts = new WeakMap(); + static #minFontSize = null; + static #pendingTextLayers = new Set(); + constructor({ + textContentSource, + container, + viewport + }) { + if (textContentSource instanceof ReadableStream) { + this.#textContentSource = textContentSource; + } else if (typeof textContentSource === "object") { + this.#textContentSource = new ReadableStream({ + start(controller) { + controller.enqueue(textContentSource); + controller.close(); + } + }); + } else { + throw new Error('No "textContentSource" parameter specified.'); + } + this.#container = this.#rootContainer = container; + this.#scale = viewport.scale * OutputScale.pixelRatio; + this.#rotation = viewport.rotation; + this.#layoutTextParams = { + div: null, + properties: null, + ctx: null + }; + const { + pageWidth, + pageHeight, + pageX, + pageY + } = viewport.rawDims; + this.#transform = [1, 0, 0, -1, -pageX, pageY + pageHeight]; + this.#pageWidth = pageWidth; + this.#pageHeight = pageHeight; + TextLayer.#ensureMinFontSizeComputed(); + container.style.setProperty("--min-font-size", TextLayer.#minFontSize); + setLayerDimensions(container, viewport); + this.#capability.promise.finally(() => { + TextLayer.#pendingTextLayers.delete(this); + this.#layoutTextParams = null; + this.#styleCache = null; + }).catch(() => {}); + } + static get fontFamilyMap() { + const { + isWindows, + isFirefox + } = FeatureTest.platform; + return shadow(this, "fontFamilyMap", new Map([["sans-serif", `${isWindows && isFirefox ? "Calibri, " : ""}sans-serif`], ["monospace", `${isWindows && isFirefox ? "Lucida Console, " : ""}monospace`]])); + } + render() { + const pump = () => { + this.#reader.read().then(({ + value, + done + }) => { + if (done) { + this.#capability.resolve(); + return; + } + this.#lang ??= value.lang; + Object.assign(this.#styleCache, value.styles); + this.#processItems(value.items); + pump(); + }, this.#capability.reject); + }; + this.#reader = this.#textContentSource.getReader(); + TextLayer.#pendingTextLayers.add(this); + pump(); + return this.#capability.promise; + } + update({ + viewport, + onBefore = null + }) { + const scale = viewport.scale * OutputScale.pixelRatio; + const rotation = viewport.rotation; + if (rotation !== this.#rotation) { + onBefore?.(); + this.#rotation = rotation; + setLayerDimensions(this.#rootContainer, { + rotation + }); + } + if (scale !== this.#scale) { + onBefore?.(); + this.#scale = scale; + const params = { + div: null, + properties: null, + ctx: TextLayer.#getCtx(this.#lang) + }; + for (const div of this.#textDivs) { + params.properties = this.#textDivProperties.get(div); + params.div = div; + this.#layout(params); + } + } + } + cancel() { + const abortEx = new AbortException("TextLayer task cancelled."); + this.#reader?.cancel(abortEx).catch(() => {}); + this.#reader = null; + this.#capability.reject(abortEx); + } + get textDivs() { + return this.#textDivs; + } + get textContentItemsStr() { + return this.#textContentItemsStr; + } + #processItems(items) { + if (this.#disableProcessItems) { + return; + } + this.#layoutTextParams.ctx ??= TextLayer.#getCtx(this.#lang); + const textDivs = this.#textDivs, + textContentItemsStr = this.#textContentItemsStr; + for (const item of items) { + if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) { + warn("Ignoring additional textDivs for performance reasons."); + this.#disableProcessItems = true; + return; + } + if (item.str === undefined) { + if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") { + const parent = this.#container; + this.#container = document.createElement("span"); + this.#container.classList.add("markedContent"); + if (item.id) { + this.#container.setAttribute("id", `${item.id}`); + } + if (item.tag === "Artifact") { + this.#container.ariaHidden = true; + } + parent.append(this.#container); + } else if (item.type === "endMarkedContent") { + this.#container = this.#container.parentNode; + } + continue; + } + textContentItemsStr.push(item.str); + this.#appendText(item); + } + } + #appendText(geom) { + const textDiv = document.createElement("span"); + const textDivProperties = { + angle: 0, + canvasWidth: 0, + hasText: geom.str !== "", + hasEOL: geom.hasEOL, + fontSize: 0 + }; + this.#textDivs.push(textDiv); + const tx = Util.transform(this.#transform, geom.transform); + let angle = Math.atan2(tx[1], tx[0]); + const style = this.#styleCache[geom.fontName]; + if (style.vertical) { + angle += Math.PI / 2; + } + let fontFamily = this.#fontInspectorEnabled && style.fontSubstitution || style.fontFamily; + fontFamily = TextLayer.fontFamilyMap.get(fontFamily) || fontFamily; + const fontHeight = Math.hypot(tx[2], tx[3]); + const fontAscent = fontHeight * TextLayer.#getAscent(fontFamily, style, this.#lang); + let left, top; + if (angle === 0) { + left = tx[4]; + top = tx[5] - fontAscent; + } else { + left = tx[4] + fontAscent * Math.sin(angle); + top = tx[5] - fontAscent * Math.cos(angle); + } + const divStyle = textDiv.style; + divStyle.left = `${(100 * left / this.#pageWidth).toFixed(2)}%`; + divStyle.top = `${(100 * top / this.#pageHeight).toFixed(2)}%`; + divStyle.setProperty("--font-height", `${fontHeight.toFixed(2)}px`); + divStyle.fontFamily = fontFamily; + textDivProperties.fontSize = fontHeight; + textDiv.setAttribute("role", "presentation"); + textDiv.textContent = geom.str; + textDiv.dir = geom.dir; + if (this.#fontInspectorEnabled) { + textDiv.dataset.fontName = style.fontSubstitutionLoadedName || geom.fontName; + } + if (angle !== 0) { + textDivProperties.angle = angle * (180 / Math.PI); + } + let shouldScaleText = false; + if (geom.str.length > 1) { + shouldScaleText = true; + } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) { + const absScaleX = Math.abs(geom.transform[0]), + absScaleY = Math.abs(geom.transform[3]); + if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) { + shouldScaleText = true; + } + } + if (shouldScaleText) { + textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width; + } + this.#textDivProperties.set(textDiv, textDivProperties); + this.#layoutTextParams.div = textDiv; + this.#layoutTextParams.properties = textDivProperties; + this.#layout(this.#layoutTextParams); + if (textDivProperties.hasText) { + this.#container.append(textDiv); + } + if (textDivProperties.hasEOL) { + const br = document.createElement("br"); + br.setAttribute("role", "presentation"); + this.#container.append(br); + } + } + #layout(params) { + const { + div, + properties, + ctx + } = params; + const { + style + } = div; + if (properties.canvasWidth !== 0 && properties.hasText) { + const { + fontFamily + } = style; + const { + canvasWidth, + fontSize + } = properties; + TextLayer.#ensureCtxFont(ctx, fontSize * this.#scale, fontFamily); + const { + width + } = ctx.measureText(div.textContent); + if (width > 0) { + style.setProperty("--scale-x", canvasWidth * this.#scale / width); + } + } + if (properties.angle !== 0) { + style.setProperty("--rotate", `${properties.angle}deg`); + } + } + static cleanup() { + if (this.#pendingTextLayers.size > 0) { + return; + } + this.#ascentCache.clear(); + for (const { + canvas + } of this.#canvasContexts.values()) { + canvas.remove(); + } + this.#canvasContexts.clear(); + } + static #getCtx(lang = null) { + let ctx = this.#canvasContexts.get(lang ||= ""); + if (!ctx) { + const canvas = document.createElement("canvas"); + canvas.className = "hiddenCanvasElement"; + canvas.lang = lang; + document.body.append(canvas); + ctx = canvas.getContext("2d", { + alpha: false, + willReadFrequently: true + }); + this.#canvasContexts.set(lang, ctx); + this.#canvasCtxFonts.set(ctx, { + size: 0, + family: "" + }); + } + return ctx; + } + static #ensureCtxFont(ctx, size, family) { + const cached = this.#canvasCtxFonts.get(ctx); + if (size === cached.size && family === cached.family) { + return; + } + ctx.font = `${size}px ${family}`; + cached.size = size; + cached.family = family; + } + static #ensureMinFontSizeComputed() { + if (this.#minFontSize !== null) { + return; + } + const div = document.createElement("div"); + div.style.opacity = 0; + div.style.lineHeight = 1; + div.style.fontSize = "1px"; + div.style.position = "absolute"; + div.textContent = "X"; + document.body.append(div); + this.#minFontSize = div.getBoundingClientRect().height; + div.remove(); + } + static #getAscent(fontFamily, style, lang) { + const cachedAscent = this.#ascentCache.get(fontFamily); + if (cachedAscent) { + return cachedAscent; + } + const ctx = this.#getCtx(lang); + ctx.canvas.width = ctx.canvas.height = DEFAULT_FONT_SIZE; + this.#ensureCtxFont(ctx, DEFAULT_FONT_SIZE, fontFamily); + const metrics = ctx.measureText(""); + const ascent = metrics.fontBoundingBoxAscent; + const descent = Math.abs(metrics.fontBoundingBoxDescent); + ctx.canvas.width = ctx.canvas.height = 0; + let ratio = 0.8; + if (ascent) { + ratio = ascent / (ascent + descent); + } else { + if (FeatureTest.platform.isFirefox) { + warn("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference " + "in `about:config` to improve TextLayer rendering."); + } + if (style.ascent) { + ratio = style.ascent; + } else if (style.descent) { + ratio = 1 + style.descent; + } + } + this.#ascentCache.set(fontFamily, ratio); + return ratio; + } +} + +;// ./src/display/api.js + + + + + + + + + + + + + + + + + + + + + + + + + +const RENDERING_CANCELLED_TIMEOUT = 100; +function getDocument(src = {}) { + if (typeof src === "string" || src instanceof URL) { + src = { + url: src + }; + } else if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) { + src = { + data: src + }; + } + const task = new PDFDocumentLoadingTask(); + const { + docId + } = task; + const url = src.url ? getUrlProp(src.url) : null; + const data = src.data ? getDataProp(src.data) : null; + const httpHeaders = src.httpHeaders || null; + const withCredentials = src.withCredentials === true; + const password = src.password ?? null; + const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null; + const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : 2 ** 16; + let worker = src.worker instanceof PDFWorker ? src.worker : null; + const verbosity = src.verbosity; + const docBaseUrl = typeof src.docBaseUrl === "string" && !isDataScheme(src.docBaseUrl) ? src.docBaseUrl : null; + const cMapUrl = getFactoryUrlProp(src.cMapUrl); + const cMapPacked = src.cMapPacked !== false; + const CMapReaderFactory = src.CMapReaderFactory || (isNodeJS ? NodeCMapReaderFactory : DOMCMapReaderFactory); + const iccUrl = getFactoryUrlProp(src.iccUrl); + const standardFontDataUrl = getFactoryUrlProp(src.standardFontDataUrl); + const StandardFontDataFactory = src.StandardFontDataFactory || (isNodeJS ? NodeStandardFontDataFactory : DOMStandardFontDataFactory); + const wasmUrl = getFactoryUrlProp(src.wasmUrl); + const WasmFactory = src.WasmFactory || (isNodeJS ? NodeWasmFactory : DOMWasmFactory); + const ignoreErrors = src.stopAtErrors !== true; + const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1; + const isEvalSupported = src.isEvalSupported !== false; + const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !isNodeJS; + const isImageDecoderSupported = typeof src.isImageDecoderSupported === "boolean" ? src.isImageDecoderSupported : !isNodeJS && (FeatureTest.platform.isFirefox || !globalThis.chrome); + const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes) ? src.canvasMaxAreaInBytes : -1; + const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : isNodeJS; + const fontExtraProperties = src.fontExtraProperties === true; + const enableXfa = src.enableXfa === true; + const ownerDocument = src.ownerDocument || globalThis.document; + const disableRange = src.disableRange === true; + const disableStream = src.disableStream === true; + const disableAutoFetch = src.disableAutoFetch === true; + const pdfBug = src.pdfBug === true; + const CanvasFactory = src.CanvasFactory || (isNodeJS ? NodeCanvasFactory : DOMCanvasFactory); + const FilterFactory = src.FilterFactory || (isNodeJS ? NodeFilterFactory : DOMFilterFactory); + const enableHWA = src.enableHWA === true; + const useWasm = src.useWasm !== false; + const pagesMapper = src.pagesMapper || new PagesMapper(); + const length = rangeTransport ? rangeTransport.length : src.length ?? NaN; + const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !isNodeJS && !disableFontFace; + const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : !!(CMapReaderFactory === DOMCMapReaderFactory && StandardFontDataFactory === DOMStandardFontDataFactory && WasmFactory === DOMWasmFactory && cMapUrl && standardFontDataUrl && wasmUrl && isValidFetchUrl(cMapUrl, document.baseURI) && isValidFetchUrl(standardFontDataUrl, document.baseURI) && isValidFetchUrl(wasmUrl, document.baseURI)); + const styleElement = null; + setVerbosityLevel(verbosity); + const transportFactory = { + canvasFactory: new CanvasFactory({ + ownerDocument, + enableHWA + }), + filterFactory: new FilterFactory({ + docId, + ownerDocument + }), + cMapReaderFactory: useWorkerFetch ? null : new CMapReaderFactory({ + baseUrl: cMapUrl, + isCompressed: cMapPacked + }), + standardFontDataFactory: useWorkerFetch ? null : new StandardFontDataFactory({ + baseUrl: standardFontDataUrl + }), + wasmFactory: useWorkerFetch ? null : new WasmFactory({ + baseUrl: wasmUrl + }) + }; + if (!worker) { + worker = PDFWorker.create({ + verbosity, + port: GlobalWorkerOptions.workerPort + }); + task._worker = worker; + } + const docParams = { + docId, + apiVersion: "5.5.207", + data, + password, + disableAutoFetch, + rangeChunkSize, + length, + docBaseUrl, + enableXfa, + evaluatorOptions: { + maxImageSize, + disableFontFace, + ignoreErrors, + isEvalSupported, + isOffscreenCanvasSupported, + isImageDecoderSupported, + canvasMaxAreaInBytes, + fontExtraProperties, + useSystemFonts, + useWasm, + useWorkerFetch, + cMapUrl, + iccUrl, + standardFontDataUrl, + wasmUrl + } + }; + const transportParams = { + ownerDocument, + pdfBug, + styleElement, + enableHWA, + loadingParams: { + disableAutoFetch, + enableXfa + } + }; + worker.promise.then(function () { + if (task.destroyed) { + throw new Error("Loading aborted"); + } + if (worker.destroyed) { + throw new Error("Worker was destroyed"); + } + const workerIdPromise = worker.messageHandler.sendWithPromise("GetDocRequest", docParams, data ? [data.buffer] : null); + let networkStream; + if (rangeTransport) { + networkStream = new PDFDataTransportStream({ + pdfDataRangeTransport: rangeTransport, + disableRange, + disableStream + }); + } else if (!data) { + if (!url) { + throw new Error("getDocument - no `url` parameter provided."); + } + const NetworkStream = isValidFetchUrl(url) ? PDFFetchStream : isNodeJS ? PDFNodeStream : PDFNetworkStream; + networkStream = new NetworkStream({ + url, + length, + httpHeaders, + withCredentials, + rangeChunkSize, + disableRange, + disableStream + }); + } + return workerIdPromise.then(workerId => { + if (task.destroyed) { + throw new Error("Loading aborted"); + } + if (worker.destroyed) { + throw new Error("Worker was destroyed"); + } + const messageHandler = new MessageHandler(docId, workerId, worker.port); + const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory, pagesMapper); + task._transport = transport; + messageHandler.send("Ready", null); + }); + }).catch(task._capability.reject); + return task; +} +class PDFDocumentLoadingTask { + static #docId = 0; + _capability = Promise.withResolvers(); + _transport = null; + _worker = null; + docId = `d${PDFDocumentLoadingTask.#docId++}`; + destroyed = false; + onPassword = null; + onProgress = null; + get promise() { + return this._capability.promise; + } + async destroy() { + this.destroyed = true; + try { + if (this._worker?.port) { + this._worker._pendingDestroy = true; + } + await this._transport?.destroy(); + } catch (ex) { + if (this._worker?.port) { + delete this._worker._pendingDestroy; + } + throw ex; + } + this._transport = null; + this._worker?.destroy(); + this._worker = null; + } + async getData() { + return this._transport.getData(); + } +} +class PDFDataRangeTransport { + #capability = Promise.withResolvers(); + #progressiveDoneListeners = []; + #progressiveReadListeners = []; + #rangeListeners = []; + constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) { + this.length = length; + this.initialData = initialData; + this.progressiveDone = progressiveDone; + this.contentDispositionFilename = contentDispositionFilename; + Object.defineProperty(this, "onDataProgress", { + value: () => { + deprecated("`PDFDataRangeTransport.prototype.onDataProgress` - method was " + "removed, since loading progress is now reported automatically " + "through the `PDFDataTransportStream` class (and related code)."); + } + }); + } + addRangeListener(listener) { + this.#rangeListeners.push(listener); + } + addProgressiveReadListener(listener) { + this.#progressiveReadListeners.push(listener); + } + addProgressiveDoneListener(listener) { + this.#progressiveDoneListeners.push(listener); + } + onDataRange(begin, chunk) { + for (const listener of this.#rangeListeners) { + listener(begin, chunk); + } + } + onDataProgressiveRead(chunk) { + this.#capability.promise.then(() => { + for (const listener of this.#progressiveReadListeners) { + listener(chunk); + } + }); + } + onDataProgressiveDone() { + this.#capability.promise.then(() => { + for (const listener of this.#progressiveDoneListeners) { + listener(); + } + }); + } + transportReady() { + this.#capability.resolve(); + } + requestDataRange(begin, end) { + unreachable("Abstract method PDFDataRangeTransport.requestDataRange"); + } + abort() {} +} +class PDFDocumentProxy { + constructor(pdfInfo, transport) { + this._pdfInfo = pdfInfo; + this._transport = transport; + } + get pagesMapper() { + return this._transport.pagesMapper; + } + get annotationStorage() { + return this._transport.annotationStorage; + } + get canvasFactory() { + return this._transport.canvasFactory; + } + get filterFactory() { + return this._transport.filterFactory; + } + get numPages() { + return this._pdfInfo.numPages; + } + get fingerprints() { + return this._pdfInfo.fingerprints; + } + get isPureXfa() { + return shadow(this, "isPureXfa", !!this._transport._htmlForXfa); + } + get allXfaHtml() { + return this._transport._htmlForXfa; + } + getPage(pageNumber) { + return this._transport.getPage(pageNumber); + } + getPageIndex(ref) { + return this._transport.getPageIndex(ref); + } + getDestinations() { + return this._transport.getDestinations(); + } + getDestination(id) { + return this._transport.getDestination(id); + } + getPageLabels() { + return this._transport.getPageLabels(); + } + getPageLayout() { + return this._transport.getPageLayout(); + } + getPageMode() { + return this._transport.getPageMode(); + } + getViewerPreferences() { + return this._transport.getViewerPreferences(); + } + getOpenAction() { + return this._transport.getOpenAction(); + } + getAttachments() { + return this._transport.getAttachments(); + } + getAnnotationsByType(types, pageIndexesToSkip) { + return this._transport.getAnnotationsByType(types, pageIndexesToSkip); + } + getJSActions() { + return this._transport.getDocJSActions(); + } + getOutline() { + return this._transport.getOutline(); + } + getOptionalContentConfig({ + intent = "display" + } = {}) { + const { + renderingIntent + } = this._transport.getRenderingIntent(intent); + return this._transport.getOptionalContentConfig(renderingIntent); + } + getPermissions() { + return this._transport.getPermissions(); + } + getMetadata() { + return this._transport.getMetadata(); + } + getMarkInfo() { + return this._transport.getMarkInfo(); + } + getData() { + return this._transport.getData(); + } + saveDocument() { + return this._transport.saveDocument(); + } + extractPages(pageInfos) { + return this._transport.extractPages(pageInfos); + } + getDownloadInfo() { + return this._transport.downloadInfoCapability.promise; + } + cleanup(keepLoadedFonts = false) { + return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa); + } + destroy() { + return this.loadingTask.destroy(); + } + cachedPageNumber(ref) { + return this._transport.cachedPageNumber(ref); + } + get loadingParams() { + return this._transport.loadingParams; + } + get loadingTask() { + return this._transport.loadingTask; + } + getFieldObjects() { + return this._transport.getFieldObjects(); + } + hasJSActions() { + return this._transport.hasJSActions(); + } + getCalculationOrderIds() { + return this._transport.getCalculationOrderIds(); + } +} +class PDFPageProxy { + #pendingCleanup = false; + #pagesMapper = null; + constructor(pageIndex, pageInfo, transport, pagesMapper, pdfBug = false) { + this._pageIndex = pageIndex; + this._pageInfo = pageInfo; + this._transport = transport; + this._stats = pdfBug ? new StatTimer() : null; + this._pdfBug = pdfBug; + this.commonObjs = transport.commonObjs; + this.objs = new PDFObjects(); + this._intentStates = new Map(); + this.destroyed = false; + this.recordedBBoxes = null; + this.#pagesMapper = pagesMapper; + } + get pageNumber() { + return this._pageIndex + 1; + } + set pageNumber(value) { + this._pageIndex = value - 1; + } + get rotate() { + return this._pageInfo.rotate; + } + get ref() { + return this._pageInfo.ref; + } + get userUnit() { + return this._pageInfo.userUnit; + } + get view() { + return this._pageInfo.view; + } + getViewport({ + scale, + rotation = this.rotate, + offsetX = 0, + offsetY = 0, + dontFlip = false + } = {}) { + return new PageViewport({ + viewBox: this.view, + userUnit: this.userUnit, + scale, + rotation, + offsetX, + offsetY, + dontFlip + }); + } + getAnnotations({ + intent = "display" + } = {}) { + const { + renderingIntent + } = this._transport.getRenderingIntent(intent); + return this._transport.getAnnotations(this._pageIndex, renderingIntent); + } + getJSActions() { + return this._transport.getPageJSActions(this._pageIndex); + } + get filterFactory() { + return this._transport.filterFactory; + } + get isPureXfa() { + return shadow(this, "isPureXfa", !!this._transport._htmlForXfa); + } + async getXfa() { + return this._transport._htmlForXfa?.children[this._pageIndex] || null; + } + render({ + canvasContext, + canvas = canvasContext.canvas, + viewport, + intent = "display", + annotationMode = AnnotationMode.ENABLE, + transform = null, + background = null, + optionalContentConfigPromise = null, + annotationCanvasMap = null, + pageColors = null, + printAnnotationStorage = null, + isEditing = false, + recordOperations = false, + operationsFilter = null + }) { + this._stats?.time("Overall"); + const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing); + const { + renderingIntent, + cacheKey + } = intentArgs; + this.#pendingCleanup = false; + optionalContentConfigPromise ||= this._transport.getOptionalContentConfig(renderingIntent); + const intentState = this._intentStates.getOrInsertComputed(cacheKey, makeObj); + if (intentState.streamReaderCancelTimeout) { + clearTimeout(intentState.streamReaderCancelTimeout); + intentState.streamReaderCancelTimeout = null; + } + const intentPrint = !!(renderingIntent & RenderingIntentFlag.PRINT); + if (!intentState.displayReadyCapability) { + intentState.displayReadyCapability = Promise.withResolvers(); + intentState.operatorList = { + fnArray: [], + argsArray: [], + lastChunk: false, + separateAnnots: null + }; + this._stats?.time("Page Request"); + this._pumpOperatorList(intentArgs); + } + const recordForDebugger = Boolean(this._pdfBug && globalThis.StepperManager?.enabled); + const shouldRecordOperations = !this.recordedBBoxes && (recordOperations || recordForDebugger); + const complete = error => { + intentState.renderTasks.delete(internalRenderTask); + if (shouldRecordOperations) { + const recordedBBoxes = internalRenderTask.gfx?.dependencyTracker.take(); + if (recordedBBoxes) { + if (internalRenderTask.stepper) { + internalRenderTask.stepper.setOperatorBBoxes(recordedBBoxes, internalRenderTask.gfx.dependencyTracker.takeDebugMetadata()); + } + if (recordOperations) { + this.recordedBBoxes = recordedBBoxes; + } + } + } + if (intentPrint) { + this.#pendingCleanup = true; + } + this.#tryCleanup(); + if (error) { + internalRenderTask.capability.reject(error); + this._abortOperatorList({ + intentState, + reason: error instanceof Error ? error : new Error(error) + }); + } else { + internalRenderTask.capability.resolve(); + } + if (this._stats) { + this._stats.timeEnd("Rendering"); + this._stats.timeEnd("Overall"); + if (globalThis.Stats?.enabled) { + globalThis.Stats.add(this.pageNumber, this._stats); + } + } + }; + const internalRenderTask = new InternalRenderTask({ + callback: complete, + params: { + canvas, + canvasContext, + dependencyTracker: shouldRecordOperations ? new CanvasDependencyTracker(canvas, intentState.operatorList.length, recordForDebugger) : null, + viewport, + transform, + background + }, + objs: this.objs, + commonObjs: this.commonObjs, + annotationCanvasMap, + operatorList: intentState.operatorList, + pageIndex: this._pageIndex, + canvasFactory: this._transport.canvasFactory, + filterFactory: this._transport.filterFactory, + useRequestAnimationFrame: !intentPrint, + pdfBug: this._pdfBug, + pageColors, + enableHWA: this._transport.enableHWA, + operationsFilter + }); + (intentState.renderTasks ||= new Set()).add(internalRenderTask); + const renderTask = internalRenderTask.task; + Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => { + if (this.destroyed) { + complete(); + return; + } + this._stats?.time("Rendering"); + if (!(optionalContentConfig.renderingIntent & renderingIntent)) { + throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` " + "and `PDFDocumentProxy.getOptionalContentConfig` methods."); + } + internalRenderTask.initializeGraphics({ + transparency, + optionalContentConfig + }); + internalRenderTask.operatorListChanged(); + }).catch(complete); + return renderTask; + } + getOperatorList({ + intent = "display", + annotationMode = AnnotationMode.ENABLE, + printAnnotationStorage = null, + isEditing = false + } = {}) { + function operatorListChanged() { + if (intentState.operatorList.lastChunk) { + intentState.opListReadCapability.resolve(intentState.operatorList); + intentState.renderTasks.delete(opListTask); + } + } + const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing, true); + const intentState = this._intentStates.getOrInsertComputed(intentArgs.cacheKey, makeObj); + let opListTask; + if (!intentState.opListReadCapability) { + opListTask = Object.create(null); + opListTask.operatorListChanged = operatorListChanged; + intentState.opListReadCapability = Promise.withResolvers(); + (intentState.renderTasks ||= new Set()).add(opListTask); + intentState.operatorList = { + fnArray: [], + argsArray: [], + lastChunk: false, + separateAnnots: null + }; + this._stats?.time("Page Request"); + this._pumpOperatorList(intentArgs); + } + return intentState.opListReadCapability.promise; + } + streamTextContent({ + includeMarkedContent = false, + disableNormalization = false + } = {}) { + const TEXT_CONTENT_CHUNK_SIZE = 100; + return this._transport.messageHandler.sendWithStream("GetTextContent", { + pageId: this.#pagesMapper.getPageId(this._pageIndex + 1) - 1, + pageIndex: this._pageIndex, + includeMarkedContent: includeMarkedContent === true, + disableNormalization: disableNormalization === true + }, { + highWaterMark: TEXT_CONTENT_CHUNK_SIZE, + size(textContent) { + return textContent.items.length; + } + }); + } + async getTextContent(params = {}) { + if (this._transport._htmlForXfa) { + return this.getXfa().then(xfa => XfaText.textContent(xfa)); + } + const readableStream = this.streamTextContent(params); + const textContent = { + items: [], + styles: Object.create(null), + lang: null + }; + for await (const value of readableStream) { + textContent.lang ??= value.lang; + Object.assign(textContent.styles, value.styles); + textContent.items.push(...value.items); + } + return textContent; + } + getStructTree() { + return this._transport.getStructTree(this._pageIndex); + } + _destroy() { + this.destroyed = true; + const waitOn = []; + for (const intentState of this._intentStates.values()) { + this._abortOperatorList({ + intentState, + reason: new Error("Page was destroyed."), + force: true + }); + if (intentState.opListReadCapability) { + continue; + } + for (const internalRenderTask of intentState.renderTasks) { + waitOn.push(internalRenderTask.completed); + internalRenderTask.cancel(); + } + } + this.objs.clear(); + this.#pendingCleanup = false; + return Promise.all(waitOn); + } + cleanup(resetStats = false) { + this.#pendingCleanup = true; + const success = this.#tryCleanup(); + if (resetStats && success) { + this._stats &&= new StatTimer(); + } + return success; + } + #tryCleanup() { + if (!this.#pendingCleanup || this.destroyed) { + return false; + } + for (const { + renderTasks, + operatorList + } of this._intentStates.values()) { + if (renderTasks.size > 0 || !operatorList.lastChunk) { + return false; + } + } + this._intentStates.clear(); + this.objs.clear(); + this.#pendingCleanup = false; + return true; + } + _startRenderPage(transparency, cacheKey) { + const intentState = this._intentStates.get(cacheKey); + if (!intentState) { + return; + } + this._stats?.timeEnd("Page Request"); + intentState.displayReadyCapability?.resolve(transparency); + } + _renderPageChunk(operatorListChunk, intentState) { + for (let i = 0, ii = operatorListChunk.length; i < ii; i++) { + intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); + intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]); + } + intentState.operatorList.lastChunk = operatorListChunk.lastChunk; + intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots; + for (const internalRenderTask of intentState.renderTasks) { + internalRenderTask.operatorListChanged(); + } + if (operatorListChunk.lastChunk) { + this.#tryCleanup(); + } + } + _pumpOperatorList({ + renderingIntent, + cacheKey, + annotationStorageSerializable, + modifiedIds + }) { + const { + map, + transfer + } = annotationStorageSerializable; + const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", { + pageId: this.#pagesMapper.getPageId(this._pageIndex + 1) - 1, + pageIndex: this._pageIndex, + intent: renderingIntent, + cacheKey, + annotationStorage: map, + modifiedIds + }, undefined, transfer); + const reader = readableStream.getReader(); + const intentState = this._intentStates.get(cacheKey); + intentState.streamReader = reader; + const pump = () => { + reader.read().then(({ + value, + done + }) => { + if (done) { + intentState.streamReader = null; + return; + } + if (this._transport.destroyed) { + return; + } + this._renderPageChunk(value, intentState); + pump(); + }, reason => { + intentState.streamReader = null; + if (this._transport.destroyed) { + return; + } + if (intentState.operatorList) { + intentState.operatorList.lastChunk = true; + for (const internalRenderTask of intentState.renderTasks) { + internalRenderTask.operatorListChanged(); + } + this.#tryCleanup(); + } + if (intentState.displayReadyCapability) { + intentState.displayReadyCapability.reject(reason); + } else if (intentState.opListReadCapability) { + intentState.opListReadCapability.reject(reason); + } else { + throw reason; + } + }); + }; + pump(); + } + _abortOperatorList({ + intentState, + reason, + force = false + }) { + if (!intentState.streamReader) { + return; + } + if (intentState.streamReaderCancelTimeout) { + clearTimeout(intentState.streamReaderCancelTimeout); + intentState.streamReaderCancelTimeout = null; + } + if (!force) { + if (intentState.renderTasks.size > 0) { + return; + } + if (reason instanceof RenderingCancelledException) { + let delay = RENDERING_CANCELLED_TIMEOUT; + if (reason.extraDelay > 0 && reason.extraDelay < 1000) { + delay += reason.extraDelay; + } + intentState.streamReaderCancelTimeout = setTimeout(() => { + intentState.streamReaderCancelTimeout = null; + this._abortOperatorList({ + intentState, + reason, + force: true + }); + }, delay); + return; + } + } + intentState.streamReader.cancel(new AbortException(reason.message)).catch(() => {}); + intentState.streamReader = null; + if (this._transport.destroyed) { + return; + } + for (const [curCacheKey, curIntentState] of this._intentStates) { + if (curIntentState === intentState) { + this._intentStates.delete(curCacheKey); + break; + } + } + this.cleanup(); + } + get stats() { + return this._stats; + } +} +class PDFWorker { + #capability = Promise.withResolvers(); + #messageHandler = null; + #port = null; + #webWorker = null; + static #fakeWorkerId = 0; + static #isWorkerDisabled = false; + static #workerPorts = new WeakMap(); + static { + if (isNodeJS) { + this.#isWorkerDisabled = true; + GlobalWorkerOptions.workerSrc ||= "./pdf.worker.mjs"; + } + this._isSameOrigin = (baseUrl, otherUrl) => { + const base = URL.parse(baseUrl); + if (!base?.origin || base.origin === "null") { + return false; + } + const other = new URL(otherUrl, base); + return base.origin === other.origin; + }; + this._createCDNWrapper = url => { + const wrapper = `await import("${url}");`; + return URL.createObjectURL(new Blob([wrapper], { + type: "text/javascript" + })); + }; + this.fromPort = params => { + deprecated("`PDFWorker.fromPort` - please use `PDFWorker.create` instead."); + if (!params?.port) { + throw new Error("PDFWorker.fromPort - invalid method signature."); + } + return this.create(params); + }; + } + constructor({ + name = null, + port = null, + verbosity = getVerbosityLevel() + } = {}) { + this.name = name; + this.destroyed = false; + this.verbosity = verbosity; + if (port) { + if (PDFWorker.#workerPorts.has(port)) { + throw new Error("Cannot use more than one PDFWorker per port."); + } + PDFWorker.#workerPorts.set(port, this); + this.#initializeFromPort(port); + } else { + this.#initialize(); + } + } + get promise() { + return this.#capability.promise; + } + #resolve() { + this.#capability.resolve(); + this.#messageHandler.send("configure", { + verbosity: this.verbosity + }); + } + get port() { + return this.#port; + } + get messageHandler() { + return this.#messageHandler; + } + #initializeFromPort(port) { + this.#port = port; + this.#messageHandler = new MessageHandler("main", "worker", port); + this.#messageHandler.on("ready", () => {}); + this.#resolve(); + } + #initialize() { + if (PDFWorker.#isWorkerDisabled || PDFWorker.#mainThreadWorkerMessageHandler) { + this.#setupFakeWorker(); + return; + } + let { + workerSrc + } = PDFWorker; + try { + if (!PDFWorker._isSameOrigin(window.location, workerSrc)) { + workerSrc = PDFWorker._createCDNWrapper(new URL(workerSrc, window.location).href); + } + const worker = new Worker(workerSrc, { + type: "module" + }); + const messageHandler = new MessageHandler("main", "worker", worker); + const terminateEarly = () => { + ac.abort(); + messageHandler.destroy(); + worker.terminate(); + if (this.destroyed) { + this.#capability.reject(new Error("Worker was destroyed")); + } else { + this.#setupFakeWorker(); + } + }; + const ac = new AbortController(); + worker.addEventListener("error", () => { + if (!this.#webWorker) { + terminateEarly(); + } + }, { + signal: ac.signal + }); + messageHandler.on("test", data => { + ac.abort(); + if (this.destroyed || !data) { + terminateEarly(); + return; + } + this.#messageHandler = messageHandler; + this.#port = worker; + this.#webWorker = worker; + this.#resolve(); + }); + messageHandler.on("ready", data => { + ac.abort(); + if (this.destroyed) { + terminateEarly(); + return; + } + try { + sendTest(); + } catch { + this.#setupFakeWorker(); + } + }); + const sendTest = () => { + const testObj = new Uint8Array(); + messageHandler.send("test", testObj, [testObj.buffer]); + }; + sendTest(); + return; + } catch { + info("The worker has been disabled."); + } + this.#setupFakeWorker(); + } + #setupFakeWorker() { + if (!PDFWorker.#isWorkerDisabled) { + warn("Setting up fake worker."); + PDFWorker.#isWorkerDisabled = true; + } + PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => { + if (this.destroyed) { + this.#capability.reject(new Error("Worker was destroyed")); + return; + } + const port = new LoopbackPort(); + this.#port = port; + const id = `fake${PDFWorker.#fakeWorkerId++}`; + const workerHandler = new MessageHandler(id + "_worker", id, port); + WorkerMessageHandler.setup(workerHandler, port); + this.#messageHandler = new MessageHandler(id, id + "_worker", port); + this.#resolve(); + }).catch(reason => { + this.#capability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`)); + }); + } + destroy() { + this.destroyed = true; + this.#webWorker?.terminate(); + this.#webWorker = null; + PDFWorker.#workerPorts.delete(this.#port); + this.#port = null; + this.#messageHandler?.destroy(); + this.#messageHandler = null; + } + static create(params) { + const cachedPort = this.#workerPorts.get(params?.port); + if (cachedPort) { + if (cachedPort._pendingDestroy) { + throw new Error("PDFWorker.create - the worker is being destroyed.\n" + "Please remember to await `PDFDocumentLoadingTask.destroy()`-calls."); + } + return cachedPort; + } + return new PDFWorker(params); + } + static get workerSrc() { + if (GlobalWorkerOptions.workerSrc) { + return GlobalWorkerOptions.workerSrc; + } + throw new Error('No "GlobalWorkerOptions.workerSrc" specified.'); + } + static get #mainThreadWorkerMessageHandler() { + try { + return globalThis.pdfjsWorker?.WorkerMessageHandler || null; + } catch { + return null; + } + } + static get _setupFakeWorkerGlobal() { + const loader = async () => { + if (this.#mainThreadWorkerMessageHandler) { + return this.#mainThreadWorkerMessageHandler; + } + const worker = await import( + /*webpackIgnore: true*/ + /*@vite-ignore*/ + this.workerSrc); + return worker.WorkerMessageHandler; + }; + return shadow(this, "_setupFakeWorkerGlobal", loader()); + } +} +class WorkerTransport { + downloadInfoCapability = Promise.withResolvers(); + #fullReader = null; + #methodPromises = new Map(); + #networkStream = null; + #pageCache = new Map(); + #pagePromises = new Map(); + #pageRefCache = new Map(); + #passwordCapability = null; + #copiedPageInfo = null; + constructor(messageHandler, loadingTask, networkStream, params, factory, pagesMapper) { + this.messageHandler = messageHandler; + this.loadingTask = loadingTask; + this.#networkStream = networkStream; + this.commonObjs = new PDFObjects(); + this.fontLoader = new FontLoader({ + ownerDocument: params.ownerDocument, + styleElement: params.styleElement + }); + this.enableHWA = params.enableHWA; + this.loadingParams = params.loadingParams; + this._params = params; + this.canvasFactory = factory.canvasFactory; + this.filterFactory = factory.filterFactory; + this.cMapReaderFactory = factory.cMapReaderFactory; + this.standardFontDataFactory = factory.standardFontDataFactory; + this.wasmFactory = factory.wasmFactory; + this.destroyed = false; + this.destroyCapability = null; + this.setupMessageHandler(); + this.pagesMapper = pagesMapper; + this.pagesMapper.addListener(this.#updateCaches.bind(this)); + } + #updateCaches({ + type, + pageNumbers + }) { + if (type === "copy") { + this.#copiedPageInfo = new Map(); + for (const pageNum of pageNumbers) { + this.#copiedPageInfo.set(pageNum, { + proxy: this.#pageCache.get(pageNum - 1) || null, + promise: this.#pagePromises.get(pageNum - 1) || null + }); + } + return; + } + if (type === "delete") { + for (const pageNum of pageNumbers) { + this.#pageCache.delete(pageNum - 1); + this.#pagePromises.delete(pageNum - 1); + } + } + const newPageCache = new Map(); + const newPromiseCache = new Map(); + const { + pagesMapper + } = this; + for (let i = 0, ii = pagesMapper.pagesNumber; i < ii; i++) { + const prevPageNumber = pagesMapper.getPrevPageNumber(i + 1); + if (prevPageNumber < 0) { + const { + proxy, + promise + } = this.#copiedPageInfo?.get(-prevPageNumber) || {}; + if (proxy) { + newPageCache.set(i, proxy); + } + if (promise) { + newPromiseCache.set(i, promise); + } + continue; + } + const prevPageIndex = prevPageNumber - 1; + const page = this.#pageCache.get(prevPageIndex); + if (page) { + newPageCache.set(i, page); + } + const promise = this.#pagePromises.get(prevPageIndex); + if (promise) { + newPromiseCache.set(i, promise); + } + } + this.#pageCache = newPageCache; + this.#pagePromises = newPromiseCache; + } + #cacheSimpleMethod(name, data = null) { + return this.#methodPromises.getOrInsertComputed(name, () => this.messageHandler.sendWithPromise(name, data)); + } + #onProgress({ + loaded, + total + }) { + this.loadingTask.onProgress?.({ + loaded, + total, + percent: MathClamp(Math.round(loaded / total * 100), 0, 100) + }); + } + get annotationStorage() { + return shadow(this, "annotationStorage", new AnnotationStorage()); + } + getRenderingIntent(intent, annotationMode = AnnotationMode.ENABLE, printAnnotationStorage = null, isEditing = false, isOpList = false) { + let renderingIntent = RenderingIntentFlag.DISPLAY; + let annotationStorageSerializable = SerializableEmpty; + switch (intent) { + case "any": + renderingIntent = RenderingIntentFlag.ANY; + break; + case "display": + break; + case "print": + renderingIntent = RenderingIntentFlag.PRINT; + break; + default: + warn(`getRenderingIntent - invalid intent: ${intent}`); + } + const annotationStorage = renderingIntent & RenderingIntentFlag.PRINT && printAnnotationStorage instanceof PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage; + switch (annotationMode) { + case AnnotationMode.DISABLE: + renderingIntent += RenderingIntentFlag.ANNOTATIONS_DISABLE; + break; + case AnnotationMode.ENABLE: + break; + case AnnotationMode.ENABLE_FORMS: + renderingIntent += RenderingIntentFlag.ANNOTATIONS_FORMS; + break; + case AnnotationMode.ENABLE_STORAGE: + renderingIntent += RenderingIntentFlag.ANNOTATIONS_STORAGE; + annotationStorageSerializable = annotationStorage.serializable; + break; + default: + warn(`getRenderingIntent - invalid annotationMode: ${annotationMode}`); + } + if (isEditing) { + renderingIntent += RenderingIntentFlag.IS_EDITING; + } + if (isOpList) { + renderingIntent += RenderingIntentFlag.OPLIST; + } + const { + ids: modifiedIds, + hash: modifiedIdsHash + } = annotationStorage.modifiedIds; + const cacheKeyBuf = [renderingIntent, annotationStorageSerializable.hash, modifiedIdsHash]; + return { + renderingIntent, + cacheKey: cacheKeyBuf.join("_"), + annotationStorageSerializable, + modifiedIds + }; + } + destroy() { + if (this.destroyCapability) { + return this.destroyCapability.promise; + } + this.destroyed = true; + this.destroyCapability = Promise.withResolvers(); + this.#passwordCapability?.reject(new Error("Worker was destroyed during onPassword callback")); + const waitOn = []; + for (const page of this.#pageCache.values()) { + waitOn.push(page._destroy()); + } + this.#pageCache.clear(); + this.#pagePromises.clear(); + this.#pageRefCache.clear(); + if (this.hasOwnProperty("annotationStorage")) { + this.annotationStorage.resetModified(); + } + const terminated = this.messageHandler.sendWithPromise("Terminate", null); + waitOn.push(terminated); + Promise.all(waitOn).then(() => { + this.commonObjs.clear(); + this.fontLoader.clear(); + this.#methodPromises.clear(); + this.filterFactory.destroy(); + TextLayer.cleanup(); + this.#networkStream?.cancelAllRequests(new AbortException("Worker was terminated.")); + this.messageHandler?.destroy(); + this.messageHandler = null; + this.destroyCapability.resolve(); + }, this.destroyCapability.reject); + return this.destroyCapability.promise; + } + setupMessageHandler() { + const { + messageHandler, + loadingTask + } = this; + messageHandler.on("GetReader", (data, sink) => { + assert(this.#networkStream, "GetReader - no `BasePDFStream` instance available."); + this.#fullReader = this.#networkStream.getFullReader(); + this.#fullReader.onProgress = evt => this.#onProgress(evt); + sink.onPull = () => { + this.#fullReader.read().then(function ({ + value, + done + }) { + if (done) { + sink.close(); + return; + } + assert(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer."); + sink.enqueue(new Uint8Array(value), 1, [value]); + }).catch(reason => { + sink.error(reason); + }); + }; + sink.onCancel = reason => { + this.#fullReader.cancel(reason); + sink.ready.catch(readyReason => { + if (this.destroyed) { + return; + } + throw readyReason; + }); + }; + }); + messageHandler.on("ReaderHeadersReady", async data => { + await this.#fullReader.headersReady; + const { + isStreamingSupported, + isRangeSupported, + contentLength + } = this.#fullReader; + if (isStreamingSupported && isRangeSupported) { + this.#fullReader.onProgress = null; + } + return { + isStreamingSupported, + isRangeSupported, + contentLength + }; + }); + messageHandler.on("GetRangeReader", (data, sink) => { + assert(this.#networkStream, "GetRangeReader - no `BasePDFStream` instance available."); + const rangeReader = this.#networkStream.getRangeReader(data.begin, data.end); + if (!rangeReader) { + sink.close(); + return; + } + sink.onPull = () => { + rangeReader.read().then(function ({ + value, + done + }) { + if (done) { + sink.close(); + return; + } + assert(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer."); + sink.enqueue(new Uint8Array(value), 1, [value]); + }).catch(reason => { + sink.error(reason); + }); + }; + sink.onCancel = reason => { + rangeReader.cancel(reason); + sink.ready.catch(readyReason => { + if (this.destroyed) { + return; + } + throw readyReason; + }); + }; + }); + messageHandler.on("GetDoc", ({ + pdfInfo + }) => { + this.pagesMapper.pagesNumber = pdfInfo.numPages; + this._numPages = pdfInfo.numPages; + this._htmlForXfa = pdfInfo.htmlForXfa; + delete pdfInfo.htmlForXfa; + loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this)); + }); + messageHandler.on("DocException", ex => { + loadingTask._capability.reject(wrapReason(ex)); + }); + messageHandler.on("PasswordRequest", ex => { + this.#passwordCapability = Promise.withResolvers(); + try { + if (!loadingTask.onPassword) { + throw wrapReason(ex); + } + const updatePassword = password => { + if (password instanceof Error) { + this.#passwordCapability.reject(password); + } else { + this.#passwordCapability.resolve({ + password + }); + } + }; + loadingTask.onPassword(updatePassword, ex.code); + } catch (err) { + this.#passwordCapability.reject(err); + } + return this.#passwordCapability.promise; + }); + messageHandler.on("DataLoaded", data => { + this.#onProgress({ + loaded: data.length, + total: data.length + }); + this.downloadInfoCapability.resolve(data); + }); + messageHandler.on("StartRenderPage", data => { + if (this.destroyed) { + return; + } + const page = this.#pageCache.get(data.pageIndex); + page._startRenderPage(data.transparency, data.cacheKey); + }); + messageHandler.on("commonobj", ([id, type, exportedData]) => { + if (this.destroyed) { + return null; + } + if (this.commonObjs.has(id)) { + return null; + } + switch (type) { + case "Font": + if ("error" in exportedData) { + const exportedError = exportedData.error; + warn(`Error during font loading: ${exportedError}`); + this.commonObjs.resolve(id, exportedError); + break; + } + const fontData = new FontInfo(exportedData); + const inspectFont = this._params.pdfBug && globalThis.FontInspector?.enabled ? (font, url) => globalThis.FontInspector.fontAdded(font, url) : null; + const font = new FontFaceObject(fontData, inspectFont, exportedData.extra, exportedData.charProcOperatorList); + this.fontLoader.bind(font).catch(() => messageHandler.sendWithPromise("FontFallback", { + id + })).finally(() => { + if (!font.fontExtraProperties && font.data) { + font.clearData(); + } + this.commonObjs.resolve(id, font); + }); + break; + case "CopyLocalImage": + const { + imageRef + } = exportedData; + assert(imageRef, "The imageRef must be defined."); + for (const pageProxy of this.#pageCache.values()) { + for (const [, data] of pageProxy.objs) { + if (data?.ref !== imageRef) { + continue; + } + if (!data.dataLen) { + return null; + } + this.commonObjs.resolve(id, structuredClone(data)); + return data.dataLen; + } + } + break; + case "FontPath": + this.commonObjs.resolve(id, new FontPathInfo(exportedData)); + break; + case "Image": + this.commonObjs.resolve(id, exportedData); + break; + case "Pattern": + const pattern = new PatternInfo(exportedData); + this.commonObjs.resolve(id, pattern.getIR()); + break; + default: + throw new Error(`Got unknown common object type ${type}`); + } + return null; + }); + messageHandler.on("obj", ([id, pageIndex, type, imageData]) => { + if (this.destroyed) { + return; + } + const pageProxy = this.#pageCache.get(pageIndex); + if (pageProxy.objs.has(id)) { + return; + } + if (pageProxy._intentStates.size === 0) { + imageData?.bitmap?.close(); + return; + } + switch (type) { + case "Image": + case "Pattern": + pageProxy.objs.resolve(id, imageData); + break; + default: + throw new Error(`Got unknown object type ${type}`); + } + }); + messageHandler.on("DocProgress", data => { + if (this.destroyed) { + return; + } + this.#onProgress(data); + }); + messageHandler.on("FetchBinaryData", async data => { + if (this.destroyed) { + throw new Error("Worker was destroyed."); + } + const factory = this[data.type]; + if (!factory) { + throw new Error(`${data.type} not initialized, see the \`useWorkerFetch\` parameter.`); + } + return factory.fetch(data); + }); + } + getData() { + return this.messageHandler.sendWithPromise("GetData", null); + } + saveDocument() { + if (this.annotationStorage.size <= 0) { + warn("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead."); + } + const { + map, + transfer + } = this.annotationStorage.serializable; + return this.messageHandler.sendWithPromise("SaveDocument", { + isPureXfa: !!this._htmlForXfa, + numPages: this._numPages, + annotationStorage: map, + filename: this.#fullReader?.filename ?? null + }, transfer).finally(() => { + this.annotationStorage.resetModified(); + }); + } + extractPages(pageInfos) { + return this.messageHandler.sendWithPromise("ExtractPages", { + pageInfos + }); + } + getPage(pageNumber) { + if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this.pagesMapper.pagesNumber) { + return Promise.reject(new Error("Invalid page request.")); + } + const pageIndex = pageNumber - 1; + const newPageIndex = this.pagesMapper.getPageId(pageNumber) - 1; + const cachedPromise = this.#pagePromises.get(pageIndex); + if (cachedPromise) { + return cachedPromise; + } + const promise = this.messageHandler.sendWithPromise("GetPage", { + pageIndex: newPageIndex + }).then(pageInfo => { + if (this.destroyed) { + throw new Error("Transport destroyed"); + } + if (pageInfo.refStr) { + this.#pageRefCache.set(pageInfo.refStr, newPageIndex); + } + const page = new PDFPageProxy(pageIndex, pageInfo, this, this.pagesMapper, this._params.pdfBug); + this.#pageCache.set(pageIndex, page); + return page; + }); + this.#pagePromises.set(pageIndex, promise); + return promise; + } + async getPageIndex(ref) { + if (!isRefProxy(ref)) { + throw new Error("Invalid pageIndex request."); + } + const index = await this.messageHandler.sendWithPromise("GetPageIndex", { + num: ref.num, + gen: ref.gen + }); + const pageNumber = this.pagesMapper.getPageNumber(index + 1); + if (pageNumber === 0) { + throw new Error("GetPageIndex: page has been removed."); + } + return pageNumber - 1; + } + getAnnotations(pageIndex, intent) { + return this.messageHandler.sendWithPromise("GetAnnotations", { + pageIndex: this.pagesMapper.getPageId(pageIndex + 1) - 1, + intent + }); + } + getFieldObjects() { + return this.#cacheSimpleMethod("GetFieldObjects"); + } + hasJSActions() { + return this.#cacheSimpleMethod("HasJSActions"); + } + getCalculationOrderIds() { + return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null); + } + getDestinations() { + return this.messageHandler.sendWithPromise("GetDestinations", null); + } + getDestination(id) { + if (typeof id !== "string") { + return Promise.reject(new Error("Invalid destination request.")); + } + return this.messageHandler.sendWithPromise("GetDestination", { + id + }); + } + getPageLabels() { + return this.messageHandler.sendWithPromise("GetPageLabels", null); + } + getPageLayout() { + return this.messageHandler.sendWithPromise("GetPageLayout", null); + } + getPageMode() { + return this.messageHandler.sendWithPromise("GetPageMode", null); + } + getViewerPreferences() { + return this.messageHandler.sendWithPromise("GetViewerPreferences", null); + } + getOpenAction() { + return this.messageHandler.sendWithPromise("GetOpenAction", null); + } + getAttachments() { + return this.messageHandler.sendWithPromise("GetAttachments", null); + } + getAnnotationsByType(types, pageIndexesToSkip) { + return this.messageHandler.sendWithPromise("GetAnnotationsByType", { + types, + pageIndexesToSkip + }); + } + getDocJSActions() { + return this.#cacheSimpleMethod("GetDocJSActions"); + } + getPageJSActions(pageIndex) { + return this.messageHandler.sendWithPromise("GetPageJSActions", { + pageIndex: this.pagesMapper.getPageId(pageIndex + 1) - 1 + }); + } + getStructTree(pageIndex) { + return this.messageHandler.sendWithPromise("GetStructTree", { + pageIndex: this.pagesMapper.getPageId(pageIndex + 1) - 1 + }); + } + getOutline() { + return this.messageHandler.sendWithPromise("GetOutline", null); + } + getOptionalContentConfig(renderingIntent) { + return this.#cacheSimpleMethod("GetOptionalContentConfig").then(data => new OptionalContentConfig(data, renderingIntent)); + } + getPermissions() { + return this.messageHandler.sendWithPromise("GetPermissions", null); + } + getMetadata() { + const name = "GetMetadata"; + return this.#methodPromises.getOrInsertComputed(name, () => this.messageHandler.sendWithPromise(name, null).then(results => ({ + info: results[0], + metadata: results[1] ? new Metadata(results[1]) : null, + contentDispositionFilename: this.#fullReader?.filename ?? null, + contentLength: this.#fullReader?.contentLength ?? null, + hasStructTree: results[2] + }))); + } + getMarkInfo() { + return this.messageHandler.sendWithPromise("GetMarkInfo", null); + } + async startCleanup(keepLoadedFonts = false) { + if (this.destroyed) { + return; + } + await this.messageHandler.sendWithPromise("Cleanup", null); + for (const page of this.#pageCache.values()) { + const cleanupSuccessful = page.cleanup(); + if (!cleanupSuccessful) { + throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`); + } + } + this.commonObjs.clear(); + if (!keepLoadedFonts) { + this.fontLoader.clear(); + } + this.#methodPromises.clear(); + this.filterFactory.destroy(true); + TextLayer.cleanup(); + } + cachedPageNumber(ref) { + if (!isRefProxy(ref)) { + return null; + } + const refStr = ref.gen === 0 ? `${ref.num}R` : `${ref.num}R${ref.gen}`; + const pageIndex = this.#pageRefCache.get(refStr); + if (pageIndex >= 0) { + const pageNumber = this.pagesMapper.getPageNumber(pageIndex + 1); + if (pageNumber !== 0) { + return pageNumber; + } + } + return null; + } +} +class RenderTask { + _internalRenderTask = null; + onContinue = null; + onError = null; + constructor(internalRenderTask) { + this._internalRenderTask = internalRenderTask; + } + get promise() { + return this._internalRenderTask.capability.promise; + } + cancel(extraDelay = 0) { + this._internalRenderTask.cancel(null, extraDelay); + } + get separateAnnots() { + const { + separateAnnots + } = this._internalRenderTask.operatorList; + if (!separateAnnots) { + return false; + } + const { + annotationCanvasMap + } = this._internalRenderTask; + return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0; + } +} +class InternalRenderTask { + #rAF = null; + static #canvasInUse = new WeakSet(); + constructor({ + callback, + params, + objs, + commonObjs, + annotationCanvasMap, + operatorList, + pageIndex, + canvasFactory, + filterFactory, + useRequestAnimationFrame = false, + pdfBug = false, + pageColors = null, + enableHWA = false, + operationsFilter = null + }) { + this.callback = callback; + this.params = params; + this.objs = objs; + this.commonObjs = commonObjs; + this.annotationCanvasMap = annotationCanvasMap; + this.operatorListIdx = null; + this.operatorList = operatorList; + this._pageIndex = pageIndex; + this.canvasFactory = canvasFactory; + this.filterFactory = filterFactory; + this._pdfBug = pdfBug; + this.pageColors = pageColors; + this.running = false; + this.graphicsReadyCallback = null; + this.graphicsReady = false; + this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined"; + this.cancelled = false; + this.capability = Promise.withResolvers(); + this.task = new RenderTask(this); + this._cancelBound = this.cancel.bind(this); + this._continueBound = this._continue.bind(this); + this._scheduleNextBound = this._scheduleNext.bind(this); + this._nextBound = this._next.bind(this); + this._canvas = params.canvas; + this._canvasContext = params.canvas ? null : params.canvasContext; + this._enableHWA = enableHWA; + this._dependencyTracker = params.dependencyTracker; + this._operationsFilter = operationsFilter; + } + get completed() { + return this.capability.promise.catch(function () {}); + } + initializeGraphics({ + transparency = false, + optionalContentConfig + }) { + if (this.cancelled) { + return; + } + if (this._canvas) { + if (InternalRenderTask.#canvasInUse.has(this._canvas)) { + throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed."); + } + InternalRenderTask.#canvasInUse.add(this._canvas); + } + if (this._pdfBug && globalThis.StepperManager?.enabled) { + this.stepper = globalThis.StepperManager.create(this._pageIndex); + this.stepper.init(this.operatorList); + this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint(); + } + const { + viewport, + transform, + background, + dependencyTracker + } = this.params; + const canvasContext = this._canvasContext || this._canvas.getContext("2d", { + alpha: false, + willReadFrequently: !this._enableHWA + }); + this.gfx = new CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, { + optionalContentConfig + }, this.annotationCanvasMap, this.pageColors, dependencyTracker); + this.gfx.beginDrawing({ + transform, + viewport, + transparency, + background + }); + this.operatorListIdx = 0; + this.graphicsReady = true; + this.graphicsReadyCallback?.(); + } + cancel(error = null, extraDelay = 0) { + this.running = false; + this.cancelled = true; + this.gfx?.endDrawing(); + if (this.#rAF) { + window.cancelAnimationFrame(this.#rAF); + this.#rAF = null; + } + InternalRenderTask.#canvasInUse.delete(this._canvas); + error ||= new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, extraDelay); + this.callback(error); + this.task.onError?.(error); + } + operatorListChanged() { + if (!this.graphicsReady) { + this.graphicsReadyCallback ||= this._continueBound; + return; + } + this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length); + this.stepper?.updateOperatorList(this.operatorList); + if (this.running) { + return; + } + this._continue(); + } + _continue() { + this.running = true; + if (this.cancelled) { + return; + } + if (this.task.onContinue) { + this.task.onContinue(this._scheduleNextBound); + } else { + this._scheduleNext(); + } + } + _scheduleNext() { + if (this._useRequestAnimationFrame) { + this.#rAF = window.requestAnimationFrame(() => { + this.#rAF = null; + this._nextBound().catch(this._cancelBound); + }); + } else { + Promise.resolve().then(this._nextBound).catch(this._cancelBound); + } + } + async _next() { + if (this.cancelled) { + return; + } + this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper, this._operationsFilter); + if (this.operatorListIdx === this.operatorList.argsArray.length) { + this.running = false; + if (this.operatorList.lastChunk) { + this.gfx.endDrawing(); + InternalRenderTask.#canvasInUse.delete(this._canvas); + this.callback(); + } + } + } +} +const version = "5.5.207"; +const build = "527964698"; + +;// ./src/display/editor/color_picker.js + + + +class ColorPicker { + #button = null; + #buttonSwatch = null; + #defaultColor; + #dropdown = null; + #dropdownWasFromKeyboard = false; + #isMainColorPicker = false; + #editor = null; + #eventBus; + #openDropdownAC = null; + #uiManager = null; + static #l10nColor = null; + static get _keyboardManager() { + return shadow(this, "_keyboardManager", new KeyboardManager([[["Escape", "mac+Escape"], ColorPicker.prototype._hideDropdownFromKeyboard], [[" ", "mac+ "], ColorPicker.prototype._colorSelectFromKeyboard], [["ArrowDown", "ArrowRight", "mac+ArrowDown", "mac+ArrowRight"], ColorPicker.prototype._moveToNext], [["ArrowUp", "ArrowLeft", "mac+ArrowUp", "mac+ArrowLeft"], ColorPicker.prototype._moveToPrevious], [["Home", "mac+Home"], ColorPicker.prototype._moveToBeginning], [["End", "mac+End"], ColorPicker.prototype._moveToEnd]])); + } + constructor({ + editor = null, + uiManager = null + }) { + if (editor) { + this.#isMainColorPicker = false; + this.#editor = editor; + } else { + this.#isMainColorPicker = true; + } + this.#uiManager = editor?._uiManager || uiManager; + this.#eventBus = this.#uiManager._eventBus; + this.#defaultColor = editor?.color?.toUpperCase() || this.#uiManager?.highlightColors.values().next().value || "#FFFF98"; + ColorPicker.#l10nColor ||= Object.freeze({ + blue: "pdfjs-editor-colorpicker-blue", + green: "pdfjs-editor-colorpicker-green", + pink: "pdfjs-editor-colorpicker-pink", + red: "pdfjs-editor-colorpicker-red", + yellow: "pdfjs-editor-colorpicker-yellow" + }); + } + renderButton() { + const button = this.#button = document.createElement("button"); + button.className = "colorPicker"; + button.tabIndex = "0"; + button.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-button"); + button.ariaHasPopup = "true"; + if (this.#editor) { + button.ariaControls = `${this.#editor.id}_colorpicker_dropdown`; + } + const signal = this.#uiManager._signal; + button.addEventListener("click", this.#openDropdown.bind(this), { + signal + }); + button.addEventListener("keydown", this.#keyDown.bind(this), { + signal + }); + const swatch = this.#buttonSwatch = document.createElement("span"); + swatch.className = "swatch"; + swatch.ariaHidden = "true"; + swatch.style.backgroundColor = this.#defaultColor; + button.append(swatch); + return button; + } + renderMainDropdown() { + const dropdown = this.#dropdown = this.#getDropdownRoot(); + dropdown.ariaOrientation = "horizontal"; + dropdown.ariaLabelledBy = "highlightColorPickerLabel"; + return dropdown; + } + #getDropdownRoot() { + const div = document.createElement("div"); + const signal = this.#uiManager._signal; + div.addEventListener("contextmenu", noContextMenu, { + signal + }); + div.className = "dropdown"; + div.role = "listbox"; + div.ariaMultiSelectable = "false"; + div.ariaOrientation = "vertical"; + div.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-dropdown"); + if (this.#editor) { + div.id = `${this.#editor.id}_colorpicker_dropdown`; + } + for (const [name, color] of this.#uiManager.highlightColors) { + const button = document.createElement("button"); + button.tabIndex = "0"; + button.role = "option"; + button.setAttribute("data-color", color); + button.title = name; + button.setAttribute("data-l10n-id", ColorPicker.#l10nColor[name]); + const swatch = document.createElement("span"); + button.append(swatch); + swatch.className = "swatch"; + swatch.style.backgroundColor = color; + button.ariaSelected = color === this.#defaultColor; + button.addEventListener("click", this.#colorSelect.bind(this, color), { + signal + }); + div.append(button); + } + div.addEventListener("keydown", this.#keyDown.bind(this), { + signal + }); + return div; + } + #colorSelect(color, event) { + event.stopPropagation(); + this.#eventBus.dispatch("switchannotationeditorparams", { + source: this, + type: AnnotationEditorParamsType.HIGHLIGHT_COLOR, + value: color + }); + this.updateColor(color); + } + _colorSelectFromKeyboard(event) { + if (event.target === this.#button) { + this.#openDropdown(event); + return; + } + const color = event.target.getAttribute("data-color"); + if (!color) { + return; + } + this.#colorSelect(color, event); + } + _moveToNext(event) { + if (!this.#isDropdownVisible) { + this.#openDropdown(event); + return; + } + if (event.target === this.#button) { + this.#dropdown.firstElementChild?.focus(); + return; + } + event.target.nextSibling?.focus(); + } + _moveToPrevious(event) { + if (event.target === this.#dropdown?.firstElementChild || event.target === this.#button) { + if (this.#isDropdownVisible) { + this._hideDropdownFromKeyboard(); + } + return; + } + if (!this.#isDropdownVisible) { + this.#openDropdown(event); + } + event.target.previousSibling?.focus(); + } + _moveToBeginning(event) { + if (!this.#isDropdownVisible) { + this.#openDropdown(event); + return; + } + this.#dropdown.firstElementChild?.focus(); + } + _moveToEnd(event) { + if (!this.#isDropdownVisible) { + this.#openDropdown(event); + return; + } + this.#dropdown.lastElementChild?.focus(); + } + #keyDown(event) { + ColorPicker._keyboardManager.exec(this, event); + } + #openDropdown(event) { + if (this.#isDropdownVisible) { + this.hideDropdown(); + return; + } + this.#dropdownWasFromKeyboard = event.detail === 0; + if (!this.#openDropdownAC) { + this.#openDropdownAC = new AbortController(); + window.addEventListener("pointerdown", this.#pointerDown.bind(this), { + signal: this.#uiManager.combinedSignal(this.#openDropdownAC) + }); + } + this.#button.ariaExpanded = "true"; + if (this.#dropdown) { + this.#dropdown.classList.remove("hidden"); + return; + } + const root = this.#dropdown = this.#getDropdownRoot(); + this.#button.append(root); + } + #pointerDown(event) { + if (this.#dropdown?.contains(event.target)) { + return; + } + this.hideDropdown(); + } + hideDropdown() { + this.#dropdown?.classList.add("hidden"); + this.#button.ariaExpanded = "false"; + this.#openDropdownAC?.abort(); + this.#openDropdownAC = null; + } + get #isDropdownVisible() { + return this.#dropdown && !this.#dropdown.classList.contains("hidden"); + } + _hideDropdownFromKeyboard() { + if (this.#isMainColorPicker) { + return; + } + if (!this.#isDropdownVisible) { + this.#editor?.unselect(); + return; + } + this.hideDropdown(); + this.#button.focus({ + preventScroll: true, + focusVisible: this.#dropdownWasFromKeyboard + }); + } + updateColor(color) { + if (this.#buttonSwatch) { + this.#buttonSwatch.style.backgroundColor = color; + } + if (!this.#dropdown) { + return; + } + const i = this.#uiManager.highlightColors.values(); + for (const child of this.#dropdown.children) { + child.ariaSelected = i.next().value === color.toUpperCase(); + } + } + destroy() { + this.#button?.remove(); + this.#button = null; + this.#buttonSwatch = null; + this.#dropdown?.remove(); + this.#dropdown = null; + } +} +class BasicColorPicker { + #input = null; + #editor = null; + #uiManager = null; + static #l10nColor = null; + constructor(editor) { + this.#editor = editor; + this.#uiManager = editor._uiManager; + BasicColorPicker.#l10nColor ||= Object.freeze({ + freetext: "pdfjs-editor-color-picker-free-text-input", + ink: "pdfjs-editor-color-picker-ink-input" + }); + } + renderButton() { + if (this.#input) { + return this.#input; + } + const { + editorType, + colorType, + color + } = this.#editor; + const input = this.#input = document.createElement("input"); + input.type = "color"; + input.value = color || "#000000"; + input.className = "basicColorPicker"; + input.tabIndex = 0; + input.setAttribute("data-l10n-id", BasicColorPicker.#l10nColor[editorType]); + input.addEventListener("input", () => { + this.#uiManager.updateParams(colorType, input.value); + }, { + signal: this.#uiManager._signal + }); + return input; + } + update(value) { + if (!this.#input) { + return; + } + this.#input.value = value; + } + destroy() { + this.#input?.remove(); + this.#input = null; + } + hideDropdown() {} +} + +;// ./src/shared/scripting_utils.js +function makeColorComp(n) { + return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0"); +} +function scaleAndClamp(x) { + return Math.max(0, Math.min(255, 255 * x)); +} +class ColorConverters { + static CMYK_G([c, y, m, k]) { + return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)]; + } + static G_CMYK([g]) { + return ["CMYK", 0, 0, 0, 1 - g]; + } + static G_RGB([g]) { + return ["RGB", g, g, g]; + } + static G_rgb([g]) { + g = scaleAndClamp(g); + return [g, g, g]; + } + static G_HTML([g]) { + const G = makeColorComp(g); + return `#${G}${G}${G}`; + } + static RGB_G([r, g, b]) { + return ["G", 0.3 * r + 0.59 * g + 0.11 * b]; + } + static RGB_rgb(color) { + return color.map(scaleAndClamp); + } + static RGB_HTML(color) { + return `#${color.map(makeColorComp).join("")}`; + } + static T_HTML() { + return "#00000000"; + } + static T_rgb() { + return [null]; + } + static CMYK_RGB([c, y, m, k]) { + return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)]; + } + static CMYK_rgb([c, y, m, k]) { + return [scaleAndClamp(1 - Math.min(1, c + k)), scaleAndClamp(1 - Math.min(1, m + k)), scaleAndClamp(1 - Math.min(1, y + k))]; + } + static CMYK_HTML(components) { + const rgb = this.CMYK_RGB(components).slice(1); + return this.RGB_HTML(rgb); + } + static RGB_CMYK([r, g, b]) { + const c = 1 - r; + const m = 1 - g; + const y = 1 - b; + const k = Math.min(c, m, y); + return ["CMYK", c, m, y, k]; + } +} +const DateFormats = (/* unused pure expression or super */ null && (["m/d", "m/d/yy", "mm/dd/yy", "mm/yy", "d-mmm", "d-mmm-yy", "dd-mmm-yy", "yy-mm-dd", "mmm-yy", "mmmm-yy", "mmm d, yyyy", "mmmm d, yyyy", "m/d/yy h:MM tt", "m/d/yy HH:MM"])); +const TimeFormats = (/* unused pure expression or super */ null && (["HH:MM", "h:MM tt", "HH:MM:ss", "h:MM:ss tt"])); + +;// ./src/display/svg_factory.js + + +class BaseSVGFactory { + create(width, height, skipDimensions = false) { + if (width <= 0 || height <= 0) { + throw new Error("Invalid SVG dimensions"); + } + const svg = this._createSVG("svg:svg"); + svg.setAttribute("version", "1.1"); + if (!skipDimensions) { + svg.setAttribute("width", `${width}px`); + svg.setAttribute("height", `${height}px`); + } + svg.setAttribute("preserveAspectRatio", "none"); + svg.setAttribute("viewBox", `0 0 ${width} ${height}`); + return svg; + } + createElement(type) { + if (typeof type !== "string") { + throw new Error("Invalid SVG element type"); + } + return this._createSVG(type); + } + _createSVG(type) { + unreachable("Abstract method `_createSVG` called."); + } +} +class DOMSVGFactory extends BaseSVGFactory { + _createSVG(type) { + return document.createElementNS(SVG_NS, type); + } +} + +;// ./src/display/annotation_layer.js + + + + + +const annotation_layer_DEFAULT_FONT_SIZE = 9; +const GetElementsByNameSet = new WeakSet(); +const TIMEZONE_OFFSET = new Date().getTimezoneOffset() * 60 * 1000; +class AnnotationElementFactory { + static create(parameters) { + const subtype = parameters.data.annotationType; + switch (subtype) { + case AnnotationType.LINK: + return new LinkAnnotationElement(parameters); + case AnnotationType.TEXT: + return new TextAnnotationElement(parameters); + case AnnotationType.WIDGET: + const fieldType = parameters.data.fieldType; + switch (fieldType) { + case "Tx": + return new TextWidgetAnnotationElement(parameters); + case "Btn": + if (parameters.data.radioButton) { + return new RadioButtonWidgetAnnotationElement(parameters); + } else if (parameters.data.checkBox) { + return new CheckboxWidgetAnnotationElement(parameters); + } + return new PushButtonWidgetAnnotationElement(parameters); + case "Ch": + return new ChoiceWidgetAnnotationElement(parameters); + case "Sig": + return new SignatureWidgetAnnotationElement(parameters); + } + return new WidgetAnnotationElement(parameters); + case AnnotationType.POPUP: + return new PopupAnnotationElement(parameters); + case AnnotationType.FREETEXT: + return new FreeTextAnnotationElement(parameters); + case AnnotationType.LINE: + return new LineAnnotationElement(parameters); + case AnnotationType.SQUARE: + return new SquareAnnotationElement(parameters); + case AnnotationType.CIRCLE: + return new CircleAnnotationElement(parameters); + case AnnotationType.POLYLINE: + return new PolylineAnnotationElement(parameters); + case AnnotationType.CARET: + return new CaretAnnotationElement(parameters); + case AnnotationType.INK: + return new InkAnnotationElement(parameters); + case AnnotationType.POLYGON: + return new PolygonAnnotationElement(parameters); + case AnnotationType.HIGHLIGHT: + return new HighlightAnnotationElement(parameters); + case AnnotationType.UNDERLINE: + return new UnderlineAnnotationElement(parameters); + case AnnotationType.SQUIGGLY: + return new SquigglyAnnotationElement(parameters); + case AnnotationType.STRIKEOUT: + return new StrikeOutAnnotationElement(parameters); + case AnnotationType.STAMP: + return new StampAnnotationElement(parameters); + case AnnotationType.FILEATTACHMENT: + return new FileAttachmentAnnotationElement(parameters); + default: + return new AnnotationElement(parameters); + } + } +} +class AnnotationElement { + #updates = null; + #hasBorder = false; + #popupElement = null; + constructor(parameters, { + isRenderable = false, + ignoreBorder = false, + createQuadrilaterals = false + } = {}) { + this.isRenderable = isRenderable; + this.data = parameters.data; + this.layer = parameters.layer; + this.linkService = parameters.linkService; + this.downloadManager = parameters.downloadManager; + this.imageResourcesPath = parameters.imageResourcesPath; + this.renderForms = parameters.renderForms; + this.svgFactory = parameters.svgFactory; + this.annotationStorage = parameters.annotationStorage; + this.enableComment = parameters.enableComment; + this.enableScripting = parameters.enableScripting; + this.hasJSActions = parameters.hasJSActions; + this._fieldObjects = parameters.fieldObjects; + this.parent = parameters.parent; + this.hasOwnCommentButton = false; + if (isRenderable) { + this.contentElement = this.container = this._createContainer(ignoreBorder); + } + if (createQuadrilaterals) { + this._createQuadrilaterals(); + } + } + static _hasPopupData({ + contentsObj, + richText + }) { + return !!(contentsObj?.str || richText?.str); + } + get _isEditable() { + return this.data.isEditable; + } + get hasPopupData() { + return AnnotationElement._hasPopupData(this.data) || this.enableComment && !!this.commentText; + } + get commentData() { + const { + data + } = this; + const editor = this.annotationStorage?.getEditor(data.id); + if (editor) { + return editor.getData(); + } + return data; + } + get hasCommentButton() { + return this.enableComment && this.hasPopupElement; + } + get commentButtonPosition() { + const editor = this.annotationStorage?.getEditor(this.data.id); + if (editor) { + return editor.commentButtonPositionInPage; + } + const { + quadPoints, + inkLists, + rect + } = this.data; + let maxX = -Infinity; + let maxY = -Infinity; + if (quadPoints?.length >= 8) { + for (let i = 0; i < quadPoints.length; i += 8) { + if (quadPoints[i + 1] > maxY) { + maxY = quadPoints[i + 1]; + maxX = quadPoints[i + 2]; + } else if (quadPoints[i + 1] === maxY) { + maxX = Math.max(maxX, quadPoints[i + 2]); + } + } + return [maxX, maxY]; + } + if (inkLists?.length >= 1) { + for (const inkList of inkLists) { + for (let i = 0, ii = inkList.length; i < ii; i += 2) { + if (inkList[i + 1] > maxY) { + maxY = inkList[i + 1]; + maxX = inkList[i]; + } else if (inkList[i + 1] === maxY) { + maxX = Math.max(maxX, inkList[i]); + } + } + } + if (maxX !== Infinity) { + return [maxX, maxY]; + } + } + if (rect) { + return [rect[2], rect[3]]; + } + return null; + } + _normalizePoint(point) { + const { + page: { + view + }, + viewport: { + rawDims: { + pageWidth, + pageHeight, + pageX, + pageY + } + } + } = this.parent; + point[1] = view[3] - point[1] + view[1]; + point[0] = 100 * (point[0] - pageX) / pageWidth; + point[1] = 100 * (point[1] - pageY) / pageHeight; + return point; + } + get commentText() { + const { + data + } = this; + return this.annotationStorage.getRawValue(`${AnnotationEditorPrefix}${data.id}`)?.popup?.contents || data.contentsObj?.str || ""; + } + set commentText(text) { + const { + data + } = this; + const popup = { + deleted: !text, + contents: text || "" + }; + if (!this.annotationStorage.updateEditor(data.id, { + popup + })) { + this.annotationStorage.setValue(`${AnnotationEditorPrefix}${data.id}`, { + id: data.id, + annotationType: data.annotationType, + page: this.parent.page, + popup, + popupRef: data.popupRef, + modificationDate: new Date() + }); + } + if (!text) { + this.removePopup(); + } + } + removePopup() { + (this.#popupElement?.popup || this.popup)?.remove(); + this.#popupElement = this.popup = null; + } + updateEdited(params) { + if (!this.container) { + return; + } + if (params.rect) { + this.#updates ||= { + rect: this.data.rect.slice(0) + }; + } + const { + rect, + popup: newPopup + } = params; + if (rect) { + this.#setRectEdited(rect); + } + let popup = this.#popupElement?.popup || this.popup; + if (!popup && newPopup?.text) { + this._createPopup(newPopup); + popup = this.#popupElement.popup; + } + if (!popup) { + return; + } + popup.updateEdited(params); + if (newPopup?.deleted) { + popup.remove(); + this.#popupElement = null; + this.popup = null; + } + } + resetEdited() { + if (!this.#updates) { + return; + } + this.#setRectEdited(this.#updates.rect); + this.#popupElement?.popup.resetEdited(); + this.#updates = null; + } + #setRectEdited(rect) { + const { + container: { + style + }, + data: { + rect: currentRect, + rotation + }, + parent: { + viewport: { + rawDims: { + pageWidth, + pageHeight, + pageX, + pageY + } + } + } + } = this; + currentRect?.splice(0, 4, ...rect); + style.left = `${100 * (rect[0] - pageX) / pageWidth}%`; + style.top = `${100 * (pageHeight - rect[3] + pageY) / pageHeight}%`; + if (rotation === 0) { + style.width = `${100 * (rect[2] - rect[0]) / pageWidth}%`; + style.height = `${100 * (rect[3] - rect[1]) / pageHeight}%`; + } else { + this.setRotation(rotation); + } + } + _createContainer(ignoreBorder) { + const { + data, + parent: { + page, + viewport + } + } = this; + const container = document.createElement("section"); + container.setAttribute("data-annotation-id", data.id); + if (!(this instanceof WidgetAnnotationElement) && !(this instanceof LinkAnnotationElement)) { + container.tabIndex = 0; + } + const { + style + } = container; + style.zIndex = this.parent.zIndex; + this.parent.zIndex += 2; + if (data.alternativeText) { + container.title = data.alternativeText; + } + if (data.noRotate) { + container.classList.add("norotate"); + } + if (!data.rect || this instanceof PopupAnnotationElement) { + const { + rotation + } = data; + if (!data.hasOwnCanvas && rotation !== 0) { + this.setRotation(rotation, container); + } + return container; + } + const { + width, + height + } = this; + if (!ignoreBorder && data.borderStyle.width > 0) { + style.borderWidth = `${data.borderStyle.width}px`; + const horizontalRadius = data.borderStyle.horizontalCornerRadius; + const verticalRadius = data.borderStyle.verticalCornerRadius; + if (horizontalRadius > 0 || verticalRadius > 0) { + const radius = `calc(${horizontalRadius}px * var(--total-scale-factor)) / calc(${verticalRadius}px * var(--total-scale-factor))`; + style.borderRadius = radius; + } else if (this instanceof RadioButtonWidgetAnnotationElement) { + const radius = `calc(${width}px * var(--total-scale-factor)) / calc(${height}px * var(--total-scale-factor))`; + style.borderRadius = radius; + } + switch (data.borderStyle.style) { + case AnnotationBorderStyleType.SOLID: + style.borderStyle = "solid"; + break; + case AnnotationBorderStyleType.DASHED: + style.borderStyle = "dashed"; + break; + case AnnotationBorderStyleType.BEVELED: + warn("Unimplemented border style: beveled"); + break; + case AnnotationBorderStyleType.INSET: + warn("Unimplemented border style: inset"); + break; + case AnnotationBorderStyleType.UNDERLINE: + style.borderBottomStyle = "solid"; + break; + default: + break; + } + const borderColor = data.borderColor || null; + if (borderColor) { + this.#hasBorder = true; + style.borderColor = Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0); + } else { + style.borderWidth = 0; + } + } + const rect = Util.normalizeRect([data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1]]); + const { + pageWidth, + pageHeight, + pageX, + pageY + } = viewport.rawDims; + style.left = `${100 * (rect[0] - pageX) / pageWidth}%`; + style.top = `${100 * (rect[1] - pageY) / pageHeight}%`; + const { + rotation + } = data; + if (data.hasOwnCanvas || rotation === 0) { + style.width = `${100 * width / pageWidth}%`; + style.height = `${100 * height / pageHeight}%`; + } else { + this.setRotation(rotation, container); + } + return container; + } + setRotation(angle, container = this.container) { + if (!this.data.rect) { + return; + } + const { + pageWidth, + pageHeight + } = this.parent.viewport.rawDims; + let { + width, + height + } = this; + if (angle % 180 !== 0) { + [width, height] = [height, width]; + } + container.style.width = `${100 * width / pageWidth}%`; + container.style.height = `${100 * height / pageHeight}%`; + container.setAttribute("data-main-rotation", (360 - angle) % 360); + } + get _commonActions() { + const setColor = (jsName, styleName, event) => { + const color = event.detail[jsName]; + const colorType = color[0]; + const colorArray = color.slice(1); + event.target.style[styleName] = ColorConverters[`${colorType}_HTML`](colorArray); + this.annotationStorage.setValue(this.data.id, { + [styleName]: ColorConverters[`${colorType}_rgb`](colorArray) + }); + }; + return shadow(this, "_commonActions", { + display: event => { + const { + display + } = event.detail; + const hidden = display % 2 === 1; + this.container.style.visibility = hidden ? "hidden" : "visible"; + this.annotationStorage.setValue(this.data.id, { + noView: hidden, + noPrint: display === 1 || display === 2 + }); + }, + print: event => { + this.annotationStorage.setValue(this.data.id, { + noPrint: !event.detail.print + }); + }, + hidden: event => { + const { + hidden + } = event.detail; + this.container.style.visibility = hidden ? "hidden" : "visible"; + this.annotationStorage.setValue(this.data.id, { + noPrint: hidden, + noView: hidden + }); + }, + focus: event => { + setTimeout(() => event.target.focus({ + preventScroll: false + }), 0); + }, + userName: event => { + event.target.title = event.detail.userName; + }, + readonly: event => { + event.target.disabled = event.detail.readonly; + }, + required: event => { + this._setRequired(event.target, event.detail.required); + }, + bgColor: event => { + setColor("bgColor", "backgroundColor", event); + }, + fillColor: event => { + setColor("fillColor", "backgroundColor", event); + }, + fgColor: event => { + setColor("fgColor", "color", event); + }, + textColor: event => { + setColor("textColor", "color", event); + }, + borderColor: event => { + setColor("borderColor", "borderColor", event); + }, + strokeColor: event => { + setColor("strokeColor", "borderColor", event); + }, + rotation: event => { + const angle = event.detail.rotation; + this.setRotation(angle); + this.annotationStorage.setValue(this.data.id, { + rotation: angle + }); + } + }); + } + _dispatchEventFromSandbox(actions, jsEvent) { + const commonActions = this._commonActions; + for (const name of Object.keys(jsEvent.detail)) { + const action = actions[name] || commonActions[name]; + action?.(jsEvent); + } + } + _setDefaultPropertiesFromJS(element) { + if (!this.enableScripting) { + return; + } + const storedData = this.annotationStorage.getRawValue(this.data.id); + if (!storedData) { + return; + } + const commonActions = this._commonActions; + for (const [actionName, detail] of Object.entries(storedData)) { + const action = commonActions[actionName]; + if (action) { + const eventProxy = { + detail: { + [actionName]: detail + }, + target: element + }; + action(eventProxy); + delete storedData[actionName]; + } + } + } + _createQuadrilaterals() { + if (!this.container) { + return; + } + const { + quadPoints + } = this.data; + if (!quadPoints) { + return; + } + const [rectBlX, rectBlY, rectTrX, rectTrY] = this.data.rect.map(x => Math.fround(x)); + if (quadPoints.length === 8) { + const [trX, trY, blX, blY] = quadPoints.subarray(2, 6); + if (rectTrX === trX && rectTrY === trY && rectBlX === blX && rectBlY === blY) { + return; + } + } + const { + style + } = this.container; + let svgBuffer; + if (this.#hasBorder) { + const { + borderColor, + borderWidth + } = style; + style.borderWidth = 0; + svgBuffer = ["url('data:image/svg+xml;utf8,", `<svg xmlns="http://www.w3.org/2000/svg"`, ` preserveAspectRatio="none" viewBox="0 0 1 1">`, `<g fill="transparent" stroke="${borderColor}" stroke-width="${borderWidth}">`]; + this.container.classList.add("hasBorder"); + } + const width = rectTrX - rectBlX; + const height = rectTrY - rectBlY; + const { + svgFactory + } = this; + const svg = svgFactory.createElement("svg"); + svg.classList.add("quadrilateralsContainer"); + svg.setAttribute("width", 0); + svg.setAttribute("height", 0); + svg.role = "none"; + const defs = svgFactory.createElement("defs"); + svg.append(defs); + const clipPath = svgFactory.createElement("clipPath"); + const id = `clippath_${this.data.id}`; + clipPath.setAttribute("id", id); + clipPath.setAttribute("clipPathUnits", "objectBoundingBox"); + defs.append(clipPath); + for (let i = 2, ii = quadPoints.length; i < ii; i += 8) { + const trX = quadPoints[i]; + const trY = quadPoints[i + 1]; + const blX = quadPoints[i + 2]; + const blY = quadPoints[i + 3]; + const rect = svgFactory.createElement("rect"); + const x = (blX - rectBlX) / width; + const y = (rectTrY - trY) / height; + const rectWidth = (trX - blX) / width; + const rectHeight = (trY - blY) / height; + rect.setAttribute("x", x); + rect.setAttribute("y", y); + rect.setAttribute("width", rectWidth); + rect.setAttribute("height", rectHeight); + clipPath.append(rect); + svgBuffer?.push(`<rect vector-effect="non-scaling-stroke" x="${x}" y="${y}" width="${rectWidth}" height="${rectHeight}"/>`); + } + if (this.#hasBorder) { + svgBuffer.push(`</g></svg>')`); + style.backgroundImage = svgBuffer.join(""); + } + this.container.append(svg); + this.container.style.clipPath = `url(#${id})`; + } + _createPopup(popupData = null) { + const { + data + } = this; + let contentsObj, modificationDate; + if (popupData) { + contentsObj = { + str: popupData.text + }; + modificationDate = popupData.date; + } else { + contentsObj = data.contentsObj; + modificationDate = data.modificationDate; + } + this.#popupElement = new PopupAnnotationElement({ + data: { + color: data.color, + titleObj: data.titleObj, + modificationDate, + contentsObj, + richText: data.richText, + parentRect: data.rect, + borderStyle: 0, + id: `popup_${data.id}`, + rotation: data.rotation, + noRotate: true + }, + linkService: this.linkService, + parent: this.parent, + elements: [this] + }); + } + get hasPopupElement() { + return !!(this.#popupElement || this.popup || this.data.popupRef); + } + get extraPopupElement() { + return this.#popupElement; + } + render() { + unreachable("Abstract method `AnnotationElement.render` called"); + } + _getElementsByName(name, skipId = null) { + const fields = []; + if (this._fieldObjects) { + const fieldObj = this._fieldObjects[name]; + if (fieldObj) { + for (const { + page, + id, + exportValues + } of fieldObj) { + if (page === -1) { + continue; + } + if (id === skipId) { + continue; + } + const exportValue = typeof exportValues === "string" ? exportValues : null; + const domElement = document.querySelector(`[data-element-id="${id}"]`); + if (domElement && !GetElementsByNameSet.has(domElement)) { + warn(`_getElementsByName - element not allowed: ${id}`); + continue; + } + fields.push({ + id, + exportValue, + domElement + }); + } + } + return fields; + } + for (const domElement of document.getElementsByName(name)) { + const { + exportValue + } = domElement; + const id = domElement.getAttribute("data-element-id"); + if (id === skipId) { + continue; + } + if (!GetElementsByNameSet.has(domElement)) { + continue; + } + fields.push({ + id, + exportValue, + domElement + }); + } + return fields; + } + show() { + if (this.container) { + this.container.hidden = false; + } + this.popup?.maybeShow(); + } + hide() { + if (this.container) { + this.container.hidden = true; + } + this.popup?.forceHide(); + } + getElementsToTriggerPopup() { + return this.container; + } + addHighlightArea() { + const triggers = this.getElementsToTriggerPopup(); + if (Array.isArray(triggers)) { + for (const element of triggers) { + element.classList.add("highlightArea"); + } + } else { + triggers.classList.add("highlightArea"); + } + } + _editOnDoubleClick() { + if (!this._isEditable) { + return; + } + const { + annotationEditorType: mode, + data: { + id: editId + } + } = this; + this.container.addEventListener("dblclick", () => { + this.linkService.eventBus?.dispatch("switchannotationeditormode", { + source: this, + mode, + editId, + mustEnterInEditMode: true + }); + }); + } + get width() { + return this.data.rect[2] - this.data.rect[0]; + } + get height() { + return this.data.rect[3] - this.data.rect[1]; + } +} +class EditorAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + this.editor = parameters.editor; + } + render() { + this.container.className = "editorAnnotation"; + return this.container; + } + createOrUpdatePopup() { + const { + editor + } = this; + if (!editor.hasComment) { + return; + } + this._createPopup(editor.comment); + } + get hasCommentButton() { + return this.enableComment && this.editor.hasComment; + } + get commentButtonPosition() { + return this.editor.commentButtonPositionInPage; + } + get commentText() { + return this.editor.comment.text; + } + set commentText(text) { + this.editor.comment = text; + if (!text) { + this.removePopup(); + } + } + get commentData() { + return this.editor.getData(); + } + remove() { + this.parent.removeAnnotation(this.data.id); + this.container.remove(); + this.container = null; + this.removePopup(); + } +} +class LinkAnnotationElement extends AnnotationElement { + constructor(parameters, options = null) { + super(parameters, { + isRenderable: true, + ignoreBorder: !!options?.ignoreBorder, + createQuadrilaterals: true + }); + this.isTooltipOnly = parameters.data.isTooltipOnly; + } + render() { + const { + data, + linkService + } = this; + const link = document.createElement("a"); + link.setAttribute("data-element-id", data.id); + let isBound = false; + if (data.url) { + linkService.addLinkAttributes(link, data.url, data.newWindow); + isBound = true; + } else if (data.action) { + this._bindNamedAction(link, data.action, data.overlaidText); + isBound = true; + } else if (data.attachment) { + this.#bindAttachment(link, data.attachment, data.overlaidText, data.attachmentDest); + isBound = true; + } else if (data.setOCGState) { + this.#bindSetOCGState(link, data.setOCGState, data.overlaidText); + isBound = true; + } else if (data.dest) { + this._bindLink(link, data.dest, data.overlaidText); + isBound = true; + } else { + if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) { + this._bindJSAction(link, data); + isBound = true; + } + if (data.resetForm) { + this._bindResetFormAction(link, data.resetForm); + isBound = true; + } else if (this.isTooltipOnly && !isBound) { + this._bindLink(link, ""); + isBound = true; + } + } + this.container.classList.add("linkAnnotation"); + if (isBound) { + this.contentElement = link; + this.container.append(link); + } + return this.container; + } + #setInternalLink() { + this.container.setAttribute("data-internal-link", ""); + } + _bindLink(link, destination, overlaidText = "") { + link.href = this.linkService.getDestinationHash(destination); + link.onclick = () => { + if (destination) { + this.linkService.goToDestination(destination); + } + return false; + }; + if (destination || destination === "") { + this.#setInternalLink(); + } + if (overlaidText) { + link.title = overlaidText; + } + } + _bindNamedAction(link, action, overlaidText = "") { + link.href = this.linkService.getAnchorUrl(""); + link.onclick = () => { + this.linkService.executeNamedAction(action); + return false; + }; + if (overlaidText) { + link.title = overlaidText; + } + this.#setInternalLink(); + } + #bindAttachment(link, attachment, overlaidText = "", dest = null) { + link.href = this.linkService.getAnchorUrl(""); + if (attachment.description) { + link.title = attachment.description; + } else if (overlaidText) { + link.title = overlaidText; + } + link.onclick = () => { + this.downloadManager?.openOrDownloadData(attachment.content, attachment.filename, dest); + return false; + }; + this.#setInternalLink(); + } + #bindSetOCGState(link, action, overlaidText = "") { + link.href = this.linkService.getAnchorUrl(""); + link.onclick = () => { + this.linkService.executeSetOCGState(action); + return false; + }; + if (overlaidText) { + link.title = overlaidText; + } + this.#setInternalLink(); + } + _bindJSAction(link, data) { + link.href = this.linkService.getAnchorUrl(""); + const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]); + for (const name of Object.keys(data.actions)) { + const jsName = map.get(name); + if (!jsName) { + continue; + } + link[jsName] = () => { + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id: data.id, + name + } + }); + return false; + }; + } + if (data.overlaidText) { + link.title = data.overlaidText; + } + if (!link.onclick) { + link.onclick = () => false; + } + this.#setInternalLink(); + } + _bindResetFormAction(link, resetForm) { + const otherClickAction = link.onclick; + if (!otherClickAction) { + link.href = this.linkService.getAnchorUrl(""); + } + this.#setInternalLink(); + if (!this._fieldObjects) { + warn(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided."); + if (!otherClickAction) { + link.onclick = () => false; + } + return; + } + link.onclick = () => { + otherClickAction?.(); + const { + fields: resetFormFields, + refs: resetFormRefs, + include + } = resetForm; + const allFields = []; + if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) { + const fieldIds = new Set(resetFormRefs); + for (const fieldName of resetFormFields) { + const fields = this._fieldObjects[fieldName] || []; + for (const { + id + } of fields) { + fieldIds.add(id); + } + } + for (const fields of Object.values(this._fieldObjects)) { + for (const field of fields) { + if (fieldIds.has(field.id) === include) { + allFields.push(field); + } + } + } + } else { + for (const fields of Object.values(this._fieldObjects)) { + allFields.push(...fields); + } + } + const storage = this.annotationStorage; + const allIds = []; + for (const field of allFields) { + const { + id + } = field; + allIds.push(id); + switch (field.type) { + case "text": + { + const value = field.defaultValue || ""; + storage.setValue(id, { + value + }); + break; + } + case "checkbox": + case "radiobutton": + { + const value = field.defaultValue === field.exportValues; + storage.setValue(id, { + value + }); + break; + } + case "combobox": + case "listbox": + { + const value = field.defaultValue || ""; + storage.setValue(id, { + value + }); + break; + } + default: + continue; + } + const domElement = document.querySelector(`[data-element-id="${id}"]`); + if (!domElement) { + continue; + } else if (!GetElementsByNameSet.has(domElement)) { + warn(`_bindResetFormAction - element not allowed: ${id}`); + continue; + } + domElement.dispatchEvent(new Event("resetform")); + } + if (this.enableScripting) { + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id: "app", + ids: allIds, + name: "ResetForm" + } + }); + } + return false; + }; + } +} +class TextAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true + }); + } + render() { + this.container.classList.add("textAnnotation"); + const image = document.createElement("img"); + image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg"; + image.setAttribute("data-l10n-id", "pdfjs-text-annotation-type"); + image.setAttribute("data-l10n-args", JSON.stringify({ + type: this.data.name + })); + if (!this.data.popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + this.container.append(image); + return this.container; + } +} +class WidgetAnnotationElement extends AnnotationElement { + render() { + return this.container; + } + showElementAndHideCanvas(element) { + if (this.data.hasOwnCanvas) { + if (element.previousSibling?.nodeName === "CANVAS") { + element.previousSibling.hidden = true; + } + element.hidden = false; + } + } + _getKeyModifier(event) { + return FeatureTest.platform.isMac ? event.metaKey : event.ctrlKey; + } + _setEventListener(element, elementData, baseName, eventName, valueGetter) { + if (baseName.includes("mouse")) { + element.addEventListener(baseName, event => { + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id: this.data.id, + name: eventName, + value: valueGetter(event), + shift: event.shiftKey, + modifier: this._getKeyModifier(event) + } + }); + }); + } else { + element.addEventListener(baseName, event => { + if (baseName === "blur") { + if (!elementData.focused || !event.relatedTarget) { + return; + } + elementData.focused = false; + } else if (baseName === "focus") { + if (elementData.focused) { + return; + } + elementData.focused = true; + } + if (!valueGetter) { + return; + } + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id: this.data.id, + name: eventName, + value: valueGetter(event) + } + }); + }); + } + } + _setEventListeners(element, elementData, names, getter) { + for (const [baseName, eventName] of names) { + if (eventName === "Action" || this.data.actions?.[eventName]) { + if (eventName === "Focus" || eventName === "Blur") { + elementData ||= { + focused: false + }; + } + this._setEventListener(element, elementData, baseName, eventName, getter); + if (eventName === "Focus" && !this.data.actions?.Blur) { + this._setEventListener(element, elementData, "blur", "Blur", null); + } else if (eventName === "Blur" && !this.data.actions?.Focus) { + this._setEventListener(element, elementData, "focus", "Focus", null); + } + } + } + } + _setBackgroundColor(element) { + const color = this.data.backgroundColor || null; + element.style.backgroundColor = color === null ? "transparent" : Util.makeHexColor(color[0], color[1], color[2]); + } + _setTextStyle(element) { + const TEXT_ALIGNMENT = ["left", "center", "right"]; + const { + fontColor + } = this.data.defaultAppearanceData; + const fontSize = this.data.defaultAppearanceData.fontSize || annotation_layer_DEFAULT_FONT_SIZE; + const style = element.style; + let computedFontSize; + const BORDER_SIZE = 2; + const roundToOneDecimal = x => Math.round(10 * x) / 10; + if (this.data.multiLine) { + const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE); + const numberOfLines = Math.round(height / (LINE_FACTOR * fontSize)) || 1; + const lineHeight = height / numberOfLines; + computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / LINE_FACTOR)); + } else { + const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE); + computedFontSize = Math.min(fontSize, roundToOneDecimal(height / LINE_FACTOR)); + } + style.fontSize = `calc(${computedFontSize}px * var(--total-scale-factor))`; + style.color = Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]); + if (this.data.textAlignment !== null) { + style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment]; + } + } + _setRequired(element, isRequired) { + if (isRequired) { + element.setAttribute("required", true); + } else { + element.removeAttribute("required"); + } + element.setAttribute("aria-required", isRequired); + } +} +class TextWidgetAnnotationElement extends WidgetAnnotationElement { + constructor(parameters) { + const isRenderable = parameters.renderForms || parameters.data.hasOwnCanvas || !parameters.data.hasAppearance && !!parameters.data.fieldValue; + super(parameters, { + isRenderable + }); + } + setPropertyOnSiblings(base, key, value, keyInStorage) { + const storage = this.annotationStorage; + for (const element of this._getElementsByName(base.name, base.id)) { + if (element.domElement) { + element.domElement[key] = value; + } + storage.setValue(element.id, { + [keyInStorage]: value + }); + } + } + render() { + const storage = this.annotationStorage; + const id = this.data.id; + this.container.classList.add("textWidgetAnnotation"); + let element = null; + if (this.renderForms) { + const storedData = storage.getValue(id, { + value: this.data.fieldValue + }); + let textContent = storedData.value || ""; + const maxLen = storage.getValue(id, { + charLimit: this.data.maxLen + }).charLimit; + if (maxLen && textContent.length > maxLen) { + textContent = textContent.slice(0, maxLen); + } + let fieldFormattedValues = storedData.formattedValue || this.data.textContent?.join("\n") || null; + if (fieldFormattedValues && this.data.comb) { + fieldFormattedValues = fieldFormattedValues.replaceAll(/\s+/g, ""); + } + const elementData = { + userValue: textContent, + formattedValue: fieldFormattedValues, + lastCommittedValue: null, + commitKey: 1, + focused: false + }; + if (this.data.multiLine) { + element = document.createElement("textarea"); + element.textContent = fieldFormattedValues ?? textContent; + if (this.data.doNotScroll) { + element.style.overflowY = "hidden"; + } + } else { + element = document.createElement("input"); + element.type = this.data.password ? "password" : "text"; + element.setAttribute("value", fieldFormattedValues ?? textContent); + if (this.data.doNotScroll) { + element.style.overflowX = "hidden"; + } + } + if (this.data.hasOwnCanvas) { + element.hidden = true; + } + GetElementsByNameSet.add(element); + this.contentElement = element; + element.setAttribute("data-element-id", id); + element.disabled = this.data.readOnly; + element.name = this.data.fieldName; + element.tabIndex = 0; + const { + datetimeFormat, + datetimeType, + timeStep + } = this.data; + const hasDateOrTime = !!datetimeType && this.enableScripting; + if (datetimeFormat) { + element.title = datetimeFormat; + } + this._setRequired(element, this.data.required); + if (maxLen) { + element.maxLength = maxLen; + } + element.addEventListener("input", event => { + storage.setValue(id, { + value: event.target.value + }); + this.setPropertyOnSiblings(element, "value", event.target.value, "value"); + elementData.formattedValue = null; + }); + element.addEventListener("resetform", event => { + const defaultValue = this.data.defaultFieldValue ?? ""; + element.value = elementData.userValue = defaultValue; + elementData.formattedValue = null; + }); + let blurListener = event => { + const { + formattedValue + } = elementData; + if (formattedValue !== null && formattedValue !== undefined) { + event.target.value = formattedValue; + } + event.target.scrollLeft = 0; + }; + if (this.enableScripting && this.hasJSActions) { + element.addEventListener("focus", event => { + if (elementData.focused) { + return; + } + const { + target + } = event; + if (hasDateOrTime) { + target.type = datetimeType; + if (timeStep) { + target.step = timeStep; + } + } + if (elementData.userValue) { + const value = elementData.userValue; + if (hasDateOrTime) { + if (datetimeType === "time") { + const date = new Date(value); + const parts = [date.getHours(), date.getMinutes(), date.getSeconds()]; + target.value = parts.map(v => v.toString().padStart(2, "0")).join(":"); + } else { + target.value = new Date(value - TIMEZONE_OFFSET).toISOString().split(datetimeType === "date" ? "T" : ".", 1)[0]; + } + } else { + target.value = value; + } + } + elementData.lastCommittedValue = target.value; + elementData.commitKey = 1; + if (!this.data.actions?.Focus) { + elementData.focused = true; + } + }); + element.addEventListener("updatefromsandbox", jsEvent => { + this.showElementAndHideCanvas(jsEvent.target); + const actions = { + value(event) { + elementData.userValue = event.detail.value ?? ""; + if (!hasDateOrTime) { + storage.setValue(id, { + value: elementData.userValue.toString() + }); + } + event.target.value = elementData.userValue; + }, + formattedValue(event) { + const { + formattedValue + } = event.detail; + elementData.formattedValue = formattedValue; + if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) { + event.target.value = formattedValue; + } + const data = { + formattedValue + }; + if (hasDateOrTime) { + data.value = formattedValue; + } + storage.setValue(id, data); + }, + selRange(event) { + event.target.setSelectionRange(...event.detail.selRange); + }, + charLimit: event => { + const { + charLimit + } = event.detail; + const { + target + } = event; + if (charLimit === 0) { + target.removeAttribute("maxLength"); + return; + } + target.setAttribute("maxLength", charLimit); + let value = elementData.userValue; + if (!value || value.length <= charLimit) { + return; + } + value = value.slice(0, charLimit); + target.value = elementData.userValue = value; + storage.setValue(id, { + value + }); + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value, + willCommit: true, + commitKey: 1, + selStart: target.selectionStart, + selEnd: target.selectionEnd + } + }); + } + }; + this._dispatchEventFromSandbox(actions, jsEvent); + }); + element.addEventListener("keydown", event => { + elementData.commitKey = 1; + let commitKey = -1; + if (event.key === "Escape") { + commitKey = 0; + } else if (event.key === "Enter" && !this.data.multiLine) { + commitKey = 2; + } else if (event.key === "Tab") { + elementData.commitKey = 3; + } + if (commitKey === -1) { + return; + } + const { + value + } = event.target; + if (elementData.lastCommittedValue === value) { + return; + } + elementData.lastCommittedValue = value; + elementData.userValue = value; + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value, + willCommit: true, + commitKey, + selStart: event.target.selectionStart, + selEnd: event.target.selectionEnd + } + }); + }); + const _blurListener = blurListener; + blurListener = null; + element.addEventListener("blur", event => { + if (!elementData.focused || !event.relatedTarget) { + return; + } + if (!this.data.actions?.Blur) { + elementData.focused = false; + } + const { + target + } = event; + let { + value + } = target; + if (hasDateOrTime) { + if (value && datetimeType === "time") { + const parts = value.split(":").map(v => parseInt(v, 10)); + value = new Date(2000, 0, 1, parts[0], parts[1], parts[2] || 0).valueOf(); + target.step = ""; + } else { + if (!value.includes("T")) { + value = `${value}T00:00`; + } + value = new Date(value).valueOf(); + } + target.type = "text"; + } + elementData.userValue = value; + if (elementData.lastCommittedValue !== value) { + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value, + willCommit: true, + commitKey: elementData.commitKey, + selStart: event.target.selectionStart, + selEnd: event.target.selectionEnd + } + }); + } + _blurListener(event); + }); + if (this.data.actions?.Keystroke) { + element.addEventListener("beforeinput", event => { + elementData.lastCommittedValue = null; + const { + data, + target + } = event; + const { + value, + selectionStart, + selectionEnd + } = target; + let selStart = selectionStart, + selEnd = selectionEnd; + switch (event.inputType) { + case "deleteWordBackward": + { + const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/); + if (match) { + selStart -= match[0].length; + } + break; + } + case "deleteWordForward": + { + const match = value.substring(selectionStart).match(/^[^\w]*\w*/); + if (match) { + selEnd += match[0].length; + } + break; + } + case "deleteContentBackward": + if (selectionStart === selectionEnd) { + selStart -= 1; + } + break; + case "deleteContentForward": + if (selectionStart === selectionEnd) { + selEnd += 1; + } + break; + } + event.preventDefault(); + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value, + change: data || "", + willCommit: false, + selStart, + selEnd + } + }); + }); + } + this._setEventListeners(element, elementData, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value); + } + if (blurListener) { + element.addEventListener("blur", blurListener); + } + if (this.data.comb) { + const fieldWidth = this.data.rect[2] - this.data.rect[0]; + const combWidth = fieldWidth / maxLen; + element.classList.add("comb"); + element.style.letterSpacing = `calc(${combWidth}px * var(--total-scale-factor) - 1ch)`; + } + } else { + element = document.createElement("div"); + element.textContent = this.data.fieldValue; + element.style.verticalAlign = "middle"; + element.style.display = "table-cell"; + if (this.data.hasOwnCanvas) { + element.hidden = true; + } + } + this._setTextStyle(element); + this._setBackgroundColor(element); + this._setDefaultPropertiesFromJS(element); + this.container.append(element); + return this.container; + } +} +class SignatureWidgetAnnotationElement extends WidgetAnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: !!parameters.data.hasOwnCanvas + }); + } +} +class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: parameters.renderForms + }); + } + render() { + const storage = this.annotationStorage; + const data = this.data; + const id = data.id; + let value = storage.getValue(id, { + value: data.exportValue === data.fieldValue + }).value; + if (typeof value === "string") { + value = value !== "Off"; + storage.setValue(id, { + value + }); + } + this.container.classList.add("buttonWidgetAnnotation", "checkBox"); + const element = document.createElement("input"); + GetElementsByNameSet.add(element); + element.setAttribute("data-element-id", id); + element.disabled = data.readOnly; + this._setRequired(element, this.data.required); + element.type = "checkbox"; + element.name = data.fieldName; + if (value) { + element.setAttribute("checked", true); + } + element.setAttribute("exportValue", data.exportValue); + element.tabIndex = 0; + element.addEventListener("change", event => { + const { + name, + checked + } = event.target; + for (const checkbox of this._getElementsByName(name, id)) { + const curChecked = checked && checkbox.exportValue === data.exportValue; + if (checkbox.domElement) { + checkbox.domElement.checked = curChecked; + } + storage.setValue(checkbox.id, { + value: curChecked + }); + } + storage.setValue(id, { + value: checked + }); + }); + element.addEventListener("resetform", event => { + const defaultValue = data.defaultFieldValue || "Off"; + event.target.checked = defaultValue === data.exportValue; + }); + if (this.enableScripting && this.hasJSActions) { + element.addEventListener("updatefromsandbox", jsEvent => { + const actions = { + value(event) { + event.target.checked = event.detail.value !== "Off"; + storage.setValue(id, { + value: event.target.checked + }); + } + }; + this._dispatchEventFromSandbox(actions, jsEvent); + }); + this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked); + } + this._setBackgroundColor(element); + this._setDefaultPropertiesFromJS(element); + this.container.append(element); + return this.container; + } +} +class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: parameters.renderForms + }); + } + render() { + this.container.classList.add("buttonWidgetAnnotation", "radioButton"); + const storage = this.annotationStorage; + const data = this.data; + const id = data.id; + let value = storage.getValue(id, { + value: data.fieldValue === data.buttonValue + }).value; + if (typeof value === "string") { + value = value !== data.buttonValue; + storage.setValue(id, { + value + }); + } + if (value) { + for (const radio of this._getElementsByName(data.fieldName, id)) { + storage.setValue(radio.id, { + value: false + }); + } + } + const element = document.createElement("input"); + GetElementsByNameSet.add(element); + element.setAttribute("data-element-id", id); + element.disabled = data.readOnly; + this._setRequired(element, this.data.required); + element.type = "radio"; + element.name = data.fieldName; + if (value) { + element.setAttribute("checked", true); + } + element.tabIndex = 0; + element.addEventListener("change", event => { + const { + name, + checked + } = event.target; + for (const radio of this._getElementsByName(name, id)) { + storage.setValue(radio.id, { + value: false + }); + } + storage.setValue(id, { + value: checked + }); + }); + element.addEventListener("resetform", event => { + const defaultValue = data.defaultFieldValue; + event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue; + }); + if (this.enableScripting && this.hasJSActions) { + const pdfButtonValue = data.buttonValue; + element.addEventListener("updatefromsandbox", jsEvent => { + const actions = { + value: event => { + const checked = pdfButtonValue === event.detail.value; + for (const radio of this._getElementsByName(event.target.name)) { + const curChecked = checked && radio.id === id; + if (radio.domElement) { + radio.domElement.checked = curChecked; + } + storage.setValue(radio.id, { + value: curChecked + }); + } + } + }; + this._dispatchEventFromSandbox(actions, jsEvent); + }); + this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked); + } + this._setBackgroundColor(element); + this._setDefaultPropertiesFromJS(element); + this.container.append(element); + return this.container; + } +} +class PushButtonWidgetAnnotationElement extends LinkAnnotationElement { + constructor(parameters) { + super(parameters, { + ignoreBorder: parameters.data.hasAppearance + }); + } + render() { + const container = super.render(); + container.classList.add("buttonWidgetAnnotation", "pushButton"); + const linkElement = container.lastChild; + if (this.enableScripting && this.hasJSActions && linkElement) { + this._setDefaultPropertiesFromJS(linkElement); + linkElement.addEventListener("updatefromsandbox", jsEvent => { + this._dispatchEventFromSandbox({}, jsEvent); + }); + } + return container; + } +} +class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: parameters.renderForms + }); + } + render() { + this.container.classList.add("choiceWidgetAnnotation"); + const storage = this.annotationStorage; + const id = this.data.id; + const storedData = storage.getValue(id, { + value: this.data.fieldValue + }); + const selectElement = document.createElement("select"); + GetElementsByNameSet.add(selectElement); + selectElement.setAttribute("data-element-id", id); + selectElement.disabled = this.data.readOnly; + this._setRequired(selectElement, this.data.required); + selectElement.name = this.data.fieldName; + selectElement.tabIndex = 0; + let addAnEmptyEntry = this.data.combo && this.data.options.length > 0; + if (!this.data.combo) { + selectElement.size = this.data.options.length; + if (this.data.multiSelect) { + selectElement.multiple = true; + } + } + selectElement.addEventListener("resetform", event => { + const defaultValue = this.data.defaultFieldValue; + for (const option of selectElement.options) { + option.selected = option.value === defaultValue; + } + }); + for (const option of this.data.options) { + const optionElement = document.createElement("option"); + optionElement.textContent = option.displayValue; + optionElement.value = option.exportValue; + if (storedData.value.includes(option.exportValue)) { + optionElement.setAttribute("selected", true); + addAnEmptyEntry = false; + } + selectElement.append(optionElement); + } + let removeEmptyEntry = null; + if (addAnEmptyEntry) { + const noneOptionElement = document.createElement("option"); + noneOptionElement.value = " "; + noneOptionElement.setAttribute("hidden", true); + noneOptionElement.setAttribute("selected", true); + selectElement.prepend(noneOptionElement); + removeEmptyEntry = () => { + noneOptionElement.remove(); + selectElement.removeEventListener("input", removeEmptyEntry); + removeEmptyEntry = null; + }; + selectElement.addEventListener("input", removeEmptyEntry); + } + const getValue = isExport => { + const name = isExport ? "value" : "textContent"; + const { + options, + multiple + } = selectElement; + if (!multiple) { + return options.selectedIndex === -1 ? null : options[options.selectedIndex][name]; + } + return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]); + }; + let selectedValues = getValue(false); + const getItems = event => { + const options = event.target.options; + return Array.prototype.map.call(options, option => ({ + displayValue: option.textContent, + exportValue: option.value + })); + }; + if (this.enableScripting && this.hasJSActions) { + selectElement.addEventListener("updatefromsandbox", jsEvent => { + const actions = { + value(event) { + removeEmptyEntry?.(); + const value = event.detail.value; + const values = new Set(Array.isArray(value) ? value : [value]); + for (const option of selectElement.options) { + option.selected = values.has(option.value); + } + storage.setValue(id, { + value: getValue(true) + }); + selectedValues = getValue(false); + }, + multipleSelection(event) { + selectElement.multiple = true; + }, + remove(event) { + const options = selectElement.options; + const index = event.detail.remove; + options[index].selected = false; + selectElement.remove(index); + if (options.length > 0) { + const i = Array.prototype.findIndex.call(options, option => option.selected); + if (i === -1) { + options[0].selected = true; + } + } + storage.setValue(id, { + value: getValue(true), + items: getItems(event) + }); + selectedValues = getValue(false); + }, + clear(event) { + while (selectElement.length !== 0) { + selectElement.remove(0); + } + storage.setValue(id, { + value: null, + items: [] + }); + selectedValues = getValue(false); + }, + insert(event) { + const { + index, + displayValue, + exportValue + } = event.detail.insert; + const selectChild = selectElement.children[index]; + const optionElement = document.createElement("option"); + optionElement.textContent = displayValue; + optionElement.value = exportValue; + if (selectChild) { + selectChild.before(optionElement); + } else { + selectElement.append(optionElement); + } + storage.setValue(id, { + value: getValue(true), + items: getItems(event) + }); + selectedValues = getValue(false); + }, + items(event) { + const { + items + } = event.detail; + while (selectElement.length !== 0) { + selectElement.remove(0); + } + for (const item of items) { + const { + displayValue, + exportValue + } = item; + const optionElement = document.createElement("option"); + optionElement.textContent = displayValue; + optionElement.value = exportValue; + selectElement.append(optionElement); + } + if (selectElement.options.length > 0) { + selectElement.options[0].selected = true; + } + storage.setValue(id, { + value: getValue(true), + items: getItems(event) + }); + selectedValues = getValue(false); + }, + indices(event) { + const indices = new Set(event.detail.indices); + for (const option of event.target.options) { + option.selected = indices.has(option.index); + } + storage.setValue(id, { + value: getValue(true) + }); + selectedValues = getValue(false); + }, + editable(event) { + event.target.disabled = !event.detail.editable; + } + }; + this._dispatchEventFromSandbox(actions, jsEvent); + }); + selectElement.addEventListener("input", event => { + const exportValue = getValue(true); + const change = getValue(false); + storage.setValue(id, { + value: exportValue + }); + event.preventDefault(); + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value: selectedValues, + change, + changeEx: exportValue, + willCommit: false, + commitKey: 1, + keyDown: false + } + }); + }); + this._setEventListeners(selectElement, null, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"], ["input", "Validate"]], event => event.target.value); + } else { + selectElement.addEventListener("input", function (event) { + storage.setValue(id, { + value: getValue(true) + }); + }); + } + if (this.data.combo) { + this._setTextStyle(selectElement); + } else {} + this._setBackgroundColor(selectElement); + this._setDefaultPropertiesFromJS(selectElement); + this.container.append(selectElement); + return this.container; + } +} +class PopupAnnotationElement extends AnnotationElement { + constructor(parameters) { + const { + data, + elements, + parent + } = parameters; + const hasCommentManager = !!parent._commentManager; + super(parameters, { + isRenderable: !hasCommentManager && AnnotationElement._hasPopupData(data) + }); + this.elements = elements; + if (hasCommentManager && AnnotationElement._hasPopupData(data)) { + const popup = this.popup = this.#createPopup(); + for (const element of elements) { + element.popup = popup; + } + } else { + this.popup = null; + } + } + #createPopup() { + return new PopupElement({ + container: this.container, + color: this.data.color, + titleObj: this.data.titleObj, + modificationDate: this.data.modificationDate || this.data.creationDate, + contentsObj: this.data.contentsObj, + richText: this.data.richText, + rect: this.data.rect, + parentRect: this.data.parentRect || null, + parent: this.parent, + elements: this.elements, + open: this.data.open, + commentManager: this.parent._commentManager + }); + } + render() { + const { + container + } = this; + container.classList.add("popupAnnotation"); + container.role = "comment"; + const popup = this.popup = this.#createPopup(); + const elementIds = []; + for (const element of this.elements) { + element.popup = popup; + element.container.ariaHasPopup = "dialog"; + elementIds.push(element.data.id); + element.addHighlightArea(); + } + this.container.setAttribute("aria-controls", elementIds.map(id => `${AnnotationPrefix}${id}`).join(",")); + return this.container; + } +} +class PopupElement { + #commentManager = null; + #boundKeyDown = this.#keyDown.bind(this); + #boundHide = this.#hide.bind(this); + #boundShow = this.#show.bind(this); + #boundToggle = this.#toggle.bind(this); + #color = null; + #container = null; + #contentsObj = null; + #dateObj = null; + #elements = null; + #parent = null; + #parentRect = null; + #pinned = false; + #popup = null; + #popupAbortController = null; + #position = null; + #commentButton = null; + #commentButtonPosition = null; + #popupPosition = null; + #rect = null; + #richText = null; + #titleObj = null; + #updates = null; + #wasVisible = false; + #firstElement = null; + #commentText = null; + constructor({ + container, + color, + elements, + titleObj, + modificationDate, + contentsObj, + richText, + parent, + rect, + parentRect, + open, + commentManager = null + }) { + this.#container = container; + this.#titleObj = titleObj; + this.#contentsObj = contentsObj; + this.#richText = richText; + this.#parent = parent; + this.#color = color; + this.#rect = rect; + this.#parentRect = parentRect; + this.#elements = elements; + this.#commentManager = commentManager; + this.#firstElement = elements[0]; + this.#dateObj = PDFDateString.toDateObject(modificationDate); + this.trigger = elements.flatMap(e => e.getElementsToTriggerPopup()); + if (!commentManager) { + this.#addEventListeners(); + this.#container.hidden = true; + if (open) { + this.#toggle(); + } + } + } + #addEventListeners() { + if (this.#popupAbortController) { + return; + } + this.#popupAbortController = new AbortController(); + const { + signal + } = this.#popupAbortController; + for (const element of this.trigger) { + element.addEventListener("click", this.#boundToggle, { + signal + }); + element.addEventListener("pointerenter", this.#boundShow, { + signal + }); + element.addEventListener("pointerleave", this.#boundHide, { + signal + }); + element.classList.add("popupTriggerArea"); + } + for (const element of this.#elements) { + element.container?.addEventListener("keydown", this.#boundKeyDown, { + signal + }); + } + } + #setCommentButtonPosition() { + const element = this.#elements.find(e => e.hasCommentButton); + if (!element) { + return; + } + this.#commentButtonPosition = element._normalizePoint(element.commentButtonPosition); + } + renderCommentButton() { + if (this.#commentButton) { + if (!this.#commentButton.parentNode) { + this.#firstElement.container.after(this.#commentButton); + } + return; + } + if (!this.#commentButtonPosition) { + this.#setCommentButtonPosition(); + } + if (!this.#commentButtonPosition) { + return; + } + const { + signal + } = this.#popupAbortController = new AbortController(); + const hasOwnButton = this.#firstElement.hasOwnCommentButton; + const togglePopup = () => { + this.#commentManager.toggleCommentPopup(this, true, undefined, !hasOwnButton); + }; + const showPopup = () => { + this.#commentManager.toggleCommentPopup(this, false, true, !hasOwnButton); + }; + const hidePopup = () => { + this.#commentManager.toggleCommentPopup(this, false, false); + }; + if (!hasOwnButton) { + const button = this.#commentButton = document.createElement("button"); + button.className = "annotationCommentButton"; + const parentContainer = this.#firstElement.container; + button.style.zIndex = parentContainer.style.zIndex + 1; + button.tabIndex = 0; + button.ariaHasPopup = "dialog"; + button.ariaControls = "commentPopup"; + button.setAttribute("data-l10n-id", "pdfjs-show-comment-button"); + this.#updateColor(); + this.#updateCommentButtonPosition(); + button.addEventListener("keydown", this.#boundKeyDown, { + signal + }); + button.addEventListener("click", togglePopup, { + signal + }); + button.addEventListener("pointerenter", showPopup, { + signal + }); + button.addEventListener("pointerleave", hidePopup, { + signal + }); + parentContainer.after(button); + } else { + this.#commentButton = this.#firstElement.container; + for (const element of this.trigger) { + element.ariaHasPopup = "dialog"; + element.ariaControls = "commentPopup"; + element.addEventListener("keydown", this.#boundKeyDown, { + signal + }); + element.addEventListener("click", togglePopup, { + signal + }); + element.addEventListener("pointerenter", showPopup, { + signal + }); + element.addEventListener("pointerleave", hidePopup, { + signal + }); + element.classList.add("popupTriggerArea"); + } + } + } + #updateCommentButtonPosition() { + if (this.#firstElement.extraPopupElement && !this.#firstElement.editor) { + return; + } + if (!this.#commentButton) { + this.renderCommentButton(); + } + const [x, y] = this.#commentButtonPosition; + const { + style + } = this.#commentButton; + style.left = `calc(${x}%)`; + style.top = `calc(${y}% - var(--comment-button-dim))`; + } + #updateColor() { + if (this.#firstElement.extraPopupElement) { + return; + } + if (!this.#commentButton) { + this.renderCommentButton(); + } + this.#commentButton.style.backgroundColor = this.commentButtonColor || ""; + } + get commentButtonColor() { + const { + color, + opacity + } = this.#firstElement.commentData; + if (!color) { + return null; + } + return this.#parent._commentManager.makeCommentColor(color, opacity); + } + focusCommentButton() { + setTimeout(() => { + this.#commentButton?.focus(); + }, 0); + } + getData() { + const { + richText, + color, + opacity, + creationDate, + modificationDate + } = this.#firstElement.commentData; + return { + contentsObj: { + str: this.comment + }, + richText, + color, + opacity, + creationDate, + modificationDate + }; + } + get elementBeforePopup() { + return this.#commentButton; + } + get comment() { + this.#commentText ||= this.#firstElement.commentText; + return this.#commentText; + } + set comment(text) { + if (text === this.comment) { + return; + } + this.#firstElement.commentText = this.#commentText = text; + } + focus() { + this.#firstElement.container?.focus(); + } + get parentBoundingClientRect() { + return this.#firstElement.layer.getBoundingClientRect(); + } + setCommentButtonStates({ + selected, + hasPopup + }) { + if (!this.#commentButton) { + return; + } + this.#commentButton.classList.toggle("selected", selected); + this.#commentButton.ariaExpanded = hasPopup; + } + setSelectedCommentButton(selected) { + this.#commentButton.classList.toggle("selected", selected); + } + get commentPopupPosition() { + if (this.#popupPosition) { + return this.#popupPosition; + } + const { + x, + y, + height + } = this.#commentButton.getBoundingClientRect(); + const { + x: parentX, + y: parentY, + width: parentWidth, + height: parentHeight + } = this.#firstElement.layer.getBoundingClientRect(); + return [(x - parentX) / parentWidth, (y + height - parentY) / parentHeight]; + } + set commentPopupPosition(pos) { + this.#popupPosition = pos; + } + hasDefaultPopupPosition() { + return this.#popupPosition === null; + } + get commentButtonPosition() { + return this.#commentButtonPosition; + } + get commentButtonWidth() { + return this.#commentButton.getBoundingClientRect().width / this.parentBoundingClientRect.width; + } + editComment(options) { + const [posX, posY] = this.#popupPosition || this.commentButtonPosition.map(x => x / 100); + const parentDimensions = this.parentBoundingClientRect; + const { + x: parentX, + y: parentY, + width: parentWidth, + height: parentHeight + } = parentDimensions; + this.#commentManager.showDialog(null, this, parentX + posX * parentWidth, parentY + posY * parentHeight, { + ...options, + parentDimensions + }); + } + render() { + if (this.#popup) { + return; + } + const popup = this.#popup = document.createElement("div"); + popup.className = "popup"; + if (this.#color) { + const baseColor = popup.style.outlineColor = Util.makeHexColor(...this.#color); + popup.style.backgroundColor = `color-mix(in srgb, ${baseColor} 30%, white)`; + } + const header = document.createElement("span"); + header.className = "header"; + if (this.#titleObj?.str) { + const title = document.createElement("span"); + title.className = "title"; + header.append(title); + ({ + dir: title.dir, + str: title.textContent + } = this.#titleObj); + } + popup.append(header); + if (this.#dateObj) { + const modificationDate = document.createElement("time"); + modificationDate.className = "popupDate"; + modificationDate.setAttribute("data-l10n-id", "pdfjs-annotation-date-time-string"); + modificationDate.setAttribute("data-l10n-args", JSON.stringify({ + dateObj: this.#dateObj.valueOf() + })); + modificationDate.dateTime = this.#dateObj.toISOString(); + header.append(modificationDate); + } + renderRichText({ + html: this.#html || this.#contentsObj.str, + dir: this.#contentsObj?.dir, + className: "popupContent" + }, popup); + this.#container.append(popup); + } + get #html() { + const richText = this.#richText; + const contentsObj = this.#contentsObj; + if (richText?.str && (!contentsObj?.str || contentsObj.str === richText.str)) { + return this.#richText.html || null; + } + return null; + } + get #fontSize() { + return this.#html?.attributes?.style?.fontSize || 0; + } + get #fontColor() { + return this.#html?.attributes?.style?.color || null; + } + #makePopupContent(text) { + const popupLines = []; + const popupContent = { + str: text, + html: { + name: "div", + attributes: { + dir: "auto" + }, + children: [{ + name: "p", + children: popupLines + }] + } + }; + const lineAttributes = { + style: { + color: this.#fontColor, + fontSize: this.#fontSize ? `calc(${this.#fontSize}px * var(--total-scale-factor))` : "" + } + }; + for (const line of text.split("\n")) { + popupLines.push({ + name: "span", + value: line, + attributes: lineAttributes + }); + } + return popupContent; + } + #keyDown(event) { + if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) { + return; + } + if (event.key === "Enter" || event.key === "Escape" && this.#pinned) { + this.#toggle(); + } + } + updateEdited({ + rect, + popup, + deleted + }) { + if (this.#commentManager) { + if (deleted) { + this.remove(); + this.#commentText = null; + } else if (popup) { + if (popup.deleted) { + this.remove(); + } else { + this.#updateColor(); + this.#commentText = popup.text; + } + } + if (rect) { + this.#commentButtonPosition = null; + this.#setCommentButtonPosition(); + this.#updateCommentButtonPosition(); + } + return; + } + if (deleted || popup?.deleted) { + this.remove(); + return; + } + this.#addEventListeners(); + this.#updates ||= { + contentsObj: this.#contentsObj, + richText: this.#richText + }; + if (rect) { + this.#position = null; + } + if (popup && popup.text) { + this.#richText = this.#makePopupContent(popup.text); + this.#dateObj = PDFDateString.toDateObject(popup.date); + this.#contentsObj = null; + } + this.#popup?.remove(); + this.#popup = null; + } + resetEdited() { + if (!this.#updates) { + return; + } + ({ + contentsObj: this.#contentsObj, + richText: this.#richText + } = this.#updates); + this.#updates = null; + this.#popup?.remove(); + this.#popup = null; + this.#position = null; + } + remove() { + this.#popupAbortController?.abort(); + this.#popupAbortController = null; + this.#popup?.remove(); + this.#popup = null; + this.#wasVisible = false; + this.#pinned = false; + this.#commentButton?.remove(); + this.#commentButton = null; + if (this.trigger) { + for (const element of this.trigger) { + element.classList.remove("popupTriggerArea"); + } + } + } + #setPosition() { + if (this.#position !== null) { + return; + } + const { + page: { + view + }, + viewport: { + rawDims: { + pageWidth, + pageHeight, + pageX, + pageY + } + } + } = this.#parent; + let useParentRect = !!this.#parentRect; + let rect = useParentRect ? this.#parentRect : this.#rect; + for (const element of this.#elements) { + if (!rect || Util.intersect(element.data.rect, rect) !== null) { + rect = element.data.rect; + useParentRect = true; + break; + } + } + const normalizedRect = Util.normalizeRect([rect[0], view[3] - rect[1] + view[1], rect[2], view[3] - rect[3] + view[1]]); + const HORIZONTAL_SPACE_AFTER_ANNOTATION = 5; + const parentWidth = useParentRect ? rect[2] - rect[0] + HORIZONTAL_SPACE_AFTER_ANNOTATION : 0; + const popupLeft = normalizedRect[0] + parentWidth; + const popupTop = normalizedRect[1]; + this.#position = [100 * (popupLeft - pageX) / pageWidth, 100 * (popupTop - pageY) / pageHeight]; + const { + style + } = this.#container; + style.left = `${this.#position[0]}%`; + style.top = `${this.#position[1]}%`; + } + #toggle() { + if (this.#commentManager) { + this.#commentManager.toggleCommentPopup(this, false); + return; + } + this.#pinned = !this.#pinned; + if (this.#pinned) { + this.#show(); + this.#container.addEventListener("click", this.#boundToggle); + this.#container.addEventListener("keydown", this.#boundKeyDown); + } else { + this.#hide(); + this.#container.removeEventListener("click", this.#boundToggle); + this.#container.removeEventListener("keydown", this.#boundKeyDown); + } + } + #show() { + if (!this.#popup) { + this.render(); + } + if (!this.isVisible) { + this.#setPosition(); + this.#container.hidden = false; + this.#container.style.zIndex = parseInt(this.#container.style.zIndex) + 1000; + } else if (this.#pinned) { + this.#container.classList.add("focused"); + } + } + #hide() { + this.#container.classList.remove("focused"); + if (this.#pinned || !this.isVisible) { + return; + } + this.#container.hidden = true; + this.#container.style.zIndex = parseInt(this.#container.style.zIndex) - 1000; + } + forceHide() { + this.#wasVisible = this.isVisible; + if (!this.#wasVisible) { + return; + } + this.#container.hidden = true; + } + maybeShow() { + if (this.#commentManager) { + return; + } + this.#addEventListeners(); + if (!this.#wasVisible) { + return; + } + if (!this.#popup) { + this.#show(); + } + this.#wasVisible = false; + this.#container.hidden = false; + } + get isVisible() { + if (this.#commentManager) { + return false; + } + return this.#container.hidden === false; + } +} +class FreeTextAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + this.textContent = parameters.data.textContent; + this.textPosition = parameters.data.textPosition; + this.annotationEditorType = AnnotationEditorType.FREETEXT; + } + render() { + this.container.classList.add("freeTextAnnotation"); + if (this.textContent) { + const content = this.contentElement = document.createElement("div"); + content.classList.add("annotationTextContent"); + content.setAttribute("role", "comment"); + for (const line of this.textContent) { + const lineSpan = document.createElement("span"); + lineSpan.textContent = line; + content.append(lineSpan); + } + this.container.append(content); + } + if (!this.data.popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + this._editOnDoubleClick(); + return this.container; + } +} +class LineAnnotationElement extends AnnotationElement { + #line = null; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + } + render() { + this.container.classList.add("lineAnnotation"); + const { + data, + width, + height + } = this; + const svg = this.svgFactory.create(width, height, true); + const line = this.#line = this.svgFactory.createElement("svg:line"); + line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]); + line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]); + line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]); + line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]); + line.setAttribute("stroke-width", data.borderStyle.width || 1); + line.setAttribute("stroke", "transparent"); + line.setAttribute("fill", "transparent"); + svg.append(line); + this.container.append(svg); + if (!data.popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + return this.container; + } + getElementsToTriggerPopup() { + return this.#line; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } +} +class SquareAnnotationElement extends AnnotationElement { + #square = null; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + } + render() { + this.container.classList.add("squareAnnotation"); + const { + data, + width, + height + } = this; + const svg = this.svgFactory.create(width, height, true); + const borderWidth = data.borderStyle.width; + const square = this.#square = this.svgFactory.createElement("svg:rect"); + square.setAttribute("x", borderWidth / 2); + square.setAttribute("y", borderWidth / 2); + square.setAttribute("width", width - borderWidth); + square.setAttribute("height", height - borderWidth); + square.setAttribute("stroke-width", borderWidth || 1); + square.setAttribute("stroke", "transparent"); + square.setAttribute("fill", "transparent"); + svg.append(square); + this.container.append(svg); + if (!data.popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + return this.container; + } + getElementsToTriggerPopup() { + return this.#square; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } +} +class CircleAnnotationElement extends AnnotationElement { + #circle = null; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + } + render() { + this.container.classList.add("circleAnnotation"); + const { + data, + width, + height + } = this; + const svg = this.svgFactory.create(width, height, true); + const borderWidth = data.borderStyle.width; + const circle = this.#circle = this.svgFactory.createElement("svg:ellipse"); + circle.setAttribute("cx", width / 2); + circle.setAttribute("cy", height / 2); + circle.setAttribute("rx", width / 2 - borderWidth / 2); + circle.setAttribute("ry", height / 2 - borderWidth / 2); + circle.setAttribute("stroke-width", borderWidth || 1); + circle.setAttribute("stroke", "transparent"); + circle.setAttribute("fill", "transparent"); + svg.append(circle); + this.container.append(svg); + if (!data.popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + return this.container; + } + getElementsToTriggerPopup() { + return this.#circle; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } +} +class PolylineAnnotationElement extends AnnotationElement { + #polyline = null; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + this.containerClassName = "polylineAnnotation"; + this.svgElementName = "svg:polyline"; + } + render() { + this.container.classList.add(this.containerClassName); + const { + data: { + rect, + vertices, + borderStyle, + popupRef + }, + width, + height + } = this; + if (!vertices) { + return this.container; + } + const svg = this.svgFactory.create(width, height, true); + let points = []; + for (let i = 0, ii = vertices.length; i < ii; i += 2) { + const x = vertices[i] - rect[0]; + const y = rect[3] - vertices[i + 1]; + points.push(`${x},${y}`); + } + points = points.join(" "); + const polyline = this.#polyline = this.svgFactory.createElement(this.svgElementName); + polyline.setAttribute("points", points); + polyline.setAttribute("stroke-width", borderStyle.width || 1); + polyline.setAttribute("stroke", "transparent"); + polyline.setAttribute("fill", "transparent"); + svg.append(polyline); + this.container.append(svg); + if (!popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + return this.container; + } + getElementsToTriggerPopup() { + return this.#polyline; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } +} +class PolygonAnnotationElement extends PolylineAnnotationElement { + constructor(parameters) { + super(parameters); + this.containerClassName = "polygonAnnotation"; + this.svgElementName = "svg:polygon"; + } +} +class CaretAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + } + render() { + this.container.classList.add("caretAnnotation"); + if (!this.data.popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + return this.container; + } +} +class InkAnnotationElement extends AnnotationElement { + #polylinesGroupElement = null; + #polylines = []; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + this.containerClassName = "inkAnnotation"; + this.svgElementName = "svg:polyline"; + this.annotationEditorType = this.data.it === "InkHighlight" ? AnnotationEditorType.HIGHLIGHT : AnnotationEditorType.INK; + } + #getTransform(rotation, rect) { + switch (rotation) { + case 90: + return { + transform: `rotate(90) translate(${-rect[0]},${rect[1]}) scale(1,-1)`, + width: rect[3] - rect[1], + height: rect[2] - rect[0] + }; + case 180: + return { + transform: `rotate(180) translate(${-rect[2]},${rect[1]}) scale(1,-1)`, + width: rect[2] - rect[0], + height: rect[3] - rect[1] + }; + case 270: + return { + transform: `rotate(270) translate(${-rect[2]},${rect[3]}) scale(1,-1)`, + width: rect[3] - rect[1], + height: rect[2] - rect[0] + }; + default: + return { + transform: `translate(${-rect[0]},${rect[3]}) scale(1,-1)`, + width: rect[2] - rect[0], + height: rect[3] - rect[1] + }; + } + } + render() { + this.container.classList.add(this.containerClassName); + const { + data: { + rect, + rotation, + inkLists, + borderStyle, + popupRef + } + } = this; + const { + transform, + width, + height + } = this.#getTransform(rotation, rect); + const svg = this.svgFactory.create(width, height, true); + const g = this.#polylinesGroupElement = this.svgFactory.createElement("svg:g"); + svg.append(g); + g.setAttribute("stroke-width", borderStyle.width || 1); + g.setAttribute("stroke-linecap", "round"); + g.setAttribute("stroke-linejoin", "round"); + g.setAttribute("stroke-miterlimit", 10); + g.setAttribute("stroke", "transparent"); + g.setAttribute("fill", "transparent"); + g.setAttribute("transform", transform); + for (let i = 0, ii = inkLists.length; i < ii; i++) { + const polyline = this.svgFactory.createElement(this.svgElementName); + this.#polylines.push(polyline); + polyline.setAttribute("points", inkLists[i].join(",")); + g.append(polyline); + } + if (!popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + this.container.append(svg); + this._editOnDoubleClick(); + return this.container; + } + updateEdited(params) { + super.updateEdited(params); + const { + thickness, + points, + rect + } = params; + const g = this.#polylinesGroupElement; + if (thickness >= 0) { + g.setAttribute("stroke-width", thickness || 1); + } + if (points) { + for (let i = 0, ii = this.#polylines.length; i < ii; i++) { + this.#polylines[i].setAttribute("points", points[i].join(",")); + } + } + if (rect) { + const { + transform, + width, + height + } = this.#getTransform(this.data.rotation, rect); + const root = g.parentElement; + root.setAttribute("viewBox", `0 0 ${width} ${height}`); + g.setAttribute("transform", transform); + } + } + getElementsToTriggerPopup() { + return this.#polylines; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } +} +class HighlightAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true, + createQuadrilaterals: true + }); + this.annotationEditorType = AnnotationEditorType.HIGHLIGHT; + } + render() { + const { + data: { + overlaidText, + popupRef + } + } = this; + if (!popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + this.container.classList.add("highlightAnnotation"); + this._editOnDoubleClick(); + if (overlaidText) { + const mark = document.createElement("mark"); + mark.classList.add("overlaidText"); + mark.textContent = overlaidText; + this.container.append(mark); + } + return this.container; + } +} +class UnderlineAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true, + createQuadrilaterals: true + }); + } + render() { + const { + data: { + overlaidText, + popupRef + } + } = this; + if (!popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + this.container.classList.add("underlineAnnotation"); + if (overlaidText) { + const underline = document.createElement("u"); + underline.classList.add("overlaidText"); + underline.textContent = overlaidText; + this.container.append(underline); + } + return this.container; + } +} +class SquigglyAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true, + createQuadrilaterals: true + }); + } + render() { + const { + data: { + overlaidText, + popupRef + } + } = this; + if (!popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + this.container.classList.add("squigglyAnnotation"); + if (overlaidText) { + const underline = document.createElement("u"); + underline.classList.add("overlaidText"); + underline.textContent = overlaidText; + this.container.append(underline); + } + return this.container; + } +} +class StrikeOutAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true, + createQuadrilaterals: true + }); + } + render() { + const { + data: { + overlaidText, + popupRef + } + } = this; + if (!popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + this.container.classList.add("strikeoutAnnotation"); + if (overlaidText) { + const strikeout = document.createElement("s"); + strikeout.classList.add("overlaidText"); + strikeout.textContent = overlaidText; + this.container.append(strikeout); + } + return this.container; + } +} +class StampAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + this.annotationEditorType = AnnotationEditorType.STAMP; + } + render() { + this.container.classList.add("stampAnnotation"); + this.container.setAttribute("role", "img"); + if (!this.data.popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + this._editOnDoubleClick(); + return this.container; + } +} +class FileAttachmentAnnotationElement extends AnnotationElement { + #trigger = null; + constructor(parameters) { + super(parameters, { + isRenderable: true + }); + const { + file + } = this.data; + this.filename = file.filename; + this.content = file.content; + this.linkService.eventBus?.dispatch("fileattachmentannotation", { + source: this, + ...file + }); + } + render() { + this.container.classList.add("fileAttachmentAnnotation"); + const { + container, + data + } = this; + let trigger; + if (data.hasAppearance || data.fillAlpha === 0) { + trigger = document.createElement("div"); + } else { + trigger = document.createElement("img"); + trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(data.name) ? "paperclip" : "pushpin"}.svg`; + if (data.fillAlpha && data.fillAlpha < 1) { + trigger.style = `filter: opacity(${Math.round(data.fillAlpha * 100)}%);`; + } + } + trigger.addEventListener("dblclick", this.#download.bind(this)); + this.#trigger = trigger; + const { + isMac + } = FeatureTest.platform; + container.addEventListener("keydown", evt => { + if (evt.key === "Enter" && (isMac ? evt.metaKey : evt.ctrlKey)) { + this.#download(); + } + }); + if (!data.popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } else { + trigger.classList.add("popupTriggerArea"); + } + container.append(trigger); + return container; + } + getElementsToTriggerPopup() { + return this.#trigger; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } + #download() { + this.downloadManager?.openOrDownloadData(this.content, this.filename); + } +} +class AnnotationLayer { + #accessibilityManager = null; + #annotationCanvasMap = null; + #annotationStorage = null; + #editableAnnotations = new Map(); + #structTreeLayer = null; + #linkService = null; + #elements = []; + #hasAriaAttributesFromStructTree = false; + constructor({ + div, + accessibilityManager, + annotationCanvasMap, + annotationEditorUIManager, + page, + viewport, + structTreeLayer, + commentManager, + linkService, + annotationStorage + }) { + this.div = div; + this.#accessibilityManager = accessibilityManager; + this.#annotationCanvasMap = annotationCanvasMap; + this.#structTreeLayer = structTreeLayer || null; + this.#linkService = linkService || null; + this.#annotationStorage = annotationStorage || new AnnotationStorage(); + this.page = page; + this.viewport = viewport; + this.zIndex = 0; + this._annotationEditorUIManager = annotationEditorUIManager; + this._commentManager = commentManager || null; + } + hasEditableAnnotations() { + return this.#editableAnnotations.size > 0; + } + async render(params) { + const { + annotations + } = params; + const layer = this.div; + setLayerDimensions(layer, this.viewport); + const popupToElements = new Map(); + const popupAnnotations = []; + const elementParams = { + data: null, + layer, + linkService: this.#linkService, + downloadManager: params.downloadManager, + imageResourcesPath: params.imageResourcesPath || "", + renderForms: params.renderForms !== false, + svgFactory: new DOMSVGFactory(), + annotationStorage: this.#annotationStorage, + enableComment: params.enableComment === true, + enableScripting: params.enableScripting === true, + hasJSActions: params.hasJSActions, + fieldObjects: params.fieldObjects, + parent: this, + elements: null + }; + for (const data of annotations) { + if (data.noHTML) { + continue; + } + const isPopupAnnotation = data.annotationType === AnnotationType.POPUP; + if (!isPopupAnnotation) { + if (data.rect[2] === data.rect[0] || data.rect[3] === data.rect[1]) { + continue; + } + } else { + const elements = popupToElements.get(data.id); + if (!elements) { + continue; + } + if (!this._commentManager) { + popupAnnotations.push(data); + continue; + } + elementParams.elements = elements; + } + elementParams.data = data; + const element = AnnotationElementFactory.create(elementParams); + if (!element.isRenderable) { + continue; + } + if (!isPopupAnnotation) { + this.#elements.push(element); + if (data.popupRef) { + popupToElements.getOrInsertComputed(data.popupRef, makeArr).push(element); + } + } + const rendered = element.render(); + if (data.hidden) { + rendered.style.visibility = "hidden"; + } + if (element._isEditable) { + this.#editableAnnotations.set(element.data.id, element); + this._annotationEditorUIManager?.renderAnnotationElement(element); + } + } + await this.#addElementsToDOM(); + for (const data of popupAnnotations) { + const elements = elementParams.elements = popupToElements.get(data.id); + elementParams.data = data; + const element = AnnotationElementFactory.create(elementParams); + if (!element.isRenderable) { + continue; + } + const rendered = element.render(); + element.contentElement.id = `${AnnotationPrefix}${data.id}`; + if (data.hidden) { + rendered.style.visibility = "hidden"; + } + elements.at(-1).container.after(rendered); + } + this.#setAnnotationCanvasMap(); + } + async #addElementsToDOM() { + if (this.#elements.length === 0) { + return; + } + this.div.replaceChildren(); + const promises = []; + if (!this.#hasAriaAttributesFromStructTree) { + this.#hasAriaAttributesFromStructTree = true; + for (const { + contentElement, + data: { + id + } + } of this.#elements) { + const annotationId = contentElement.id = `${AnnotationPrefix}${id}`; + promises.push(this.#structTreeLayer?.getAriaAttributes(annotationId).then(ariaAttributes => { + if (ariaAttributes) { + for (const [key, value] of ariaAttributes) { + contentElement.setAttribute(key, value); + } + } + })); + } + } + this.#elements.sort(({ + data: { + rect: [a0, a1, a2, a3] + } + }, { + data: { + rect: [b0, b1, b2, b3] + } + }) => { + if (a0 === a2 && a1 === a3) { + return +1; + } + if (b0 === b2 && b1 === b3) { + return -1; + } + const top1 = a3; + const bot1 = a1; + const mid1 = (a1 + a3) / 2; + const top2 = b3; + const bot2 = b1; + const mid2 = (b1 + b3) / 2; + if (mid1 >= top2 && mid2 <= bot1) { + return -1; + } + if (mid2 >= top1 && mid1 <= bot2) { + return +1; + } + const centerX1 = (a0 + a2) / 2; + const centerX2 = (b0 + b2) / 2; + return centerX1 - centerX2; + }); + const fragment = document.createDocumentFragment(); + for (const element of this.#elements) { + fragment.append(element.container); + if (this._commentManager) { + (element.extraPopupElement?.popup || element.popup)?.renderCommentButton(); + } else if (element.extraPopupElement) { + fragment.append(element.extraPopupElement.render()); + } + } + this.div.append(fragment); + await Promise.all(promises); + if (this.#accessibilityManager) { + for (const element of this.#elements) { + this.#accessibilityManager.addPointerInTextLayer(element.contentElement, false); + } + } + } + async addLinkAnnotations(annotations) { + const elementParams = { + data: null, + layer: this.div, + linkService: this.#linkService, + svgFactory: new DOMSVGFactory(), + parent: this + }; + for (const data of annotations) { + data.borderStyle ||= AnnotationLayer._defaultBorderStyle; + elementParams.data = data; + const element = AnnotationElementFactory.create(elementParams); + if (!element.isRenderable) { + continue; + } + element.render(); + element.contentElement.id = `${AnnotationPrefix}${data.id}`; + this.#elements.push(element); + } + await this.#addElementsToDOM(); + } + update({ + viewport + }) { + const layer = this.div; + this.viewport = viewport; + setLayerDimensions(layer, { + rotation: viewport.rotation + }); + this.#setAnnotationCanvasMap(); + layer.hidden = false; + } + #setAnnotationCanvasMap() { + if (!this.#annotationCanvasMap) { + return; + } + const layer = this.div; + for (const [id, canvas] of this.#annotationCanvasMap) { + const element = layer.querySelector(`[data-annotation-id="${id}"]`); + if (!element) { + continue; + } + canvas.className = "annotationContent"; + const { + firstChild + } = element; + if (!firstChild) { + element.append(canvas); + } else if (firstChild.nodeName === "CANVAS") { + firstChild.replaceWith(canvas); + } else if (!firstChild.classList.contains("annotationContent")) { + firstChild.before(canvas); + } else { + firstChild.after(canvas); + } + const editableAnnotation = this.#editableAnnotations.get(id); + if (!editableAnnotation) { + continue; + } + if (editableAnnotation._hasNoCanvas) { + this._annotationEditorUIManager?.setMissingCanvas(id, element.id, canvas); + editableAnnotation._hasNoCanvas = false; + } else { + editableAnnotation.canvas = canvas; + } + } + this.#annotationCanvasMap.clear(); + } + getEditableAnnotations() { + return Array.from(this.#editableAnnotations.values()); + } + getEditableAnnotation(id) { + return this.#editableAnnotations.get(id); + } + addFakeAnnotation(editor) { + const { + div + } = this; + const { + id, + rotation + } = editor; + const element = new EditorAnnotationElement({ + data: { + id, + rect: editor.getPDFRect(), + rotation + }, + editor, + layer: div, + parent: this, + enableComment: !!this._commentManager, + linkService: this.#linkService, + annotationStorage: this.#annotationStorage + }); + element.render(); + element.contentElement.id = `${AnnotationPrefix}${id}`; + element.createOrUpdatePopup(); + this.#elements.push(element); + return element; + } + removeAnnotation(id) { + const index = this.#elements.findIndex(el => el.data.id === id); + if (index < 0) { + return; + } + const [element] = this.#elements.splice(index, 1); + this.#accessibilityManager?.removePointerInTextLayer(element.contentElement); + } + updateFakeAnnotations(editors) { + if (editors.length === 0) { + return; + } + for (const editor of editors) { + editor.updateFakeAnnotationElement(this); + } + this.#addElementsToDOM(); + } + togglePointerEvents(enabled = false) { + this.div.classList.toggle("disabled", !enabled); + } + static get _defaultBorderStyle() { + return shadow(this, "_defaultBorderStyle", Object.freeze({ + width: 1, + rawWidth: 1, + style: AnnotationBorderStyleType.SOLID, + dashArray: [3], + horizontalCornerRadius: 0, + verticalCornerRadius: 0 + })); + } +} + +;// ./src/display/editor/freetext.js + + + + + +const EOL_PATTERN = /\r\n?|\n/g; +class FreeTextEditor extends AnnotationEditor { + #content = ""; + #editorDivId = `${this.id}-editor`; + #editModeAC = null; + #fontSize; + _colorPicker = null; + static _freeTextDefaultContent = ""; + static _internalPadding = 0; + static _defaultColor = null; + static _defaultFontSize = 10; + static get _keyboardManager() { + const proto = FreeTextEditor.prototype; + const arrowChecker = self => self.isEmpty(); + const small = AnnotationEditorUIManager.TRANSLATE_SMALL; + const big = AnnotationEditorUIManager.TRANSLATE_BIG; + return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+s", "mac+meta+s", "ctrl+p", "mac+meta+p"], proto.commitOrRemove, { + bubbles: true + }], [["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], proto.commitOrRemove], [["ArrowLeft", "mac+ArrowLeft"], proto._translateEmpty, { + args: [-small, 0], + checker: arrowChecker + }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto._translateEmpty, { + args: [-big, 0], + checker: arrowChecker + }], [["ArrowRight", "mac+ArrowRight"], proto._translateEmpty, { + args: [small, 0], + checker: arrowChecker + }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto._translateEmpty, { + args: [big, 0], + checker: arrowChecker + }], [["ArrowUp", "mac+ArrowUp"], proto._translateEmpty, { + args: [0, -small], + checker: arrowChecker + }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto._translateEmpty, { + args: [0, -big], + checker: arrowChecker + }], [["ArrowDown", "mac+ArrowDown"], proto._translateEmpty, { + args: [0, small], + checker: arrowChecker + }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto._translateEmpty, { + args: [0, big], + checker: arrowChecker + }]])); + } + static _type = "freetext"; + static _editorType = AnnotationEditorType.FREETEXT; + constructor(params) { + super({ + ...params, + name: "freeTextEditor" + }); + this.color = params.color || FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor; + this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize; + if (!this.annotationElementId) { + this._uiManager.a11yAlert("pdfjs-editor-freetext-added-alert"); + } + this.canAddComment = false; + } + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager); + const style = getComputedStyle(document.documentElement); + this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding")); + } + static updateDefaultParams(type, value) { + switch (type) { + case AnnotationEditorParamsType.FREETEXT_SIZE: + FreeTextEditor._defaultFontSize = value; + break; + case AnnotationEditorParamsType.FREETEXT_COLOR: + FreeTextEditor._defaultColor = value; + break; + } + } + updateParams(type, value) { + switch (type) { + case AnnotationEditorParamsType.FREETEXT_SIZE: + this.#updateFontSize(value); + break; + case AnnotationEditorParamsType.FREETEXT_COLOR: + this.#updateColor(value); + break; + } + } + static get defaultPropertiesToUpdate() { + return [[AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor]]; + } + get propertiesToUpdate() { + return [[AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, this.color]]; + } + get toolbarButtons() { + this._colorPicker ||= new BasicColorPicker(this); + return [["colorPicker", this._colorPicker]]; + } + get colorType() { + return AnnotationEditorParamsType.FREETEXT_COLOR; + } + #updateFontSize(fontSize) { + const setFontsize = size => { + this.editorDiv.style.fontSize = `calc(${size}px * var(--total-scale-factor))`; + this.translate(0, -(size - this.#fontSize) * this.parentScale); + this.#fontSize = size; + this.#setEditorDimensions(); + }; + const savedFontsize = this.#fontSize; + this.addCommands({ + cmd: setFontsize.bind(this, fontSize), + undo: setFontsize.bind(this, savedFontsize), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type: AnnotationEditorParamsType.FREETEXT_SIZE, + overwriteIfSameType: true, + keepUndo: true + }); + } + onUpdatedColor() { + this.editorDiv.style.color = this.color; + this._colorPicker?.update(this.color); + super.onUpdatedColor(); + } + #updateColor(color) { + const setColor = col => { + this.color = col; + this.onUpdatedColor(); + }; + const savedColor = this.color; + this.addCommands({ + cmd: setColor.bind(this, color), + undo: setColor.bind(this, savedColor), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type: AnnotationEditorParamsType.FREETEXT_COLOR, + overwriteIfSameType: true, + keepUndo: true + }); + } + _translateEmpty(x, y) { + this._uiManager.translateSelectedEditors(x, y, true); + } + getInitialTranslation() { + const scale = this.parentScale; + return [-FreeTextEditor._internalPadding * scale, -(FreeTextEditor._internalPadding + this.#fontSize) * scale]; + } + rebuild() { + if (!this.parent) { + return; + } + super.rebuild(); + if (this.div === null) { + return; + } + if (!this.isAttachedToDOM) { + this.parent.add(this); + } + } + enableEditMode() { + if (!super.enableEditMode()) { + return false; + } + this.overlayDiv.classList.remove("enabled"); + this.editorDiv.contentEditable = true; + this._isDraggable = false; + this.div.removeAttribute("aria-activedescendant"); + this.#editModeAC = new AbortController(); + const signal = this._uiManager.combinedSignal(this.#editModeAC); + this.editorDiv.addEventListener("keydown", this.editorDivKeydown.bind(this), { + signal + }); + this.editorDiv.addEventListener("focus", this.editorDivFocus.bind(this), { + signal + }); + this.editorDiv.addEventListener("blur", this.editorDivBlur.bind(this), { + signal + }); + this.editorDiv.addEventListener("input", this.editorDivInput.bind(this), { + signal + }); + this.editorDiv.addEventListener("paste", this.editorDivPaste.bind(this), { + signal + }); + return true; + } + disableEditMode() { + if (!super.disableEditMode()) { + return false; + } + this.overlayDiv.classList.add("enabled"); + this.editorDiv.contentEditable = false; + this.div.setAttribute("aria-activedescendant", this.#editorDivId); + this._isDraggable = true; + this.#editModeAC?.abort(); + this.#editModeAC = null; + this.div.focus({ + preventScroll: true + }); + this.isEditing = false; + this.parent.div.classList.add("freetextEditing"); + return true; + } + focusin(event) { + if (!this._focusEventsAllowed) { + return; + } + super.focusin(event); + if (event.target !== this.editorDiv) { + this.editorDiv.focus(); + } + } + onceAdded(focus) { + if (this.width) { + return; + } + this.enableEditMode(); + if (focus) { + this.editorDiv.focus(); + } + if (this._initialOptions?.isCentered) { + this.center(); + } + this._initialOptions = null; + } + isEmpty() { + return !this.editorDiv || this.editorDiv.innerText.trim() === ""; + } + remove() { + this.isEditing = false; + if (this.parent) { + this.parent.setEditingState(true); + this.parent.div.classList.add("freetextEditing"); + } + super.remove(); + } + #extractText() { + const buffer = []; + this.editorDiv.normalize(); + let prevChild = null; + for (const child of this.editorDiv.childNodes) { + if (prevChild?.nodeType === Node.TEXT_NODE && child.nodeName === "BR") { + continue; + } + buffer.push(FreeTextEditor.#getNodeContent(child)); + prevChild = child; + } + return buffer.join("\n"); + } + #setEditorDimensions() { + const [parentWidth, parentHeight] = this.parentDimensions; + let rect; + if (this.isAttachedToDOM) { + rect = this.div.getBoundingClientRect(); + } else { + const { + currentLayer, + div + } = this; + const savedDisplay = div.style.display; + const savedVisibility = div.classList.contains("hidden"); + div.classList.remove("hidden"); + div.style.display = "hidden"; + currentLayer.div.append(this.div); + rect = div.getBoundingClientRect(); + div.remove(); + div.style.display = savedDisplay; + div.classList.toggle("hidden", savedVisibility); + } + if (this.rotation % 180 === this.parentRotation % 180) { + this.width = rect.width / parentWidth; + this.height = rect.height / parentHeight; + } else { + this.width = rect.height / parentWidth; + this.height = rect.width / parentHeight; + } + this.fixAndSetPosition(); + } + commit() { + if (!this.isInEditMode()) { + return; + } + super.commit(); + this.disableEditMode(); + const savedText = this.#content; + const newText = this.#content = this.#extractText().trimEnd(); + if (savedText === newText) { + return; + } + const setText = text => { + this.#content = text; + if (!text) { + this.remove(); + return; + } + this.#setContent(); + this._uiManager.rebuild(this); + this.#setEditorDimensions(); + }; + this.addCommands({ + cmd: () => { + setText(newText); + }, + undo: () => { + setText(savedText); + }, + mustExec: false + }); + this.#setEditorDimensions(); + } + shouldGetKeyboardEvents() { + return this.isInEditMode(); + } + enterInEditMode() { + this.enableEditMode(); + this.editorDiv.focus(); + } + keydown(event) { + if (event.target === this.div && event.key === "Enter") { + this.enterInEditMode(); + event.preventDefault(); + } + } + editorDivKeydown(event) { + FreeTextEditor._keyboardManager.exec(this, event); + } + editorDivFocus(event) { + this.isEditing = true; + } + editorDivBlur(event) { + this.isEditing = false; + } + editorDivInput(event) { + this.parent.div.classList.toggle("freetextEditing", this.isEmpty()); + } + disableEditing() { + this.editorDiv.setAttribute("role", "comment"); + this.editorDiv.removeAttribute("aria-multiline"); + } + enableEditing() { + this.editorDiv.setAttribute("role", "textbox"); + this.editorDiv.setAttribute("aria-multiline", true); + } + get canChangeContent() { + return true; + } + render() { + if (this.div) { + return this.div; + } + let baseX, baseY; + if (this._isCopy || this.annotationElementId) { + baseX = this.x; + baseY = this.y; + } + super.render(); + this.editorDiv = document.createElement("div"); + this.editorDiv.className = "internal"; + this.editorDiv.setAttribute("id", this.#editorDivId); + this.editorDiv.setAttribute("data-l10n-id", "pdfjs-free-text2"); + this.editorDiv.setAttribute("data-l10n-attrs", "default-content"); + this.enableEditing(); + this.editorDiv.contentEditable = true; + const { + style + } = this.editorDiv; + style.fontSize = `calc(${this.#fontSize}px * var(--total-scale-factor))`; + style.color = this.color; + this.div.append(this.editorDiv); + this.overlayDiv = document.createElement("div"); + this.overlayDiv.classList.add("overlay", "enabled"); + this.div.append(this.overlayDiv); + if (this._isCopy || this.annotationElementId) { + const [parentWidth, parentHeight] = this.parentDimensions; + if (this.annotationElementId) { + const { + position + } = this._initialData; + let [tx, ty] = this.getInitialTranslation(); + [tx, ty] = this.pageTranslationToScreen(tx, ty); + const [pageWidth, pageHeight] = this.pageDimensions; + const [pageX, pageY] = this.pageTranslation; + let posX, posY; + switch (this.rotation) { + case 0: + posX = baseX + (position[0] - pageX) / pageWidth; + posY = baseY + this.height - (position[1] - pageY) / pageHeight; + break; + case 90: + posX = baseX + (position[0] - pageX) / pageWidth; + posY = baseY - (position[1] - pageY) / pageHeight; + [tx, ty] = [ty, -tx]; + break; + case 180: + posX = baseX - this.width + (position[0] - pageX) / pageWidth; + posY = baseY - (position[1] - pageY) / pageHeight; + [tx, ty] = [-tx, -ty]; + break; + case 270: + posX = baseX + (position[0] - pageX - this.height * pageHeight) / pageWidth; + posY = baseY + (position[1] - pageY - this.width * pageWidth) / pageHeight; + [tx, ty] = [-ty, tx]; + break; + } + this.setAt(posX * parentWidth, posY * parentHeight, tx, ty); + } else { + this._moveAfterPaste(baseX, baseY); + } + this.#setContent(); + this._isDraggable = true; + this.editorDiv.contentEditable = false; + } else { + this._isDraggable = false; + this.editorDiv.contentEditable = true; + } + return this.div; + } + static #getNodeContent(node) { + return (node.nodeType === Node.TEXT_NODE ? node.nodeValue : node.innerText).replaceAll(EOL_PATTERN, ""); + } + editorDivPaste(event) { + const clipboardData = event.clipboardData || window.clipboardData; + const { + types + } = clipboardData; + if (types.length === 1 && types[0] === "text/plain") { + return; + } + event.preventDefault(); + const paste = FreeTextEditor.#deserializeContent(clipboardData.getData("text") || "").replaceAll(EOL_PATTERN, "\n"); + if (!paste) { + return; + } + const selection = window.getSelection(); + if (!selection.rangeCount) { + return; + } + this.editorDiv.normalize(); + selection.deleteFromDocument(); + const range = selection.getRangeAt(0); + if (!paste.includes("\n")) { + range.insertNode(document.createTextNode(paste)); + this.editorDiv.normalize(); + selection.collapseToStart(); + return; + } + const { + startContainer, + startOffset + } = range; + const bufferBefore = []; + const bufferAfter = []; + if (startContainer.nodeType === Node.TEXT_NODE) { + const parent = startContainer.parentElement; + bufferAfter.push(startContainer.nodeValue.slice(startOffset).replaceAll(EOL_PATTERN, "")); + if (parent !== this.editorDiv) { + let buffer = bufferBefore; + for (const child of this.editorDiv.childNodes) { + if (child === parent) { + buffer = bufferAfter; + continue; + } + buffer.push(FreeTextEditor.#getNodeContent(child)); + } + } + bufferBefore.push(startContainer.nodeValue.slice(0, startOffset).replaceAll(EOL_PATTERN, "")); + } else if (startContainer === this.editorDiv) { + let buffer = bufferBefore; + let i = 0; + for (const child of this.editorDiv.childNodes) { + if (i++ === startOffset) { + buffer = bufferAfter; + } + buffer.push(FreeTextEditor.#getNodeContent(child)); + } + } + this.#content = `${bufferBefore.join("\n")}${paste}${bufferAfter.join("\n")}`; + this.#setContent(); + const newRange = new Range(); + let beforeLength = Math.sumPrecise(bufferBefore.map(line => line.length)); + for (const { + firstChild + } of this.editorDiv.childNodes) { + if (firstChild.nodeType === Node.TEXT_NODE) { + const length = firstChild.nodeValue.length; + if (beforeLength <= length) { + newRange.setStart(firstChild, beforeLength); + newRange.setEnd(firstChild, beforeLength); + break; + } + beforeLength -= length; + } + } + selection.removeAllRanges(); + selection.addRange(newRange); + } + #setContent() { + this.editorDiv.replaceChildren(); + if (!this.#content) { + return; + } + for (const line of this.#content.split("\n")) { + const div = document.createElement("div"); + div.append(line ? document.createTextNode(line) : document.createElement("br")); + this.editorDiv.append(div); + } + } + #serializeContent() { + return this.#content.replaceAll("\xa0", " "); + } + static #deserializeContent(content) { + return content.replaceAll(" ", "\xa0"); + } + get contentDiv() { + return this.editorDiv; + } + getPDFRect() { + const padding = FreeTextEditor._internalPadding * this.parentScale; + return this.getRect(padding, padding); + } + static async deserialize(data, parent, uiManager) { + let initialData = null; + if (data instanceof FreeTextAnnotationElement) { + const { + data: { + defaultAppearanceData: { + fontSize, + fontColor + }, + rect, + rotation, + id, + popupRef, + richText, + contentsObj, + creationDate, + modificationDate + }, + textContent, + textPosition, + parent: { + page: { + pageNumber + } + } + } = data; + if (!textContent || textContent.length === 0) { + return null; + } + initialData = data = { + annotationType: AnnotationEditorType.FREETEXT, + color: Array.from(fontColor), + fontSize, + value: textContent.join("\n"), + position: textPosition, + pageIndex: pageNumber - 1, + rect: rect.slice(0), + rotation, + annotationElementId: id, + id, + deleted: false, + popupRef, + comment: contentsObj?.str || null, + richText, + creationDate, + modificationDate + }; + } + const editor = await super.deserialize(data, parent, uiManager); + editor.#fontSize = data.fontSize; + editor.color = Util.makeHexColor(...data.color); + editor.#content = FreeTextEditor.#deserializeContent(data.value); + editor._initialData = initialData; + if (data.comment) { + editor.setCommentData(data); + } + return editor; + } + serialize(isForCopying = false) { + if (this.isEmpty()) { + return null; + } + if (this.deleted) { + return this.serializeDeleted(); + } + const color = AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.color); + const serialized = Object.assign(super.serialize(isForCopying), { + color, + fontSize: this.#fontSize, + value: this.#serializeContent() + }); + this.addComment(serialized); + if (isForCopying) { + serialized.isCopy = true; + return serialized; + } + if (this.annotationElementId && !this.#hasElementChanged(serialized)) { + return null; + } + serialized.id = this.annotationElementId; + return serialized; + } + #hasElementChanged(serialized) { + const { + value, + fontSize, + color, + pageIndex + } = this._initialData; + return this.hasEditedComment || this._hasBeenMoved || serialized.value !== value || serialized.fontSize !== fontSize || serialized.color.some((c, i) => c !== color[i]) || serialized.pageIndex !== pageIndex; + } + renderAnnotationElement(annotation) { + const content = super.renderAnnotationElement(annotation); + if (!content) { + return null; + } + const { + style + } = content; + style.fontSize = `calc(${this.#fontSize}px * var(--total-scale-factor))`; + style.color = this.color; + content.replaceChildren(); + for (const line of this.#content.split("\n")) { + const div = document.createElement("div"); + div.append(line ? document.createTextNode(line) : document.createElement("br")); + content.append(div); + } + annotation.updateEdited({ + rect: this.getPDFRect(), + popup: this._uiManager.hasCommentManager() || this.hasEditedComment ? this.comment : { + text: this.#content + } + }); + return content; + } + resetAnnotationElement(annotation) { + super.resetAnnotationElement(annotation); + annotation.resetEdited(); + } +} + +;// ./src/display/editor/drawers/outline.js + +class Outline { + static PRECISION = 1e-4; + toSVGPath() { + unreachable("Abstract method `toSVGPath` must be implemented."); + } + get box() { + unreachable("Abstract getter `box` must be implemented."); + } + serialize(_bbox, _rotation) { + unreachable("Abstract method `serialize` must be implemented."); + } + static _rescale(src, tx, ty, sx, sy, dest) { + dest ||= new Float32Array(src.length); + for (let i = 0, ii = src.length; i < ii; i += 2) { + dest[i] = tx + src[i] * sx; + dest[i + 1] = ty + src[i + 1] * sy; + } + return dest; + } + static _rescaleAndSwap(src, tx, ty, sx, sy, dest) { + dest ||= new Float32Array(src.length); + for (let i = 0, ii = src.length; i < ii; i += 2) { + dest[i] = tx + src[i + 1] * sx; + dest[i + 1] = ty + src[i] * sy; + } + return dest; + } + static _translate(src, tx, ty, dest) { + dest ||= new Float32Array(src.length); + for (let i = 0, ii = src.length; i < ii; i += 2) { + dest[i] = tx + src[i]; + dest[i + 1] = ty + src[i + 1]; + } + return dest; + } + static svgRound(x) { + return Math.round(x * 10000); + } + static _normalizePoint(x, y, parentWidth, parentHeight, rotation) { + switch (rotation) { + case 90: + return [1 - y / parentWidth, x / parentHeight]; + case 180: + return [1 - x / parentWidth, 1 - y / parentHeight]; + case 270: + return [y / parentWidth, 1 - x / parentHeight]; + default: + return [x / parentWidth, y / parentHeight]; + } + } + static _normalizePagePoint(x, y, rotation) { + switch (rotation) { + case 90: + return [1 - y, x]; + case 180: + return [1 - x, 1 - y]; + case 270: + return [y, 1 - x]; + default: + return [x, y]; + } + } + static createBezierPoints(x1, y1, x2, y2, x3, y3) { + return [(x1 + 5 * x2) / 6, (y1 + 5 * y2) / 6, (5 * x2 + x3) / 6, (5 * y2 + y3) / 6, (x2 + x3) / 2, (y2 + y3) / 2]; + } +} + +;// ./src/display/editor/drawers/freedraw.js + + +class FreeDrawOutliner { + #box; + #bottom = []; + #innerMargin; + #isLTR; + #top = []; + #last = new Float32Array(18); + #lastX; + #lastY; + #min; + #min_dist; + #scaleFactor; + #thickness; + #points = []; + static #MIN_DIST = 8; + static #MIN_DIFF = 2; + static #MIN = FreeDrawOutliner.#MIN_DIST + FreeDrawOutliner.#MIN_DIFF; + constructor({ + x, + y + }, box, scaleFactor, thickness, isLTR, innerMargin = 0) { + this.#box = box; + this.#thickness = thickness * scaleFactor; + this.#isLTR = isLTR; + this.#last.set([NaN, NaN, NaN, NaN, x, y], 6); + this.#innerMargin = innerMargin; + this.#min_dist = FreeDrawOutliner.#MIN_DIST * scaleFactor; + this.#min = FreeDrawOutliner.#MIN * scaleFactor; + this.#scaleFactor = scaleFactor; + this.#points.push(x, y); + } + isEmpty() { + return isNaN(this.#last[8]); + } + #getLastCoords() { + const lastTop = this.#last.subarray(4, 6); + const lastBottom = this.#last.subarray(16, 18); + const [x, y, width, height] = this.#box; + return [(this.#lastX + (lastTop[0] - lastBottom[0]) / 2 - x) / width, (this.#lastY + (lastTop[1] - lastBottom[1]) / 2 - y) / height, (this.#lastX + (lastBottom[0] - lastTop[0]) / 2 - x) / width, (this.#lastY + (lastBottom[1] - lastTop[1]) / 2 - y) / height]; + } + add({ + x, + y + }) { + this.#lastX = x; + this.#lastY = y; + const [layerX, layerY, layerWidth, layerHeight] = this.#box; + let [x1, y1, x2, y2] = this.#last.subarray(8, 12); + const diffX = x - x2; + const diffY = y - y2; + const d = Math.hypot(diffX, diffY); + if (d < this.#min) { + return false; + } + const diffD = d - this.#min_dist; + const K = diffD / d; + const shiftX = K * diffX; + const shiftY = K * diffY; + let x0 = x1; + let y0 = y1; + x1 = x2; + y1 = y2; + x2 += shiftX; + y2 += shiftY; + this.#points?.push(x, y); + const nX = -shiftY / diffD; + const nY = shiftX / diffD; + const thX = nX * this.#thickness; + const thY = nY * this.#thickness; + this.#last.set(this.#last.subarray(2, 8), 0); + this.#last.set([x2 + thX, y2 + thY], 4); + this.#last.set(this.#last.subarray(14, 18), 12); + this.#last.set([x2 - thX, y2 - thY], 16); + if (isNaN(this.#last[6])) { + if (this.#top.length === 0) { + this.#last.set([x1 + thX, y1 + thY], 2); + this.#top.push(NaN, NaN, NaN, NaN, (x1 + thX - layerX) / layerWidth, (y1 + thY - layerY) / layerHeight); + this.#last.set([x1 - thX, y1 - thY], 14); + this.#bottom.push(NaN, NaN, NaN, NaN, (x1 - thX - layerX) / layerWidth, (y1 - thY - layerY) / layerHeight); + } + this.#last.set([x0, y0, x1, y1, x2, y2], 6); + return !this.isEmpty(); + } + this.#last.set([x0, y0, x1, y1, x2, y2], 6); + const angle = Math.abs(Math.atan2(y0 - y1, x0 - x1) - Math.atan2(shiftY, shiftX)); + if (angle < Math.PI / 2) { + [x1, y1, x2, y2] = this.#last.subarray(2, 6); + this.#top.push(NaN, NaN, NaN, NaN, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight); + [x1, y1, x0, y0] = this.#last.subarray(14, 18); + this.#bottom.push(NaN, NaN, NaN, NaN, ((x0 + x1) / 2 - layerX) / layerWidth, ((y0 + y1) / 2 - layerY) / layerHeight); + return true; + } + [x0, y0, x1, y1, x2, y2] = this.#last.subarray(0, 6); + this.#top.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x2) / 6 - layerX) / layerWidth, ((5 * y1 + y2) / 6 - layerY) / layerHeight, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight); + [x2, y2, x1, y1, x0, y0] = this.#last.subarray(12, 18); + this.#bottom.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x2) / 6 - layerX) / layerWidth, ((5 * y1 + y2) / 6 - layerY) / layerHeight, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight); + return true; + } + toSVGPath() { + if (this.isEmpty()) { + return ""; + } + const top = this.#top; + const bottom = this.#bottom; + if (isNaN(this.#last[6]) && !this.isEmpty()) { + return this.#toSVGPathTwoPoints(); + } + const buffer = []; + buffer.push(`M${top[4]} ${top[5]}`); + for (let i = 6; i < top.length; i += 6) { + if (isNaN(top[i])) { + buffer.push(`L${top[i + 4]} ${top[i + 5]}`); + } else { + buffer.push(`C${top[i]} ${top[i + 1]} ${top[i + 2]} ${top[i + 3]} ${top[i + 4]} ${top[i + 5]}`); + } + } + this.#toSVGPathEnd(buffer); + for (let i = bottom.length - 6; i >= 6; i -= 6) { + if (isNaN(bottom[i])) { + buffer.push(`L${bottom[i + 4]} ${bottom[i + 5]}`); + } else { + buffer.push(`C${bottom[i]} ${bottom[i + 1]} ${bottom[i + 2]} ${bottom[i + 3]} ${bottom[i + 4]} ${bottom[i + 5]}`); + } + } + this.#toSVGPathStart(buffer); + return buffer.join(" "); + } + #toSVGPathTwoPoints() { + const [x, y, width, height] = this.#box; + const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords(); + return `M${(this.#last[2] - x) / width} ${(this.#last[3] - y) / height} L${(this.#last[4] - x) / width} ${(this.#last[5] - y) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(this.#last[16] - x) / width} ${(this.#last[17] - y) / height} L${(this.#last[14] - x) / width} ${(this.#last[15] - y) / height} Z`; + } + #toSVGPathStart(buffer) { + const bottom = this.#bottom; + buffer.push(`L${bottom[4]} ${bottom[5]} Z`); + } + #toSVGPathEnd(buffer) { + const [x, y, width, height] = this.#box; + const lastTop = this.#last.subarray(4, 6); + const lastBottom = this.#last.subarray(16, 18); + const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords(); + buffer.push(`L${(lastTop[0] - x) / width} ${(lastTop[1] - y) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(lastBottom[0] - x) / width} ${(lastBottom[1] - y) / height}`); + } + newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) { + return new FreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR); + } + getOutlines() { + const top = this.#top; + const bottom = this.#bottom; + const last = this.#last; + const [layerX, layerY, layerWidth, layerHeight] = this.#box; + const points = new Float32Array((this.#points?.length ?? 0) + 2); + for (let i = 0, ii = points.length - 2; i < ii; i += 2) { + points[i] = (this.#points[i] - layerX) / layerWidth; + points[i + 1] = (this.#points[i + 1] - layerY) / layerHeight; + } + points[points.length - 2] = (this.#lastX - layerX) / layerWidth; + points[points.length - 1] = (this.#lastY - layerY) / layerHeight; + if (isNaN(last[6]) && !this.isEmpty()) { + return this.#getOutlineTwoPoints(points); + } + const outline = new Float32Array(this.#top.length + 24 + this.#bottom.length); + let N = top.length; + for (let i = 0; i < N; i += 2) { + if (isNaN(top[i])) { + outline[i] = outline[i + 1] = NaN; + continue; + } + outline[i] = top[i]; + outline[i + 1] = top[i + 1]; + } + N = this.#getOutlineEnd(outline, N); + for (let i = bottom.length - 6; i >= 6; i -= 6) { + for (let j = 0; j < 6; j += 2) { + if (isNaN(bottom[i + j])) { + outline[N] = outline[N + 1] = NaN; + N += 2; + continue; + } + outline[N] = bottom[i + j]; + outline[N + 1] = bottom[i + j + 1]; + N += 2; + } + } + this.#getOutlineStart(outline, N); + return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR); + } + #getOutlineTwoPoints(points) { + const last = this.#last; + const [layerX, layerY, layerWidth, layerHeight] = this.#box; + const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords(); + const outline = new Float32Array(36); + outline.set([NaN, NaN, NaN, NaN, (last[2] - layerX) / layerWidth, (last[3] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[4] - layerX) / layerWidth, (last[5] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (last[16] - layerX) / layerWidth, (last[17] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[14] - layerX) / layerWidth, (last[15] - layerY) / layerHeight], 0); + return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR); + } + #getOutlineStart(outline, pos) { + const bottom = this.#bottom; + outline.set([NaN, NaN, NaN, NaN, bottom[4], bottom[5]], pos); + return pos += 6; + } + #getOutlineEnd(outline, pos) { + const lastTop = this.#last.subarray(4, 6); + const lastBottom = this.#last.subarray(16, 18); + const [layerX, layerY, layerWidth, layerHeight] = this.#box; + const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords(); + outline.set([NaN, NaN, NaN, NaN, (lastTop[0] - layerX) / layerWidth, (lastTop[1] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (lastBottom[0] - layerX) / layerWidth, (lastBottom[1] - layerY) / layerHeight], pos); + return pos += 24; + } +} +class FreeDrawOutline extends Outline { + #box; + #bbox = new Float32Array(4); + #innerMargin; + #isLTR; + #points; + #scaleFactor; + #outline; + constructor(outline, points, box, scaleFactor, innerMargin, isLTR) { + super(); + this.#outline = outline; + this.#points = points; + this.#box = box; + this.#scaleFactor = scaleFactor; + this.#innerMargin = innerMargin; + this.#isLTR = isLTR; + this.firstPoint = [NaN, NaN]; + this.lastPoint = [NaN, NaN]; + this.#computeMinMax(isLTR); + const [x, y, width, height] = this.#bbox; + for (let i = 0, ii = outline.length; i < ii; i += 2) { + outline[i] = (outline[i] - x) / width; + outline[i + 1] = (outline[i + 1] - y) / height; + } + for (let i = 0, ii = points.length; i < ii; i += 2) { + points[i] = (points[i] - x) / width; + points[i + 1] = (points[i + 1] - y) / height; + } + } + toSVGPath() { + const buffer = [`M${this.#outline[4]} ${this.#outline[5]}`]; + for (let i = 6, ii = this.#outline.length; i < ii; i += 6) { + if (isNaN(this.#outline[i])) { + buffer.push(`L${this.#outline[i + 4]} ${this.#outline[i + 5]}`); + continue; + } + buffer.push(`C${this.#outline[i]} ${this.#outline[i + 1]} ${this.#outline[i + 2]} ${this.#outline[i + 3]} ${this.#outline[i + 4]} ${this.#outline[i + 5]}`); + } + buffer.push("Z"); + return buffer.join(" "); + } + serialize([blX, blY, trX, trY], rotation) { + const width = trX - blX; + const height = trY - blY; + let outline; + let points; + switch (rotation) { + case 0: + outline = Outline._rescale(this.#outline, blX, trY, width, -height); + points = Outline._rescale(this.#points, blX, trY, width, -height); + break; + case 90: + outline = Outline._rescaleAndSwap(this.#outline, blX, blY, width, height); + points = Outline._rescaleAndSwap(this.#points, blX, blY, width, height); + break; + case 180: + outline = Outline._rescale(this.#outline, trX, blY, -width, height); + points = Outline._rescale(this.#points, trX, blY, -width, height); + break; + case 270: + outline = Outline._rescaleAndSwap(this.#outline, trX, trY, -width, -height); + points = Outline._rescaleAndSwap(this.#points, trX, trY, -width, -height); + break; + } + return { + outline: Array.from(outline), + points: [Array.from(points)] + }; + } + #computeMinMax(isLTR) { + const outline = this.#outline; + let lastX = outline[4]; + let lastY = outline[5]; + const minMax = [lastX, lastY, lastX, lastY]; + let firstPointX = lastX; + let firstPointY = lastY; + let lastPointX = lastX; + let lastPointY = lastY; + const ltrCallback = isLTR ? Math.max : Math.min; + const bezierBbox = new Float32Array(4); + for (let i = 6, ii = outline.length; i < ii; i += 6) { + const x = outline[i + 4], + y = outline[i + 5]; + if (isNaN(outline[i])) { + Util.pointBoundingBox(x, y, minMax); + if (firstPointY > y) { + firstPointX = x; + firstPointY = y; + } else if (firstPointY === y) { + firstPointX = ltrCallback(firstPointX, x); + } + if (lastPointY < y) { + lastPointX = x; + lastPointY = y; + } else if (lastPointY === y) { + lastPointX = ltrCallback(lastPointX, x); + } + } else { + bezierBbox[0] = bezierBbox[1] = Infinity; + bezierBbox[2] = bezierBbox[3] = -Infinity; + Util.bezierBoundingBox(lastX, lastY, ...outline.slice(i, i + 6), bezierBbox); + Util.rectBoundingBox(bezierBbox[0], bezierBbox[1], bezierBbox[2], bezierBbox[3], minMax); + if (firstPointY > bezierBbox[1]) { + firstPointX = bezierBbox[0]; + firstPointY = bezierBbox[1]; + } else if (firstPointY === bezierBbox[1]) { + firstPointX = ltrCallback(firstPointX, bezierBbox[0]); + } + if (lastPointY < bezierBbox[3]) { + lastPointX = bezierBbox[2]; + lastPointY = bezierBbox[3]; + } else if (lastPointY === bezierBbox[3]) { + lastPointX = ltrCallback(lastPointX, bezierBbox[2]); + } + } + lastX = x; + lastY = y; + } + const bbox = this.#bbox; + bbox[0] = minMax[0] - this.#innerMargin; + bbox[1] = minMax[1] - this.#innerMargin; + bbox[2] = minMax[2] - minMax[0] + 2 * this.#innerMargin; + bbox[3] = minMax[3] - minMax[1] + 2 * this.#innerMargin; + this.firstPoint = [firstPointX, firstPointY]; + this.lastPoint = [lastPointX, lastPointY]; + } + get box() { + return this.#bbox; + } + newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) { + return new FreeDrawOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin); + } + getNewOutline(thickness, innerMargin) { + const [x, y, width, height] = this.#bbox; + const [layerX, layerY, layerWidth, layerHeight] = this.#box; + const sx = width * layerWidth; + const sy = height * layerHeight; + const tx = x * layerWidth + layerX; + const ty = y * layerHeight + layerY; + const outliner = this.newOutliner({ + x: this.#points[0] * sx + tx, + y: this.#points[1] * sy + ty + }, this.#box, this.#scaleFactor, thickness, this.#isLTR, innerMargin ?? this.#innerMargin); + for (let i = 2; i < this.#points.length; i += 2) { + outliner.add({ + x: this.#points[i] * sx + tx, + y: this.#points[i + 1] * sy + ty + }); + } + return outliner.getOutlines(); + } +} + +;// ./src/display/editor/drawers/highlight.js + + + +class HighlightOutliner { + #box; + #firstPoint; + #lastPoint; + #verticalEdges = []; + #intervals = []; + constructor(boxes, borderWidth = 0, innerMargin = 0, isLTR = true) { + const minMax = [Infinity, Infinity, -Infinity, -Infinity]; + const NUMBER_OF_DIGITS = 4; + const EPSILON = 10 ** -NUMBER_OF_DIGITS; + for (const { + x, + y, + width, + height + } of boxes) { + const x1 = Math.floor((x - borderWidth) / EPSILON) * EPSILON; + const x2 = Math.ceil((x + width + borderWidth) / EPSILON) * EPSILON; + const y1 = Math.floor((y - borderWidth) / EPSILON) * EPSILON; + const y2 = Math.ceil((y + height + borderWidth) / EPSILON) * EPSILON; + const left = [x1, y1, y2, true]; + const right = [x2, y1, y2, false]; + this.#verticalEdges.push(left, right); + Util.rectBoundingBox(x1, y1, x2, y2, minMax); + } + const bboxWidth = minMax[2] - minMax[0] + 2 * innerMargin; + const bboxHeight = minMax[3] - minMax[1] + 2 * innerMargin; + const shiftedMinX = minMax[0] - innerMargin; + const shiftedMinY = minMax[1] - innerMargin; + let firstPointX = isLTR ? -Infinity : Infinity; + let firstPointY = Infinity; + const lastEdge = this.#verticalEdges.at(isLTR ? -1 : -2); + const lastPoint = [lastEdge[0], lastEdge[2]]; + for (const edge of this.#verticalEdges) { + const [x, y1, y2, left] = edge; + if (!left && isLTR) { + if (y1 < firstPointY) { + firstPointY = y1; + firstPointX = x; + } else if (y1 === firstPointY) { + firstPointX = Math.max(firstPointX, x); + } + } else if (left && !isLTR) { + if (y1 < firstPointY) { + firstPointY = y1; + firstPointX = x; + } else if (y1 === firstPointY) { + firstPointX = Math.min(firstPointX, x); + } + } + edge[0] = (x - shiftedMinX) / bboxWidth; + edge[1] = (y1 - shiftedMinY) / bboxHeight; + edge[2] = (y2 - shiftedMinY) / bboxHeight; + } + this.#box = new Float32Array([shiftedMinX, shiftedMinY, bboxWidth, bboxHeight]); + this.#firstPoint = [firstPointX, firstPointY]; + this.#lastPoint = lastPoint; + } + getOutlines() { + this.#verticalEdges.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]); + const outlineVerticalEdges = []; + for (const edge of this.#verticalEdges) { + if (edge[3]) { + outlineVerticalEdges.push(...this.#breakEdge(edge)); + this.#insert(edge); + } else { + this.#remove(edge); + outlineVerticalEdges.push(...this.#breakEdge(edge)); + } + } + return this.#getOutlines(outlineVerticalEdges); + } + #getOutlines(outlineVerticalEdges) { + const edges = []; + const allEdges = new Set(); + for (const edge of outlineVerticalEdges) { + const [x, y1, y2] = edge; + edges.push([x, y1, edge], [x, y2, edge]); + } + edges.sort((a, b) => a[1] - b[1] || a[0] - b[0]); + for (let i = 0, ii = edges.length; i < ii; i += 2) { + const edge1 = edges[i][2]; + const edge2 = edges[i + 1][2]; + edge1.push(edge2); + edge2.push(edge1); + allEdges.add(edge1); + allEdges.add(edge2); + } + const outlines = []; + let outline; + while (allEdges.size > 0) { + const edge = allEdges.values().next().value; + let [x, y1, y2, edge1, edge2] = edge; + allEdges.delete(edge); + let lastPointX = x; + let lastPointY = y1; + outline = [x, y2]; + outlines.push(outline); + while (true) { + let e; + if (allEdges.has(edge1)) { + e = edge1; + } else if (allEdges.has(edge2)) { + e = edge2; + } else { + break; + } + allEdges.delete(e); + [x, y1, y2, edge1, edge2] = e; + if (lastPointX !== x) { + outline.push(lastPointX, lastPointY, x, lastPointY === y1 ? y1 : y2); + lastPointX = x; + } + lastPointY = lastPointY === y1 ? y2 : y1; + } + outline.push(lastPointX, lastPointY); + } + return new HighlightOutline(outlines, this.#box, this.#firstPoint, this.#lastPoint); + } + #binarySearch(y) { + const array = this.#intervals; + let start = 0; + let end = array.length - 1; + while (start <= end) { + const middle = start + end >> 1; + const y1 = array[middle][0]; + if (y1 === y) { + return middle; + } + if (y1 < y) { + start = middle + 1; + } else { + end = middle - 1; + } + } + return end + 1; + } + #insert([, y1, y2]) { + const index = this.#binarySearch(y1); + this.#intervals.splice(index, 0, [y1, y2]); + } + #remove([, y1, y2]) { + const index = this.#binarySearch(y1); + for (let i = index; i < this.#intervals.length; i++) { + const [start, end] = this.#intervals[i]; + if (start !== y1) { + break; + } + if (start === y1 && end === y2) { + this.#intervals.splice(i, 1); + return; + } + } + for (let i = index - 1; i >= 0; i--) { + const [start, end] = this.#intervals[i]; + if (start !== y1) { + break; + } + if (start === y1 && end === y2) { + this.#intervals.splice(i, 1); + return; + } + } + } + #breakEdge(edge) { + const [x, y1, y2] = edge; + const results = [[x, y1, y2]]; + const index = this.#binarySearch(y2); + for (let i = 0; i < index; i++) { + const [start, end] = this.#intervals[i]; + for (let j = 0, jj = results.length; j < jj; j++) { + const [, y3, y4] = results[j]; + if (end <= y3 || y4 <= start) { + continue; + } + if (y3 >= start) { + if (y4 > end) { + results[j][1] = end; + } else { + if (jj === 1) { + return []; + } + results.splice(j, 1); + j--; + jj--; + } + continue; + } + results[j][2] = start; + if (y4 > end) { + results.push([x, end, y4]); + } + } + } + return results; + } +} +class HighlightOutline extends Outline { + #box; + #outlines; + constructor(outlines, box, firstPoint, lastPoint) { + super(); + this.#outlines = outlines; + this.#box = box; + this.firstPoint = firstPoint; + this.lastPoint = lastPoint; + } + toSVGPath() { + const buffer = []; + for (const polygon of this.#outlines) { + let [prevX, prevY] = polygon; + buffer.push(`M${prevX} ${prevY}`); + for (let i = 2; i < polygon.length; i += 2) { + const x = polygon[i]; + const y = polygon[i + 1]; + if (x === prevX) { + buffer.push(`V${y}`); + prevY = y; + } else if (y === prevY) { + buffer.push(`H${x}`); + prevX = x; + } + } + buffer.push("Z"); + } + return buffer.join(" "); + } + serialize([blX, blY, trX, trY], _rotation) { + const outlines = []; + const width = trX - blX; + const height = trY - blY; + for (const outline of this.#outlines) { + const points = new Array(outline.length); + for (let i = 0; i < outline.length; i += 2) { + points[i] = blX + outline[i] * width; + points[i + 1] = trY - outline[i + 1] * height; + } + outlines.push(points); + } + return outlines; + } + get box() { + return this.#box; + } + get classNamesForOutlining() { + return ["highlightOutline"]; + } +} +class FreeHighlightOutliner extends FreeDrawOutliner { + newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) { + return new FreeHighlightOutline(outline, points, box, scaleFactor, innerMargin, isLTR); + } +} +class FreeHighlightOutline extends FreeDrawOutline { + newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) { + return new FreeHighlightOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin); + } +} + +;// ./src/display/editor/highlight.js + + + + + + + +class HighlightEditor extends AnnotationEditor { + #anchorNode = null; + #anchorOffset = 0; + #boxes; + #clipPathId = null; + #colorPicker = null; + #focusOutlines = null; + #focusNode = null; + #focusOffset = 0; + #highlightDiv = null; + #highlightOutlines = null; + #id = null; + #isFreeHighlight = false; + #firstPoint = null; + #lastPoint = null; + #outlineId = null; + #text = ""; + #thickness; + #methodOfCreation = ""; + static _defaultColor = null; + static _defaultOpacity = 1; + static _defaultThickness = 12; + static _type = "highlight"; + static _editorType = AnnotationEditorType.HIGHLIGHT; + static _freeHighlightId = -1; + static _freeHighlight = null; + static _freeHighlightClipId = ""; + static get _keyboardManager() { + const proto = HighlightEditor.prototype; + return shadow(this, "_keyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], proto._moveCaret, { + args: [0] + }], [["ArrowRight", "mac+ArrowRight"], proto._moveCaret, { + args: [1] + }], [["ArrowUp", "mac+ArrowUp"], proto._moveCaret, { + args: [2] + }], [["ArrowDown", "mac+ArrowDown"], proto._moveCaret, { + args: [3] + }]])); + } + constructor(params) { + super({ + ...params, + name: "highlightEditor" + }); + this.color = params.color || HighlightEditor._defaultColor; + this.#thickness = params.thickness || HighlightEditor._defaultThickness; + this.opacity = params.opacity || HighlightEditor._defaultOpacity; + this.#boxes = params.boxes || null; + this.#methodOfCreation = params.methodOfCreation || ""; + this.#text = params.text || ""; + this._isDraggable = false; + this.defaultL10nId = "pdfjs-editor-highlight-editor"; + if (params.highlightId > -1) { + this.#isFreeHighlight = true; + this.#createFreeOutlines(params); + this.#addToDrawLayer(); + } else if (this.#boxes) { + this.#anchorNode = params.anchorNode; + this.#anchorOffset = params.anchorOffset; + this.#focusNode = params.focusNode; + this.#focusOffset = params.focusOffset; + this.#createOutlines(); + this.#addToDrawLayer(); + this.rotate(this.rotation); + } + if (!this.annotationElementId) { + this._uiManager.a11yAlert("pdfjs-editor-highlight-added-alert"); + } + } + get telemetryInitialData() { + return { + action: "added", + type: this.#isFreeHighlight ? "free_highlight" : "highlight", + color: this._uiManager.getNonHCMColorName(this.color), + thickness: this.#thickness, + methodOfCreation: this.#methodOfCreation + }; + } + get telemetryFinalData() { + return { + type: "highlight", + color: this._uiManager.getNonHCMColorName(this.color) + }; + } + static computeTelemetryFinalData(data) { + return { + numberOfColors: data.get("color").size + }; + } + #createOutlines() { + const outliner = new HighlightOutliner(this.#boxes, 0.001); + this.#highlightOutlines = outliner.getOutlines(); + [this.x, this.y, this.width, this.height] = this.#highlightOutlines.box; + const outlinerForOutline = new HighlightOutliner(this.#boxes, 0.0025, 0.001, this._uiManager.direction === "ltr"); + this.#focusOutlines = outlinerForOutline.getOutlines(); + const { + firstPoint + } = this.#highlightOutlines; + this.#firstPoint = [(firstPoint[0] - this.x) / this.width, (firstPoint[1] - this.y) / this.height]; + const { + lastPoint + } = this.#focusOutlines; + this.#lastPoint = [(lastPoint[0] - this.x) / this.width, (lastPoint[1] - this.y) / this.height]; + } + #createFreeOutlines({ + highlightOutlines, + highlightId, + clipPathId + }) { + this.#highlightOutlines = highlightOutlines; + const extraThickness = 1.5; + this.#focusOutlines = highlightOutlines.getNewOutline(this.#thickness / 2 + extraThickness, 0.0025); + if (highlightId >= 0) { + this.#id = highlightId; + this.#clipPathId = clipPathId; + this.parent.drawLayer.finalizeDraw(highlightId, { + bbox: highlightOutlines.box, + path: { + d: highlightOutlines.toSVGPath() + } + }); + this.#outlineId = this.parent.drawLayer.drawOutline({ + rootClass: { + highlightOutline: true, + free: true + }, + bbox: this.#focusOutlines.box, + path: { + d: this.#focusOutlines.toSVGPath() + } + }, true); + } else if (this.parent) { + const angle = this.parent.viewport.rotation; + this.parent.drawLayer.updateProperties(this.#id, { + bbox: HighlightEditor.#rotateBbox(this.#highlightOutlines.box, (angle - this.rotation + 360) % 360), + path: { + d: highlightOutlines.toSVGPath() + } + }); + this.parent.drawLayer.updateProperties(this.#outlineId, { + bbox: HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle), + path: { + d: this.#focusOutlines.toSVGPath() + } + }); + } + const [x, y, width, height] = highlightOutlines.box; + switch (this.rotation) { + case 0: + this.x = x; + this.y = y; + this.width = width; + this.height = height; + break; + case 90: + { + const [pageWidth, pageHeight] = this.parentDimensions; + this.x = y; + this.y = 1 - x; + this.width = width * pageHeight / pageWidth; + this.height = height * pageWidth / pageHeight; + break; + } + case 180: + this.x = 1 - x; + this.y = 1 - y; + this.width = width; + this.height = height; + break; + case 270: + { + const [pageWidth, pageHeight] = this.parentDimensions; + this.x = 1 - y; + this.y = x; + this.width = width * pageHeight / pageWidth; + this.height = height * pageWidth / pageHeight; + break; + } + } + const { + firstPoint + } = highlightOutlines; + this.#firstPoint = [(firstPoint[0] - x) / width, (firstPoint[1] - y) / height]; + const { + lastPoint + } = this.#focusOutlines; + this.#lastPoint = [(lastPoint[0] - x) / width, (lastPoint[1] - y) / height]; + } + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager); + HighlightEditor._defaultColor ||= uiManager.highlightColors?.values().next().value || "#fff066"; + } + static updateDefaultParams(type, value) { + switch (type) { + case AnnotationEditorParamsType.HIGHLIGHT_COLOR: + HighlightEditor._defaultColor = value; + break; + case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS: + HighlightEditor._defaultThickness = value; + break; + } + } + translateInPage(x, y) {} + get toolbarPosition() { + return this.#lastPoint; + } + get commentButtonPosition() { + return this.#firstPoint; + } + updateParams(type, value) { + switch (type) { + case AnnotationEditorParamsType.HIGHLIGHT_COLOR: + this.#updateColor(value); + break; + case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS: + this.#updateThickness(value); + break; + } + } + static get defaultPropertiesToUpdate() { + return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, HighlightEditor._defaultThickness]]; + } + get propertiesToUpdate() { + return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, this.color || HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, this.#thickness || HighlightEditor._defaultThickness], [AnnotationEditorParamsType.HIGHLIGHT_FREE, this.#isFreeHighlight]]; + } + onUpdatedColor() { + this.parent?.drawLayer.updateProperties(this.#id, { + root: { + fill: this.color, + "fill-opacity": this.opacity + } + }); + this.#colorPicker?.updateColor(this.color); + super.onUpdatedColor(); + } + #updateColor(color) { + const setColorAndOpacity = (col, opa) => { + this.color = col; + this.opacity = opa; + this.onUpdatedColor(); + }; + const savedColor = this.color; + const savedOpacity = this.opacity; + this.addCommands({ + cmd: setColorAndOpacity.bind(this, color, HighlightEditor._defaultOpacity), + undo: setColorAndOpacity.bind(this, savedColor, savedOpacity), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type: AnnotationEditorParamsType.HIGHLIGHT_COLOR, + overwriteIfSameType: true, + keepUndo: true + }); + this._reportTelemetry({ + action: "color_changed", + color: this._uiManager.getNonHCMColorName(color) + }, true); + } + #updateThickness(thickness) { + const savedThickness = this.#thickness; + const setThickness = th => { + this.#thickness = th; + this.#changeThickness(th); + }; + this.addCommands({ + cmd: setThickness.bind(this, thickness), + undo: setThickness.bind(this, savedThickness), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type: AnnotationEditorParamsType.INK_THICKNESS, + overwriteIfSameType: true, + keepUndo: true + }); + this._reportTelemetry({ + action: "thickness_changed", + thickness + }, true); + } + get toolbarButtons() { + if (this._uiManager.highlightColors) { + const colorPicker = this.#colorPicker = new ColorPicker({ + editor: this + }); + return [["colorPicker", colorPicker]]; + } + return super.toolbarButtons; + } + disableEditing() { + super.disableEditing(); + this.div.classList.toggle("disabled", true); + } + enableEditing() { + super.enableEditing(); + this.div.classList.toggle("disabled", false); + } + fixAndSetPosition() { + return super.fixAndSetPosition(this.#getRotation()); + } + getBaseTranslation() { + return [0, 0]; + } + getRect(tx, ty) { + return super.getRect(tx, ty, this.#getRotation()); + } + onceAdded(focus) { + if (!this.annotationElementId) { + this.parent.addUndoableEditor(this); + } + if (focus) { + this.div.focus(); + } + } + remove() { + this.#cleanDrawLayer(); + this._reportTelemetry({ + action: "deleted" + }); + super.remove(); + } + rebuild() { + if (!this.parent) { + return; + } + super.rebuild(); + if (this.div === null) { + return; + } + this.#addToDrawLayer(); + if (!this.isAttachedToDOM) { + this.parent.add(this); + } + } + setParent(parent) { + let mustBeSelected = false; + if (this.parent && !parent) { + this.#cleanDrawLayer(); + } else if (parent) { + this.#addToDrawLayer(parent); + mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor"); + } + super.setParent(parent); + this.show(this._isVisible); + if (mustBeSelected) { + this.select(); + } + } + #changeThickness(thickness) { + if (!this.#isFreeHighlight) { + return; + } + this.#createFreeOutlines({ + highlightOutlines: this.#highlightOutlines.getNewOutline(thickness / 2) + }); + this.fixAndSetPosition(); + this.setDims(); + } + #cleanDrawLayer() { + if (this.#id === null || !this.parent) { + return; + } + this.parent.drawLayer.remove(this.#id); + this.#id = null; + this.parent.drawLayer.remove(this.#outlineId); + this.#outlineId = null; + } + #addToDrawLayer(parent = this.parent) { + if (this.#id !== null) { + return; + } + ({ + id: this.#id, + clipPathId: this.#clipPathId + } = parent.drawLayer.draw({ + bbox: this.#highlightOutlines.box, + root: { + viewBox: "0 0 1 1", + fill: this.color, + "fill-opacity": this.opacity + }, + rootClass: { + highlight: true, + free: this.#isFreeHighlight + }, + path: { + d: this.#highlightOutlines.toSVGPath() + } + }, false, true)); + this.#outlineId = parent.drawLayer.drawOutline({ + rootClass: { + highlightOutline: true, + free: this.#isFreeHighlight + }, + bbox: this.#focusOutlines.box, + path: { + d: this.#focusOutlines.toSVGPath() + } + }, this.#isFreeHighlight); + if (this.#highlightDiv) { + this.#highlightDiv.style.clipPath = this.#clipPathId; + } + } + static #rotateBbox([x, y, width, height], angle) { + switch (angle) { + case 90: + return [1 - y - height, x, height, width]; + case 180: + return [1 - x - width, 1 - y - height, width, height]; + case 270: + return [y, 1 - x - width, height, width]; + } + return [x, y, width, height]; + } + rotate(angle) { + const { + drawLayer + } = this.parent; + let box; + if (this.#isFreeHighlight) { + angle = (angle - this.rotation + 360) % 360; + box = HighlightEditor.#rotateBbox(this.#highlightOutlines.box, angle); + } else { + box = HighlightEditor.#rotateBbox([this.x, this.y, this.width, this.height], angle); + } + drawLayer.updateProperties(this.#id, { + bbox: box, + root: { + "data-main-rotation": angle + } + }); + drawLayer.updateProperties(this.#outlineId, { + bbox: HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle), + root: { + "data-main-rotation": angle + } + }); + } + render() { + if (this.div) { + return this.div; + } + const div = super.render(); + if (this.#text) { + div.setAttribute("aria-label", this.#text); + div.setAttribute("role", "mark"); + } + if (this.#isFreeHighlight) { + div.classList.add("free"); + } else { + this.div.addEventListener("keydown", this.#keydown.bind(this), { + signal: this._uiManager._signal + }); + } + const highlightDiv = this.#highlightDiv = document.createElement("div"); + div.append(highlightDiv); + highlightDiv.setAttribute("aria-hidden", "true"); + highlightDiv.className = "internal"; + highlightDiv.style.clipPath = this.#clipPathId; + this.setDims(); + bindEvents(this, this.#highlightDiv, ["pointerover", "pointerleave"]); + this.enableEditing(); + return div; + } + pointerover() { + if (!this.isSelected) { + this.parent?.drawLayer.updateProperties(this.#outlineId, { + rootClass: { + hovered: true + } + }); + } + } + pointerleave() { + if (!this.isSelected) { + this.parent?.drawLayer.updateProperties(this.#outlineId, { + rootClass: { + hovered: false + } + }); + } + } + #keydown(event) { + HighlightEditor._keyboardManager.exec(this, event); + } + _moveCaret(direction) { + this.parent.unselect(this); + switch (direction) { + case 0: + case 2: + this.#setCaret(true); + break; + case 1: + case 3: + this.#setCaret(false); + break; + } + } + #setCaret(start) { + if (!this.#anchorNode) { + return; + } + const selection = window.getSelection(); + if (start) { + selection.setPosition(this.#anchorNode, this.#anchorOffset); + } else { + selection.setPosition(this.#focusNode, this.#focusOffset); + } + } + select() { + super.select(); + if (!this.#outlineId) { + return; + } + this.parent?.drawLayer.updateProperties(this.#outlineId, { + rootClass: { + hovered: false, + selected: true + } + }); + } + unselect() { + super.unselect(); + if (!this.#outlineId) { + return; + } + this.parent?.drawLayer.updateProperties(this.#outlineId, { + rootClass: { + selected: false + } + }); + if (!this.#isFreeHighlight) { + this.#setCaret(false); + } + } + get _mustFixPosition() { + return !this.#isFreeHighlight; + } + show(visible = this._isVisible) { + super.show(visible); + if (this.parent) { + this.parent.drawLayer.updateProperties(this.#id, { + rootClass: { + hidden: !visible + } + }); + this.parent.drawLayer.updateProperties(this.#outlineId, { + rootClass: { + hidden: !visible + } + }); + } + } + #getRotation() { + return this.#isFreeHighlight ? this.rotation : 0; + } + #serializeBoxes() { + if (this.#isFreeHighlight) { + return null; + } + const [pageWidth, pageHeight] = this.pageDimensions; + const [pageX, pageY] = this.pageTranslation; + const boxes = this.#boxes; + const quadPoints = new Float32Array(boxes.length * 8); + let i = 0; + for (const { + x, + y, + width, + height + } of boxes) { + const sx = x * pageWidth + pageX; + const sy = (1 - y) * pageHeight + pageY; + quadPoints[i] = quadPoints[i + 4] = sx; + quadPoints[i + 1] = quadPoints[i + 3] = sy; + quadPoints[i + 2] = quadPoints[i + 6] = sx + width * pageWidth; + quadPoints[i + 5] = quadPoints[i + 7] = sy - height * pageHeight; + i += 8; + } + return quadPoints; + } + #serializeOutlines(rect) { + return this.#highlightOutlines.serialize(rect, this.#getRotation()); + } + static startHighlighting(parent, isLTR, { + target: textLayer, + x, + y + }) { + const { + x: layerX, + y: layerY, + width: parentWidth, + height: parentHeight + } = textLayer.getBoundingClientRect(); + const ac = new AbortController(); + const signal = parent.combinedSignal(ac); + const pointerUpCallback = e => { + ac.abort(); + this.#endHighlight(parent, e); + }; + window.addEventListener("blur", pointerUpCallback, { + signal + }); + window.addEventListener("pointerup", pointerUpCallback, { + signal + }); + window.addEventListener("pointerdown", stopEvent, { + capture: true, + passive: false, + signal + }); + window.addEventListener("contextmenu", noContextMenu, { + signal + }); + textLayer.addEventListener("pointermove", this.#highlightMove.bind(this, parent), { + signal + }); + this._freeHighlight = new FreeHighlightOutliner({ + x, + y + }, [layerX, layerY, parentWidth, parentHeight], parent.scale, this._defaultThickness / 2, isLTR, 0.001); + ({ + id: this._freeHighlightId, + clipPathId: this._freeHighlightClipId + } = parent.drawLayer.draw({ + bbox: [0, 0, 1, 1], + root: { + viewBox: "0 0 1 1", + fill: this._defaultColor, + "fill-opacity": this._defaultOpacity + }, + rootClass: { + highlight: true, + free: true + }, + path: { + d: this._freeHighlight.toSVGPath() + } + }, true, true)); + } + static #highlightMove(parent, event) { + if (this._freeHighlight.add(event)) { + parent.drawLayer.updateProperties(this._freeHighlightId, { + path: { + d: this._freeHighlight.toSVGPath() + } + }); + } + } + static #endHighlight(parent, event) { + if (!this._freeHighlight.isEmpty()) { + parent.createAndAddNewEditor(event, false, { + highlightId: this._freeHighlightId, + highlightOutlines: this._freeHighlight.getOutlines(), + clipPathId: this._freeHighlightClipId, + methodOfCreation: "main_toolbar" + }); + } else { + parent.drawLayer.remove(this._freeHighlightId); + } + this._freeHighlightId = -1; + this._freeHighlight = null; + this._freeHighlightClipId = ""; + } + static async deserialize(data, parent, uiManager) { + let initialData = null; + if (data instanceof HighlightAnnotationElement) { + const { + data: { + quadPoints, + rect, + rotation, + id, + color, + opacity, + popupRef, + richText, + contentsObj, + creationDate, + modificationDate + }, + parent: { + page: { + pageNumber + } + } + } = data; + initialData = data = { + annotationType: AnnotationEditorType.HIGHLIGHT, + color: Array.from(color), + opacity, + quadPoints, + boxes: null, + pageIndex: pageNumber - 1, + rect: rect.slice(0), + rotation, + annotationElementId: id, + id, + deleted: false, + popupRef, + richText, + comment: contentsObj?.str || null, + creationDate, + modificationDate + }; + } else if (data instanceof InkAnnotationElement) { + const { + data: { + inkLists, + rect, + rotation, + id, + color, + borderStyle: { + rawWidth: thickness + }, + popupRef, + richText, + contentsObj, + creationDate, + modificationDate + }, + parent: { + page: { + pageNumber + } + } + } = data; + initialData = data = { + annotationType: AnnotationEditorType.HIGHLIGHT, + color: Array.from(color), + thickness, + inkLists, + boxes: null, + pageIndex: pageNumber - 1, + rect: rect.slice(0), + rotation, + annotationElementId: id, + id, + deleted: false, + popupRef, + richText, + comment: contentsObj?.str || null, + creationDate, + modificationDate + }; + } + const { + color, + quadPoints, + inkLists, + opacity + } = data; + const editor = await super.deserialize(data, parent, uiManager); + editor.color = Util.makeHexColor(...color); + editor.opacity = opacity || 1; + if (inkLists) { + editor.#thickness = data.thickness; + } + editor._initialData = initialData; + if (data.comment) { + editor.setCommentData(data); + } + const [pageWidth, pageHeight] = editor.pageDimensions; + const [pageX, pageY] = editor.pageTranslation; + if (quadPoints) { + const boxes = editor.#boxes = []; + for (let i = 0; i < quadPoints.length; i += 8) { + boxes.push({ + x: (quadPoints[i] - pageX) / pageWidth, + y: 1 - (quadPoints[i + 1] - pageY) / pageHeight, + width: (quadPoints[i + 2] - quadPoints[i]) / pageWidth, + height: (quadPoints[i + 1] - quadPoints[i + 5]) / pageHeight + }); + } + editor.#createOutlines(); + editor.#addToDrawLayer(); + editor.rotate(editor.rotation); + } else if (inkLists) { + editor.#isFreeHighlight = true; + const points = inkLists[0]; + const point = { + x: points[0] - pageX, + y: pageHeight - (points[1] - pageY) + }; + const outliner = new FreeHighlightOutliner(point, [0, 0, pageWidth, pageHeight], 1, editor.#thickness / 2, true, 0.001); + for (let i = 0, ii = points.length; i < ii; i += 2) { + point.x = points[i] - pageX; + point.y = pageHeight - (points[i + 1] - pageY); + outliner.add(point); + } + const { + id, + clipPathId + } = parent.drawLayer.draw({ + bbox: [0, 0, 1, 1], + root: { + viewBox: "0 0 1 1", + fill: editor.color, + "fill-opacity": editor._defaultOpacity + }, + rootClass: { + highlight: true, + free: true + }, + path: { + d: outliner.toSVGPath() + } + }, true, true); + editor.#createFreeOutlines({ + highlightOutlines: outliner.getOutlines(), + highlightId: id, + clipPathId + }); + editor.#addToDrawLayer(); + editor.rotate(editor.parentRotation); + } + return editor; + } + serialize(isForCopying = false) { + if (this.isEmpty() || isForCopying) { + return null; + } + if (this.deleted) { + return this.serializeDeleted(); + } + const color = AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color)); + const serialized = super.serialize(isForCopying); + Object.assign(serialized, { + color, + opacity: this.opacity, + thickness: this.#thickness, + quadPoints: this.#serializeBoxes(), + outlines: this.#serializeOutlines(serialized.rect) + }); + this.addComment(serialized); + if (this.annotationElementId && !this.#hasElementChanged(serialized)) { + return null; + } + serialized.id = this.annotationElementId; + return serialized; + } + #hasElementChanged(serialized) { + const { + color + } = this._initialData; + return this.hasEditedComment || serialized.color.some((c, i) => c !== color[i]); + } + renderAnnotationElement(annotation) { + if (this.deleted) { + annotation.hide(); + return null; + } + annotation.updateEdited({ + rect: this.getPDFRect(), + popup: this.comment + }); + return null; + } + static canCreateNewEmptyEditor() { + return false; + } +} + +;// ./src/display/editor/draw.js + + + + +class DrawingOptions { + #svgProperties = Object.create(null); + updateProperty(name, value) { + this[name] = value; + this.updateSVGProperty(name, value); + } + updateProperties(properties) { + if (!properties) { + return; + } + for (const [name, value] of Object.entries(properties)) { + if (!name.startsWith("_")) { + this.updateProperty(name, value); + } + } + } + updateSVGProperty(name, value) { + this.#svgProperties[name] = value; + } + toSVGProperties() { + const root = this.#svgProperties; + this.#svgProperties = Object.create(null); + return { + root + }; + } + reset() { + this.#svgProperties = Object.create(null); + } + updateAll(options = this) { + this.updateProperties(options); + } + clone() { + unreachable("Not implemented"); + } +} +class DrawingEditor extends AnnotationEditor { + #drawOutlines = null; + #mustBeCommitted; + _colorPicker = null; + _drawId = null; + static _currentDrawId = -1; + static _currentParent = null; + static #currentDraw = null; + static #currentDrawingAC = null; + static #currentDrawingOptions = null; + static _INNER_MARGIN = 3; + constructor(params) { + super(params); + this.#mustBeCommitted = params.mustBeCommitted || false; + this._addOutlines(params); + } + onUpdatedColor() { + this._colorPicker?.update(this.color); + super.onUpdatedColor(); + } + _addOutlines(params) { + if (params.drawOutlines) { + this.#createDrawOutlines(params); + this.#addToDrawLayer(); + } + } + #createDrawOutlines({ + drawOutlines, + drawId, + drawingOptions + }) { + this.#drawOutlines = drawOutlines; + this._drawingOptions ||= drawingOptions; + if (!this.annotationElementId) { + this._uiManager.a11yAlert(`pdfjs-editor-${this.editorType}-added-alert`); + } + if (drawId >= 0) { + this._drawId = drawId; + this.parent.drawLayer.finalizeDraw(drawId, drawOutlines.defaultProperties); + } else { + this._drawId = this.#createDrawing(drawOutlines, this.parent); + } + this.#updateBbox(drawOutlines.box); + } + #createDrawing(drawOutlines, parent) { + const { + id + } = parent.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(), drawOutlines.defaultSVGProperties), false, false); + return id; + } + static _mergeSVGProperties(p1, p2) { + const p1Keys = new Set(Object.keys(p1)); + for (const [key, value] of Object.entries(p2)) { + if (p1Keys.has(key)) { + Object.assign(p1[key], value); + } else { + p1[key] = value; + } + } + return p1; + } + static getDefaultDrawingOptions(_options) { + unreachable("Not implemented"); + } + static get typesMap() { + unreachable("Not implemented"); + } + static get isDrawer() { + return true; + } + static get supportMultipleDrawings() { + return false; + } + static updateDefaultParams(type, value) { + const propertyName = this.typesMap.get(type); + if (propertyName) { + this._defaultDrawingOptions.updateProperty(propertyName, value); + } + if (this._currentParent) { + DrawingEditor.#currentDraw.updateProperty(propertyName, value); + this._currentParent.drawLayer.updateProperties(this._currentDrawId, this._defaultDrawingOptions.toSVGProperties()); + } + } + updateParams(type, value) { + const propertyName = this.constructor.typesMap.get(type); + if (propertyName) { + this._updateProperty(type, propertyName, value); + } + } + static get defaultPropertiesToUpdate() { + const properties = []; + const options = this._defaultDrawingOptions; + for (const [type, name] of this.typesMap) { + properties.push([type, options[name]]); + } + return properties; + } + get propertiesToUpdate() { + const properties = []; + const { + _drawingOptions + } = this; + for (const [type, name] of this.constructor.typesMap) { + properties.push([type, _drawingOptions[name]]); + } + return properties; + } + _updateProperty(type, name, value) { + const options = this._drawingOptions; + const savedValue = options[name]; + const setter = val => { + options.updateProperty(name, val); + const bbox = this.#drawOutlines.updateProperty(name, val); + if (bbox) { + this.#updateBbox(bbox); + } + this.parent?.drawLayer.updateProperties(this._drawId, options.toSVGProperties()); + if (type === this.colorType) { + this.onUpdatedColor(); + } + }; + this.addCommands({ + cmd: setter.bind(this, value), + undo: setter.bind(this, savedValue), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type, + overwriteIfSameType: true, + keepUndo: true + }); + } + _onResizing() { + this.parent?.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathResizingSVGProperties(this.#convertToDrawSpace()), { + bbox: this.#rotateBox() + })); + } + _onResized() { + this.parent?.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathResizedSVGProperties(this.#convertToDrawSpace()), { + bbox: this.#rotateBox() + })); + } + _onTranslating(_x, _y) { + this.parent?.drawLayer.updateProperties(this._drawId, { + bbox: this.#rotateBox() + }); + } + _onTranslated() { + this.parent?.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathTranslatedSVGProperties(this.#convertToDrawSpace(), this.parentDimensions), { + bbox: this.#rotateBox() + })); + } + _onStartDragging() { + this.parent?.drawLayer.updateProperties(this._drawId, { + rootClass: { + moving: true + } + }); + } + _onStopDragging() { + this.parent?.drawLayer.updateProperties(this._drawId, { + rootClass: { + moving: false + } + }); + } + commit() { + super.commit(); + this.disableEditMode(); + this.disableEditing(); + } + disableEditing() { + super.disableEditing(); + this.div.classList.toggle("disabled", true); + } + enableEditing() { + super.enableEditing(); + this.div.classList.toggle("disabled", false); + } + getBaseTranslation() { + return [0, 0]; + } + get isResizable() { + return true; + } + onceAdded(focus) { + if (!this.annotationElementId) { + this.parent.addUndoableEditor(this); + } + this._isDraggable = true; + if (this.#mustBeCommitted) { + this.#mustBeCommitted = false; + this.commit(); + this.parent.setSelected(this); + if (focus && this.isOnScreen) { + this.div.focus(); + } + } + } + remove() { + this.#cleanDrawLayer(); + super.remove(); + } + rebuild() { + if (!this.parent) { + return; + } + super.rebuild(); + if (this.div === null) { + return; + } + this.#addToDrawLayer(); + this.#updateBbox(this.#drawOutlines.box); + if (!this.isAttachedToDOM) { + this.parent.add(this); + } + } + setParent(parent) { + let mustBeSelected = false; + if (this.parent && !parent) { + this._uiManager.removeShouldRescale(this); + this.#cleanDrawLayer(); + } else if (parent) { + this._uiManager.addShouldRescale(this); + this.#addToDrawLayer(parent); + mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor"); + } + super.setParent(parent); + if (mustBeSelected) { + this.select(); + } + } + #cleanDrawLayer() { + if (this._drawId === null || !this.parent) { + return; + } + this.parent.drawLayer.remove(this._drawId); + this._drawId = null; + this._drawingOptions.reset(); + } + #addToDrawLayer(parent = this.parent) { + if (this._drawId !== null && this.parent === parent) { + return; + } + if (this._drawId !== null) { + this.parent.drawLayer.updateParent(this._drawId, parent.drawLayer); + return; + } + this._drawingOptions.updateAll(); + this._drawId = this.#createDrawing(this.#drawOutlines, parent); + } + #convertToParentSpace([x, y, width, height]) { + const { + parentDimensions: [pW, pH], + rotation + } = this; + switch (rotation) { + case 90: + return [y, 1 - x, width * (pH / pW), height * (pW / pH)]; + case 180: + return [1 - x, 1 - y, width, height]; + case 270: + return [1 - y, x, width * (pH / pW), height * (pW / pH)]; + default: + return [x, y, width, height]; + } + } + #convertToDrawSpace() { + const { + x, + y, + width, + height, + parentDimensions: [pW, pH], + rotation + } = this; + switch (rotation) { + case 90: + return [1 - y, x, width * (pW / pH), height * (pH / pW)]; + case 180: + return [1 - x, 1 - y, width, height]; + case 270: + return [y, 1 - x, width * (pW / pH), height * (pH / pW)]; + default: + return [x, y, width, height]; + } + } + #updateBbox(bbox) { + [this.x, this.y, this.width, this.height] = this.#convertToParentSpace(bbox); + if (this.div) { + this.fixAndSetPosition(); + this.setDims(); + } + this._onResized(); + } + #rotateBox() { + const { + x, + y, + width, + height, + rotation, + parentRotation, + parentDimensions: [pW, pH] + } = this; + switch ((rotation * 4 + parentRotation) / 90) { + case 1: + return [1 - y - height, x, height, width]; + case 2: + return [1 - x - width, 1 - y - height, width, height]; + case 3: + return [y, 1 - x - width, height, width]; + case 4: + return [x, y - width * (pW / pH), height * (pH / pW), width * (pW / pH)]; + case 5: + return [1 - y, x, width * (pW / pH), height * (pH / pW)]; + case 6: + return [1 - x - height * (pH / pW), 1 - y, height * (pH / pW), width * (pW / pH)]; + case 7: + return [y - width * (pW / pH), 1 - x - height * (pH / pW), width * (pW / pH), height * (pH / pW)]; + case 8: + return [x - width, y - height, width, height]; + case 9: + return [1 - y, x - width, height, width]; + case 10: + return [1 - x, 1 - y, width, height]; + case 11: + return [y - height, 1 - x, height, width]; + case 12: + return [x - height * (pH / pW), y, height * (pH / pW), width * (pW / pH)]; + case 13: + return [1 - y - width * (pW / pH), x - height * (pH / pW), width * (pW / pH), height * (pH / pW)]; + case 14: + return [1 - x, 1 - y - width * (pW / pH), height * (pH / pW), width * (pW / pH)]; + case 15: + return [y, 1 - x, width * (pW / pH), height * (pH / pW)]; + default: + return [x, y, width, height]; + } + } + rotate() { + if (!this.parent) { + return; + } + this.parent.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties({ + bbox: this.#rotateBox() + }, this.#drawOutlines.updateRotation((this.parentRotation - this.rotation + 360) % 360))); + } + onScaleChanging() { + if (!this.parent) { + return; + } + this.#updateBbox(this.#drawOutlines.updateParentDimensions(this.parentDimensions, this.parent.scale)); + } + static onScaleChangingWhenDrawing() {} + render() { + if (this.div) { + return this.div; + } + let baseX, baseY; + if (this._isCopy) { + baseX = this.x; + baseY = this.y; + } + const div = super.render(); + div.classList.add("draw"); + const drawDiv = document.createElement("div"); + div.append(drawDiv); + drawDiv.setAttribute("aria-hidden", "true"); + drawDiv.className = "internal"; + this.setDims(); + this._uiManager.addShouldRescale(this); + this.disableEditing(); + if (this._isCopy) { + this._moveAfterPaste(baseX, baseY); + } + return div; + } + static createDrawerInstance(_x, _y, _parentWidth, _parentHeight, _rotation) { + unreachable("Not implemented"); + } + static startDrawing(parent, uiManager, _isLTR, event) { + const { + target, + offsetX: x, + offsetY: y, + pointerId, + pointerType + } = event; + if (CurrentPointers.isInitializedAndDifferentPointerType(pointerType)) { + return; + } + const { + viewport: { + rotation + } + } = parent; + const { + width: parentWidth, + height: parentHeight + } = target.getBoundingClientRect(); + const ac = DrawingEditor.#currentDrawingAC = new AbortController(); + const signal = parent.combinedSignal(ac); + CurrentPointers.setPointer(pointerType, pointerId); + window.addEventListener("pointerup", e => { + if (CurrentPointers.isSamePointerIdOrRemove(e.pointerId)) { + this._endDraw(e); + } + }, { + signal + }); + window.addEventListener("pointercancel", e => { + if (CurrentPointers.isSamePointerIdOrRemove(e.pointerId)) { + this._currentParent.endDrawingSession(); + } + }, { + signal + }); + window.addEventListener("pointerdown", e => { + if (!CurrentPointers.isSamePointerType(e.pointerType)) { + return; + } + CurrentPointers.initializeAndAddPointerId(e.pointerId); + if (DrawingEditor.#currentDraw.isCancellable()) { + DrawingEditor.#currentDraw.removeLastElement(); + if (DrawingEditor.#currentDraw.isEmpty()) { + this._currentParent.endDrawingSession(true); + } else { + this._endDraw(null); + } + } + }, { + capture: true, + passive: false, + signal + }); + window.addEventListener("contextmenu", noContextMenu, { + signal + }); + target.addEventListener("pointermove", this._drawMove.bind(this), { + signal + }); + target.addEventListener("touchmove", e => { + if (CurrentPointers.isSameTimeStamp(e.timeStamp)) { + stopEvent(e); + } + }, { + signal + }); + parent.toggleDrawing(); + uiManager._editorUndoBar?.hide(); + if (DrawingEditor.#currentDraw) { + parent.drawLayer.updateProperties(this._currentDrawId, DrawingEditor.#currentDraw.startNew(x, y, parentWidth, parentHeight, rotation)); + return; + } + uiManager.updateUIForDefaultProperties(this); + DrawingEditor.#currentDraw = this.createDrawerInstance(x, y, parentWidth, parentHeight, rotation); + DrawingEditor.#currentDrawingOptions = this.getDefaultDrawingOptions(); + this._currentParent = parent; + ({ + id: this._currentDrawId + } = parent.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#currentDrawingOptions.toSVGProperties(), DrawingEditor.#currentDraw.defaultSVGProperties), true, false)); + } + static _drawMove(event) { + CurrentPointers.isSameTimeStamp(event.timeStamp); + if (!DrawingEditor.#currentDraw) { + return; + } + const { + offsetX, + offsetY, + pointerId + } = event; + if (!CurrentPointers.isSamePointerId(pointerId)) { + return; + } + if (CurrentPointers.isUsingMultiplePointers()) { + this._endDraw(event); + return; + } + this._currentParent.drawLayer.updateProperties(this._currentDrawId, DrawingEditor.#currentDraw.add(offsetX, offsetY)); + CurrentPointers.setTimeStamp(event.timeStamp); + stopEvent(event); + } + static _cleanup(all) { + if (all) { + this._currentDrawId = -1; + this._currentParent = null; + DrawingEditor.#currentDraw = null; + DrawingEditor.#currentDrawingOptions = null; + CurrentPointers.clearTimeStamp(); + } + if (DrawingEditor.#currentDrawingAC) { + DrawingEditor.#currentDrawingAC.abort(); + DrawingEditor.#currentDrawingAC = null; + CurrentPointers.clearPointerIds(); + } + } + static _endDraw(event) { + const parent = this._currentParent; + if (!parent) { + return; + } + parent.toggleDrawing(true); + this._cleanup(false); + if (event?.target === parent.div) { + parent.drawLayer.updateProperties(this._currentDrawId, DrawingEditor.#currentDraw.end(event.offsetX, event.offsetY)); + } + if (this.supportMultipleDrawings) { + const draw = DrawingEditor.#currentDraw; + const drawId = this._currentDrawId; + const lastElement = draw.getLastElement(); + parent.addCommands({ + cmd: () => { + parent.drawLayer.updateProperties(drawId, draw.setLastElement(lastElement)); + }, + undo: () => { + parent.drawLayer.updateProperties(drawId, draw.removeLastElement()); + }, + mustExec: false, + type: AnnotationEditorParamsType.DRAW_STEP + }); + return; + } + this.endDrawing(false); + } + static endDrawing(isAborted) { + const parent = this._currentParent; + if (!parent) { + return null; + } + parent.toggleDrawing(true); + parent.cleanUndoStack(AnnotationEditorParamsType.DRAW_STEP); + if (!DrawingEditor.#currentDraw.isEmpty()) { + const { + pageDimensions: [pageWidth, pageHeight], + scale + } = parent; + const editor = parent.createAndAddNewEditor({ + offsetX: 0, + offsetY: 0 + }, false, { + drawId: this._currentDrawId, + drawOutlines: DrawingEditor.#currentDraw.getOutlines(pageWidth * scale, pageHeight * scale, scale, this._INNER_MARGIN), + drawingOptions: DrawingEditor.#currentDrawingOptions, + mustBeCommitted: !isAborted + }); + this._cleanup(true); + return editor; + } + parent.drawLayer.remove(this._currentDrawId); + this._cleanup(true); + return null; + } + createDrawingOptions(_data) {} + static deserializeDraw(_pageX, _pageY, _pageWidth, _pageHeight, _innerWidth, _data) { + unreachable("Not implemented"); + } + static async deserialize(data, parent, uiManager) { + const { + rawDims: { + pageWidth, + pageHeight, + pageX, + pageY + } + } = parent.viewport; + const drawOutlines = this.deserializeDraw(pageX, pageY, pageWidth, pageHeight, this._INNER_MARGIN, data); + const editor = await super.deserialize(data, parent, uiManager); + editor.createDrawingOptions(data); + editor.#createDrawOutlines({ + drawOutlines + }); + editor.#addToDrawLayer(); + editor.onScaleChanging(); + editor.rotate(); + return editor; + } + serializeDraw(isForCopying) { + const [pageX, pageY] = this.pageTranslation; + const [pageWidth, pageHeight] = this.pageDimensions; + return this.#drawOutlines.serialize([pageX, pageY, pageWidth, pageHeight], isForCopying); + } + renderAnnotationElement(annotation) { + annotation.updateEdited({ + rect: this.getPDFRect() + }); + return null; + } + static canCreateNewEmptyEditor() { + return false; + } +} + +;// ./src/display/editor/drawers/inkdraw.js + + +class InkDrawOutliner { + #last = new Float64Array(6); + #line; + #lines; + #rotation; + #thickness; + #points; + #lastSVGPath = ""; + #lastIndex = 0; + #outlines = new InkDrawOutline(); + #parentWidth; + #parentHeight; + constructor(x, y, parentWidth, parentHeight, rotation, thickness) { + this.#parentWidth = parentWidth; + this.#parentHeight = parentHeight; + this.#rotation = rotation; + this.#thickness = thickness; + [x, y] = this.#normalizePoint(x, y); + const line = this.#line = [NaN, NaN, NaN, NaN, x, y]; + this.#points = [x, y]; + this.#lines = [{ + line, + points: this.#points + }]; + this.#last.set(line, 0); + } + updateProperty(name, value) { + if (name === "stroke-width") { + this.#thickness = value; + } + } + #normalizePoint(x, y) { + return Outline._normalizePoint(x, y, this.#parentWidth, this.#parentHeight, this.#rotation); + } + isEmpty() { + return !this.#lines || this.#lines.length === 0; + } + isCancellable() { + return this.#points.length <= 10; + } + add(x, y) { + [x, y] = this.#normalizePoint(x, y); + const [x1, y1, x2, y2] = this.#last.subarray(2, 6); + const diffX = x - x2; + const diffY = y - y2; + const d = Math.hypot(this.#parentWidth * diffX, this.#parentHeight * diffY); + if (d <= 2) { + return null; + } + this.#points.push(x, y); + if (isNaN(x1)) { + this.#last.set([x2, y2, x, y], 2); + this.#line.push(NaN, NaN, NaN, NaN, x, y); + return { + path: { + d: this.toSVGPath() + } + }; + } + if (isNaN(this.#last[0])) { + this.#line.splice(6, 6); + } + this.#last.set([x1, y1, x2, y2, x, y], 0); + this.#line.push(...Outline.createBezierPoints(x1, y1, x2, y2, x, y)); + return { + path: { + d: this.toSVGPath() + } + }; + } + end(x, y) { + const change = this.add(x, y); + if (change) { + return change; + } + if (this.#points.length === 2) { + return { + path: { + d: this.toSVGPath() + } + }; + } + return null; + } + startNew(x, y, parentWidth, parentHeight, rotation) { + this.#parentWidth = parentWidth; + this.#parentHeight = parentHeight; + this.#rotation = rotation; + [x, y] = this.#normalizePoint(x, y); + const line = this.#line = [NaN, NaN, NaN, NaN, x, y]; + this.#points = [x, y]; + const last = this.#lines.at(-1); + if (last) { + last.line = new Float32Array(last.line); + last.points = new Float32Array(last.points); + } + this.#lines.push({ + line, + points: this.#points + }); + this.#last.set(line, 0); + this.#lastIndex = 0; + this.toSVGPath(); + return null; + } + getLastElement() { + return this.#lines.at(-1); + } + setLastElement(element) { + if (!this.#lines) { + return this.#outlines.setLastElement(element); + } + this.#lines.push(element); + this.#line = element.line; + this.#points = element.points; + this.#lastIndex = 0; + return { + path: { + d: this.toSVGPath() + } + }; + } + removeLastElement() { + if (!this.#lines) { + return this.#outlines.removeLastElement(); + } + this.#lines.pop(); + this.#lastSVGPath = ""; + for (let i = 0, ii = this.#lines.length; i < ii; i++) { + const { + line, + points + } = this.#lines[i]; + this.#line = line; + this.#points = points; + this.#lastIndex = 0; + this.toSVGPath(); + } + return { + path: { + d: this.#lastSVGPath + } + }; + } + toSVGPath() { + const firstX = Outline.svgRound(this.#line[4]); + const firstY = Outline.svgRound(this.#line[5]); + if (this.#points.length === 2) { + this.#lastSVGPath = `${this.#lastSVGPath} M ${firstX} ${firstY} Z`; + return this.#lastSVGPath; + } + if (this.#points.length <= 6) { + const i = this.#lastSVGPath.lastIndexOf("M"); + this.#lastSVGPath = `${this.#lastSVGPath.slice(0, i)} M ${firstX} ${firstY}`; + this.#lastIndex = 6; + } + if (this.#points.length === 4) { + const secondX = Outline.svgRound(this.#line[10]); + const secondY = Outline.svgRound(this.#line[11]); + this.#lastSVGPath = `${this.#lastSVGPath} L ${secondX} ${secondY}`; + this.#lastIndex = 12; + return this.#lastSVGPath; + } + const buffer = []; + if (this.#lastIndex === 0) { + buffer.push(`M ${firstX} ${firstY}`); + this.#lastIndex = 6; + } + for (let i = this.#lastIndex, ii = this.#line.length; i < ii; i += 6) { + const [c1x, c1y, c2x, c2y, x, y] = this.#line.slice(i, i + 6).map(Outline.svgRound); + buffer.push(`C${c1x} ${c1y} ${c2x} ${c2y} ${x} ${y}`); + } + this.#lastSVGPath += buffer.join(" "); + this.#lastIndex = this.#line.length; + return this.#lastSVGPath; + } + getOutlines(parentWidth, parentHeight, scale, innerMargin) { + const last = this.#lines.at(-1); + last.line = new Float32Array(last.line); + last.points = new Float32Array(last.points); + this.#outlines.build(this.#lines, parentWidth, parentHeight, scale, this.#rotation, this.#thickness, innerMargin); + this.#last = null; + this.#line = null; + this.#lines = null; + this.#lastSVGPath = null; + return this.#outlines; + } + get defaultSVGProperties() { + return { + root: { + viewBox: "0 0 10000 10000" + }, + rootClass: { + draw: true + }, + bbox: [0, 0, 1, 1] + }; + } +} +class InkDrawOutline extends Outline { + #bbox; + #currentRotation = 0; + #innerMargin; + #lines; + #parentWidth; + #parentHeight; + #parentScale; + #rotation; + #thickness; + build(lines, parentWidth, parentHeight, parentScale, rotation, thickness, innerMargin) { + this.#parentWidth = parentWidth; + this.#parentHeight = parentHeight; + this.#parentScale = parentScale; + this.#rotation = rotation; + this.#thickness = thickness; + this.#innerMargin = innerMargin ?? 0; + this.#lines = lines; + this.#computeBbox(); + } + get thickness() { + return this.#thickness; + } + setLastElement(element) { + this.#lines.push(element); + return { + path: { + d: this.toSVGPath() + } + }; + } + removeLastElement() { + this.#lines.pop(); + return { + path: { + d: this.toSVGPath() + } + }; + } + toSVGPath() { + const buffer = []; + for (const { + line + } of this.#lines) { + buffer.push(`M${Outline.svgRound(line[4])} ${Outline.svgRound(line[5])}`); + if (line.length === 6) { + buffer.push("Z"); + continue; + } + if (line.length === 12 && isNaN(line[6])) { + buffer.push(`L${Outline.svgRound(line[10])} ${Outline.svgRound(line[11])}`); + continue; + } + for (let i = 6, ii = line.length; i < ii; i += 6) { + const [c1x, c1y, c2x, c2y, x, y] = line.subarray(i, i + 6).map(Outline.svgRound); + buffer.push(`C${c1x} ${c1y} ${c2x} ${c2y} ${x} ${y}`); + } + } + return buffer.join(""); + } + serialize([pageX, pageY, pageWidth, pageHeight], isForCopying) { + const serializedLines = []; + const serializedPoints = []; + const [x, y, width, height] = this.#getBBoxWithNoMargin(); + let tx, ty, sx, sy, x1, y1, x2, y2, rescaleFn; + switch (this.#rotation) { + case 0: + rescaleFn = Outline._rescale; + tx = pageX; + ty = pageY + pageHeight; + sx = pageWidth; + sy = -pageHeight; + x1 = pageX + x * pageWidth; + y1 = pageY + (1 - y - height) * pageHeight; + x2 = pageX + (x + width) * pageWidth; + y2 = pageY + (1 - y) * pageHeight; + break; + case 90: + rescaleFn = Outline._rescaleAndSwap; + tx = pageX; + ty = pageY; + sx = pageWidth; + sy = pageHeight; + x1 = pageX + y * pageWidth; + y1 = pageY + x * pageHeight; + x2 = pageX + (y + height) * pageWidth; + y2 = pageY + (x + width) * pageHeight; + break; + case 180: + rescaleFn = Outline._rescale; + tx = pageX + pageWidth; + ty = pageY; + sx = -pageWidth; + sy = pageHeight; + x1 = pageX + (1 - x - width) * pageWidth; + y1 = pageY + y * pageHeight; + x2 = pageX + (1 - x) * pageWidth; + y2 = pageY + (y + height) * pageHeight; + break; + case 270: + rescaleFn = Outline._rescaleAndSwap; + tx = pageX + pageWidth; + ty = pageY + pageHeight; + sx = -pageWidth; + sy = -pageHeight; + x1 = pageX + (1 - y - height) * pageWidth; + y1 = pageY + (1 - x - width) * pageHeight; + x2 = pageX + (1 - y) * pageWidth; + y2 = pageY + (1 - x) * pageHeight; + break; + } + for (const { + line, + points + } of this.#lines) { + serializedLines.push(rescaleFn(line, tx, ty, sx, sy, isForCopying ? new Array(line.length) : null)); + serializedPoints.push(rescaleFn(points, tx, ty, sx, sy, isForCopying ? new Array(points.length) : null)); + } + return { + lines: serializedLines, + points: serializedPoints, + rect: [x1, y1, x2, y2] + }; + } + static deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, { + paths: { + lines, + points + }, + rotation, + thickness + }) { + const newLines = []; + let tx, ty, sx, sy, rescaleFn; + switch (rotation) { + case 0: + rescaleFn = Outline._rescale; + tx = -pageX / pageWidth; + ty = pageY / pageHeight + 1; + sx = 1 / pageWidth; + sy = -1 / pageHeight; + break; + case 90: + rescaleFn = Outline._rescaleAndSwap; + tx = -pageY / pageHeight; + ty = -pageX / pageWidth; + sx = 1 / pageHeight; + sy = 1 / pageWidth; + break; + case 180: + rescaleFn = Outline._rescale; + tx = pageX / pageWidth + 1; + ty = -pageY / pageHeight; + sx = -1 / pageWidth; + sy = 1 / pageHeight; + break; + case 270: + rescaleFn = Outline._rescaleAndSwap; + tx = pageY / pageHeight + 1; + ty = pageX / pageWidth + 1; + sx = -1 / pageHeight; + sy = -1 / pageWidth; + break; + } + if (!lines) { + lines = []; + for (const point of points) { + const len = point.length; + if (len === 2) { + lines.push(new Float32Array([NaN, NaN, NaN, NaN, point[0], point[1]])); + continue; + } + if (len === 4) { + lines.push(new Float32Array([NaN, NaN, NaN, NaN, point[0], point[1], NaN, NaN, NaN, NaN, point[2], point[3]])); + continue; + } + const line = new Float32Array(3 * (len - 2)); + lines.push(line); + let [x1, y1, x2, y2] = point.subarray(0, 4); + line.set([NaN, NaN, NaN, NaN, x1, y1], 0); + for (let i = 4; i < len; i += 2) { + const x = point[i]; + const y = point[i + 1]; + line.set(Outline.createBezierPoints(x1, y1, x2, y2, x, y), (i - 2) * 3); + [x1, y1, x2, y2] = [x2, y2, x, y]; + } + } + } + for (let i = 0, ii = lines.length; i < ii; i++) { + newLines.push({ + line: rescaleFn(lines[i].map(x => x ?? NaN), tx, ty, sx, sy), + points: rescaleFn(points[i].map(x => x ?? NaN), tx, ty, sx, sy) + }); + } + const outlines = new this.prototype.constructor(); + outlines.build(newLines, pageWidth, pageHeight, 1, rotation, thickness, innerMargin); + return outlines; + } + #getMarginComponents(thickness = this.#thickness) { + const margin = this.#innerMargin + thickness / 2 * this.#parentScale; + return this.#rotation % 180 === 0 ? [margin / this.#parentWidth, margin / this.#parentHeight] : [margin / this.#parentHeight, margin / this.#parentWidth]; + } + #getBBoxWithNoMargin() { + const [x, y, width, height] = this.#bbox; + const [marginX, marginY] = this.#getMarginComponents(0); + return [x + marginX, y + marginY, width - 2 * marginX, height - 2 * marginY]; + } + #computeBbox() { + const bbox = this.#bbox = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]); + for (const { + line + } of this.#lines) { + if (line.length <= 12) { + for (let i = 4, ii = line.length; i < ii; i += 6) { + Util.pointBoundingBox(line[i], line[i + 1], bbox); + } + continue; + } + let lastX = line[4], + lastY = line[5]; + for (let i = 6, ii = line.length; i < ii; i += 6) { + const [c1x, c1y, c2x, c2y, x, y] = line.subarray(i, i + 6); + Util.bezierBoundingBox(lastX, lastY, c1x, c1y, c2x, c2y, x, y, bbox); + lastX = x; + lastY = y; + } + } + const [marginX, marginY] = this.#getMarginComponents(); + bbox[0] = MathClamp(bbox[0] - marginX, 0, 1); + bbox[1] = MathClamp(bbox[1] - marginY, 0, 1); + bbox[2] = MathClamp(bbox[2] + marginX, 0, 1); + bbox[3] = MathClamp(bbox[3] + marginY, 0, 1); + bbox[2] -= bbox[0]; + bbox[3] -= bbox[1]; + } + get box() { + return this.#bbox; + } + updateProperty(name, value) { + if (name === "stroke-width") { + return this.#updateThickness(value); + } + return null; + } + #updateThickness(thickness) { + const [oldMarginX, oldMarginY] = this.#getMarginComponents(); + this.#thickness = thickness; + const [newMarginX, newMarginY] = this.#getMarginComponents(); + const [diffMarginX, diffMarginY] = [newMarginX - oldMarginX, newMarginY - oldMarginY]; + const bbox = this.#bbox; + bbox[0] -= diffMarginX; + bbox[1] -= diffMarginY; + bbox[2] += 2 * diffMarginX; + bbox[3] += 2 * diffMarginY; + return bbox; + } + updateParentDimensions([width, height], scale) { + const [oldMarginX, oldMarginY] = this.#getMarginComponents(); + this.#parentWidth = width; + this.#parentHeight = height; + this.#parentScale = scale; + const [newMarginX, newMarginY] = this.#getMarginComponents(); + const diffMarginX = newMarginX - oldMarginX; + const diffMarginY = newMarginY - oldMarginY; + const bbox = this.#bbox; + bbox[0] -= diffMarginX; + bbox[1] -= diffMarginY; + bbox[2] += 2 * diffMarginX; + bbox[3] += 2 * diffMarginY; + return bbox; + } + updateRotation(rotation) { + this.#currentRotation = rotation; + return { + path: { + transform: this.rotationTransform + } + }; + } + get viewBox() { + return this.#bbox.map(Outline.svgRound).join(" "); + } + get defaultProperties() { + const [x, y] = this.#bbox; + return { + root: { + viewBox: this.viewBox + }, + path: { + "transform-origin": `${Outline.svgRound(x)} ${Outline.svgRound(y)}` + } + }; + } + get rotationTransform() { + const [,, width, height] = this.#bbox; + let a = 0, + b = 0, + c = 0, + d = 0, + e = 0, + f = 0; + switch (this.#currentRotation) { + case 90: + b = height / width; + c = -width / height; + e = width; + break; + case 180: + a = -1; + d = -1; + e = width; + f = height; + break; + case 270: + b = -height / width; + c = width / height; + f = height; + break; + default: + return ""; + } + return `matrix(${a} ${b} ${c} ${d} ${Outline.svgRound(e)} ${Outline.svgRound(f)})`; + } + getPathResizingSVGProperties([newX, newY, newWidth, newHeight]) { + const [marginX, marginY] = this.#getMarginComponents(); + const [x, y, width, height] = this.#bbox; + if (Math.abs(width - marginX) <= Outline.PRECISION || Math.abs(height - marginY) <= Outline.PRECISION) { + const tx = newX + newWidth / 2 - (x + width / 2); + const ty = newY + newHeight / 2 - (y + height / 2); + return { + path: { + "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`, + transform: `${this.rotationTransform} translate(${tx} ${ty})` + } + }; + } + const s1x = (newWidth - 2 * marginX) / (width - 2 * marginX); + const s1y = (newHeight - 2 * marginY) / (height - 2 * marginY); + const s2x = width / newWidth; + const s2y = height / newHeight; + return { + path: { + "transform-origin": `${Outline.svgRound(x)} ${Outline.svgRound(y)}`, + transform: `${this.rotationTransform} scale(${s2x} ${s2y}) ` + `translate(${Outline.svgRound(marginX)} ${Outline.svgRound(marginY)}) scale(${s1x} ${s1y}) ` + `translate(${Outline.svgRound(-marginX)} ${Outline.svgRound(-marginY)})` + } + }; + } + getPathResizedSVGProperties([newX, newY, newWidth, newHeight]) { + const [marginX, marginY] = this.#getMarginComponents(); + const bbox = this.#bbox; + const [x, y, width, height] = bbox; + bbox[0] = newX; + bbox[1] = newY; + bbox[2] = newWidth; + bbox[3] = newHeight; + if (Math.abs(width - marginX) <= Outline.PRECISION || Math.abs(height - marginY) <= Outline.PRECISION) { + const tx = newX + newWidth / 2 - (x + width / 2); + const ty = newY + newHeight / 2 - (y + height / 2); + for (const { + line, + points + } of this.#lines) { + Outline._translate(line, tx, ty, line); + Outline._translate(points, tx, ty, points); + } + return { + root: { + viewBox: this.viewBox + }, + path: { + "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`, + transform: this.rotationTransform || null, + d: this.toSVGPath() + } + }; + } + const s1x = (newWidth - 2 * marginX) / (width - 2 * marginX); + const s1y = (newHeight - 2 * marginY) / (height - 2 * marginY); + const tx = -s1x * (x + marginX) + newX + marginX; + const ty = -s1y * (y + marginY) + newY + marginY; + if (s1x !== 1 || s1y !== 1 || tx !== 0 || ty !== 0) { + for (const { + line, + points + } of this.#lines) { + Outline._rescale(line, tx, ty, s1x, s1y, line); + Outline._rescale(points, tx, ty, s1x, s1y, points); + } + } + return { + root: { + viewBox: this.viewBox + }, + path: { + "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`, + transform: this.rotationTransform || null, + d: this.toSVGPath() + } + }; + } + getPathTranslatedSVGProperties([newX, newY], parentDimensions) { + const [newParentWidth, newParentHeight] = parentDimensions; + const bbox = this.#bbox; + const tx = newX - bbox[0]; + const ty = newY - bbox[1]; + if (this.#parentWidth === newParentWidth && this.#parentHeight === newParentHeight) { + for (const { + line, + points + } of this.#lines) { + Outline._translate(line, tx, ty, line); + Outline._translate(points, tx, ty, points); + } + } else { + const sx = this.#parentWidth / newParentWidth; + const sy = this.#parentHeight / newParentHeight; + this.#parentWidth = newParentWidth; + this.#parentHeight = newParentHeight; + for (const { + line, + points + } of this.#lines) { + Outline._rescale(line, tx, ty, sx, sy, line); + Outline._rescale(points, tx, ty, sx, sy, points); + } + bbox[2] *= sx; + bbox[3] *= sy; + } + bbox[0] = newX; + bbox[1] = newY; + return { + root: { + viewBox: this.viewBox + }, + path: { + d: this.toSVGPath(), + "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}` + } + }; + } + get defaultSVGProperties() { + const bbox = this.#bbox; + return { + root: { + viewBox: this.viewBox + }, + rootClass: { + draw: true + }, + path: { + d: this.toSVGPath(), + "transform-origin": `${Outline.svgRound(bbox[0])} ${Outline.svgRound(bbox[1])}`, + transform: this.rotationTransform || null + }, + bbox + }; + } +} + +;// ./src/display/editor/ink.js + + + + + + +class InkDrawingOptions extends DrawingOptions { + constructor(viewerParameters) { + super(); + this._viewParameters = viewerParameters; + super.updateProperties({ + fill: "none", + stroke: AnnotationEditor._defaultLineColor, + "stroke-opacity": 1, + "stroke-width": 1, + "stroke-linecap": "round", + "stroke-linejoin": "round", + "stroke-miterlimit": 10 + }); + } + updateSVGProperty(name, value) { + if (name === "stroke-width") { + value ??= this["stroke-width"]; + value *= this._viewParameters.realScale; + } + super.updateSVGProperty(name, value); + } + clone() { + const clone = new InkDrawingOptions(this._viewParameters); + clone.updateAll(this); + return clone; + } +} +class InkEditor extends DrawingEditor { + static _type = "ink"; + static _editorType = AnnotationEditorType.INK; + static _defaultDrawingOptions = null; + constructor(params) { + super({ + ...params, + name: "inkEditor" + }); + this._willKeepAspectRatio = true; + this.defaultL10nId = "pdfjs-editor-ink-editor"; + } + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager); + this._defaultDrawingOptions = new InkDrawingOptions(uiManager.viewParameters); + } + static getDefaultDrawingOptions(options) { + const clone = this._defaultDrawingOptions.clone(); + clone.updateProperties(options); + return clone; + } + static get supportMultipleDrawings() { + return true; + } + static get typesMap() { + return shadow(this, "typesMap", new Map([[AnnotationEditorParamsType.INK_THICKNESS, "stroke-width"], [AnnotationEditorParamsType.INK_COLOR, "stroke"], [AnnotationEditorParamsType.INK_OPACITY, "stroke-opacity"]])); + } + static createDrawerInstance(x, y, parentWidth, parentHeight, rotation) { + return new InkDrawOutliner(x, y, parentWidth, parentHeight, rotation, this._defaultDrawingOptions["stroke-width"]); + } + static deserializeDraw(pageX, pageY, pageWidth, pageHeight, innerMargin, data) { + return InkDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data); + } + static async deserialize(data, parent, uiManager) { + let initialData = null; + if (data instanceof InkAnnotationElement) { + const { + data: { + inkLists, + rect, + rotation, + id, + color, + opacity, + borderStyle: { + rawWidth: thickness + }, + popupRef, + richText, + contentsObj, + creationDate, + modificationDate + }, + parent: { + page: { + pageNumber + } + } + } = data; + initialData = data = { + annotationType: AnnotationEditorType.INK, + color: Array.from(color), + thickness, + opacity, + paths: { + points: inkLists + }, + boxes: null, + pageIndex: pageNumber - 1, + rect: rect.slice(0), + rotation, + annotationElementId: id, + id, + deleted: false, + popupRef, + richText, + comment: contentsObj?.str || null, + creationDate, + modificationDate + }; + } + const editor = await super.deserialize(data, parent, uiManager); + editor._initialData = initialData; + if (data.comment) { + editor.setCommentData(data); + } + return editor; + } + get toolbarButtons() { + this._colorPicker ||= new BasicColorPicker(this); + return [["colorPicker", this._colorPicker]]; + } + get colorType() { + return AnnotationEditorParamsType.INK_COLOR; + } + get color() { + return this._drawingOptions.stroke; + } + get opacity() { + return this._drawingOptions["stroke-opacity"]; + } + onScaleChanging() { + if (!this.parent) { + return; + } + super.onScaleChanging(); + const { + _drawId, + _drawingOptions, + parent + } = this; + _drawingOptions.updateSVGProperty("stroke-width"); + parent.drawLayer.updateProperties(_drawId, _drawingOptions.toSVGProperties()); + } + static onScaleChangingWhenDrawing() { + const parent = this._currentParent; + if (!parent) { + return; + } + super.onScaleChangingWhenDrawing(); + this._defaultDrawingOptions.updateSVGProperty("stroke-width"); + parent.drawLayer.updateProperties(this._currentDrawId, this._defaultDrawingOptions.toSVGProperties()); + } + createDrawingOptions({ + color, + thickness, + opacity + }) { + this._drawingOptions = InkEditor.getDefaultDrawingOptions({ + stroke: Util.makeHexColor(...color), + "stroke-width": thickness, + "stroke-opacity": opacity + }); + } + serialize(isForCopying = false) { + if (this.isEmpty()) { + return null; + } + if (this.deleted) { + return this.serializeDeleted(); + } + const { + lines, + points + } = this.serializeDraw(isForCopying); + const { + _drawingOptions: { + stroke, + "stroke-opacity": opacity, + "stroke-width": thickness + } + } = this; + const serialized = Object.assign(super.serialize(isForCopying), { + color: AnnotationEditor._colorManager.convert(stroke), + opacity, + thickness, + paths: { + lines, + points + } + }); + this.addComment(serialized); + if (isForCopying) { + serialized.isCopy = true; + return serialized; + } + if (this.annotationElementId && !this.#hasElementChanged(serialized)) { + return null; + } + serialized.id = this.annotationElementId; + return serialized; + } + #hasElementChanged(serialized) { + const { + color, + thickness, + opacity, + pageIndex + } = this._initialData; + return this.hasEditedComment || this._hasBeenMoved || this._hasBeenResized || serialized.color.some((c, i) => c !== color[i]) || serialized.thickness !== thickness || serialized.opacity !== opacity || serialized.pageIndex !== pageIndex; + } + renderAnnotationElement(annotation) { + if (this.deleted) { + annotation.hide(); + return null; + } + const { + points, + rect + } = this.serializeDraw(false); + annotation.updateEdited({ + rect, + thickness: this._drawingOptions["stroke-width"], + points, + popup: this.comment + }); + return null; + } +} + +;// ./src/display/editor/drawers/contour.js + +class ContourDrawOutline extends InkDrawOutline { + toSVGPath() { + let path = super.toSVGPath(); + if (!path.endsWith("Z")) { + path += "Z"; + } + return path; + } +} + +;// ./src/display/editor/drawers/signaturedraw.js + + + + +const BASE_HEADER_LENGTH = 8; +const POINTS_PROPERTIES_NUMBER = 3; +class SignatureExtractor { + static #PARAMETERS = { + maxDim: 512, + sigmaSFactor: 0.02, + sigmaR: 25, + kernelSize: 16 + }; + static #neighborIndexToId(i0, j0, i, j) { + i -= i0; + j -= j0; + if (i === 0) { + return j > 0 ? 0 : 4; + } + if (i === 1) { + return j + 6; + } + return 2 - j; + } + static #neighborIdToIndex = new Int32Array([0, 1, -1, 1, -1, 0, -1, -1, 0, -1, 1, -1, 1, 0, 1, 1]); + static #clockwiseNonZero(buf, width, i0, j0, i, j, offset) { + const id = this.#neighborIndexToId(i0, j0, i, j); + for (let k = 0; k < 8; k++) { + const kk = (-k + id - offset + 16) % 8; + const shiftI = this.#neighborIdToIndex[2 * kk]; + const shiftJ = this.#neighborIdToIndex[2 * kk + 1]; + if (buf[(i0 + shiftI) * width + (j0 + shiftJ)] !== 0) { + return kk; + } + } + return -1; + } + static #counterClockwiseNonZero(buf, width, i0, j0, i, j, offset) { + const id = this.#neighborIndexToId(i0, j0, i, j); + for (let k = 0; k < 8; k++) { + const kk = (k + id + offset + 16) % 8; + const shiftI = this.#neighborIdToIndex[2 * kk]; + const shiftJ = this.#neighborIdToIndex[2 * kk + 1]; + if (buf[(i0 + shiftI) * width + (j0 + shiftJ)] !== 0) { + return kk; + } + } + return -1; + } + static #findContours(buf, width, height, threshold) { + const N = buf.length; + const types = new Int32Array(N); + for (let i = 0; i < N; i++) { + types[i] = buf[i] <= threshold ? 1 : 0; + } + for (let i = 1; i < height - 1; i++) { + types[i * width] = types[i * width + width - 1] = 0; + } + for (let i = 0; i < width; i++) { + types[i] = types[width * height - 1 - i] = 0; + } + let nbd = 1; + let lnbd; + const contours = []; + for (let i = 1; i < height - 1; i++) { + lnbd = 1; + for (let j = 1; j < width - 1; j++) { + const ij = i * width + j; + const pix = types[ij]; + if (pix === 0) { + continue; + } + let i2 = i; + let j2 = j; + if (pix === 1 && types[ij - 1] === 0) { + nbd += 1; + j2 -= 1; + } else if (pix >= 1 && types[ij + 1] === 0) { + nbd += 1; + j2 += 1; + if (pix > 1) { + lnbd = pix; + } + } else { + if (pix !== 1) { + lnbd = Math.abs(pix); + } + continue; + } + const points = [j, i]; + const isHole = j2 === j + 1; + const contour = { + isHole, + points, + id: nbd, + parent: 0 + }; + contours.push(contour); + let contour0; + for (const c of contours) { + if (c.id === lnbd) { + contour0 = c; + break; + } + } + if (!contour0) { + contour.parent = isHole ? lnbd : 0; + } else if (contour0.isHole) { + contour.parent = isHole ? contour0.parent : lnbd; + } else { + contour.parent = isHole ? lnbd : contour0.parent; + } + const k = this.#clockwiseNonZero(types, width, i, j, i2, j2, 0); + if (k === -1) { + types[ij] = -nbd; + if (types[ij] !== 1) { + lnbd = Math.abs(types[ij]); + } + continue; + } + let shiftI = this.#neighborIdToIndex[2 * k]; + let shiftJ = this.#neighborIdToIndex[2 * k + 1]; + const i1 = i + shiftI; + const j1 = j + shiftJ; + i2 = i1; + j2 = j1; + let i3 = i; + let j3 = j; + while (true) { + const kk = this.#counterClockwiseNonZero(types, width, i3, j3, i2, j2, 1); + shiftI = this.#neighborIdToIndex[2 * kk]; + shiftJ = this.#neighborIdToIndex[2 * kk + 1]; + const i4 = i3 + shiftI; + const j4 = j3 + shiftJ; + points.push(j4, i4); + const ij3 = i3 * width + j3; + if (types[ij3 + 1] === 0) { + types[ij3] = -nbd; + } else if (types[ij3] === 1) { + types[ij3] = nbd; + } + if (i4 === i && j4 === j && i3 === i1 && j3 === j1) { + if (types[ij] !== 1) { + lnbd = Math.abs(types[ij]); + } + break; + } else { + i2 = i3; + j2 = j3; + i3 = i4; + j3 = j4; + } + } + } + } + return contours; + } + static #douglasPeuckerHelper(points, start, end, output) { + if (end - start <= 4) { + for (let i = start; i < end - 2; i += 2) { + output.push(points[i], points[i + 1]); + } + return; + } + const ax = points[start]; + const ay = points[start + 1]; + const abx = points[end - 4] - ax; + const aby = points[end - 3] - ay; + const dist = Math.hypot(abx, aby); + const nabx = abx / dist; + const naby = aby / dist; + const aa = nabx * ay - naby * ax; + const m = aby / abx; + const invS = 1 / dist; + const phi = Math.atan(m); + const cosPhi = Math.cos(phi); + const sinPhi = Math.sin(phi); + const tmax = invS * (Math.abs(cosPhi) + Math.abs(sinPhi)); + const poly = invS * (1 - tmax + tmax ** 2); + const partialPhi = Math.max(Math.atan(Math.abs(sinPhi + cosPhi) * poly), Math.atan(Math.abs(sinPhi - cosPhi) * poly)); + let dmax = 0; + let index = start; + for (let i = start + 2; i < end - 2; i += 2) { + const d = Math.abs(aa - nabx * points[i + 1] + naby * points[i]); + if (d > dmax) { + index = i; + dmax = d; + } + } + if (dmax > (dist * partialPhi) ** 2) { + this.#douglasPeuckerHelper(points, start, index + 2, output); + this.#douglasPeuckerHelper(points, index, end, output); + } else { + output.push(ax, ay); + } + } + static #douglasPeucker(points) { + const output = []; + const len = points.length; + this.#douglasPeuckerHelper(points, 0, len, output); + output.push(points[len - 2], points[len - 1]); + return output.length <= 4 ? null : output; + } + static #bilateralFilter(buf, width, height, sigmaS, sigmaR, kernelSize) { + const kernel = new Float32Array(kernelSize ** 2); + const sigmaS2 = -2 * sigmaS ** 2; + const halfSize = kernelSize >> 1; + for (let i = 0; i < kernelSize; i++) { + const x = (i - halfSize) ** 2; + for (let j = 0; j < kernelSize; j++) { + kernel[i * kernelSize + j] = Math.exp((x + (j - halfSize) ** 2) / sigmaS2); + } + } + const rangeValues = new Float32Array(256); + const sigmaR2 = -2 * sigmaR ** 2; + for (let i = 0; i < 256; i++) { + rangeValues[i] = Math.exp(i ** 2 / sigmaR2); + } + const N = buf.length; + const out = new Uint8Array(N); + const histogram = new Uint32Array(256); + for (let i = 0; i < height; i++) { + for (let j = 0; j < width; j++) { + const ij = i * width + j; + const center = buf[ij]; + let sum = 0; + let norm = 0; + for (let k = 0; k < kernelSize; k++) { + const y = i + k - halfSize; + if (y < 0 || y >= height) { + continue; + } + for (let l = 0; l < kernelSize; l++) { + const x = j + l - halfSize; + if (x < 0 || x >= width) { + continue; + } + const neighbour = buf[y * width + x]; + const w = kernel[k * kernelSize + l] * rangeValues[Math.abs(neighbour - center)]; + sum += neighbour * w; + norm += w; + } + } + const pix = out[ij] = Math.round(sum / norm); + histogram[pix]++; + } + } + return [out, histogram]; + } + static #getHistogram(buf) { + const histogram = new Uint32Array(256); + for (const g of buf) { + histogram[g]++; + } + return histogram; + } + static #toUint8(buf) { + const N = buf.length; + const out = new Uint8ClampedArray(N >> 2); + let max = -Infinity; + let min = Infinity; + for (let i = 0, ii = out.length; i < ii; i++) { + const pix = out[i] = buf[i << 2]; + max = Math.max(max, pix); + min = Math.min(min, pix); + } + const ratio = 255 / (max - min); + for (let i = 0, ii = out.length; i < ii; i++) { + out[i] = (out[i] - min) * ratio; + } + return out; + } + static #guessThreshold(histogram) { + let i; + let M = -Infinity; + let L = -Infinity; + const min = histogram.findIndex(v => v !== 0); + let pos = min; + let spos = min; + for (i = min; i < 256; i++) { + const v = histogram[i]; + if (v > M) { + if (i - pos > L) { + L = i - pos; + spos = i - 1; + } + M = v; + pos = i; + } + } + for (i = spos - 1; i >= 0; i--) { + if (histogram[i] > histogram[i + 1]) { + break; + } + } + return i; + } + static #getGrayPixels(bitmap) { + const originalBitmap = bitmap; + const { + width, + height + } = bitmap; + const { + maxDim + } = this.#PARAMETERS; + let newWidth = width; + let newHeight = height; + if (width > maxDim || height > maxDim) { + let prevWidth = width; + let prevHeight = height; + let steps = Math.log2(Math.max(width, height) / maxDim); + const isteps = Math.floor(steps); + steps = steps === isteps ? isteps - 1 : isteps; + for (let i = 0; i < steps; i++) { + newWidth = Math.ceil(prevWidth / 2); + newHeight = Math.ceil(prevHeight / 2); + const offscreen = new OffscreenCanvas(newWidth, newHeight); + const ctx = offscreen.getContext("2d"); + ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight); + prevWidth = newWidth; + prevHeight = newHeight; + if (bitmap !== originalBitmap) { + bitmap.close(); + } + bitmap = offscreen.transferToImageBitmap(); + } + const ratio = Math.min(maxDim / newWidth, maxDim / newHeight); + newWidth = Math.round(newWidth * ratio); + newHeight = Math.round(newHeight * ratio); + } + const offscreen = new OffscreenCanvas(newWidth, newHeight); + const ctx = offscreen.getContext("2d", { + willReadFrequently: true + }); + ctx.fillStyle = "white"; + ctx.fillRect(0, 0, newWidth, newHeight); + ctx.filter = "grayscale(1)"; + ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, newWidth, newHeight); + const grayImage = ctx.getImageData(0, 0, newWidth, newHeight).data; + const uint8Buf = this.#toUint8(grayImage); + return [uint8Buf, newWidth, newHeight]; + } + static extractContoursFromText(text, { + fontFamily, + fontStyle, + fontWeight + }, pageWidth, pageHeight, rotation, innerMargin) { + let canvas = new OffscreenCanvas(1, 1); + let ctx = canvas.getContext("2d", { + alpha: false + }); + const fontSize = 200; + const font = ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`; + const { + actualBoundingBoxLeft, + actualBoundingBoxRight, + actualBoundingBoxAscent, + actualBoundingBoxDescent, + fontBoundingBoxAscent, + fontBoundingBoxDescent, + width + } = ctx.measureText(text); + const SCALE = 1.5; + const canvasWidth = Math.ceil(Math.max(Math.abs(actualBoundingBoxLeft) + Math.abs(actualBoundingBoxRight) || 0, width) * SCALE); + const canvasHeight = Math.ceil(Math.max(Math.abs(actualBoundingBoxAscent) + Math.abs(actualBoundingBoxDescent) || fontSize, Math.abs(fontBoundingBoxAscent) + Math.abs(fontBoundingBoxDescent) || fontSize) * SCALE); + canvas = new OffscreenCanvas(canvasWidth, canvasHeight); + ctx = canvas.getContext("2d", { + alpha: true, + willReadFrequently: true + }); + ctx.font = font; + ctx.filter = "grayscale(1)"; + ctx.fillStyle = "white"; + ctx.fillRect(0, 0, canvasWidth, canvasHeight); + ctx.fillStyle = "black"; + ctx.fillText(text, canvasWidth * (SCALE - 1) / 2, canvasHeight * (3 - SCALE) / 2); + const uint8Buf = this.#toUint8(ctx.getImageData(0, 0, canvasWidth, canvasHeight).data); + const histogram = this.#getHistogram(uint8Buf); + const threshold = this.#guessThreshold(histogram); + const contourList = this.#findContours(uint8Buf, canvasWidth, canvasHeight, threshold); + return this.processDrawnLines({ + lines: { + curves: contourList, + width: canvasWidth, + height: canvasHeight + }, + pageWidth, + pageHeight, + rotation, + innerMargin, + mustSmooth: true, + areContours: true + }); + } + static process(bitmap, pageWidth, pageHeight, rotation, innerMargin) { + const [uint8Buf, width, height] = this.#getGrayPixels(bitmap); + const [buffer, histogram] = this.#bilateralFilter(uint8Buf, width, height, Math.hypot(width, height) * this.#PARAMETERS.sigmaSFactor, this.#PARAMETERS.sigmaR, this.#PARAMETERS.kernelSize); + const threshold = this.#guessThreshold(histogram); + const contourList = this.#findContours(buffer, width, height, threshold); + return this.processDrawnLines({ + lines: { + curves: contourList, + width, + height + }, + pageWidth, + pageHeight, + rotation, + innerMargin, + mustSmooth: true, + areContours: true + }); + } + static processDrawnLines({ + lines, + pageWidth, + pageHeight, + rotation, + innerMargin, + mustSmooth, + areContours + }) { + if (rotation % 180 !== 0) { + [pageWidth, pageHeight] = [pageHeight, pageWidth]; + } + const { + curves, + width, + height + } = lines; + const thickness = lines.thickness ?? 0; + const linesAndPoints = []; + const ratio = Math.min(pageWidth / width, pageHeight / height); + const xScale = ratio / pageWidth; + const yScale = ratio / pageHeight; + const newCurves = []; + for (const { + points + } of curves) { + const reducedPoints = mustSmooth ? this.#douglasPeucker(points) : points; + if (!reducedPoints) { + continue; + } + newCurves.push(reducedPoints); + const len = reducedPoints.length; + const newPoints = new Float32Array(len); + const line = new Float32Array(3 * (len === 2 ? 2 : len - 2)); + linesAndPoints.push({ + line, + points: newPoints + }); + if (len === 2) { + newPoints[0] = reducedPoints[0] * xScale; + newPoints[1] = reducedPoints[1] * yScale; + line.set([NaN, NaN, NaN, NaN, newPoints[0], newPoints[1]], 0); + continue; + } + let [x1, y1, x2, y2] = reducedPoints; + x1 *= xScale; + y1 *= yScale; + x2 *= xScale; + y2 *= yScale; + newPoints.set([x1, y1, x2, y2], 0); + line.set([NaN, NaN, NaN, NaN, x1, y1], 0); + for (let i = 4; i < len; i += 2) { + const x = newPoints[i] = reducedPoints[i] * xScale; + const y = newPoints[i + 1] = reducedPoints[i + 1] * yScale; + line.set(Outline.createBezierPoints(x1, y1, x2, y2, x, y), (i - 2) * 3); + [x1, y1, x2, y2] = [x2, y2, x, y]; + } + } + if (linesAndPoints.length === 0) { + return null; + } + const outline = areContours ? new ContourDrawOutline() : new InkDrawOutline(); + outline.build(linesAndPoints, pageWidth, pageHeight, 1, rotation, areContours ? 0 : thickness, innerMargin); + return { + outline, + newCurves, + areContours, + thickness, + width, + height + }; + } + static async compressSignature({ + outlines, + areContours, + thickness, + width, + height + }) { + let minDiff = Infinity; + let maxDiff = -Infinity; + let outlinesLength = 0; + for (const points of outlines) { + outlinesLength += points.length; + for (let i = 2, ii = points.length; i < ii; i++) { + const dx = points[i] - points[i - 2]; + minDiff = Math.min(minDiff, dx); + maxDiff = Math.max(maxDiff, dx); + } + } + let bufferType; + if (minDiff >= -128 && maxDiff <= 127) { + bufferType = Int8Array; + } else if (minDiff >= -32768 && maxDiff <= 32767) { + bufferType = Int16Array; + } else { + bufferType = Int32Array; + } + const len = outlines.length; + const headerLength = BASE_HEADER_LENGTH + POINTS_PROPERTIES_NUMBER * len; + const header = new Uint32Array(headerLength); + let offset = 0; + header[offset++] = headerLength * Uint32Array.BYTES_PER_ELEMENT + (outlinesLength - 2 * len) * bufferType.BYTES_PER_ELEMENT; + header[offset++] = 0; + header[offset++] = width; + header[offset++] = height; + header[offset++] = areContours ? 0 : 1; + header[offset++] = Math.max(0, Math.floor(thickness ?? 0)); + header[offset++] = len; + header[offset++] = bufferType.BYTES_PER_ELEMENT; + for (const points of outlines) { + header[offset++] = points.length - 2; + header[offset++] = points[0]; + header[offset++] = points[1]; + } + const cs = new CompressionStream("deflate-raw"); + const writer = cs.writable.getWriter(); + await writer.ready; + writer.write(header); + const BufferCtor = bufferType.prototype.constructor; + for (const points of outlines) { + const diffs = new BufferCtor(points.length - 2); + for (let i = 2, ii = points.length; i < ii; i++) { + diffs[i - 2] = points[i] - points[i - 2]; + } + writer.write(diffs); + } + writer.close(); + const buf = await new Response(cs.readable).arrayBuffer(); + const bytes = new Uint8Array(buf); + return bytes.toBase64(); + } + static async decompressSignature(signatureData) { + try { + const bytes = Uint8Array.fromBase64(signatureData); + const { + readable, + writable + } = new DecompressionStream("deflate-raw"); + const writer = writable.getWriter(); + await writer.ready; + writer.write(bytes).then(async () => { + await writer.ready; + await writer.close(); + }).catch(() => {}); + let data = null; + let offset = 0; + for await (const chunk of readable) { + data ||= new Uint8Array(new Uint32Array(chunk.buffer, 0, 4)[0]); + data.set(chunk, offset); + offset += chunk.length; + } + const header = new Uint32Array(data.buffer, 0, data.length >> 2); + const version = header[1]; + if (version !== 0) { + throw new Error(`Invalid version: ${version}`); + } + const width = header[2]; + const height = header[3]; + const areContours = header[4] === 0; + const thickness = header[5]; + const numberOfDrawings = header[6]; + const bufferType = header[7]; + const outlines = []; + const diffsOffset = (BASE_HEADER_LENGTH + POINTS_PROPERTIES_NUMBER * numberOfDrawings) * Uint32Array.BYTES_PER_ELEMENT; + let diffs; + switch (bufferType) { + case Int8Array.BYTES_PER_ELEMENT: + diffs = new Int8Array(data.buffer, diffsOffset); + break; + case Int16Array.BYTES_PER_ELEMENT: + diffs = new Int16Array(data.buffer, diffsOffset); + break; + case Int32Array.BYTES_PER_ELEMENT: + diffs = new Int32Array(data.buffer, diffsOffset); + break; + } + offset = 0; + for (let i = 0; i < numberOfDrawings; i++) { + const len = header[POINTS_PROPERTIES_NUMBER * i + BASE_HEADER_LENGTH]; + const points = new Float32Array(len + 2); + outlines.push(points); + for (let j = 0; j < POINTS_PROPERTIES_NUMBER - 1; j++) { + points[j] = header[POINTS_PROPERTIES_NUMBER * i + BASE_HEADER_LENGTH + j + 1]; + } + for (let j = 0; j < len; j++) { + points[j + 2] = points[j] + diffs[offset++]; + } + } + return { + areContours, + thickness, + outlines, + width, + height + }; + } catch (e) { + warn(`decompressSignature: ${e}`); + return null; + } + } +} + +;// ./src/display/editor/signature.js + + + + + + + +class SignatureOptions extends DrawingOptions { + constructor() { + super(); + super.updateProperties({ + fill: AnnotationEditor._defaultLineColor, + "stroke-width": 0 + }); + } + clone() { + const clone = new SignatureOptions(); + clone.updateAll(this); + return clone; + } +} +class DrawnSignatureOptions extends InkDrawingOptions { + constructor(viewerParameters) { + super(viewerParameters); + super.updateProperties({ + stroke: AnnotationEditor._defaultLineColor, + "stroke-width": 1 + }); + } + clone() { + const clone = new DrawnSignatureOptions(this._viewParameters); + clone.updateAll(this); + return clone; + } +} +class SignatureEditor extends DrawingEditor { + #isExtracted = false; + #description = null; + #signatureData = null; + #signatureUUID = null; + static _type = "signature"; + static _editorType = AnnotationEditorType.SIGNATURE; + static _defaultDrawingOptions = null; + constructor(params) { + super({ + ...params, + mustBeCommitted: true, + name: "signatureEditor" + }); + this._willKeepAspectRatio = true; + this.#signatureData = params.signatureData || null; + this.#description = null; + this.defaultL10nId = "pdfjs-editor-signature-editor1"; + } + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager); + this._defaultDrawingOptions = new SignatureOptions(); + this._defaultDrawnSignatureOptions = new DrawnSignatureOptions(uiManager.viewParameters); + } + static getDefaultDrawingOptions(options) { + const clone = this._defaultDrawingOptions.clone(); + clone.updateProperties(options); + return clone; + } + static get supportMultipleDrawings() { + return false; + } + static get typesMap() { + return shadow(this, "typesMap", new Map()); + } + static get isDrawer() { + return false; + } + get telemetryFinalData() { + return { + type: "signature", + hasDescription: !!this.#description + }; + } + static computeTelemetryFinalData(data) { + const hasDescriptionStats = data.get("hasDescription"); + return { + hasAltText: hasDescriptionStats.get(true) ?? 0, + hasNoAltText: hasDescriptionStats.get(false) ?? 0 + }; + } + get isResizable() { + return true; + } + onScaleChanging() { + if (this._drawId === null) { + return; + } + super.onScaleChanging(); + } + render() { + if (this.div) { + return this.div; + } + let baseX, baseY; + const { + _isCopy + } = this; + if (_isCopy) { + this._isCopy = false; + baseX = this.x; + baseY = this.y; + } + super.render(); + if (this._drawId === null) { + if (this.#signatureData) { + const { + lines, + mustSmooth, + areContours, + description, + uuid, + heightInPage + } = this.#signatureData; + const { + rawDims: { + pageWidth, + pageHeight + }, + rotation + } = this.parent.viewport; + const outline = SignatureExtractor.processDrawnLines({ + lines, + pageWidth, + pageHeight, + rotation, + innerMargin: SignatureEditor._INNER_MARGIN, + mustSmooth, + areContours + }); + this.addSignature(outline, heightInPage, description, uuid); + } else { + this.div.setAttribute("data-l10n-args", JSON.stringify({ + description: "" + })); + this.div.hidden = true; + this._uiManager.getSignature(this); + } + } else { + this.div.setAttribute("data-l10n-args", JSON.stringify({ + description: this.#description || "" + })); + } + if (_isCopy) { + this._isCopy = true; + this._moveAfterPaste(baseX, baseY); + } + return this.div; + } + setUuid(uuid) { + this.#signatureUUID = uuid; + this.addEditToolbar(); + } + getUuid() { + return this.#signatureUUID; + } + get description() { + return this.#description; + } + set description(description) { + this.#description = description; + if (!this.div) { + return; + } + this.div.setAttribute("data-l10n-args", JSON.stringify({ + description + })); + super.addEditToolbar().then(toolbar => { + toolbar?.updateEditSignatureButton(description); + }); + } + getSignaturePreview() { + const { + newCurves, + areContours, + thickness, + width, + height + } = this.#signatureData; + const maxDim = Math.max(width, height); + const outlineData = SignatureExtractor.processDrawnLines({ + lines: { + curves: newCurves.map(points => ({ + points + })), + thickness, + width, + height + }, + pageWidth: maxDim, + pageHeight: maxDim, + rotation: 0, + innerMargin: 0, + mustSmooth: false, + areContours + }); + return { + areContours, + outline: outlineData.outline + }; + } + get toolbarButtons() { + if (this._uiManager.signatureManager) { + return [["editSignature", this._uiManager.signatureManager]]; + } + return super.toolbarButtons; + } + addSignature(data, heightInPage, description, uuid) { + const { + x: savedX, + y: savedY + } = this; + const { + outline + } = this.#signatureData = data; + this.#isExtracted = outline instanceof ContourDrawOutline; + this.description = description; + let drawingOptions; + if (this.#isExtracted) { + drawingOptions = SignatureEditor.getDefaultDrawingOptions(); + } else { + drawingOptions = SignatureEditor._defaultDrawnSignatureOptions.clone(); + drawingOptions.updateProperties({ + "stroke-width": outline.thickness + }); + } + this._addOutlines({ + drawOutlines: outline, + drawingOptions + }); + const [, pageHeight] = this.pageDimensions; + let newHeight = heightInPage / pageHeight; + newHeight = newHeight >= 1 ? 0.5 : newHeight; + this.width *= newHeight / this.height; + if (this.width >= 1) { + newHeight *= 0.9 / this.width; + this.width = 0.9; + } + this.height = newHeight; + this.setDims(); + this.x = savedX; + this.y = savedY; + this.center(); + this._onResized(); + this.onScaleChanging(); + this.rotate(); + this._uiManager.addToAnnotationStorage(this); + this.setUuid(uuid); + this._reportTelemetry({ + action: "pdfjs.signature.inserted", + data: { + hasBeenSaved: !!uuid, + hasDescription: !!description + } + }); + this.div.hidden = false; + } + getFromImage(bitmap) { + const { + rawDims: { + pageWidth, + pageHeight + }, + rotation + } = this.parent.viewport; + return SignatureExtractor.process(bitmap, pageWidth, pageHeight, rotation, SignatureEditor._INNER_MARGIN); + } + getFromText(text, fontInfo) { + const { + rawDims: { + pageWidth, + pageHeight + }, + rotation + } = this.parent.viewport; + return SignatureExtractor.extractContoursFromText(text, fontInfo, pageWidth, pageHeight, rotation, SignatureEditor._INNER_MARGIN); + } + getDrawnSignature(curves) { + const { + rawDims: { + pageWidth, + pageHeight + }, + rotation + } = this.parent.viewport; + return SignatureExtractor.processDrawnLines({ + lines: curves, + pageWidth, + pageHeight, + rotation, + innerMargin: SignatureEditor._INNER_MARGIN, + mustSmooth: false, + areContours: false + }); + } + createDrawingOptions({ + areContours, + thickness + }) { + if (areContours) { + this._drawingOptions = SignatureEditor.getDefaultDrawingOptions(); + } else { + this._drawingOptions = SignatureEditor._defaultDrawnSignatureOptions.clone(); + this._drawingOptions.updateProperties({ + "stroke-width": thickness + }); + } + } + serialize(isForCopying = false) { + if (this.isEmpty()) { + return null; + } + const { + lines, + points + } = this.serializeDraw(isForCopying); + const { + _drawingOptions: { + "stroke-width": thickness + } + } = this; + const serialized = Object.assign(super.serialize(isForCopying), { + isSignature: true, + areContours: this.#isExtracted, + color: [0, 0, 0], + thickness: this.#isExtracted ? 0 : thickness + }); + this.addComment(serialized); + if (isForCopying) { + serialized.paths = { + lines, + points + }; + serialized.uuid = this.#signatureUUID; + serialized.isCopy = true; + } else { + serialized.lines = lines; + } + if (this.#description) { + serialized.accessibilityData = { + type: "Figure", + alt: this.#description + }; + } + return serialized; + } + static deserializeDraw(pageX, pageY, pageWidth, pageHeight, innerMargin, data) { + if (data.areContours) { + return ContourDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data); + } + return InkDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data); + } + static async deserialize(data, parent, uiManager) { + const editor = await super.deserialize(data, parent, uiManager); + editor.#isExtracted = data.areContours; + editor.description = data.accessibilityData?.alt || ""; + editor.#signatureUUID = data.uuid; + return editor; + } +} + +;// ./src/display/editor/stamp.js + + + + +class StampEditor extends AnnotationEditor { + #bitmap = null; + #bitmapId = null; + #bitmapPromise = null; + #bitmapUrl = null; + #bitmapFile = null; + #bitmapFileName = ""; + #canvas = null; + #missingCanvas = false; + #resizeTimeoutId = null; + #isSvg = false; + #hasBeenAddedInUndoStack = false; + static _type = "stamp"; + static _editorType = AnnotationEditorType.STAMP; + constructor(params) { + super({ + ...params, + name: "stampEditor" + }); + this.#bitmapUrl = params.bitmapUrl; + this.#bitmapFile = params.bitmapFile; + this.defaultL10nId = "pdfjs-editor-stamp-editor"; + } + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager); + } + static isHandlingMimeForPasting(mime) { + return SupportedImageMimeTypes.includes(mime); + } + static paste(item, parent) { + parent.pasteEditor({ + mode: AnnotationEditorType.STAMP + }, { + bitmapFile: item.getAsFile() + }); + } + altTextFinish() { + if (this._uiManager.useNewAltTextFlow) { + this.div.hidden = false; + } + super.altTextFinish(); + } + get telemetryFinalData() { + return { + type: "stamp", + hasAltText: !!this.altTextData?.altText + }; + } + static computeTelemetryFinalData(data) { + const hasAltTextStats = data.get("hasAltText"); + return { + hasAltText: hasAltTextStats.get(true) ?? 0, + hasNoAltText: hasAltTextStats.get(false) ?? 0 + }; + } + #getBitmapFetched(data, fromId = false) { + if (!data) { + this.remove(); + return; + } + this.#bitmap = data.bitmap; + if (!fromId) { + this.#bitmapId = data.id; + this.#isSvg = data.isSvg; + } + if (data.file) { + this.#bitmapFileName = data.file.name; + } + this.#createCanvas(); + } + #getBitmapDone() { + this.#bitmapPromise = null; + this._uiManager.enableWaiting(false); + if (!this.#canvas) { + return; + } + if (this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) { + this.addEditToolbar().then(() => { + this._editToolbar.hide(); + this._uiManager.editAltText(this, true); + }); + return; + } + if (!this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) { + this._reportTelemetry({ + action: "pdfjs.image.image_added", + data: { + alt_text_modal: false, + alt_text_type: "empty" + } + }); + try { + this.mlGuessAltText(); + } catch {} + } + this.div.focus(); + } + async mlGuessAltText(imageData = null, updateAltTextData = true) { + if (this.hasAltTextData()) { + return null; + } + const { + mlManager + } = this._uiManager; + if (!mlManager) { + throw new Error("No ML."); + } + if (!(await mlManager.isEnabledFor("altText"))) { + throw new Error("ML isn't enabled for alt text."); + } + const { + data, + width, + height + } = imageData || this.copyCanvas(null, null, true).imageData; + const response = await mlManager.guess({ + name: "altText", + request: { + data, + width, + height, + channels: data.length / (width * height) + } + }); + if (!response) { + throw new Error("No response from the AI service."); + } + if (response.error) { + throw new Error("Error from the AI service."); + } + if (response.cancel) { + return null; + } + if (!response.output) { + throw new Error("No valid response from the AI service."); + } + const altText = response.output; + await this.setGuessedAltText(altText); + if (updateAltTextData && !this.hasAltTextData()) { + this.altTextData = { + alt: altText, + decorative: false + }; + } + return altText; + } + #getBitmap() { + if (this.#bitmapId) { + this._uiManager.enableWaiting(true); + this._uiManager.imageManager.getFromId(this.#bitmapId).then(data => this.#getBitmapFetched(data, true)).finally(() => this.#getBitmapDone()); + return; + } + if (this.#bitmapUrl) { + const url = this.#bitmapUrl; + this.#bitmapUrl = null; + this._uiManager.enableWaiting(true); + this.#bitmapPromise = this._uiManager.imageManager.getFromUrl(url).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone()); + return; + } + if (this.#bitmapFile) { + const file = this.#bitmapFile; + this.#bitmapFile = null; + this._uiManager.enableWaiting(true); + this.#bitmapPromise = this._uiManager.imageManager.getFromFile(file).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone()); + return; + } + const input = document.createElement("input"); + input.type = "file"; + input.accept = SupportedImageMimeTypes.join(","); + const signal = this._uiManager._signal; + this.#bitmapPromise = new Promise(resolve => { + input.addEventListener("change", async () => { + if (!input.files || input.files.length === 0) { + this.remove(); + } else { + this._uiManager.enableWaiting(true); + const data = await this._uiManager.imageManager.getFromFile(input.files[0]); + this._reportTelemetry({ + action: "pdfjs.image.image_selected", + data: { + alt_text_modal: this._uiManager.useNewAltTextFlow + } + }); + this.#getBitmapFetched(data); + } + resolve(); + }, { + signal + }); + input.addEventListener("cancel", () => { + this.remove(); + resolve(); + }, { + signal + }); + }).finally(() => this.#getBitmapDone()); + input.click(); + } + remove() { + if (this.#bitmapId) { + this.#bitmap = null; + this._uiManager.imageManager.deleteId(this.#bitmapId); + this.#canvas?.remove(); + this.#canvas = null; + if (this.#resizeTimeoutId) { + clearTimeout(this.#resizeTimeoutId); + this.#resizeTimeoutId = null; + } + } + super.remove(); + } + rebuild() { + if (!this.parent) { + if (this.#bitmapId) { + this.#getBitmap(); + } + return; + } + super.rebuild(); + if (this.div === null) { + return; + } + if (this.#bitmapId && this.#canvas === null) { + this.#getBitmap(); + } + if (!this.isAttachedToDOM) { + this.parent.add(this); + } + } + onceAdded(focus) { + this._isDraggable = true; + if (focus) { + this.div.focus(); + } + } + isEmpty() { + return !(this.#bitmapPromise || this.#bitmap || this.#bitmapUrl || this.#bitmapFile || this.#bitmapId || this.#missingCanvas); + } + get toolbarButtons() { + return [["altText", this.createAltText()]]; + } + get isResizable() { + return true; + } + render() { + if (this.div) { + return this.div; + } + let baseX, baseY; + if (this._isCopy) { + baseX = this.x; + baseY = this.y; + } + super.render(); + this.div.hidden = true; + this.createAltText(); + if (!this.#missingCanvas) { + if (this.#bitmap) { + this.#createCanvas(); + } else { + this.#getBitmap(); + } + } + if (this._isCopy) { + this._moveAfterPaste(baseX, baseY); + } + this._uiManager.addShouldRescale(this); + return this.div; + } + setCanvas(annotationElementId, canvas) { + const { + id: bitmapId, + bitmap + } = this._uiManager.imageManager.getFromCanvas(annotationElementId, canvas); + canvas.remove(); + if (bitmapId && this._uiManager.imageManager.isValidId(bitmapId)) { + this.#bitmapId = bitmapId; + if (bitmap) { + this.#bitmap = bitmap; + } + this.#missingCanvas = false; + this.#createCanvas(); + } + } + _onResized() { + this.onScaleChanging(); + } + onScaleChanging() { + if (!this.parent) { + return; + } + if (this.#resizeTimeoutId !== null) { + clearTimeout(this.#resizeTimeoutId); + } + const TIME_TO_WAIT = 200; + this.#resizeTimeoutId = setTimeout(() => { + this.#resizeTimeoutId = null; + this.#drawBitmap(); + }, TIME_TO_WAIT); + } + #createCanvas() { + const { + div + } = this; + let { + width, + height + } = this.#bitmap; + const [pageWidth, pageHeight] = this.pageDimensions; + const MAX_RATIO = 0.75; + if (this.width) { + width = this.width * pageWidth; + height = this.height * pageHeight; + } else if (width > MAX_RATIO * pageWidth || height > MAX_RATIO * pageHeight) { + const factor = Math.min(MAX_RATIO * pageWidth / width, MAX_RATIO * pageHeight / height); + width *= factor; + height *= factor; + } + this._uiManager.enableWaiting(false); + const canvas = this.#canvas = document.createElement("canvas"); + canvas.setAttribute("role", "img"); + this.addContainer(canvas); + this.width = width / pageWidth; + this.height = height / pageHeight; + this.setDims(); + if (this._initialOptions?.isCentered) { + this.center(); + } else { + this.fixAndSetPosition(); + } + this._initialOptions = null; + if (!this._uiManager.useNewAltTextWhenAddingImage || !this._uiManager.useNewAltTextFlow || this.annotationElementId) { + div.hidden = false; + } + this.#drawBitmap(); + if (!this.#hasBeenAddedInUndoStack) { + this.parent.addUndoableEditor(this); + this.#hasBeenAddedInUndoStack = true; + } + this._reportTelemetry({ + action: "inserted_image" + }); + if (this.#bitmapFileName) { + this.div.setAttribute("aria-description", this.#bitmapFileName); + } + if (!this.annotationElementId) { + this._uiManager.a11yAlert("pdfjs-editor-stamp-added-alert"); + } + } + copyCanvas(maxDataDimension, maxPreviewDimension, createImageData = false) { + if (!maxDataDimension) { + maxDataDimension = 224; + } + const { + width: bitmapWidth, + height: bitmapHeight + } = this.#bitmap; + const outputScale = new OutputScale(); + let bitmap = this.#bitmap; + let width = bitmapWidth, + height = bitmapHeight; + let canvas = null; + if (maxPreviewDimension) { + if (bitmapWidth > maxPreviewDimension || bitmapHeight > maxPreviewDimension) { + const ratio = Math.min(maxPreviewDimension / bitmapWidth, maxPreviewDimension / bitmapHeight); + width = Math.floor(bitmapWidth * ratio); + height = Math.floor(bitmapHeight * ratio); + } + canvas = document.createElement("canvas"); + const scaledWidth = canvas.width = Math.ceil(width * outputScale.sx); + const scaledHeight = canvas.height = Math.ceil(height * outputScale.sy); + if (!this.#isSvg) { + bitmap = this.#scaleBitmap(scaledWidth, scaledHeight); + } + const ctx = canvas.getContext("2d"); + ctx.filter = this._uiManager.hcmFilter; + let white = "white", + black = "#cfcfd8"; + if (this._uiManager.hcmFilter !== "none") { + black = "black"; + } else if (ColorScheme.isDarkMode) { + white = "#8f8f9d"; + black = "#42414d"; + } + const boxDim = 15; + const boxDimWidth = boxDim * outputScale.sx; + const boxDimHeight = boxDim * outputScale.sy; + const pattern = new OffscreenCanvas(boxDimWidth * 2, boxDimHeight * 2); + const patternCtx = pattern.getContext("2d"); + patternCtx.fillStyle = white; + patternCtx.fillRect(0, 0, boxDimWidth * 2, boxDimHeight * 2); + patternCtx.fillStyle = black; + patternCtx.fillRect(0, 0, boxDimWidth, boxDimHeight); + patternCtx.fillRect(boxDimWidth, boxDimHeight, boxDimWidth, boxDimHeight); + ctx.fillStyle = ctx.createPattern(pattern, "repeat"); + ctx.fillRect(0, 0, scaledWidth, scaledHeight); + ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight); + } + let imageData = null; + if (createImageData) { + let dataWidth, dataHeight; + if (outputScale.symmetric && bitmap.width < maxDataDimension && bitmap.height < maxDataDimension) { + dataWidth = bitmap.width; + dataHeight = bitmap.height; + } else { + bitmap = this.#bitmap; + if (bitmapWidth > maxDataDimension || bitmapHeight > maxDataDimension) { + const ratio = Math.min(maxDataDimension / bitmapWidth, maxDataDimension / bitmapHeight); + dataWidth = Math.floor(bitmapWidth * ratio); + dataHeight = Math.floor(bitmapHeight * ratio); + if (!this.#isSvg) { + bitmap = this.#scaleBitmap(dataWidth, dataHeight); + } + } + } + const offscreen = new OffscreenCanvas(dataWidth, dataHeight); + const offscreenCtx = offscreen.getContext("2d", { + willReadFrequently: true + }); + offscreenCtx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, dataWidth, dataHeight); + imageData = { + width: dataWidth, + height: dataHeight, + data: offscreenCtx.getImageData(0, 0, dataWidth, dataHeight).data + }; + } + return { + canvas, + width, + height, + imageData + }; + } + #scaleBitmap(width, height) { + const { + width: bitmapWidth, + height: bitmapHeight + } = this.#bitmap; + let newWidth = bitmapWidth; + let newHeight = bitmapHeight; + let bitmap = this.#bitmap; + while (newWidth > 2 * width || newHeight > 2 * height) { + const prevWidth = newWidth; + const prevHeight = newHeight; + if (newWidth > 2 * width) { + newWidth = newWidth >= 16384 ? Math.floor(newWidth / 2) - 1 : Math.ceil(newWidth / 2); + } + if (newHeight > 2 * height) { + newHeight = newHeight >= 16384 ? Math.floor(newHeight / 2) - 1 : Math.ceil(newHeight / 2); + } + const offscreen = new OffscreenCanvas(newWidth, newHeight); + const ctx = offscreen.getContext("2d"); + ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight); + bitmap = offscreen.transferToImageBitmap(); + } + return bitmap; + } + #drawBitmap() { + const [parentWidth, parentHeight] = this.parentDimensions; + const { + width, + height + } = this; + const outputScale = new OutputScale(); + const scaledWidth = Math.ceil(width * parentWidth * outputScale.sx); + const scaledHeight = Math.ceil(height * parentHeight * outputScale.sy); + const canvas = this.#canvas; + if (!canvas || canvas.width === scaledWidth && canvas.height === scaledHeight) { + return; + } + canvas.width = scaledWidth; + canvas.height = scaledHeight; + const bitmap = this.#isSvg ? this.#bitmap : this.#scaleBitmap(scaledWidth, scaledHeight); + const ctx = canvas.getContext("2d"); + ctx.filter = this._uiManager.hcmFilter; + ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight); + } + #serializeBitmap(toUrl) { + if (toUrl) { + if (this.#isSvg) { + const url = this._uiManager.imageManager.getSvgUrl(this.#bitmapId); + if (url) { + return url; + } + } + const canvas = document.createElement("canvas"); + ({ + width: canvas.width, + height: canvas.height + } = this.#bitmap); + const ctx = canvas.getContext("2d"); + ctx.drawImage(this.#bitmap, 0, 0); + return canvas.toDataURL(); + } + if (this.#isSvg) { + const [pageWidth, pageHeight] = this.pageDimensions; + const width = Math.round(this.width * pageWidth * PixelsPerInch.PDF_TO_CSS_UNITS); + const height = Math.round(this.height * pageHeight * PixelsPerInch.PDF_TO_CSS_UNITS); + const offscreen = new OffscreenCanvas(width, height); + const ctx = offscreen.getContext("2d"); + ctx.drawImage(this.#bitmap, 0, 0, this.#bitmap.width, this.#bitmap.height, 0, 0, width, height); + return offscreen.transferToImageBitmap(); + } + return structuredClone(this.#bitmap); + } + static async deserialize(data, parent, uiManager) { + let initialData = null; + let missingCanvas = false; + if (data instanceof StampAnnotationElement) { + const { + data: { + rect, + rotation, + id, + structParent, + popupRef, + richText, + contentsObj, + creationDate, + modificationDate + }, + container, + parent: { + page: { + pageNumber + } + }, + canvas + } = data; + let bitmapId, bitmap; + if (canvas) { + delete data.canvas; + ({ + id: bitmapId, + bitmap + } = uiManager.imageManager.getFromCanvas(container.id, canvas)); + canvas.remove(); + } else { + missingCanvas = true; + data._hasNoCanvas = true; + } + const altText = (await parent._structTree.getAriaAttributes(`${AnnotationPrefix}${id}`))?.get("aria-label") || ""; + initialData = data = { + annotationType: AnnotationEditorType.STAMP, + bitmapId, + bitmap, + pageIndex: pageNumber - 1, + rect: rect.slice(0), + rotation, + annotationElementId: id, + id, + deleted: false, + accessibilityData: { + decorative: false, + altText + }, + isSvg: false, + structParent, + popupRef, + richText, + comment: contentsObj?.str || null, + creationDate, + modificationDate + }; + } + const editor = await super.deserialize(data, parent, uiManager); + const { + rect, + bitmap, + bitmapUrl, + bitmapId, + isSvg, + accessibilityData + } = data; + if (missingCanvas) { + uiManager.addMissingCanvas(data.id, editor); + editor.#missingCanvas = true; + } else if (bitmapId && uiManager.imageManager.isValidId(bitmapId)) { + editor.#bitmapId = bitmapId; + if (bitmap) { + editor.#bitmap = bitmap; + } + } else { + editor.#bitmapUrl = bitmapUrl; + } + editor.#isSvg = isSvg; + const [parentWidth, parentHeight] = editor.pageDimensions; + editor.width = (rect[2] - rect[0]) / parentWidth; + editor.height = (rect[3] - rect[1]) / parentHeight; + if (accessibilityData) { + editor.altTextData = accessibilityData; + } + editor._initialData = initialData; + if (data.comment) { + editor.setCommentData(data); + } + editor.#hasBeenAddedInUndoStack = !!initialData; + return editor; + } + serialize(isForCopying = false, context = null) { + if (this.isEmpty()) { + return null; + } + if (this.deleted) { + return this.serializeDeleted(); + } + const serialized = Object.assign(super.serialize(isForCopying), { + bitmapId: this.#bitmapId, + isSvg: this.#isSvg + }); + this.addComment(serialized); + if (isForCopying) { + serialized.bitmapUrl = this.#serializeBitmap(true); + serialized.accessibilityData = this.serializeAltText(true); + serialized.isCopy = true; + return serialized; + } + const { + decorative, + altText + } = this.serializeAltText(false); + if (!decorative && altText) { + serialized.accessibilityData = { + type: "Figure", + alt: altText + }; + } + if (this.annotationElementId) { + const changes = this.#hasElementChanged(serialized); + if (changes.isSame) { + return null; + } + if (changes.isSameAltText) { + delete serialized.accessibilityData; + } else { + serialized.accessibilityData.structParent = this._initialData.structParent ?? -1; + } + serialized.id = this.annotationElementId; + delete serialized.bitmapId; + return serialized; + } + if (context === null) { + return serialized; + } + context.stamps ||= new Map(); + const area = this.#isSvg ? (serialized.rect[2] - serialized.rect[0]) * (serialized.rect[3] - serialized.rect[1]) : null; + if (!context.stamps.has(this.#bitmapId)) { + context.stamps.set(this.#bitmapId, { + area, + serialized + }); + serialized.bitmap = this.#serializeBitmap(false); + } else if (this.#isSvg) { + const prevData = context.stamps.get(this.#bitmapId); + if (area > prevData.area) { + prevData.area = area; + prevData.serialized.bitmap.close(); + prevData.serialized.bitmap = this.#serializeBitmap(false); + } + } + return serialized; + } + #hasElementChanged(serialized) { + const { + pageIndex, + accessibilityData: { + altText + } + } = this._initialData; + const isSamePageIndex = serialized.pageIndex === pageIndex; + const isSameAltText = (serialized.accessibilityData?.alt || "") === altText; + return { + isSame: !this.hasEditedComment && !this._hasBeenMoved && !this._hasBeenResized && isSamePageIndex && isSameAltText, + isSameAltText + }; + } + renderAnnotationElement(annotation) { + if (this.deleted) { + annotation.hide(); + return null; + } + annotation.updateEdited({ + rect: this.getPDFRect(), + popup: this.comment + }); + return null; + } +} + +;// ./src/display/editor/annotation_editor_layer.js + + + + + + + + +class AnnotationEditorLayer { + #accessibilityManager; + #allowClick = false; + #annotationLayer = null; + #clickAC = null; + #editorFocusTimeoutId = null; + #editors = new Map(); + #hadPointerDown = false; + #isDisabling = false; + #isEnabling = false; + #drawingAC = null; + #focusedElement = null; + #textLayer = null; + #textSelectionAC = null; + #textLayerDblClickAC = null; + #lastPointerDownTimestamp = -1; + #uiManager; + static _initialized = false; + static #editorTypes = new Map([FreeTextEditor, InkEditor, StampEditor, HighlightEditor, SignatureEditor].map(type => [type._editorType, type])); + constructor({ + uiManager, + pageIndex, + div, + structTreeLayer, + accessibilityManager, + annotationLayer, + drawLayer, + textLayer, + viewport, + l10n + }) { + const editorTypes = [...AnnotationEditorLayer.#editorTypes.values()]; + if (!AnnotationEditorLayer._initialized) { + AnnotationEditorLayer._initialized = true; + for (const editorType of editorTypes) { + editorType.initialize(l10n, uiManager); + } + } + uiManager.registerEditorTypes(editorTypes); + this.#uiManager = uiManager; + this.pageIndex = pageIndex; + this.div = div; + this.#accessibilityManager = accessibilityManager; + this.#annotationLayer = annotationLayer; + this.viewport = viewport; + this.#textLayer = textLayer; + this.drawLayer = drawLayer; + this._structTree = structTreeLayer; + this.#uiManager.addLayer(this); + } + updatePageIndex(newPageIndex) { + for (const editor of this.#allEditorsIterator) { + editor.updatePageIndex(newPageIndex); + } + this.pageIndex = newPageIndex; + this.#uiManager.addLayer(this); + } + async setClonedFrom(clonedFrom) { + if (!clonedFrom) { + return; + } + const promises = []; + for (const editor of clonedFrom.#allEditorsIterator) { + const serialized = editor.serialize(true); + if (!serialized) { + continue; + } + serialized.isCopy = false; + promises.push(this.deserialize(serialized).then(deserialized => { + if (deserialized) { + this.addOrRebuild(deserialized); + } + })); + } + await Promise.all(promises); + } + get isEmpty() { + return this.#editors.size === 0; + } + get isInvisible() { + return this.isEmpty && this.#uiManager.getMode() === AnnotationEditorType.NONE; + } + updateToolbar(options) { + this.#uiManager.updateToolbar(options); + } + updateMode(mode = this.#uiManager.getMode()) { + this.#cleanup(); + switch (mode) { + case AnnotationEditorType.NONE: + this.div.classList.toggle("nonEditing", true); + this.disableTextSelection(); + this.togglePointerEvents(false); + this.toggleAnnotationLayerPointerEvents(true); + this.disableClick(); + return; + case AnnotationEditorType.INK: + this.disableTextSelection(); + this.togglePointerEvents(true); + this.enableClick(); + break; + case AnnotationEditorType.HIGHLIGHT: + this.enableTextSelection(); + this.togglePointerEvents(false); + this.disableClick(); + break; + default: + this.disableTextSelection(); + this.togglePointerEvents(true); + this.enableClick(); + } + this.toggleAnnotationLayerPointerEvents(false); + const { + classList + } = this.div; + classList.toggle("nonEditing", false); + if (mode === AnnotationEditorType.POPUP) { + classList.toggle("commentEditing", true); + } else { + classList.toggle("commentEditing", false); + for (const editorType of AnnotationEditorLayer.#editorTypes.values()) { + classList.toggle(`${editorType._type}Editing`, mode === editorType._editorType); + } + } + this.div.hidden = false; + } + hasTextLayer(textLayer) { + return textLayer === this.#textLayer?.div; + } + setEditingState(isEditing) { + this.#uiManager.setEditingState(isEditing); + } + addCommands(params) { + this.#uiManager.addCommands(params); + } + cleanUndoStack(type) { + this.#uiManager.cleanUndoStack(type); + } + toggleDrawing(enabled = false) { + this.div.classList.toggle("drawing", !enabled); + } + togglePointerEvents(enabled = false) { + this.div.classList.toggle("disabled", !enabled); + } + toggleAnnotationLayerPointerEvents(enabled = false) { + this.#annotationLayer?.togglePointerEvents(enabled); + } + get #allEditorsIterator() { + return this.#editors.size !== 0 ? this.#editors.values() : this.#uiManager.getEditors(this.pageIndex); + } + async enable() { + this.#isEnabling = true; + this.div.tabIndex = 0; + this.togglePointerEvents(true); + this.div.classList.toggle("nonEditing", false); + this.#textLayerDblClickAC?.abort(); + this.#textLayerDblClickAC = null; + const annotationElementIds = new Set(); + for (const editor of this.#allEditorsIterator) { + editor.enableEditing(); + editor.show(true); + if (editor.annotationElementId) { + this.#uiManager.removeChangedExistingAnnotation(editor); + annotationElementIds.add(editor.annotationElementId); + } + } + const annotationLayer = this.#annotationLayer; + if (annotationLayer) { + for (const editable of annotationLayer.getEditableAnnotations()) { + editable.hide(); + if (this.#uiManager.isDeletedAnnotationElement(editable.data.id)) { + continue; + } + if (annotationElementIds.has(editable.data.id)) { + continue; + } + const editor = await this.deserialize(editable); + if (!editor) { + continue; + } + this.addOrRebuild(editor); + editor.enableEditing(); + } + } + this.#isEnabling = false; + this.#uiManager._eventBus.dispatch("editorsrendered", { + source: this, + pageNumber: this.pageIndex + 1 + }); + } + disable() { + this.#isDisabling = true; + this.div.tabIndex = -1; + this.togglePointerEvents(false); + this.div.classList.toggle("nonEditing", true); + if (this.#textLayer && !this.#textLayerDblClickAC) { + this.#textLayerDblClickAC = new AbortController(); + const signal = this.#uiManager.combinedSignal(this.#textLayerDblClickAC); + this.#textLayer.div.addEventListener("pointerdown", e => { + const DBL_CLICK_THRESHOLD = 500; + const { + clientX, + clientY, + timeStamp + } = e; + const lastPointerDownTimestamp = this.#lastPointerDownTimestamp; + if (timeStamp - lastPointerDownTimestamp > DBL_CLICK_THRESHOLD) { + this.#lastPointerDownTimestamp = timeStamp; + return; + } + this.#lastPointerDownTimestamp = -1; + const { + classList + } = this.div; + classList.toggle("getElements", true); + const elements = document.elementsFromPoint(clientX, clientY); + classList.toggle("getElements", false); + if (!this.div.contains(elements[0])) { + return; + } + let id; + const regex = new RegExp(`^${AnnotationEditorPrefix}[0-9]+$`); + for (const element of elements) { + if (regex.test(element.id)) { + id = element.id; + break; + } + } + if (!id) { + return; + } + const editor = this.#editors.get(id); + if (editor?.annotationElementId === null) { + e.stopPropagation(); + e.preventDefault(); + editor.dblclick(e); + } + }, { + signal, + capture: true + }); + } + const annotationLayer = this.#annotationLayer; + const needFakeAnnotation = []; + if (annotationLayer) { + const changedAnnotations = new Map(); + const resetAnnotations = new Map(); + for (const editor of this.#allEditorsIterator) { + editor.disableEditing(); + if (!editor.annotationElementId) { + needFakeAnnotation.push(editor); + continue; + } + if (editor.serialize() !== null) { + changedAnnotations.set(editor.annotationElementId, editor); + continue; + } else { + resetAnnotations.set(editor.annotationElementId, editor); + } + this.getEditableAnnotation(editor.annotationElementId)?.show(); + editor.remove(); + } + const editables = annotationLayer.getEditableAnnotations(); + for (const editable of editables) { + const { + id + } = editable.data; + if (this.#uiManager.isDeletedAnnotationElement(id)) { + editable.updateEdited({ + deleted: true + }); + continue; + } + let editor = resetAnnotations.get(id); + if (editor) { + editor.resetAnnotationElement(editable); + editor.show(false); + editable.show(); + continue; + } + editor = changedAnnotations.get(id); + if (editor) { + this.#uiManager.addChangedExistingAnnotation(editor); + if (editor.renderAnnotationElement(editable)) { + editor.show(false); + } + } + editable.show(); + } + } + this.#cleanup(); + if (this.isEmpty) { + this.div.hidden = true; + } + const { + classList + } = this.div; + for (const editorType of AnnotationEditorLayer.#editorTypes.values()) { + classList.remove(`${editorType._type}Editing`); + } + this.disableTextSelection(); + this.toggleAnnotationLayerPointerEvents(true); + annotationLayer?.updateFakeAnnotations(needFakeAnnotation); + this.#isDisabling = false; + } + getEditableAnnotation(id) { + return this.#annotationLayer?.getEditableAnnotation(id) || null; + } + setActiveEditor(editor) { + const currentActive = this.#uiManager.getActive(); + if (currentActive === editor) { + return; + } + this.#uiManager.setActiveEditor(editor); + } + enableTextSelection() { + this.div.tabIndex = -1; + if (this.#textLayer?.div && !this.#textSelectionAC) { + this.#textSelectionAC = new AbortController(); + const signal = this.#uiManager.combinedSignal(this.#textSelectionAC); + this.#textLayer.div.addEventListener("pointerdown", this.#textLayerPointerDown.bind(this), { + signal + }); + this.#textLayer.div.classList.add("highlighting"); + } + } + disableTextSelection() { + this.div.tabIndex = 0; + if (this.#textLayer?.div && this.#textSelectionAC) { + this.#textSelectionAC.abort(); + this.#textSelectionAC = null; + this.#textLayer.div.classList.remove("highlighting"); + } + } + #textLayerPointerDown(event) { + this.#uiManager.unselectAll(); + const { + target + } = event; + if (target === this.#textLayer.div || (target.getAttribute("role") === "img" || target.classList.contains("endOfContent")) && this.#textLayer.div.contains(target)) { + const { + isMac + } = FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + return; + } + this.#uiManager.showAllEditors("highlight", true, true); + this.#textLayer.div.classList.add("free"); + this.toggleDrawing(); + HighlightEditor.startHighlighting(this, this.#uiManager.direction === "ltr", { + target: this.#textLayer.div, + x: event.x, + y: event.y + }); + this.#textLayer.div.addEventListener("pointerup", () => { + this.#textLayer.div.classList.remove("free"); + this.toggleDrawing(true); + }, { + once: true, + signal: this.#uiManager._signal + }); + event.preventDefault(); + } + } + enableClick() { + if (this.#clickAC) { + return; + } + this.#clickAC = new AbortController(); + const signal = this.#uiManager.combinedSignal(this.#clickAC); + this.div.addEventListener("pointerdown", this.pointerdown.bind(this), { + signal + }); + const pointerup = this.pointerup.bind(this); + this.div.addEventListener("pointerup", pointerup, { + signal + }); + this.div.addEventListener("pointercancel", pointerup, { + signal + }); + } + disableClick() { + this.#clickAC?.abort(); + this.#clickAC = null; + } + attach(editor) { + this.#editors.set(editor.id, editor); + const { + annotationElementId + } = editor; + if (annotationElementId && this.#uiManager.isDeletedAnnotationElement(annotationElementId)) { + this.#uiManager.removeDeletedAnnotationElement(editor); + } + } + detach(editor) { + this.#editors.delete(editor.id); + this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv); + if (!this.#isDisabling && editor.annotationElementId) { + this.#uiManager.addDeletedAnnotationElement(editor); + } + } + remove(editor) { + this.detach(editor); + this.#uiManager.removeEditor(editor); + editor.div.remove(); + editor.isAttachedToDOM = false; + } + changeParent(editor) { + if (editor.parent === this) { + return; + } + if (editor.parent && editor.annotationElementId) { + this.#uiManager.addDeletedAnnotationElement(editor); + AnnotationEditor.deleteAnnotationElement(editor); + editor.annotationElementId = null; + } + this.attach(editor); + editor.parent?.detach(editor); + editor.setParent(this); + if (editor.div && editor.isAttachedToDOM) { + editor.div.remove(); + this.div.append(editor.div); + } + } + add(editor) { + if (editor.parent === this && editor.isAttachedToDOM) { + return; + } + this.changeParent(editor); + this.#uiManager.addEditor(editor); + this.attach(editor); + if (!editor.isAttachedToDOM) { + const div = editor.render(); + this.div.append(div); + editor.isAttachedToDOM = true; + } + editor.fixAndSetPosition(); + editor.onceAdded(!this.#isEnabling); + this.#uiManager.addToAnnotationStorage(editor); + editor._reportTelemetry(editor.telemetryInitialData); + } + moveEditorInDOM(editor) { + if (!editor.isAttachedToDOM) { + return; + } + const { + activeElement + } = document; + if (editor.div.contains(activeElement) && !this.#editorFocusTimeoutId) { + editor._focusEventsAllowed = false; + this.#editorFocusTimeoutId = setTimeout(() => { + this.#editorFocusTimeoutId = null; + if (!editor.div.contains(document.activeElement)) { + editor.div.addEventListener("focusin", () => { + editor._focusEventsAllowed = true; + }, { + once: true, + signal: this.#uiManager._signal + }); + activeElement.focus(); + } else { + editor._focusEventsAllowed = true; + } + }, 0); + } + editor._structTreeParentId = this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true); + } + addOrRebuild(editor) { + if (editor.needsToBeRebuilt()) { + editor.parent ||= this; + editor.rebuild(); + editor.show(); + } else { + this.add(editor); + } + } + addUndoableEditor(editor) { + const cmd = () => editor._uiManager.rebuild(editor); + const undo = () => { + editor.remove(); + }; + this.addCommands({ + cmd, + undo, + mustExec: false + }); + } + getEditorByUID(uid) { + for (const editor of this.#editors.values()) { + if (editor.uid === uid) { + return editor; + } + } + return null; + } + getNextId() { + return this.#uiManager.getId(); + } + get #currentEditorType() { + return AnnotationEditorLayer.#editorTypes.get(this.#uiManager.getMode()); + } + combinedSignal(ac) { + return this.#uiManager.combinedSignal(ac); + } + #createNewEditor(params) { + const editorType = this.#currentEditorType; + return editorType ? new editorType.prototype.constructor(params) : null; + } + canCreateNewEmptyEditor() { + return this.#currentEditorType?.canCreateNewEmptyEditor(); + } + async pasteEditor(options, params) { + this.updateToolbar(options); + await this.#uiManager.updateMode(options.mode); + const { + offsetX, + offsetY + } = this.#getCenterPoint(); + const id = this.getNextId(); + const editor = this.#createNewEditor({ + parent: this, + id, + x: offsetX, + y: offsetY, + uiManager: this.#uiManager, + isCentered: true, + ...params + }); + if (editor) { + this.add(editor); + } + } + async deserialize(data) { + return (await AnnotationEditorLayer.#editorTypes.get(data.annotationType ?? data.annotationEditorType)?.deserialize(data, this, this.#uiManager)) || null; + } + createAndAddNewEditor(event, isCentered, data = {}) { + const id = this.getNextId(); + const editor = this.#createNewEditor({ + parent: this, + id, + x: event.offsetX, + y: event.offsetY, + uiManager: this.#uiManager, + isCentered, + ...data + }); + if (editor) { + this.add(editor); + } + return editor; + } + get boundingClientRect() { + return this.div.getBoundingClientRect(); + } + #getCenterPoint() { + const { + x, + y, + width, + height + } = this.boundingClientRect; + const tlX = Math.max(0, x); + const tlY = Math.max(0, y); + const brX = Math.min(window.innerWidth, x + width); + const brY = Math.min(window.innerHeight, y + height); + const centerX = (tlX + brX) / 2 - x; + const centerY = (tlY + brY) / 2 - y; + const [offsetX, offsetY] = this.viewport.rotation % 180 === 0 ? [centerX, centerY] : [centerY, centerX]; + return { + offsetX, + offsetY + }; + } + addNewEditor(data = {}) { + this.createAndAddNewEditor(this.#getCenterPoint(), true, data); + } + setSelected(editor) { + this.#uiManager.setSelected(editor); + } + toggleSelected(editor) { + this.#uiManager.toggleSelected(editor); + } + unselect(editor) { + this.#uiManager.unselect(editor); + } + pointerup(event) { + const { + isMac + } = FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + return; + } + if (event.target !== this.div) { + return; + } + if (!this.#hadPointerDown) { + return; + } + this.#hadPointerDown = false; + if (this.#currentEditorType?.isDrawer && this.#currentEditorType.supportMultipleDrawings) { + return; + } + if (!this.#allowClick) { + this.#allowClick = true; + return; + } + const currentMode = this.#uiManager.getMode(); + if (currentMode === AnnotationEditorType.STAMP || currentMode === AnnotationEditorType.SIGNATURE) { + this.#uiManager.unselectAll(); + return; + } + this.createAndAddNewEditor(event, false); + } + pointerdown(event) { + if (this.#uiManager.getMode() === AnnotationEditorType.HIGHLIGHT) { + this.enableTextSelection(); + } + if (this.#hadPointerDown) { + this.#hadPointerDown = false; + return; + } + const { + isMac + } = FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + return; + } + if (event.target !== this.div) { + return; + } + this.#hadPointerDown = true; + if (this.#currentEditorType?.isDrawer) { + this.startDrawingSession(event); + return; + } + const editor = this.#uiManager.getActive(); + this.#allowClick = !editor || editor.isEmpty(); + } + startDrawingSession(event) { + this.div.focus({ + preventScroll: true + }); + if (this.#drawingAC) { + this.#currentEditorType.startDrawing(this, this.#uiManager, false, event); + return; + } + this.#uiManager.setCurrentDrawingSession(this); + this.#drawingAC = new AbortController(); + const signal = this.#uiManager.combinedSignal(this.#drawingAC); + this.div.addEventListener("blur", ({ + relatedTarget + }) => { + if (relatedTarget && !this.div.contains(relatedTarget)) { + this.#focusedElement = null; + this.commitOrRemove(); + } + }, { + signal + }); + this.#currentEditorType.startDrawing(this, this.#uiManager, false, event); + } + pause(on) { + if (on) { + const { + activeElement + } = document; + if (this.div.contains(activeElement)) { + this.#focusedElement = activeElement; + } + return; + } + if (this.#focusedElement) { + setTimeout(() => { + this.#focusedElement?.focus(); + this.#focusedElement = null; + }, 0); + } + } + endDrawingSession(isAborted = false) { + if (!this.#drawingAC) { + return null; + } + this.#uiManager.setCurrentDrawingSession(null); + this.#drawingAC.abort(); + this.#drawingAC = null; + this.#focusedElement = null; + return this.#currentEditorType.endDrawing(isAborted); + } + findNewParent(editor, x, y) { + const layer = this.#uiManager.findParent(x, y); + if (layer === null || layer === this) { + return false; + } + layer.changeParent(editor); + return true; + } + commitOrRemove() { + if (this.#drawingAC) { + this.endDrawingSession(); + return true; + } + return false; + } + onScaleChanging() { + if (!this.#drawingAC) { + return; + } + this.#currentEditorType.onScaleChangingWhenDrawing(this); + } + destroy() { + this.commitOrRemove(); + if (this.#uiManager.getActive()?.parent === this) { + this.#uiManager.commitOrRemove(); + this.#uiManager.setActiveEditor(null); + } + if (this.#editorFocusTimeoutId) { + clearTimeout(this.#editorFocusTimeoutId); + this.#editorFocusTimeoutId = null; + } + for (const editor of this.#editors.values()) { + this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv); + editor.setParent(null); + editor.isAttachedToDOM = false; + editor.div.remove(); + } + this.div = null; + this.#editors.clear(); + this.#uiManager.removeLayer(this); + } + #cleanup() { + for (const editor of this.#editors.values()) { + if (editor.isEmpty()) { + editor.remove(); + } + } + } + render({ + viewport + }) { + this.viewport = viewport; + setLayerDimensions(this.div, viewport); + for (const editor of this.#uiManager.getEditors(this.pageIndex)) { + this.add(editor); + editor.rebuild(); + } + this.updateMode(); + } + update({ + viewport + }) { + this.#uiManager.commitOrRemove(); + this.#cleanup(); + const oldRotation = this.viewport.rotation; + const rotation = viewport.rotation; + this.viewport = viewport; + setLayerDimensions(this.div, { + rotation + }); + if (oldRotation !== rotation) { + for (const editor of this.#editors.values()) { + editor.rotate(rotation); + } + } + } + get pageDimensions() { + const { + pageWidth, + pageHeight + } = this.viewport.rawDims; + return [pageWidth, pageHeight]; + } + get scale() { + return this.#uiManager.viewParameters.realScale; + } +} + +;// ./src/display/draw_layer.js + + +class DrawLayer { + #parent = null; + #mapping = new Map(); + #toUpdate = new Map(); + static #id = 0; + setParent(parent) { + if (!this.#parent) { + this.#parent = parent; + return; + } + if (this.#parent !== parent) { + if (this.#mapping.size > 0) { + for (const root of this.#mapping.values()) { + root.remove(); + parent.append(root); + } + } + this.#parent = parent; + } + } + static get _svgFactory() { + return shadow(this, "_svgFactory", new DOMSVGFactory()); + } + static #setBox(element, [x, y, width, height]) { + const { + style + } = element; + style.top = `${100 * y}%`; + style.left = `${100 * x}%`; + style.width = `${100 * width}%`; + style.height = `${100 * height}%`; + } + #createSVG() { + const svg = DrawLayer._svgFactory.create(1, 1, true); + this.#parent.append(svg); + svg.setAttribute("aria-hidden", true); + return svg; + } + #createClipPath(defs, pathId) { + const clipPath = DrawLayer._svgFactory.createElement("clipPath"); + defs.append(clipPath); + const clipPathId = `clip_${pathId}`; + clipPath.setAttribute("id", clipPathId); + clipPath.setAttribute("clipPathUnits", "objectBoundingBox"); + const clipPathUse = DrawLayer._svgFactory.createElement("use"); + clipPath.append(clipPathUse); + clipPathUse.setAttribute("href", `#${pathId}`); + clipPathUse.classList.add("clip"); + return clipPathId; + } + #updateProperties(element, properties) { + for (const [key, value] of Object.entries(properties)) { + if (value === null) { + element.removeAttribute(key); + } else { + element.setAttribute(key, value); + } + } + } + draw(properties, isPathUpdatable = false, hasClip = false) { + const id = DrawLayer.#id++; + const root = this.#createSVG(); + const defs = DrawLayer._svgFactory.createElement("defs"); + root.append(defs); + const path = DrawLayer._svgFactory.createElement("path"); + defs.append(path); + const pathId = `path_${id}`; + path.setAttribute("id", pathId); + path.setAttribute("vector-effect", "non-scaling-stroke"); + if (isPathUpdatable) { + this.#toUpdate.set(id, path); + } + const clipPathId = hasClip ? this.#createClipPath(defs, pathId) : null; + const use = DrawLayer._svgFactory.createElement("use"); + root.append(use); + use.setAttribute("href", `#${pathId}`); + this.updateProperties(root, properties); + this.#mapping.set(id, root); + return { + id, + clipPathId: `url(#${clipPathId})` + }; + } + drawOutline(properties, mustRemoveSelfIntersections) { + const id = DrawLayer.#id++; + const root = this.#createSVG(); + const defs = DrawLayer._svgFactory.createElement("defs"); + root.append(defs); + const path = DrawLayer._svgFactory.createElement("path"); + defs.append(path); + const pathId = `path_${id}`; + path.setAttribute("id", pathId); + path.setAttribute("vector-effect", "non-scaling-stroke"); + let maskId; + if (mustRemoveSelfIntersections) { + const mask = DrawLayer._svgFactory.createElement("mask"); + defs.append(mask); + maskId = `mask_${id}`; + mask.setAttribute("id", maskId); + mask.setAttribute("maskUnits", "objectBoundingBox"); + const rect = DrawLayer._svgFactory.createElement("rect"); + mask.append(rect); + rect.setAttribute("width", "1"); + rect.setAttribute("height", "1"); + rect.setAttribute("fill", "white"); + const use = DrawLayer._svgFactory.createElement("use"); + mask.append(use); + use.setAttribute("href", `#${pathId}`); + use.setAttribute("stroke", "none"); + use.setAttribute("fill", "black"); + use.setAttribute("fill-rule", "nonzero"); + use.classList.add("mask"); + } + const use1 = DrawLayer._svgFactory.createElement("use"); + root.append(use1); + use1.setAttribute("href", `#${pathId}`); + if (maskId) { + use1.setAttribute("mask", `url(#${maskId})`); + } + const use2 = use1.cloneNode(); + root.append(use2); + use1.classList.add("mainOutline"); + use2.classList.add("secondaryOutline"); + this.updateProperties(root, properties); + this.#mapping.set(id, root); + return id; + } + finalizeDraw(id, properties) { + this.#toUpdate.delete(id); + this.updateProperties(id, properties); + } + updateProperties(elementOrId, properties) { + if (!properties) { + return; + } + const { + root, + bbox, + rootClass, + path + } = properties; + const element = typeof elementOrId === "number" ? this.#mapping.get(elementOrId) : elementOrId; + if (!element) { + return; + } + if (root) { + this.#updateProperties(element, root); + } + if (bbox) { + DrawLayer.#setBox(element, bbox); + } + if (rootClass) { + const { + classList + } = element; + for (const [className, value] of Object.entries(rootClass)) { + classList.toggle(className, value); + } + } + if (path) { + const defs = element.firstElementChild; + const pathElement = defs.firstElementChild; + this.#updateProperties(pathElement, path); + } + } + updateParent(id, layer) { + if (layer === this) { + return; + } + const root = this.#mapping.get(id); + if (!root) { + return; + } + layer.#parent.append(root); + this.#mapping.delete(id); + layer.#mapping.set(id, root); + } + remove(id) { + this.#toUpdate.delete(id); + if (this.#parent === null) { + return; + } + this.#mapping.get(id).remove(); + this.#mapping.delete(id); + } + destroy() { + this.#parent = null; + for (const root of this.#mapping.values()) { + root.remove(); + } + this.#mapping.clear(); + this.#toUpdate.clear(); + } +} + +;// ./src/pdf.js + + + + + + + + + + + + + + + + +{ + globalThis._pdfjsTestingUtils = { + HighlightOutliner: HighlightOutliner + }; +} +globalThis.pdfjsLib = { + AbortException: AbortException, + AnnotationEditorLayer: AnnotationEditorLayer, + AnnotationEditorParamsType: AnnotationEditorParamsType, + AnnotationEditorType: AnnotationEditorType, + AnnotationEditorUIManager: AnnotationEditorUIManager, + AnnotationLayer: AnnotationLayer, + AnnotationMode: AnnotationMode, + AnnotationType: AnnotationType, + applyOpacity: applyOpacity, + build: build, + ColorPicker: ColorPicker, + createValidAbsoluteUrl: createValidAbsoluteUrl, + CSSConstants: CSSConstants, + DOMSVGFactory: DOMSVGFactory, + DrawLayer: DrawLayer, + FeatureTest: FeatureTest, + fetchData: fetchData, + findContrastColor: findContrastColor, + getDocument: getDocument, + getFilenameFromUrl: getFilenameFromUrl, + getPdfFilenameFromUrl: getPdfFilenameFromUrl, + getRGB: getRGB, + getUuid: getUuid, + getXfaPageViewport: getXfaPageViewport, + GlobalWorkerOptions: GlobalWorkerOptions, + ImageKind: ImageKind, + InvalidPDFException: InvalidPDFException, + isDataScheme: isDataScheme, + isPdfFile: isPdfFile, + isValidExplicitDest: isValidExplicitDest, + makeArr: makeArr, + makeMap: makeMap, + makeObj: makeObj, + MathClamp: MathClamp, + noContextMenu: noContextMenu, + normalizeUnicode: normalizeUnicode, + OPS: OPS, + OutputScale: OutputScale, + PasswordResponses: PasswordResponses, + PDFDataRangeTransport: PDFDataRangeTransport, + PDFDateString: PDFDateString, + PDFWorker: PDFWorker, + PermissionFlag: PermissionFlag, + PixelsPerInch: PixelsPerInch, + RenderingCancelledException: RenderingCancelledException, + renderRichText: renderRichText, + ResponseException: ResponseException, + setLayerDimensions: setLayerDimensions, + shadow: shadow, + SignatureExtractor: SignatureExtractor, + stopEvent: stopEvent, + SupportedImageMimeTypes: SupportedImageMimeTypes, + TextLayer: TextLayer, + TouchManager: TouchManager, + updateUrlHash: updateUrlHash, + Util: Util, + VerbosityLevel: VerbosityLevel, + version: version, + XfaLayer: XfaLayer +}; + +export { AbortException, AnnotationEditorLayer, AnnotationEditorParamsType, AnnotationEditorType, AnnotationEditorUIManager, AnnotationLayer, AnnotationMode, AnnotationType, CSSConstants, ColorPicker, DOMSVGFactory, DrawLayer, FeatureTest, GlobalWorkerOptions, ImageKind, InvalidPDFException, MathClamp, OPS, OutputScale, PDFDataRangeTransport, PDFDateString, PDFWorker, PasswordResponses, PermissionFlag, PixelsPerInch, RenderingCancelledException, ResponseException, SignatureExtractor, SupportedImageMimeTypes, TextLayer, TouchManager, Util, VerbosityLevel, XfaLayer, applyOpacity, build, createValidAbsoluteUrl, fetchData, findContrastColor, getDocument, getFilenameFromUrl, getPdfFilenameFromUrl, getRGB, getUuid, getXfaPageViewport, isDataScheme, isPdfFile, isValidExplicitDest, makeArr, makeMap, makeObj, noContextMenu, normalizeUnicode, renderRichText, setLayerDimensions, shadow, stopEvent, updateUrlHash, version }; + +//# sourceMappingURL=pdf.mjs.map \ No newline at end of file diff --git a/go/cmd/kjol-web/frontend/vendor/pdfjs-dist/build/pdf.worker.min.mjs b/go/cmd/kjol-web/frontend/vendor/pdfjs-dist/build/pdf.worker.min.mjs new file mode 100644 index 00000000..9a18cfdf --- /dev/null +++ b/go/cmd/kjol-web/frontend/vendor/pdfjs-dist/build/pdf.worker.min.mjs @@ -0,0 +1,28 @@ +/** + * @licstart The following is the entire license notice for the + * JavaScript code in this page + * + * Copyright 2024 Mozilla Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @licend The above is the entire license notice for the + * JavaScript code in this page + */ +/** + * pdfjsVersion = 5.5.207 + * pdfjsBuild = 527964698 + */const e=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),t=[.001,0,0,.001,0,0],n=1.35,a=.35,s=.25925925925925924,r=1,i=2,o=4,l=8,f=16,c=64,h=128,u=256,m="pdfjs_internal_editor_",p=3,d=9,g=13,b=15,w=101,j={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},k=1,y=2,q=3,v=0,S=4,x=1,C=2,F=3,T={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},H="Group",O="R",R=1,D=2,M=4,E=16,N=32,z=128,L=512,U=1,_=2,X=4096,W=8192,K=32768,G=65536,V=131072,$=1048576,Y=2097152,J=8388608,Q=16777216,Z=1,ee=2,te=3,ne=4,ae=5,se={E:"Mouse Enter",X:"Mouse Exit",D:"Mouse Down",U:"Mouse Up",Fo:"Focus",Bl:"Blur",PO:"PageOpen",PC:"PageClose",PV:"PageVisible",PI:"PageInvisible",K:"Keystroke",F:"Format",V:"Validate",C:"Calculate"},re={WC:"WillClose",WS:"WillSave",DS:"DidSave",WP:"WillPrint",DP:"DidPrint"},ie={O:"PageOpen",C:"PageClose"},oe=1,le=5,fe=1,ce=2,he=3,ue=4,me=5,pe=6,de=7,ge=8,be=9,we=10,je=11,ke=12,ye=13,qe=14,ve=15,Se=16,xe=17,Ae=18,Ce=19,Ie=20,Fe=21,Te=22,He=23,Oe=24,Be=25,Re=26,De=27,Me=28,Pe=29,Ee=30,Ne=31,ze=32,Le=33,Ue=34,_e=35,Xe=36,We=37,Ke=38,Ge=39,Ve=40,$e=41,Ye=42,Je=43,Qe=44,Ze=45,et=46,tt=47,nt=48,at=49,st=50,rt=51,it=52,ot=53,lt=54,ft=55,ct=56,ht=57,ut=58,mt=59,pt=60,dt=61,gt=62,bt=63,wt=64,jt=65,kt=66,yt=67,qt=68,vt=69,St=70,xt=71,At=72,Ct=73,It=74,Ft=75,Tt=76,Ht=77,Ot=80,Bt=81,Rt=83,Dt=84,Mt=85,Pt=86,Et=87,Nt=88,zt=89,Lt=90,Ut=91,_t=92,Xt=93,Wt=94,Kt=0,Gt=1,Vt=2,$t=3,Yt=4,Jt=1,Qt=2;let Zt=oe;function getVerbosityLevel(){return Zt}function info(e){Zt>=le&&console.info(`Info: ${e}`)}function warn(e){Zt>=oe&&console.warn(`Warning: ${e}`)}function unreachable(e){throw new Error(e)}function assert(e,t){e||unreachable(t)}function createValidAbsoluteUrl(e,t=null,n=null){if(!e)return null;if(n&&"string"==typeof e){if(n.addDefaultProtocol&&e.startsWith("www.")){const t=e.match(/\./g);t?.length>=2&&(e=`http://${e}`)}if(n.tryConvertEncoding)try{e=stringToUTF8String(e)}catch{}}const a=t?URL.parse(e,t):URL.parse(e);return function _isValidProtocol(e){switch(e?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(a)?a:null}function shadow(e,t,n,a=!1){Object.defineProperty(e,t,{value:n,enumerable:!a,configurable:!0,writable:!1});return n}const en=function BaseExceptionClosure(){function BaseException(e,t){this.message=e;this.name=t}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends en{constructor(e,t){super(e,"PasswordException");this.code=t}}class UnknownErrorException extends en{constructor(e,t){super(e,"UnknownErrorException");this.details=t}}class InvalidPDFException extends en{constructor(e){super(e,"InvalidPDFException")}}class ResponseException extends en{constructor(e,t,n){super(e,"ResponseException");this.status=t;this.missing=n}}class FormatError extends en{constructor(e){super(e,"FormatError")}}class AbortException extends en{constructor(e){super(e,"AbortException")}}function bytesToString(e){"object"==typeof e&&void 0!==e?.length||unreachable("Invalid argument for bytesToString");const t=e.length,n=8192;if(t<n)return String.fromCharCode.apply(null,e);const a=[];for(let s=0;s<t;s+=n){const r=Math.min(s+n,t),i=e.subarray(s,r);a.push(String.fromCharCode.apply(null,i))}return a.join("")}function stringToBytes(e){"string"!=typeof e&&unreachable("Invalid argument for stringToBytes");const t=e.length,n=new Uint8Array(t);for(let a=0;a<t;++a)n[a]=255&e.charCodeAt(a);return n}function string32(e){return String.fromCharCode(e>>24&255,e>>16&255,e>>8&255,255&e)}function objectSize(e){return Object.keys(e).length}class FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",function isLittleEndian(){const e=new Uint8Array(4);e[0]=1;return 1===new Uint32Array(e.buffer,0,1)[0]}())}static get isEvalSupported(){return shadow(this,"isEvalSupported",function isEvalSupported(){try{new Function("");return!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get isFloat16ArraySupported(){return shadow(this,"isFloat16ArraySupported","undefined"!=typeof Float16Array)}static get isSanitizerSupported(){return shadow(this,"isSanitizerSupported","undefined"!=typeof Sanitizer)}static get platform(){const{platform:e,userAgent:t}=navigator;return shadow(this,"platform",{isAndroid:t.includes("Android"),isLinux:e.includes("Linux"),isMac:e.includes("Mac"),isWindows:e.includes("Win"),isFirefox:t.includes("Firefox")})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const tn=Array.from(Array(256).keys(),e=>e.toString(16).padStart(2,"0"));class Util{static makeHexColor(e,t,n){return`#${tn[e]}${tn[t]}${tn[n]}`}static domMatrixToTransform(e){return[e.a,e.b,e.c,e.d,e.e,e.f]}static scaleMinMax(e,t){let n;if(e[0]){if(e[0]<0){n=t[0];t[0]=t[2];t[2]=n}t[0]*=e[0];t[2]*=e[0];if(e[3]<0){n=t[1];t[1]=t[3];t[3]=n}t[1]*=e[3];t[3]*=e[3]}else{n=t[0];t[0]=t[1];t[1]=n;n=t[2];t[2]=t[3];t[3]=n;if(e[1]<0){n=t[1];t[1]=t[3];t[3]=n}t[1]*=e[1];t[3]*=e[1];if(e[2]<0){n=t[0];t[0]=t[2];t[2]=n}t[0]*=e[2];t[2]*=e[2]}t[0]+=e[4];t[1]+=e[5];t[2]+=e[4];t[3]+=e[5]}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static multiplyByDOMMatrix(e,t){return[e[0]*t.a+e[2]*t.b,e[1]*t.a+e[3]*t.b,e[0]*t.c+e[2]*t.d,e[1]*t.c+e[3]*t.d,e[0]*t.e+e[2]*t.f+e[4],e[1]*t.e+e[3]*t.f+e[5]]}static applyTransform(e,t,n=0){const a=e[n],s=e[n+1];e[n]=a*t[0]+s*t[2]+t[4];e[n+1]=a*t[1]+s*t[3]+t[5]}static applyTransformToBezier(e,t,n=0){const a=t[0],s=t[1],r=t[2],i=t[3],o=t[4],l=t[5];for(let t=0;t<6;t+=2){const f=e[n+t],c=e[n+t+1];e[n+t]=f*a+c*r+o;e[n+t+1]=f*s+c*i+l}}static applyInverseTransform(e,t){const n=e[0],a=e[1],s=t[0]*t[3]-t[1]*t[2];e[0]=(n*t[3]-a*t[2]+t[2]*t[5]-t[4]*t[3])/s;e[1]=(-n*t[1]+a*t[0]+t[4]*t[1]-t[5]*t[0])/s}static axialAlignedBoundingBox(e,t,n){const a=t[0],s=t[1],r=t[2],i=t[3],o=t[4],l=t[5],f=e[0],c=e[1],h=e[2],u=e[3];let m=a*f+o,p=m,d=a*h+o,g=d,b=i*c+l,w=b,j=i*u+l,k=j;if(0!==s||0!==r){const e=s*f,t=s*h,n=r*c,a=r*u;m+=n;g+=n;d+=a;p+=a;b+=e;k+=e;j+=t;w+=t}n[0]=Math.min(n[0],m,d,p,g);n[1]=Math.min(n[1],b,j,w,k);n[2]=Math.max(n[2],m,d,p,g);n[3]=Math.max(n[3],b,j,w,k)}static inverseTransform(e){const t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e,t){const n=e[0],a=e[1],s=e[2],r=e[3],i=n**2+a**2,o=n*s+a*r,l=s**2+r**2,f=(i+l)/2,c=Math.sqrt(f**2-(i*l-o**2));t[0]=Math.sqrt(f+c||1);t[1]=Math.sqrt(f-c||1)}static normalizeRect(e){const t=e.slice(0);if(e[0]>e[2]){t[0]=e[2];t[2]=e[0]}if(e[1]>e[3]){t[1]=e[3];t[3]=e[1]}return t}static intersect(e,t){const n=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),a=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(n>a)return null;const s=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),r=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return s>r?null:[n,s,a,r]}static pointBoundingBox(e,t,n){n[0]=Math.min(n[0],e);n[1]=Math.min(n[1],t);n[2]=Math.max(n[2],e);n[3]=Math.max(n[3],t)}static rectBoundingBox(e,t,n,a,s){s[0]=Math.min(s[0],e,n);s[1]=Math.min(s[1],t,a);s[2]=Math.max(s[2],e,n);s[3]=Math.max(s[3],t,a)}static#e(e,t,n,a,s,r,i,o,l,f){if(l<=0||l>=1)return;const c=1-l,h=l*l,u=h*l,m=c*(c*(c*e+3*l*t)+3*h*n)+u*a,p=c*(c*(c*s+3*l*r)+3*h*i)+u*o;f[0]=Math.min(f[0],m);f[1]=Math.min(f[1],p);f[2]=Math.max(f[2],m);f[3]=Math.max(f[3],p)}static#t(e,t,n,a,s,r,i,o,l,f,c,h){if(Math.abs(l)<1e-12){Math.abs(f)>=1e-12&&this.#e(e,t,n,a,s,r,i,o,-c/f,h);return}const u=f**2-4*c*l;if(u<0)return;const m=Math.sqrt(u),p=2*l;this.#e(e,t,n,a,s,r,i,o,(-f+m)/p,h);this.#e(e,t,n,a,s,r,i,o,(-f-m)/p,h)}static bezierBoundingBox(e,t,n,a,s,r,i,o,l){l[0]=Math.min(l[0],e,i);l[1]=Math.min(l[1],t,o);l[2]=Math.max(l[2],e,i);l[3]=Math.max(l[3],t,o);this.#t(e,n,s,i,t,a,r,o,3*(3*(n-s)-e+i),6*(e-2*n+s),3*(n-e),l);this.#t(e,n,s,i,t,a,r,o,3*(3*(a-r)-t+o),6*(t-2*a+r),3*(a-t),l)}}const nn=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364];function stringToPDFString(e,t=!1){if(e[0]>="ï"){let n;if("þ"===e[0]&&"ÿ"===e[1]){n="utf-16be";e.length%2==1&&(e=e.slice(0,-1))}else if("ÿ"===e[0]&&"þ"===e[1]){n="utf-16le";e.length%2==1&&(e=e.slice(0,-1))}else"ï"===e[0]&&"»"===e[1]&&"¿"===e[2]&&(n="utf-8");if(n)try{const a=new TextDecoder(n,{fatal:!0}),s=stringToBytes(e),r=a.decode(s);return t||!r.includes("")?r:r.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g,"")}catch(e){warn(`stringToPDFString: "${e}".`)}}const n=[];for(let a=0,s=e.length;a<s;a++){const r=e.charCodeAt(a);if(!t&&27===r){for(;++a<s&&27!==e.charCodeAt(a););continue}const i=nn[r];n.push(i?String.fromCharCode(i):e.charAt(a))}return n.join("")}function stringToUTF8String(e){return decodeURIComponent(escape(e))}function utf8StringToString(e){return unescape(encodeURIComponent(e))}function isArrayEqual(e,t){if(e.length!==t.length)return!1;for(let n=0,a=e.length;n<a;n++)if(e[n]!==t[n])return!1;return!0}function getModificationDate(e=new Date){e instanceof Date||(e=new Date(e));return[e.getUTCFullYear().toString(),(e.getUTCMonth()+1).toString().padStart(2,"0"),e.getUTCDate().toString().padStart(2,"0"),e.getUTCHours().toString().padStart(2,"0"),e.getUTCMinutes().toString().padStart(2,"0"),e.getUTCSeconds().toString().padStart(2,"0")].join("")}let an=null,sn=null;const makeArr=()=>[],makeMap=()=>new Map,makeObj=()=>Object.create(null);function MathClamp(e,t,n){return Math.min(Math.max(e,t),n)}"function"!=typeof Math.sumPrecise&&(Math.sumPrecise=function(e){return e.reduce((e,t)=>e+t,0)});const rn=Symbol("CIRCULAR_REF"),on=Symbol("EOF");let ln=Object.create(null),fn=Object.create(null),cn=Object.create(null);class Name{constructor(e){this.name=e}static get(e){return fn[e]||=new Name(e)}}class Cmd{constructor(e){this.cmd=e}static get(e){return ln[e]||=new Cmd(e)}}const hn=function nonSerializableClosure(){return hn};class Dict{constructor(e=null){this._map=new Map;this.xref=e;this.objId=null;this.suppressEncryption=!1;this.__nonSerializable__=hn}assignXref(e){this.xref=e}get size(){return this._map.size}get(e,t,n){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==n&&(a=this._map.get(n))}return a instanceof Ref&&this.xref?this.xref.fetch(a,this.suppressEncryption):a}async getAsync(e,t,n){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==n&&(a=this._map.get(n))}return a instanceof Ref&&this.xref?this.xref.fetchAsync(a,this.suppressEncryption):a}getArray(e,t,n){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==n&&(a=this._map.get(n))}a instanceof Ref&&this.xref&&(a=this.xref.fetch(a,this.suppressEncryption));if(Array.isArray(a)){a=a.slice();for(let e=0,t=a.length;e<t;e++)a[e]instanceof Ref&&this.xref&&(a[e]=this.xref.fetch(a[e],this.suppressEncryption))}return a}getRaw(e){return this._map.get(e)}getKeys(){return[...this._map.keys()]}getRawValues(){return[...this._map.values()]}getRawEntries(){return this._map.entries()}set(e,t){this._map.set(e,t)}setIfNotExists(e,t){this.has(e)||this.set(e,t)}setIfNumber(e,t){"number"==typeof t&&this.set(e,t)}setIfArray(e,t){(Array.isArray(t)||ArrayBuffer.isView(t))&&this.set(e,t)}setIfDefined(e,t){null!=t&&this.set(e,t)}setIfName(e,t){"string"==typeof t?this.set(e,Name.get(t)):t instanceof Name&&this.set(e,t)}setIfDict(e,t){t instanceof Dict&&this.set(e,t)}has(e){return this._map.has(e)}*[Symbol.iterator](){for(const[e,t]of this._map)yield[e,t instanceof Ref&&this.xref?this.xref.fetch(t,this.suppressEncryption):t]}static get empty(){const e=new Dict(null);e.set=(e,t)=>{unreachable("Should not call `set` on the empty dictionary.")};return shadow(this,"empty",e)}static merge({xref:e,dictArray:t,mergeSubDicts:n=!1}){const a=new Dict(e),s=new Map;for(const e of t)if(e instanceof Dict)for(const[t,a]of e._map){let e=s.get(t);if(void 0===e){e=[];s.set(t,e)}else if(!(n&&a instanceof Dict))continue;e.push(a)}for(const[t,n]of s){if(1===n.length||!(n[0]instanceof Dict)){a._map.set(t,n[0]);continue}const s=new Dict(e);for(const e of n)for(const[t,n]of e._map)s._map.has(t)||s._map.set(t,n);s.size>0&&a._map.set(t,s)}s.clear();return a.size>0?a:Dict.empty}clone(){const e=new Dict(this.xref);for(const t of this.getKeys())e.set(t,this.getRaw(t));return e}delete(e){this._map.delete(e)}}class Ref{constructor(e,t){this.num=e;this.gen=t}toString(){return 0===this.gen?`${this.num}R`:`${this.num}R${this.gen}`}static fromString(e){const t=cn[e];if(t)return t;const n=/^(\d+)R(\d*)$/.exec(e);return n&&"0"!==n[1]?cn[e]=new Ref(parseInt(n[1]),n[2]?parseInt(n[2]):0):null}static get(e,t){const n=0===t?`${e}R`:`${e}R${t}`;return cn[n]||=new Ref(e,t)}}class RefSet{constructor(e=null){this._set=new Set(e?._set)}has(e){return this._set.has(e.toString())}put(e){this._set.add(e.toString())}remove(e){this._set.delete(e.toString())}[Symbol.iterator](){return this._set.values()}clear(){this._set.clear()}}class RefSetCache{_map=new Map;get size(){return this._map.size}get(e){return this._map.get(e.toString())}has(e){return this._map.has(e.toString())}put(e,t){this._map.set(e.toString(),t)}putAlias(e,t){this._map.set(e.toString(),this.get(t))}[Symbol.iterator](){return this._map.values()}clear(){this._map.clear()}*values(){yield*this._map.values()}*items(){for(const[e,t]of this._map)yield[Ref.fromString(e),t]}*keys(){for(const e of this._map.keys())yield Ref.fromString(e)}}function isName(e,t){return e instanceof Name&&(void 0===t||e.name===t)}function isCmd(e,t){return e instanceof Cmd&&(void 0===t||e.cmd===t)}function isDict(e,t){return e instanceof Dict&&(void 0===t||isName(e.get("Type"),t))}function isRefsEqual(e,t){return e.num===t.num&&e.gen===t.gen}class BaseStream{get length(){unreachable("Abstract getter `length` accessed")}get isEmpty(){unreachable("Abstract getter `isEmpty` accessed")}get isDataLoaded(){return shadow(this,"isDataLoaded",!0)}getByte(){unreachable("Abstract method `getByte` called")}getBytes(e){unreachable("Abstract method `getBytes` called")}async getImageData(e,t){return this.getBytes(e,t)}async asyncGetBytes(){unreachable("Abstract method `asyncGetBytes` called")}get isAsync(){return!1}get isAsyncDecoder(){return!1}get isImageStream(){return!1}get canAsyncDecodeImageFromBuffer(){return!1}async getTransferableImage(){return null}peekByte(){const e=this.getByte();-1!==e&&this.pos--;return e}peekBytes(e){const t=this.getBytes(e);this.pos-=t.length;return t}getUint16(){const e=this.getByte(),t=this.getByte();return-1===e||-1===t?-1:(e<<8)+t}getInt32(){return(this.getByte()<<24)+(this.getByte()<<16)+(this.getByte()<<8)+this.getByte()}getByteRange(e,t){unreachable("Abstract method `getByteRange` called")}getString(e){return bytesToString(this.getBytes(e))}skip(e){this.pos+=e||1}reset(){unreachable("Abstract method `reset` called")}moveStart(){unreachable("Abstract method `moveStart` called")}makeSubStream(e,t,n=null){unreachable("Abstract method `makeSubStream` called")}getBaseStreams(){return null}getOriginalStream(){return this.stream?.getOriginalStream()||this}}const un=/^[1-9]\.\d$/,mn=2**31-1,pn=[1,0,0,1,0,0],dn=["ColorSpace","ExtGState","Font","Pattern","Properties","Shading","XObject"],gn=["ExtGState","Font","Properties","XObject"];function getLookupTableFactory(e){let t;return function(){if(e){t=Object.create(null);e(t);e=null}return t}}class MissingDataException extends en{constructor(e,t){super(`Missing data [${e}, ${t})`,"MissingDataException");this.begin=e;this.end=t}}class ParserEOFException extends en{constructor(e){super(e,"ParserEOFException")}}class XRefEntryException extends en{constructor(e){super(e,"XRefEntryException")}}class XRefParseException extends en{constructor(e){super(e,"XRefParseException")}}function arrayBuffersToBytes(e){const t=e.length;if(0===t)return new Uint8Array(0);if(1===t)return new Uint8Array(e[0]);let n=0;for(let a=0;a<t;a++)n+=e[a].byteLength;const a=new Uint8Array(n);let s=0;for(let n=0;n<t;n++){const t=new Uint8Array(e[n]);a.set(t,s);s+=t.byteLength}return a}async function fetchBinaryData(e){const t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch file "${e}" with "${t.statusText}".`);return t.bytes()}function getInheritableProperty({dict:e,key:t,getArray:n=!1,stopWhenFound:a=!0}){let s;const r=new RefSet;for(;e instanceof Dict&&(!e.objId||!r.has(e.objId));){e.objId&&r.put(e.objId);const i=n?e.getArray(t):e.get(t);if(void 0!==i){if(a)return i;(s||=[]).push(i)}e=e.get("Parent")}return s}const bn=["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM","","X","XX","XXX","XL","L","LX","LXX","LXXX","XC","","I","II","III","IV","V","VI","VII","VIII","IX"];function toRomanNumerals(e,t=!1){assert(Number.isInteger(e)&&e>0,"The number should be a positive integer.");const n="M".repeat(e/1e3|0)+bn[e%1e3/100|0]+bn[10+(e%100/10|0)]+bn[20+e%10];return t?n.toLowerCase():n}function log2(e){return e>0?Math.ceil(Math.log2(e)):0}function readInt8(e,t){return e[t]<<24>>24}function readInt16(e,t){return(e[t]<<24|e[t+1]<<16)>>16}function readUint16(e,t){return e[t]<<8|e[t+1]}function readUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function isWhiteSpace(e){return 32===e||9===e||13===e||10===e}function isNumberArray(e,t){return Array.isArray(e)?(null===t||e.length===t)&&e.every(e=>"number"==typeof e):ArrayBuffer.isView(e)&&!(e instanceof BigInt64Array||e instanceof BigUint64Array)&&(null===t||e.length===t)}function lookupMatrix(e,t){return isNumberArray(e,6)?e:t}function lookupRect(e,t){return isNumberArray(e,4)?e:t}function lookupNormalRect(e,t){return isNumberArray(e,4)?Util.normalizeRect(e):t}function parseXFAPath(e){const t=/(.+)\[(\d+)\]$/;return e.split(".").map(e=>{const n=e.match(t);return n?{name:n[1],pos:parseInt(n[2],10)}:{name:e,pos:0}})}function escapePDFName(e){const t=[];let n=0;for(let a=0,s=e.length;a<s;a++){const s=e.charCodeAt(a);if(s<33||s>126||35===s||40===s||41===s||60===s||62===s||91===s||93===s||123===s||125===s||47===s||37===s){n<a&&t.push(e.substring(n,a));t.push(`#${s.toString(16)}`);n=a+1}}if(0===t.length)return e;n<e.length&&t.push(e.substring(n,e.length));return t.join("")}function escapeString(e){return e.replaceAll(/([()\\\n\r])/g,e=>"\n"===e?"\\n":"\r"===e?"\\r":`\\${e}`)}function _collectJS(e,t,n,a){if(!e)return;let s=null;if(e instanceof Ref){if(a.has(e))return;s=e;a.put(s);e=t.fetch(e)}if(Array.isArray(e))for(const s of e)_collectJS(s,t,n,a);else if(e instanceof Dict){if(isName(e.get("S"),"JavaScript")){const t=e.get("JS");let a;t instanceof BaseStream?a=t.getString():"string"==typeof t&&(a=t);a&&=stringToPDFString(a,!0).replaceAll("\0","");a&&n.push(a.trim())}_collectJS(e.getRaw("Next"),t,n,a)}s&&a.remove(s)}function collectActions(e,t,n){const a=Object.create(null),s=getInheritableProperty({dict:t,key:"AA",stopWhenFound:!1});if(s)for(let t=s.length-1;t>=0;t--){const r=s[t];if(r instanceof Dict)for(const t of r.getKeys()){const s=n[t];if(!s)continue;const i=[];_collectJS(r.getRaw(t),e,i,new RefSet);i.length>0&&(a[s]=i)}}if(t.has("A")){const n=[];_collectJS(t.get("A"),e,n,new RefSet);n.length>0&&(a.Action=n)}return objectSize(a)>0?a:null}const wn={60:"<",62:">",38:"&",34:""",39:"'"};function*codePointIter(e){for(let t=0,n=e.length;t<n;t++){const n=e.codePointAt(t);n>55295&&(n<57344||n>65533)&&t++;yield n}}function encodeToXmlString(e){const t=[];let n=0;for(let a=0,s=e.length;a<s;a++){const s=e.codePointAt(a);if(32<=s&&s<=126){const r=wn[s];if(r){n<a&&t.push(e.substring(n,a));t.push(r);n=a+1}}else{n<a&&t.push(e.substring(n,a));t.push(`&#x${s.toString(16).toUpperCase()};`);s>55295&&(s<57344||s>65533)&&a++;n=a+1}}if(0===t.length)return e;n<e.length&&t.push(e.substring(n,e.length));return t.join("")}function validateFontName(e,t=!1){const n=/^("|').*("|')$/.exec(e);if(n&&n[1]===n[2]){if(new RegExp(`[^\\\\]${n[1]}`).test(e.slice(1,-1))){t&&warn(`FontFamily contains unescaped ${n[1]}: ${e}.`);return!1}}else for(const n of e.split(/[ \t]+/))if(/^(\d|(-(\d|-)))/.test(n)||!/^[\w-\\]+$/.test(n)){t&&warn(`FontFamily contains invalid <custom-ident>: ${e}.`);return!1}return!0}function validateCSSFont(e){const t=new Set(["100","200","300","400","500","600","700","800","900","1000","normal","bold","bolder","lighter"]),{fontFamily:n,fontWeight:a,italicAngle:s}=e;if(!validateFontName(n,!0))return!1;const r=a?a.toString():"";e.fontWeight=t.has(r)?r:"400";const i=parseFloat(s);e.italicAngle=isNaN(i)||i<-90||i>90?"14":s.toString();return!0}function recoverJsURL(e){const t=new RegExp("^\\s*("+["app.launchURL","window.open","xfa.host.gotoURL"].join("|").replaceAll(".","\\.")+")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))","i").exec(e);return t?.[2]?{url:t[2],newWindow:"app.launchURL"===t[1]&&"true"===t[3]}:null}function numberToString(e){if(Number.isInteger(e))return e.toString();const t=Math.round(100*e);return t%100==0?(t/100).toString():t%10==0?e.toFixed(1):e.toFixed(2)}function getNewAnnotationsMap(e){if(!e)return null;const t=new Map;for(const[n,a]of e)n.startsWith(m)&&t.getOrInsertComputed(a.pageIndex,makeArr).push(a);return t.size>0?t:null}function stringToAsciiOrUTF16BE(e){return null==e||function isAscii(e){if("string"!=typeof e)return!1;return!e||/^[\x00-\x7F]*$/.test(e)}(e)?e:stringToUTF16String(e,!0)}function stringToUTF16HexString(e){const t=[];for(let n=0,a=e.length;n<a;n++){const a=e.charCodeAt(n);t.push(tn[a>>8&255],tn[255&a])}return t.join("")}function stringToUTF16String(e,t=!1){const n=[];t&&n.push("þÿ");for(let t=0,a=e.length;t<a;t++){const a=e.charCodeAt(t);n.push(String.fromCharCode(a>>8&255),String.fromCharCode(255&a))}return n.join("")}function getRotationMatrix(e,t,n){switch(e){case 90:return[0,1,-1,0,t,0];case 180:return[-1,0,0,-1,t,n];case 270:return[0,-1,1,0,0,n];default:throw new Error("Invalid rotation")}}function getSizeInBytes(e){return Math.ceil(Math.ceil(Math.log2(1+e))/8)}class QCMS{static#n=null;static _memory=null;static _mustAddAlpha=!1;static _destBuffer=null;static _destOffset=0;static _destLength=0;static _cssColor="";static _makeHexColor=null;static get _memoryArray(){const e=this.#n;return e?.byteLength?e:this.#n=new Uint8Array(this._memory.buffer)}}let jn;const kn="undefined"!=typeof TextDecoder?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};"undefined"!=typeof TextDecoder&&kn.decode();let yn=null;function getUint8ArrayMemory0(){null!==yn&&0!==yn.byteLength||(yn=new Uint8Array(jn.memory.buffer));return yn}let qn=0;function passArray8ToWasm0(e,t){const n=t(1*e.length,1)>>>0;getUint8ArrayMemory0().set(e,n/1);qn=e.length;return n}const vn=Object.freeze({RGB8:0,0:"RGB8",RGBA8:1,1:"RGBA8",BGRA8:2,2:"BGRA8",Gray8:3,3:"Gray8",GrayA8:4,4:"GrayA8",CMYK:5,5:"CMYK"}),Sn=Object.freeze({Perceptual:0,0:"Perceptual",RelativeColorimetric:1,1:"RelativeColorimetric",Saturation:2,2:"Saturation",AbsoluteColorimetric:3,3:"AbsoluteColorimetric"});function __wbg_get_imports(){const e={wbg:{}};e.wbg.__wbg_copyresult_b08ee7d273f295dd=function(e,t){!function copy_result(e,t){const{_mustAddAlpha:n,_destBuffer:a,_destOffset:s,_destLength:r,_memoryArray:i}=QCMS;if(t!==r)if(n)for(let n=e,r=e+t,o=s;n<r;n+=3,o+=4){a[o]=i[n];a[o+1]=i[n+1];a[o+2]=i[n+2];a[o+3]=255}else for(let n=e,r=e+t,o=s;n<r;n+=3,o+=4){a[o]=i[n];a[o+1]=i[n+1];a[o+2]=i[n+2]}else a.set(i.subarray(e,e+t),s)}(e>>>0,t>>>0)};e.wbg.__wbg_copyrgb_d60ce17bb05d9b67=function(e){!function copy_rgb(e){const{_destBuffer:t,_destOffset:n,_memoryArray:a}=QCMS;t[n]=a[e];t[n+1]=a[e+1];t[n+2]=a[e+2]}(e>>>0)};e.wbg.__wbg_makecssRGB_893bf0cd9fdb302d=function(e){!function make_cssRGB(e){const{_memoryArray:t}=QCMS;QCMS._cssColor=QCMS._makeHexColor(t[e],t[e+1],t[e+2])}(e>>>0)};e.wbg.__wbindgen_init_externref_table=function(){const e=jn.__wbindgen_export_0,t=e.grow(4);e.set(0,void 0);e.set(t+0,void 0);e.set(t+1,null);e.set(t+2,!0);e.set(t+3,!1)};e.wbg.__wbindgen_throw=function(e,t){throw new Error(function getStringFromWasm0(e,t){e>>>=0;return kn.decode(getUint8ArrayMemory0().subarray(e,e+t))}(e,t))};return e}function __wbg_finalize_init(e,t){jn=e.exports;__wbg_init.__wbindgen_wasm_module=t;yn=null;jn.__wbindgen_start();return jn}async function __wbg_init(e){if(void 0!==jn)return jn;void 0!==e&&(Object.getPrototypeOf(e)===Object.prototype?({module_or_path:e}=e):console.warn("using deprecated parameters for the initialization function; pass a single object instead"));const t=__wbg_get_imports();("string"==typeof e||"function"==typeof Request&&e instanceof Request||"function"==typeof URL&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:a}=await async function __wbg_load(e,t){if("function"==typeof Response&&e instanceof Response){if("function"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(e,t)}catch(t){if("application/wasm"==e.headers.get("Content-Type"))throw t;console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",t)}const n=await e.arrayBuffer();return await WebAssembly.instantiate(n,t)}{const n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}}(await e,t);return __wbg_finalize_init(n,a)}function isDefaultDecodeHelper(e,t){if(!Array.isArray(e))return!0;const n=e.length;if(n<t){warn("Decode map length is too short.");return!0}if(n>t){info("Truncating too long decode map.");e.length=t}return!1}class ColorSpace{static#a=new Uint8ClampedArray(3);constructor(e,t){this.name=e;this.numComps=t}getRgb(e,t,n=new Uint8ClampedArray(3)){this.getRgbItem(e,t,n,0);return n}getRgbHex(e,t){const n=this.getRgb(e,t,ColorSpace.#a);return Util.makeHexColor(n[0],n[1],n[2])}getRgbItem(e,t,n,a){unreachable("Should not call ColorSpace.getRgbItem")}getRgbBuffer(e,t,n,a,s,r,i){unreachable("Should not call ColorSpace.getRgbBuffer")}getOutputLength(e,t){unreachable("Should not call ColorSpace.getOutputLength")}isPassthrough(e){return!1}isDefaultDecode(e,t){return ColorSpace.isDefaultDecode(e,this.numComps)}fillRgb(e,t,n,a,s,r,i,o,l){const f=t*n;let c=null;const h=1<<i,u=n!==s||t!==a;if(this.isPassthrough(i))c=o;else if(1===this.numComps&&f>h&&"DeviceGray"!==this.name&&"DeviceRGB"!==this.name){const t=i<=8?new Uint8Array(h):new Uint16Array(h);for(let e=0;e<h;e++)t[e]=e;const n=new Uint8ClampedArray(3*h);this.getRgbBuffer(t,0,h,n,0,i,0);if(u){c=new Uint8Array(3*f);let e=0;for(let t=0;t<f;++t){const a=3*o[t];c[e++]=n[a];c[e++]=n[a+1];c[e++]=n[a+2]}}else{let t=0;for(let a=0;a<f;++a){const s=3*o[a];e[t++]=n[s];e[t++]=n[s+1];e[t++]=n[s+2];t+=l}}}else if(u){c=new Uint8ClampedArray(3*f);this.getRgbBuffer(o,0,f,c,0,i,0)}else this.getRgbBuffer(o,0,a*r,e,0,i,l);if(c)if(u)!function resizeRgbImage(e,t,n,a,s,r,i){i=1!==i?0:i;const o=n/s,l=a/r;let f,c=0;const h=new Uint16Array(s),u=3*n;for(let e=0;e<s;e++)h[e]=3*Math.floor(e*o);for(let n=0;n<r;n++){const a=Math.floor(n*l)*u;for(let n=0;n<s;n++){f=a+h[n];t[c++]=e[f++];t[c++]=e[f++];t[c++]=e[f++];c+=i}}}(c,e,t,n,a,s,l);else{let t=0,n=0;for(let s=0,i=a*r;s<i;s++){e[t++]=c[n++];e[t++]=c[n++];e[t++]=c[n++];t+=l}}}get usesZeroToOneRange(){return shadow(this,"usesZeroToOneRange",!0)}static isDefaultDecode(e,t){if(isDefaultDecodeHelper(e,2*t))return!0;for(let t=0,n=e.length;t<n;t+=2)if(0!==e[t]||1!==e[t+1])return!1;return!0}}class AlternateCS extends ColorSpace{constructor(e,t,n){super("Alternate",e);this.base=t;this.tintFn=n;this.tmpBuf=new Float32Array(t.numComps)}getRgbItem(e,t,n,a){const s=this.tmpBuf;this.tintFn(e,t,s,0);this.base.getRgbItem(s,0,n,a)}getRgbBuffer(e,t,n,a,s,r,i){const o=this.tintFn,l=this.base,f=1/((1<<r)-1),c=l.numComps,h=l.usesZeroToOneRange,u=(l.isPassthrough(8)||!h)&&0===i;let m=u?s:0;const p=u?a:new Uint8ClampedArray(c*n),d=this.numComps,g=new Float32Array(d),b=new Float32Array(c);let w,j;for(w=0;w<n;w++){for(j=0;j<d;j++)g[j]=e[t++]*f;o(g,0,b,0);if(h)for(j=0;j<c;j++)p[m++]=255*b[j];else{l.getRgbItem(b,0,p,m);m+=c}}u||l.getRgbBuffer(p,0,n,a,s,8,i)}getOutputLength(e,t){return this.base.getOutputLength(e*this.base.numComps/this.numComps,t)}}class PatternCS extends ColorSpace{constructor(e){super("Pattern",null);this.base=e}isDefaultDecode(e,t){unreachable("Should not call PatternCS.isDefaultDecode")}}class IndexedCS extends ColorSpace{constructor(e,t,n){super("Indexed",1);this.base=e;this.highVal=t;const a=e.numComps*(t+1);this.lookup=new Uint8Array(a);if(n instanceof BaseStream){const e=n.getBytes(a);this.lookup.set(e)}else{if("string"!=typeof n)throw new FormatError(`IndexedCS - unrecognized lookup table: ${n}`);for(let e=0;e<a;++e)this.lookup[e]=255&n.charCodeAt(e)}}getRgbItem(e,t,n,a){const{base:s,highVal:r,lookup:i}=this,o=MathClamp(Math.round(e[t]),0,r)*s.numComps;s.getRgbBuffer(i,o,1,n,a,8,0)}getRgbBuffer(e,t,n,a,s,r,i){const{base:o,highVal:l,lookup:f}=this,{numComps:c}=o,h=o.getOutputLength(c,i);for(let r=0;r<n;++r){const n=MathClamp(Math.round(e[t++]),0,l)*c;o.getRgbBuffer(f,n,1,a,s,8,i);s+=h}}getOutputLength(e,t){return this.base.getOutputLength(e*this.base.numComps,t)}isDefaultDecode(e,t){if(isDefaultDecodeHelper(e,2))return!0;if(!Number.isInteger(t)||t<1){warn("Bits per component is not correct");return!0}return 0===e[0]&&e[1]===(1<<t)-1}}class DeviceGrayCS extends ColorSpace{constructor(){super("DeviceGray",1)}getRgbItem(e,t,n,a){const s=255*e[t];n[a]=n[a+1]=n[a+2]=s}getRgbBuffer(e,t,n,a,s,r,i){const o=255/((1<<r)-1);let l=t,f=s;for(let t=0;t<n;++t){const t=o*e[l++];a[f++]=t;a[f++]=t;a[f++]=t;f+=i}}getOutputLength(e,t){return e*(3+t)}}class DeviceRgbCS extends ColorSpace{constructor(){super("DeviceRGB",3)}getRgbItem(e,t,n,a){n[a]=255*e[t];n[a+1]=255*e[t+1];n[a+2]=255*e[t+2]}getRgbBuffer(e,t,n,a,s,r,i){if(8===r&&0===i){a.set(e.subarray(t,t+3*n),s);return}const o=255/((1<<r)-1);let l=t,f=s;for(let t=0;t<n;++t){a[f++]=o*e[l++];a[f++]=o*e[l++];a[f++]=o*e[l++];f+=i}}getOutputLength(e,t){return e*(3+t)/3|0}isPassthrough(e){return 8===e}}class DeviceRgbaCS extends ColorSpace{constructor(){super("DeviceRGBA",4)}getOutputLength(e,t){return 4*e}isPassthrough(e){return 8===e}fillRgb(e,t,n,a,s,r,i,o,l){n!==s||t!==a?function resizeRgbaImage(e,t,n,a,s,r,i){const o=n/s,l=a/r;let f=0;const c=new Uint16Array(s);if(1===i){for(let e=0;e<s;e++)c[e]=Math.floor(e*o);const a=new Uint32Array(e.buffer),i=new Uint32Array(t.buffer),h=FeatureTest.isLittleEndian?16777215:4294967040;for(let e=0;e<r;e++){const t=a.subarray(Math.floor(e*l)*n);for(let e=0;e<s;e++)i[f++]|=t[c[e]]&h}}else{const a=4,i=n*a;for(let e=0;e<s;e++)c[e]=Math.floor(e*o)*a;for(let n=0;n<r;n++){const a=e.subarray(Math.floor(n*l)*i);for(let e=0;e<s;e++){const n=c[e];t[f++]=a[n];t[f++]=a[n+1];t[f++]=a[n+2]}}}}(o,e,t,n,a,s,l):function copyRgbaImage(e,t,n){if(1===n){const n=new Uint32Array(e.buffer),a=new Uint32Array(t.buffer),s=FeatureTest.isLittleEndian?16777215:4294967040;for(let e=0,t=n.length;e<t;e++)a[e]|=n[e]&s}else{let n=0;for(let a=0,s=e.length;a<s;a+=4){t[n++]=e[a];t[n++]=e[a+1];t[n++]=e[a+2]}}}(o,e,l)}}class DeviceCmykCS extends ColorSpace{constructor(){super("DeviceCMYK",4)}#s(e,t,n,a,s){const r=e[t]*n,i=e[t+1]*n,o=e[t+2]*n,l=e[t+3]*n;a[s]=255+r*(-4.387332384609988*r+54.48615194189176*i+18.82290502165302*o+212.25662451639585*l-285.2331026137004)+i*(1.7149763477362134*i-5.6096736904047315*o+-17.873870861415444*l-5.497006427196366)+o*(-2.5217340131683033*o-21.248923337353073*l+17.5119270841813)+l*(-21.86122147463605*l-189.48180835922747);a[s+1]=255+r*(8.841041422036149*r+60.118027045597366*i+6.871425592049007*o+31.159100130055922*l-79.2970844816548)+i*(-15.310361306967817*i+17.575251261109482*o+131.35250912493976*l-190.9453302588951)+o*(4.444339102852739*o+9.8632861493405*l-24.86741582555878)+l*(-20.737325471181034*l-187.80453709719578);a[s+2]=255+r*(.8842522430003296*r+8.078677503112928*i+30.89978309703729*o-.23883238689178934*l-14.183576799673286)+i*(10.49593273432072*i+63.02378494754052*o+50.606957656360734*l-112.23884253719248)+o*(.03296041114873217*o+115.60384449646641*l-193.58209356861505)+l*(-22.33816807309886*l-180.12613974708367)}getRgbItem(e,t,n,a){this.#s(e,t,1,n,a)}getRgbBuffer(e,t,n,a,s,r,i){const o=1/((1<<r)-1);for(let r=0;r<n;r++){this.#s(e,t,o,a,s);t+=4;s+=3+i}}getOutputLength(e,t){return e/4*(3+t)|0}}class CalGrayCS extends ColorSpace{constructor(e,t,n){super("CalGray",1);if(!e)throw new FormatError("WhitePoint missing - required for color space CalGray");[this.XW,this.YW,this.ZW]=e;[this.XB,this.YB,this.ZB]=t||[0,0,0];this.G=n||1;if(this.XW<0||this.ZW<0||1!==this.YW)throw new FormatError(`Invalid WhitePoint components for ${this.name}, no fallback available`);if(this.XB<0||this.YB<0||this.ZB<0){info(`Invalid BlackPoint for ${this.name}, falling back to default.`);this.XB=this.YB=this.ZB=0}0===this.XB&&0===this.YB&&0===this.ZB||warn(`${this.name}, BlackPoint: XB: ${this.XB}, YB: ${this.YB}, ZB: ${this.ZB}, only default values are supported.`);if(this.G<1){info(`Invalid Gamma: ${this.G} for ${this.name}, falling back to default.`);this.G=1}}#s(e,t,n,a,s){const r=(e[t]*s)**this.G,i=this.YW*r,o=Math.max(295.8*i**.3333333333333333-40.8,0);n[a]=o;n[a+1]=o;n[a+2]=o}getRgbItem(e,t,n,a){this.#s(e,t,n,a,1)}getRgbBuffer(e,t,n,a,s,r,i){const o=1/((1<<r)-1);for(let r=0;r<n;++r){this.#s(e,t,a,s,o);t+=1;s+=3+i}}getOutputLength(e,t){return e*(3+t)}}class CalRGBCS extends ColorSpace{static#r=new Float32Array([.8951,.2664,-.1614,-.7502,1.7135,.0367,.0389,-.0685,1.0296]);static#i=new Float32Array([.9869929,-.1470543,.1599627,.4323053,.5183603,.0492912,-.0085287,.0400428,.9684867]);static#o=new Float32Array([3.2404542,-1.5371385,-.4985314,-.969266,1.8760108,.041556,.0556434,-.2040259,1.0572252]);static#l=new Float32Array([1,1,1]);static#f=new Float32Array(3);static#c=new Float32Array(3);static#h=new Float32Array(3);static#u=(24/116)**3/8;constructor(e,t,n,a){super("CalRGB",3);if(!e)throw new FormatError("WhitePoint missing - required for color space CalRGB");const[s,r,i]=this.whitePoint=e,[o,l,f]=this.blackPoint=t||new Float32Array(3);[this.GR,this.GG,this.GB]=n||new Float32Array([1,1,1]);[this.MXA,this.MYA,this.MZA,this.MXB,this.MYB,this.MZB,this.MXC,this.MYC,this.MZC]=a||new Float32Array([1,0,0,0,1,0,0,0,1]);if(s<0||i<0||1!==r)throw new FormatError(`Invalid WhitePoint components for ${this.name}, no fallback available`);if(o<0||l<0||f<0){info(`Invalid BlackPoint for ${this.name} [${o}, ${l}, ${f}], falling back to default.`);this.blackPoint=new Float32Array(3)}if(this.GR<0||this.GG<0||this.GB<0){info(`Invalid Gamma [${this.GR}, ${this.GG}, ${this.GB}] for ${this.name}, falling back to default.`);this.GR=this.GG=this.GB=1}}#m(e,t,n){n[0]=e[0]*t[0]+e[1]*t[1]+e[2]*t[2];n[1]=e[3]*t[0]+e[4]*t[1]+e[5]*t[2];n[2]=e[6]*t[0]+e[7]*t[1]+e[8]*t[2]}#p(e,t,n){n[0]=1*t[0]/e[0];n[1]=1*t[1]/e[1];n[2]=1*t[2]/e[2]}#d(e,t,n){n[0]=.95047*t[0]/e[0];n[1]=1*t[1]/e[1];n[2]=1.08883*t[2]/e[2]}#g(e){return e<=.0031308?MathClamp(12.92*e,0,1):e>=.99554525?1:MathClamp(1.055*e**(1/2.4)-.055,0,1)}#b(e){return e<0?-this.#b(-e):e>8?((e+16)/116)**3:e*CalRGBCS.#u}#w(e,t,n){if(0===e[0]&&0===e[1]&&0===e[2]){n[0]=t[0];n[1]=t[1];n[2]=t[2];return}const a=this.#b(0),s=(1-a)/(1-this.#b(e[0])),r=1-s,i=(1-a)/(1-this.#b(e[1])),o=1-i,l=(1-a)/(1-this.#b(e[2])),f=1-l;n[0]=t[0]*s+r;n[1]=t[1]*i+o;n[2]=t[2]*l+f}#j(e,t,n){if(1===e[0]&&1===e[2]){n[0]=t[0];n[1]=t[1];n[2]=t[2];return}const a=n;this.#m(CalRGBCS.#r,t,a);const s=CalRGBCS.#f;this.#p(e,a,s);this.#m(CalRGBCS.#i,s,n)}#k(e,t,n){const a=n;this.#m(CalRGBCS.#r,t,a);const s=CalRGBCS.#f;this.#d(e,a,s);this.#m(CalRGBCS.#i,s,n)}#s(e,t,n,a,s){const r=MathClamp(e[t]*s,0,1),i=MathClamp(e[t+1]*s,0,1),o=MathClamp(e[t+2]*s,0,1),l=1===r?1:r**this.GR,f=1===i?1:i**this.GG,c=1===o?1:o**this.GB,h=this.MXA*l+this.MXB*f+this.MXC*c,u=this.MYA*l+this.MYB*f+this.MYC*c,m=this.MZA*l+this.MZB*f+this.MZC*c,p=CalRGBCS.#c;p[0]=h;p[1]=u;p[2]=m;const d=CalRGBCS.#h;this.#j(this.whitePoint,p,d);const g=CalRGBCS.#c;this.#w(this.blackPoint,d,g);const b=CalRGBCS.#h;this.#k(CalRGBCS.#l,g,b);const w=CalRGBCS.#c;this.#m(CalRGBCS.#o,b,w);n[a]=255*this.#g(w[0]);n[a+1]=255*this.#g(w[1]);n[a+2]=255*this.#g(w[2])}getRgbItem(e,t,n,a){this.#s(e,t,n,a,1)}getRgbBuffer(e,t,n,a,s,r,i){const o=1/((1<<r)-1);for(let r=0;r<n;++r){this.#s(e,t,a,s,o);t+=3;s+=3+i}}getOutputLength(e,t){return e*(3+t)/3|0}}class LabCS extends ColorSpace{constructor(e,t,n){super("Lab",3);if(!e)throw new FormatError("WhitePoint missing - required for color space Lab");[this.XW,this.YW,this.ZW]=e;[this.amin,this.amax,this.bmin,this.bmax]=n||[-100,100,-100,100];[this.XB,this.YB,this.ZB]=t||[0,0,0];if(this.XW<0||this.ZW<0||1!==this.YW)throw new FormatError("Invalid WhitePoint components, no fallback available");if(this.XB<0||this.YB<0||this.ZB<0){info("Invalid BlackPoint, falling back to default");this.XB=this.YB=this.ZB=0}if(this.amin>this.amax||this.bmin>this.bmax){info("Invalid Range, falling back to defaults");this.amin=-100;this.amax=100;this.bmin=-100;this.bmax=100}}#y(e){return e>=6/29?e**3:108/841*(e-4/29)}#q(e,t,n,a){return n+e*(a-n)/t}#s(e,t,n,a,s){let r=e[t],i=e[t+1],o=e[t+2];if(!1!==n){r=this.#q(r,n,0,100);i=this.#q(i,n,this.amin,this.amax);o=this.#q(o,n,this.bmin,this.bmax)}i>this.amax?i=this.amax:i<this.amin&&(i=this.amin);o>this.bmax?o=this.bmax:o<this.bmin&&(o=this.bmin);const l=(r+16)/116,f=l+i/500,c=l-o/200,h=this.XW*this.#y(f),u=this.YW*this.#y(l),m=this.ZW*this.#y(c);let p,d,g;if(this.ZW<1){p=3.1339*h+-1.617*u+-.4906*m;d=-.9785*h+1.916*u+.0333*m;g=.072*h+-.229*u+1.4057*m}else{p=3.2406*h+-1.5372*u+-.4986*m;d=-.9689*h+1.8758*u+.0415*m;g=.0557*h+-.204*u+1.057*m}a[s]=255*Math.sqrt(p);a[s+1]=255*Math.sqrt(d);a[s+2]=255*Math.sqrt(g)}getRgbItem(e,t,n,a){this.#s(e,t,!1,n,a)}getRgbBuffer(e,t,n,a,s,r,i){const o=(1<<r)-1;for(let r=0;r<n;r++){this.#s(e,t,o,a,s);t+=3;s+=3+i}}getOutputLength(e,t){return e*(3+t)/3|0}isDefaultDecode(e,t){return!0}get usesZeroToOneRange(){return shadow(this,"usesZeroToOneRange",!1)}}function fetchSync(e){const t=new XMLHttpRequest;t.open("GET",e,!1);t.responseType="arraybuffer";t.send(null);return t.response}class IccColorSpace extends ColorSpace{#v;#S;static#x=!0;static#A=null;static#C=null;constructor(e,t,n){if(!IccColorSpace.isUsable)throw new Error("No ICC color space support");super(t,n);let a;switch(n){case 1:a=vn.Gray8;this.#S=(e,t,n)=>function qcms_convert_one(e,t,n){jn.qcms_convert_one(e,t,n)}(this.#v,255*e[t],n);break;case 3:a=vn.RGB8;this.#S=(e,t,n)=>function qcms_convert_three(e,t,n,a,s){jn.qcms_convert_three(e,t,n,a,s)}(this.#v,255*e[t],255*e[t+1],255*e[t+2],n);break;case 4:a=vn.CMYK;this.#S=(e,t,n)=>function qcms_convert_four(e,t,n,a,s,r){jn.qcms_convert_four(e,t,n,a,s,r)}(this.#v,255*e[t],255*e[t+1],255*e[t+2],255*e[t+3],n);break;default:throw new Error(`Unsupported number of components: ${n}`)}this.#v=function qcms_transformer_from_memory(e,t,n){const a=passArray8ToWasm0(e,jn.__wbindgen_malloc),s=qn;return jn.qcms_transformer_from_memory(a,s,t,n)>>>0}(e,a,Sn.Perceptual);if(!this.#v)throw new Error("Failed to create ICC color space");IccColorSpace.#C||=new FinalizationRegistry(e=>{!function qcms_drop_transformer(e){jn.qcms_drop_transformer(e)}(e)});IccColorSpace.#C.register(this,this.#v)}getRgbHex(e,t){this.#S(e,t,!0);return QCMS._cssColor}getRgbItem(e,t,n,a){QCMS._destBuffer=n;QCMS._destOffset=a;QCMS._destLength=3;this.#S(e,t,!1);QCMS._destBuffer=null}getRgbBuffer(e,t,n,a,s,r,i){e=e.subarray(t,t+n*this.numComps);if(8!==r){const t=255/((1<<r)-1);for(let n=0,a=e.length;n<a;n++)e[n]*=t}QCMS._mustAddAlpha=i&&a.buffer===e.buffer;QCMS._destBuffer=a;QCMS._destOffset=s;QCMS._destLength=n*(3+i);!function qcms_convert_array(e,t){const n=passArray8ToWasm0(t,jn.__wbindgen_malloc),a=qn;jn.qcms_convert_array(e,n,a)}(this.#v,e);QCMS._mustAddAlpha=!1;QCMS._destBuffer=null}getOutputLength(e,t){return e/this.numComps*(3+t)|0}static setOptions({useWasm:e,useWorkerFetch:t,wasmUrl:n}){if(t){this.#x=e;this.#A=n}else this.#x=!1}static get isUsable(){let e=!1;if(this.#x)if(this.#A)try{this._module=function initSync(e){if(void 0!==jn)return jn;void 0!==e&&(Object.getPrototypeOf(e)===Object.prototype?({module:e}=e):console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));const t=__wbg_get_imports();e instanceof WebAssembly.Module||(e=new WebAssembly.Module(e));return __wbg_finalize_init(new WebAssembly.Instance(e,t),e)}({module:fetchSync(`${this.#A}qcms_bg.wasm`)});e=!!this._module;QCMS._memory=this._module.memory;QCMS._makeHexColor=Util.makeHexColor}catch(e){warn(`ICCBased color space: "${e}".`)}else warn("No ICC color space support due to missing `wasmUrl` API option");return shadow(this,"isUsable",e)}}class CmykICCBasedCS extends IccColorSpace{static#I;constructor(){super(new Uint8Array(fetchSync(`${CmykICCBasedCS.#I}CGATS001Compat-v2-micro.icc`)),"DeviceCMYK",4)}static setOptions({iccUrl:e}){this.#I=e}static get isUsable(){let e=!1;IccColorSpace.isUsable&&(this.#I?e=!0:warn("No CMYK ICC profile support due to missing `iccUrl` API option"));return shadow(this,"isUsable",e)}}class Stream extends BaseStream{constructor(e,t,n,a){super();this.bytes=e instanceof Uint8Array?e:new Uint8Array(e);this.start=t||0;this.pos=this.start;this.end=t+n||this.bytes.length;this.dict=a}get length(){return this.end-this.start}get isEmpty(){return 0===this.length}getByte(){return this.pos>=this.end?-1:this.bytes[this.pos++]}getBytes(e){const t=this.bytes,n=this.pos,a=this.end;if(!e){this.pos=a;return t.subarray(n,a)}let s=n+e;s>a&&(s=a);this.pos=s;return t.subarray(n,s)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);return this.bytes.subarray(e,t)}reset(){this.pos=this.start}moveStart(){this.start=this.pos}makeSubStream(e,t,n=null){return new Stream(this.bytes.buffer,e,t,n)}clone(){return new Stream(this.bytes.buffer,this.start,this.end-this.start,this.dict.clone())}}class StringStream extends Stream{constructor(e){super(stringToBytes(e))}}class NullStream extends Stream{constructor(){super(new Uint8Array(0))}}class ChunkedStream extends Stream{progressiveDataLength=0;_lastSuccessfulEnsureByteChunk=-1;_loadedChunks=new Set;constructor(e,t,n){super(new Uint8Array(e),0,e,null);this.chunkSize=t;this.numChunks=Math.ceil(e/t);this.manager=n}getMissingChunks(){const e=[];for(let t=0,n=this.numChunks;t<n;++t)this._loadedChunks.has(t)||e.push(t);return e}get numChunksLoaded(){return this._loadedChunks.size}get isDataLoaded(){return this.numChunksLoaded===this.numChunks}onReceiveData(e,t){const n=this.chunkSize;if(e%n!==0)throw new Error(`Bad begin offset: ${e}`);const a=e+t.byteLength;if(a%n!==0&&a!==this.bytes.length)throw new Error(`Bad end offset: ${a}`);this.bytes.set(new Uint8Array(t),e);const s=Math.floor(e/n),r=Math.floor((a-1)/n)+1;for(let e=s;e<r;++e)this._loadedChunks.add(e)}onReceiveProgressiveData(e){let t=this.progressiveDataLength;const n=Math.floor(t/this.chunkSize);this.bytes.set(new Uint8Array(e),t);t+=e.byteLength;this.progressiveDataLength=t;const a=t>=this.end?this.numChunks:Math.floor(t/this.chunkSize);for(let e=n;e<a;++e)this._loadedChunks.add(e)}ensureByte(e){if(e<this.progressiveDataLength)return;const t=Math.floor(e/this.chunkSize);if(!(t>this.numChunks)&&t!==this._lastSuccessfulEnsureByteChunk){if(!this._loadedChunks.has(t))throw new MissingDataException(e,e+1);this._lastSuccessfulEnsureByteChunk=t}}ensureRange(e,t){if(e>=t)return;if(t<=this.progressiveDataLength)return;const n=Math.floor(e/this.chunkSize);if(n>this.numChunks)return;const a=Math.min(Math.floor((t-1)/this.chunkSize)+1,this.numChunks);for(let s=n;s<a;++s)if(!this._loadedChunks.has(s))throw new MissingDataException(e,t)}nextEmptyChunk(e){const t=this.numChunks;for(let n=0;n<t;++n){const a=(e+n)%t;if(!this._loadedChunks.has(a))return a}return null}hasChunk(e){return this._loadedChunks.has(e)}getByte(){const e=this.pos;if(e>=this.end)return-1;e>=this.progressiveDataLength&&this.ensureByte(e);return this.bytes[this.pos++]}getBytes(e){const t=this.bytes,n=this.pos,a=this.end;if(!e){a>this.progressiveDataLength&&this.ensureRange(n,a);return t.subarray(n,a)}let s=n+e;s>a&&(s=a);s>this.progressiveDataLength&&this.ensureRange(n,s);this.pos=s;return t.subarray(n,s)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);t>this.progressiveDataLength&&this.ensureRange(e,t);return this.bytes.subarray(e,t)}makeSubStream(e,t,n=null){t?e+t>this.progressiveDataLength&&this.ensureRange(e,e+t):e>=this.progressiveDataLength&&this.ensureByte(e);function ChunkedStreamSubstream(){}ChunkedStreamSubstream.prototype=Object.create(this);ChunkedStreamSubstream.prototype.getMissingChunks=function(){const e=this.chunkSize,t=Math.floor(this.start/e),n=Math.floor((this.end-1)/e)+1,a=[];for(let e=t;e<n;++e)this._loadedChunks.has(e)||a.push(e);return a};Object.defineProperty(ChunkedStreamSubstream.prototype,"isDataLoaded",{get(){return this.numChunksLoaded===this.numChunks||0===this.getMissingChunks().length},configurable:!0});const a=new ChunkedStreamSubstream;a.pos=a.start=e;a.end=e+t||this.end;a.dict=n;return a}getBaseStreams(){return[this]}}class ChunkedStreamManager{aborted=!1;currRequestId=0;_chunksNeededByRequest=new Map;_loadedStreamCapability=Promise.withResolvers();_promisesByRequest=new Map;_requestsByChunk=new Map;constructor(e,t){this.length=t.length;this.chunkSize=t.rangeChunkSize;this.stream=new ChunkedStream(this.length,this.chunkSize,this);this.pdfStream=e;this.disableAutoFetch=t.disableAutoFetch;this.msgHandler=t.msgHandler}async sendRequest(e,t){const n=this.pdfStream.getRangeReader(e,t);let a=[];for(;;){const{value:e,done:t}=await n.read();if(this.aborted){a=null;return}if(t)break;a.push(e)}if(0===a.length&&this.disableAutoFetch)return;const s=arrayBuffersToBytes(a);a=null;this.onReceiveData({chunk:s.buffer,begin:e})}requestAllChunks(e=!1){if(!e){const e=this.stream.getMissingChunks();this._requestChunks(e)}return this._loadedStreamCapability.promise}_requestChunks(e){const t=this.currRequestId++,n=new Set;this._chunksNeededByRequest.set(t,n);for(const t of e)this.stream.hasChunk(t)||n.add(t);if(0===n.size)return Promise.resolve();const a=Promise.withResolvers();this._promisesByRequest.set(t,a);const s=[];for(const e of n){let n=this._requestsByChunk.get(e);if(!n){n=[];this._requestsByChunk.set(e,n);s.push(e)}n.push(t)}if(s.length>0){const e=this.groupChunks(s);for(const t of e){const e=t.beginChunk*this.chunkSize,n=Math.min(t.endChunk*this.chunkSize,this.length);this.sendRequest(e,n).catch(a.reject)}}return a.promise.catch(e=>{if(!this.aborted)throw e})}getStream(){return this.stream}requestRange(e,t){t=Math.min(t,this.length);const n=this.getBeginChunk(e),a=this.getEndChunk(t),s=[];for(let e=n;e<a;++e)s.push(e);return this._requestChunks(s)}requestRanges(e=[]){const t=[];for(const n of e){const e=this.getBeginChunk(n.begin),a=this.getEndChunk(n.end);for(let n=e;n<a;++n)t.includes(n)||t.push(n)}t.sort((e,t)=>e-t);return this._requestChunks(t)}groupChunks(e){const t=[];let n=-1,a=-1;for(let s=0,r=e.length;s<r;++s){const r=e[s];n<0&&(n=r);if(a>=0&&a+1!==r){t.push({beginChunk:n,endChunk:a+1});n=r}s+1===e.length&&t.push({beginChunk:n,endChunk:r+1});a=r}return t}onReceiveData(e){const{chunkSize:t,length:n,stream:a}=this,s=e.chunk,r=void 0===e.begin,i=r?a.progressiveDataLength:e.begin,o=i+s.byteLength,l=Math.floor(i/t),f=o<n?Math.floor(o/t):Math.ceil(o/t);r?a.onReceiveProgressiveData(s):a.onReceiveData(i,s);a.isDataLoaded&&this._loadedStreamCapability.resolve(a);const c=[];for(let e=l;e<f;++e){const t=this._requestsByChunk.get(e);if(t){this._requestsByChunk.delete(e);for(const n of t){const t=this._chunksNeededByRequest.get(n);t.has(e)&&t.delete(e);t.size>0||c.push(n)}}}if(!this.disableAutoFetch&&0===this._requestsByChunk.size){let e;if(1===a.numChunksLoaded){const t=a.numChunks-1;a.hasChunk(t)||(e=t)}else e=a.nextEmptyChunk(f);Number.isInteger(e)&&this._requestChunks([e])}for(const e of c){const t=this._promisesByRequest.get(e);this._promisesByRequest.delete(e);t.resolve()}this.msgHandler.send("DocProgress",{loaded:MathClamp(a.numChunksLoaded*t,a.progressiveDataLength,n),total:n})}onError(e){this._loadedStreamCapability.reject(e)}getBeginChunk(e){return Math.floor(e/this.chunkSize)}getEndChunk(e){return Math.floor((e-1)/this.chunkSize)+1}abort(e){this.aborted=!0;this.pdfStream?.cancelAllRequests(e);for(const t of this._promisesByRequest.values())t.reject(e)}}function convertToRGBA(e){switch(e.kind){case x:return convertBlackAndWhiteToRGBA(e);case C:return function convertRGBToRGBA({src:e,srcPos:t=0,dest:n,destPos:a=0,width:s,height:r}){let i=0;const o=s*r*3,l=o>>2,f=new Uint32Array(e.buffer,t,l),c=FeatureTest.isLittleEndian?4278190080:255;if(FeatureTest.isLittleEndian){for(;i<l-2;i+=3,a+=4){const e=f[i],t=f[i+1],s=f[i+2];n[a]=e|c;n[a+1]=e>>>24|t<<8|c;n[a+2]=t>>>16|s<<16|c;n[a+3]=s>>>8|c}for(let s=4*i,r=t+o;s<r;s+=3)n[a++]=e[s]|e[s+1]<<8|e[s+2]<<16|c}else{for(;i<l-2;i+=3,a+=4){const e=f[i],t=f[i+1],s=f[i+2];n[a]=e|c;n[a+1]=e<<24|t>>>8|c;n[a+2]=t<<16|s>>>16|c;n[a+3]=s<<8|c}for(let s=4*i,r=t+o;s<r;s+=3)n[a++]=e[s]<<24|e[s+1]<<16|e[s+2]<<8|c}return{srcPos:t+o,destPos:a}}(e)}return null}function convertBlackAndWhiteToRGBA({src:e,srcPos:t=0,dest:n,width:a,height:s,nonBlackColor:r=4294967295,inverseDecode:i=!1}){const o=FeatureTest.isLittleEndian?4278190080:255,[l,f]=i?[r,o]:[o,r],c=a>>3,h=7&a,u=l^f,m=e.length;n=new Uint32Array(n.buffer);let p=0;for(let a=0;a<s;++a){for(const a=t+c;t<a;++t,p+=8){const a=e[t];n[p]=l^-(a>>7&1)&u;n[p+1]=l^-(a>>6&1)&u;n[p+2]=l^-(a>>5&1)&u;n[p+3]=l^-(a>>4&1)&u;n[p+4]=l^-(a>>3&1)&u;n[p+5]=l^-(a>>2&1)&u;n[p+6]=l^-(a>>1&1)&u;n[p+7]=l^-(1&a)&u}if(0===h)continue;const a=t<m?e[t++]:255;for(let e=0;e<h;++e,++p)n[p]=l^-(a>>7-e&1)&u}return{srcPos:t,destPos:p}}class ImageResizer{static#F=2048;static#T=FeatureTest.isImageDecoderSupported;constructor(e,t){this._imgData=e;this._isMask=t}static get canUseImageDecoder(){return shadow(this,"canUseImageDecoder",this.#T?ImageDecoder.isTypeSupported("image/bmp"):Promise.resolve(!1))}static needsToBeResized(e,t){if(e<=this.#F&&t<=this.#F)return!1;const{MAX_DIM:n}=this;if(e>n||t>n)return!0;const a=e*t;if(this._hasMaxArea)return a>this.MAX_AREA;if(a<this.#F**2)return!1;if(this._areGoodDims(e,t)){this.#F=Math.max(this.#F,Math.floor(Math.sqrt(e*t)));return!1}this.#F=this._guessMax(this.#F,n,128,0);return a>(this.MAX_AREA=this.#F**2)}static getReducePowerForJPX(e,t,n){const a=e*t,s=2**30/(4*n);if(!this.needsToBeResized(e,t))return a>s?Math.ceil(Math.log2(a/s)):0;const{MAX_DIM:r,MAX_AREA:i}=this,o=Math.max(e/r,t/r,Math.sqrt(a/Math.min(s,i)));return Math.ceil(Math.log2(o))}static get MAX_DIM(){return shadow(this,"MAX_DIM",this._guessMax(2048,32768,0,1))}static get MAX_AREA(){this._hasMaxArea=!0;return shadow(this,"MAX_AREA",this._guessMax(this.#F,this.MAX_DIM,128,0)**2)}static set MAX_AREA(e){if(e>=0){this._hasMaxArea=!0;shadow(this,"MAX_AREA",e)}}static setOptions({canvasMaxAreaInBytes:e=-1,isImageDecoderSupported:t=!1}){this._hasMaxArea||(this.MAX_AREA=e>>2);this.#T=t}static _areGoodDims(e,t){try{const n=new OffscreenCanvas(e,t),a=n.getContext("2d");a.fillRect(0,0,1,1);const s=a.getImageData(0,0,1,1).data[3];n.width=n.height=1;return 0!==s}catch{return!1}}static _guessMax(e,t,n,a){for(;e+n+1<t;){const n=Math.floor((e+t)/2),s=a||n;this._areGoodDims(n,s)?e=n:t=n}return e}static async createImage(e,t=!1){return new ImageResizer(e,t)._createImage()}async _createImage(){const{_imgData:e}=this,{width:t,height:n}=e;if(t*n*4>mn){const e=this.#H();if(e)return e}const a=this._encodeBMP();let s,r;if(await ImageResizer.canUseImageDecoder){s=new ImageDecoder({data:a,type:"image/bmp",preferAnimation:!1,transfer:[a.buffer]});r=s.decode().catch(e=>{warn(`BMP image decoding failed: ${e}`);return createImageBitmap(new Blob([this._encodeBMP().buffer],{type:"image/bmp"}))}).finally(()=>{s.close()})}else r=createImageBitmap(new Blob([a.buffer],{type:"image/bmp"}));const{MAX_AREA:i,MAX_DIM:o}=ImageResizer,l=Math.max(t/o,n/o,Math.sqrt(t*n/i)),f=Math.max(l,2),c=Math.round(10*(l+1.25))/10/f,h=Math.floor(Math.log2(c)),u=new Array(h+2).fill(2);u[0]=f;u.splice(-1,1,c/(1<<h));let m=t,p=n;const d=await r;let g=d.image||d;for(const e of u){const t=m,n=p;m=Math.floor(m/e)-1;p=Math.floor(p/e)-1;const a=new OffscreenCanvas(m,p);a.getContext("2d").drawImage(g,0,0,t,n,0,0,m,p);g.close();g=a.transferToImageBitmap()}e.data=null;e.bitmap=g;e.width=m;e.height=p;return e}#H(){const{_imgData:e}=this,{data:t,width:n,height:a,kind:s}=e,r=n*a*4,i=Math.ceil(Math.log2(r/mn)),o=n>>i,l=a>>i;let f,c=a;try{f=new Uint8Array(r)}catch{let e=Math.floor(Math.log2(r+1));for(;;)try{f=new Uint8Array(2**e-1);break}catch{e-=1}c=Math.floor((2**e-1)/(4*n));const t=n*c*4;t<f.length&&(f=new Uint8Array(t))}const h=new Uint32Array(f.buffer),u=new Uint32Array(o*l);let m=0,p=0;const d=Math.ceil(a/c),g=a%c===0?a:a%c;for(let e=0;e<d;e++){const a=e<d-1?c:g;({srcPos:m}=convertToRGBA({kind:s,src:t,dest:h,width:n,height:a,inverseDecode:this._isMask,srcPos:m}));for(let e=0,t=a>>i;e<t;e++){const t=h.subarray((e<<i)*n);for(let e=0;e<o;e++)u[p++]=t[e<<i]}}if(ImageResizer.needsToBeResized(o,l)){e.data=u;e.width=o;e.height=l;e.kind=F;return null}const b=new OffscreenCanvas(o,l);b.getContext("2d",{willReadFrequently:!0}).putImageData(new ImageData(new Uint8ClampedArray(u.buffer),o,l),0,0);e.data=null;e.bitmap=b.transferToImageBitmap();e.width=o;e.height=l;return e}_encodeBMP(){const{width:e,height:t,kind:n}=this._imgData;let a,s=this._imgData.data,r=new Uint8Array(0),i=r,o=0;switch(n){case x:{a=1;r=new Uint8Array(this._isMask?[255,255,255,255,0,0,0,0]:[0,0,0,0,255,255,255,255]);const n=e+7>>3,i=n+3&-4;if(n!==i){const e=new Uint8Array(i*t);let a=0;for(let r=0,o=t*n;r<o;r+=n,a+=i)e.set(s.subarray(r,r+n),a);s=e}break}case C:a=24;if(3&e){const n=3*e,a=n+3&-4,r=a-n,i=new Uint8Array(a*t);let o=0;for(let e=0,a=t*n;e<a;e+=n){const t=s.subarray(e,e+n);for(let e=0;e<n;e+=3){i[o++]=t[e+2];i[o++]=t[e+1];i[o++]=t[e]}o+=r}s=i}else for(let e=0,t=s.length;e<t;e+=3){const t=s[e];s[e]=s[e+2];s[e+2]=t}break;case F:a=32;o=3;i=new Uint8Array(68);const n=new DataView(i.buffer);if(FeatureTest.isLittleEndian){n.setUint32(0,255,!0);n.setUint32(4,65280,!0);n.setUint32(8,16711680,!0);n.setUint32(12,4278190080,!0)}else{n.setUint32(0,4278190080,!0);n.setUint32(4,16711680,!0);n.setUint32(8,65280,!0);n.setUint32(12,255,!0)}break;default:throw new Error("invalid format")}let l=0;const f=40+i.length,c=14+f+r.length+s.length,h=new Uint8Array(c),u=new DataView(h.buffer);u.setUint16(l,19778,!0);l+=2;u.setUint32(l,c,!0);l+=4;u.setUint32(l,0,!0);l+=4;u.setUint32(l,14+f+r.length,!0);l+=4;u.setUint32(l,f,!0);l+=4;u.setInt32(l,e,!0);l+=4;u.setInt32(l,-t,!0);l+=4;u.setUint16(l,1,!0);l+=2;u.setUint16(l,a,!0);l+=2;u.setUint32(l,o,!0);l+=4;u.setUint32(l,0,!0);l+=4;u.setInt32(l,0,!0);l+=4;u.setInt32(l,0,!0);l+=4;u.setUint32(l,r.length/4,!0);l+=4;u.setUint32(l,0,!0);l+=4;h.set(i,l);l+=i.length;h.set(r,l);l+=r.length;h.set(s,l);return h}}const xn=async function JBig2(e={}){var t=e,quit_=(e,t)=>{throw t},n=import.meta.url;try{new URL(".",n).href}catch{}0;console.log.bind(console);var a,s,r,i,o,l=console.error.bind(console),f=!1,c=!1;function updateMemoryViews(){var e=u.buffer;i=new Int8Array(e);new Int16Array(e);o=new Uint8Array(e);new Uint16Array(e);new Int32Array(e);new Uint32Array(e);new Float32Array(e);new Float64Array(e);new BigInt64Array(e);new BigUint64Array(e)}class ExitStatus{name="ExitStatus";constructor(e){this.message=`Program terminated with exit(${e})`;this.status=e}}var h,u,callRuntimeCallbacks=e=>{for(;e.length>0;)e.shift()(t)},m=[],addOnPostRun=e=>m.push(e),p=[],addOnPreRun=e=>p.push(e),d=!0,g=0,b={},handleException=e=>{if(e instanceof ExitStatus||"unwind"==e)return a;quit_(0,e)},keepRuntimeAlive=()=>d||g>0,_proc_exit=e=>{a=e;if(!keepRuntimeAlive()){t.onExit?.(e);f=!0}quit_(0,new ExitStatus(e))},_exit=(e,t)=>{a=e;_proc_exit(e)},callUserCallback=e=>{if(!f)try{return e()}catch(e){handleException(e)}finally{(()=>{if(!keepRuntimeAlive())try{_exit(a)}catch(e){handleException(e)}})()}},alignMemory=(e,t)=>Math.ceil(e/t)*t,growMemory=e=>{var t=(e-u.buffer.byteLength+65535)/65536|0;try{u.grow(t);updateMemoryViews();return 1}catch(e){}};t.noExitRuntime&&(d=t.noExitRuntime);t.print&&t.print;t.printErr&&(l=t.printErr);t.wasmBinary&&t.wasmBinary;t.arguments&&t.arguments;t.thisProgram&&t.thisProgram;if(t.preInit){"function"==typeof t.preInit&&(t.preInit=[t.preInit]);for(;t.preInit.length>0;)t.preInit.shift()()}t.writeArrayToMemory=(e,t)=>{i.set(e,t)};var w,j={e:()=>function abort(e){t.onAbort?.(e);l(e="Aborted("+e+")");f=!0;e+=". Build with -sASSERTIONS for more info.";var n=new WebAssembly.RuntimeError(e);r?.(n);throw n}(""),b:()=>{d=!1;g=0},c:(e,t)=>{if(b[e]){clearTimeout(b[e].id);delete b[e]}if(!t)return 0;var n=setTimeout(()=>{delete b[e];callUserCallback(()=>h(e,performance.now()))},t);b[e]={id:n,timeout_ms:t};return 0},g:function _createImageData(e){t.imageData=new Uint8Array(e)},d:e=>{var t=o.length,n=2147483648;if((e>>>=0)>n)return!1;for(var a=1;a<=4;a*=2){var s=t*(1+.2/a);s=Math.min(s,e+100663296);var r=Math.min(n,alignMemory(Math.max(e,s),65536));if(growMemory(r))return!0}return!1},a:_proc_exit,h:function _setImageData(e,n,a,s){if(a===n){t.imageData=new Uint8ClampedArray(o.subarray(e,e+a*s));return}const r=n*s,i=t.imageData=new Uint8ClampedArray(r);for(let t=e,s=0;s<r;t+=a,s+=n)i.set(o.subarray(t,t+n),s)},f:function _setLineData(e,n,a){t.imageData.set(o.subarray(e,e+n),a)}};w=await async function createWasm(){function receiveInstance(e,n){!function assignWasmExports(e){t._malloc=e.k;t._free=e.l;t._jbig2_decode=e.m;t._ccitt_decode=e.n;h=e.o;u=e.i;e.__indirect_function_table}(w=e.exports);updateMemoryViews();return w}var e=function getWasmImports(){return{a:j}}();return new Promise((n,a)=>{t.instantiateWasm(e,(e,t)=>{n(receiveInstance(e))})})}();!function run(){!function preRun(){if(t.preRun){"function"==typeof t.preRun&&(t.preRun=[t.preRun]);for(;t.preRun.length;)addOnPreRun(t.preRun.shift())}callRuntimeCallbacks(p)}();function doRun(){t.calledRun=!0;if(!f){!function initRuntime(){c=!0;w.j()}();s?.(t);t.onRuntimeInitialized?.();!function postRun(){if(t.postRun){"function"==typeof t.postRun&&(t.postRun=[t.postRun]);for(;t.postRun.length;)addOnPostRun(t.postRun.shift())}callRuntimeCallbacks(m)}()}}if(t.setStatus){t.setStatus("Running...");setTimeout(()=>{setTimeout(()=>t.setStatus(""),1);doRun()},1)}else doRun()}();return c?t:new Promise((e,t)=>{s=e;r=t})};class JBig2Error extends en{constructor(e){super(e,"Jbig2Error")}}class JBig2CCITTFaxWasmImage{static#O=null;static#B=null;static#R=null;static#x=!0;static#D=!0;static#A=null;static setOptions({handler:e,useWasm:t,useWorkerFetch:n,wasmUrl:a}){this.#x=t;this.#D=n;this.#A=a;n||(this.#B=e)}static async#M(e,t,n){const a="jbig2.wasm";try{this.#O||(this.#D?this.#O=await fetchBinaryData(`${this.#A}${a}`):this.#O=await this.#B.sendWithPromise("FetchBinaryData",{type:"wasmFactory",filename:a}));return n((await WebAssembly.instantiate(this.#O,t)).instance)}catch(t){warn(`JBig2Image#instantiateWasm: ${t}`);return e(null)}finally{this.#B=null}}static async decode(e,t,n,a,s){if(!this.#R){const{promise:e,resolve:t}=Promise.withResolvers(),n=[e];this.#x?n.push(xn({warn,instantiateWasm:this.#M.bind(this,t)})):t(null);this.#R=Promise.race(n)}const r=await this.#R;if(!r)throw new JBig2Error("JBig2 failed to initialize");let i,o;try{const l=e.length;i=r._malloc(l);r.writeArrayToMemory(e,i);if(s)r._ccitt_decode(i,l,t,n,s.K,s.EndOfLine?1:0,s.EncodedByteAlign?1:0,s.BlackIs1?1:0,s.Columns,s.Rows);else{const e=a?a.length:0;if(e>0){o=r._malloc(e);r.writeArrayToMemory(a,o)}r._jbig2_decode(i,l,t,n,o,e)}if(!r.imageData)throw new JBig2Error("Unknown error");const{imageData:f}=r;r.imageData=null;return f}finally{i&&r._free(i);o&&r._free(o)}}static cleanup(){this.#R=null}}const An=new Uint8Array(0);class DecodeStream extends BaseStream{constructor(e){super();this._rawMinBufferLength=e||0;this.pos=0;this.bufferLength=0;this.eof=!1;this.buffer=An;this.minBufferLength=512;if(e)for(;this.minBufferLength<e;)this.minBufferLength*=2}get isEmpty(){for(;!this.eof&&0===this.bufferLength;)this.readBlock();return 0===this.bufferLength}ensureBuffer(e){const t=this.buffer;if(e<=t.byteLength)return t;let n=this.minBufferLength;for(;n<e;)n*=2;const a=new Uint8Array(n);a.set(t);return this.buffer=a}getByte(){const e=this.pos;for(;this.bufferLength<=e;){if(this.eof)return-1;this.readBlock()}return this.buffer[this.pos++]}getBytes(e,t=null){const n=this.pos;let a;if(e){this.ensureBuffer(n+e);a=n+e;for(;!this.eof&&this.bufferLength<a;)this.readBlock(t);const s=this.bufferLength;a>s&&(a=s)}else{for(;!this.eof;)this.readBlock(t);a=this.bufferLength}this.pos=a;return this.buffer.subarray(n,a)}async getImageData(e,t){if(!this.canAsyncDecodeImageFromBuffer)return this.isAsyncDecoder?this.decodeImage(null,e,t):this.getBytes(e,t);const n=await this.stream.asyncGetBytes();return this.decodeImage(n,e,t)}async asyncGetBytesFromDecompressionStream(e){this.stream.reset();const t=this.stream.isAsync?await this.stream.asyncGetBytes():this.stream.getBytes();try{const{readable:n,writable:a}=new DecompressionStream(e),s=a.getWriter();await s.ready;s.write(t).then(async()=>{await s.ready;await s.close()}).catch(()=>{});const r=[];let i=0;for await(const e of n){r.push(e);i+=e.byteLength}const o=new Uint8Array(i);let l=0;for(const e of r){o.set(e,l);l+=e.byteLength}return{decompressed:o,compressed:t}}catch{return{decompressed:null,compressed:t}}}reset(){this.pos=0}makeSubStream(e,t,n=null){if(void 0===t)for(;!this.eof;)this.readBlock();else{const n=e+t;for(;this.bufferLength<=n&&!this.eof;)this.readBlock()}return new Stream(this.buffer,e,t,n)}getBaseStreams(){return this.stream?this.stream.getBaseStreams():null}clone(){for(;!this.eof;)this.readBlock();return new Stream(this.buffer,this.start,this.end-this.start,this.dict.clone())}}class StreamsSequenceStream extends DecodeStream{constructor(e,t=null){e=e.filter(e=>e instanceof BaseStream&&!e.isImageStream);let n=0;for(const t of e)n+=t instanceof DecodeStream?t._rawMinBufferLength:t.length;super(n);this.streams=e;this._onError=t}readBlock(){const e=this.streams;if(0===e.length){this.eof=!0;return}const t=e.shift();let n;try{n=t.getBytes()}catch(e){if(this._onError){this._onError(e,t.dict?.objId);return}throw e}const a=this.bufferLength,s=a+n.length;this.ensureBuffer(s).set(n,a);this.bufferLength=s}getBaseStreams(){const e=[];for(const t of this.streams){const n=t.getBaseStreams();n&&e.push(...n)}return e.length>0?e:null}}class ColorSpaceUtils{static parse({cs:e,xref:t,resources:n=null,pdfFunctionFactory:a,globalColorSpaceCache:s,localColorSpaceCache:r,asyncIfNotCached:i=!1}){const o={xref:t,resources:n,pdfFunctionFactory:a,globalColorSpaceCache:s,localColorSpaceCache:r};let l,f,c;if(e instanceof Ref){f=e;const n=s.getByRef(f)||r.getByRef(f);if(n)return n;e=t.fetch(e)}if(e instanceof Name){l=e.name;const t=r.getByName(l);if(t)return t}try{c=this.#P(e,o)}catch(e){if(i&&!(e instanceof MissingDataException))return Promise.reject(e);throw e}if(l||f){r.set(l,f,c);f&&s.set(null,f,c)}return i?Promise.resolve(c):c}static#E(e,t){const{globalColorSpaceCache:n}=t;let a;if(e instanceof Ref){a=e;const t=n.getByRef(a);if(t)return t}const s=this.#P(e,t);a&&n.set(null,a,s);return s}static#P(e,t){const{xref:n,resources:a,pdfFunctionFactory:s,globalColorSpaceCache:r}=t;if((e=n.fetchIfRef(e))instanceof Name)switch(e.name){case"G":case"DeviceGray":return this.gray;case"RGB":case"DeviceRGB":return this.rgb;case"DeviceRGBA":return this.rgba;case"CMYK":case"DeviceCMYK":return this.cmyk;case"Pattern":return new PatternCS(null);default:if(a instanceof Dict){const n=a.get("ColorSpace");if(n instanceof Dict){const a=n.get(e.name);if(a){if(a instanceof Name)return this.#P(a,t);e=a;break}}}warn(`Unrecognized ColorSpace: ${e.name}`);return this.gray}if(Array.isArray(e)){const a=n.fetchIfRef(e[0]).name;let i,o,l,f,c,h;switch(a){case"G":case"DeviceGray":return this.gray;case"RGB":case"DeviceRGB":return this.rgb;case"CMYK":case"DeviceCMYK":return this.cmyk;case"CalGray":i=n.fetchIfRef(e[1]);f=i.getArray("WhitePoint");c=i.getArray("BlackPoint");h=i.get("Gamma");return new CalGrayCS(f,c,h);case"CalRGB":i=n.fetchIfRef(e[1]);f=i.getArray("WhitePoint");c=i.getArray("BlackPoint");h=i.getArray("Gamma");const u=i.getArray("Matrix");return new CalRGBCS(f,c,h,u);case"ICCBased":const m=e[1]instanceof Ref;if(m){const t=r.getByRef(e[1]);if(t)return t}const p=n.fetchIfRef(e[1]),d=p.dict;o=d.get("N");if(IccColorSpace.isUsable)try{const t=new IccColorSpace(p.getBytes(),"ICCBased",o);m&&r.set(null,e[1],t);return t}catch(t){if(t instanceof MissingDataException)throw t;warn(`ICCBased color space (${e[1]}): "${t}".`)}const g=d.getRaw("Alternate");if(g){const e=this.#E(g,t);if(e.numComps===o)return e;warn("ICCBased color space: Ignoring incorrect /Alternate entry.")}if(1===o)return this.gray;if(3===o)return this.rgb;if(4===o)return this.cmyk;break;case"Pattern":l=e[1]||null;l&&(l=this.#E(l,t));return new PatternCS(l);case"I":case"Indexed":l=this.#E(e[1],t);const b=MathClamp(n.fetchIfRef(e[2]),0,255),w=n.fetchIfRef(e[3]);return new IndexedCS(l,b,w);case"Separation":case"DeviceN":const j=n.fetchIfRef(e[1]);o=Array.isArray(j)?j.length:1;l=this.#E(e[2],t);const k=s.create(e[3]);return new AlternateCS(o,l,k);case"Lab":i=n.fetchIfRef(e[1]);f=i.getArray("WhitePoint");c=i.getArray("BlackPoint");const y=i.getArray("Range");return new LabCS(f,c,y);default:warn(`Unimplemented ColorSpace object: ${a}`);return this.gray}}warn(`Unrecognized ColorSpace object: ${e}`);return this.gray}static get gray(){return shadow(this,"gray",new DeviceGrayCS)}static get rgb(){return shadow(this,"rgb",new DeviceRgbCS)}static get rgba(){return shadow(this,"rgba",new DeviceRgbaCS)}static get cmyk(){if(CmykICCBasedCS.isUsable)try{return shadow(this,"cmyk",new CmykICCBasedCS)}catch{warn("CMYK fallback: DeviceCMYK")}return shadow(this,"cmyk",new DeviceCmykCS)}}class JpegError extends en{constructor(e){super(e,"JpegError")}}class DNLMarkerError extends en{constructor(e,t){super(e,"DNLMarkerError");this.scanLines=t}}class EOIMarkerError extends en{constructor(e){super(e,"EOIMarkerError")}}const Cn=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]),In=4017,Fn=799,Tn=3406,Hn=2276,On=1567,Bn=3784,Rn=5793,Dn=2896;function buildHuffmanTable(e,t){let n,a,s=0,r=16;for(;r>0&&!e[r-1];)r--;const i=[{children:[],index:0}];let o,l=i[0];for(n=0;n<r;n++){for(a=0;a<e[n];a++){l=i.pop();l.children[l.index]=t[s];for(;l.index>0;)l=i.pop();l.index++;i.push(l);for(;i.length<=n;){i.push(o={children:[],index:0});l.children[l.index]=o.children;l=o}s++}if(n+1<r){i.push(o={children:[],index:0});l.children[l.index]=o.children;l=o}}return i[0].children}function getBlockBufferOffset(e,t,n){return 64*((e.blocksPerLine+1)*t+n)}function decodeScan(e,t,n,a,s,r,i,o,l,f=!1){const c=n.mcusPerLine,h=n.progressive,u=t;let m=0,p=0;function readBit(){if(p>0){p--;return m>>p&1}m=e[t++];if(255===m){const a=e[t++];if(a){if(220===a&&f){const a=readUint16(e,t+=2);t+=2;if(a>0&&a!==n.scanLines)throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data",a)}else if(217===a){if(f){const e=w*(8===n.precision?8:0);if(e>0&&Math.round(n.scanLines/e)>=5)throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter",e)}throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data")}throw new JpegError(`unexpected marker ${(m<<8|a).toString(16)}`)}}p=7;return m>>>7}function decodeHuffman(e){let t=e;for(;;){t=t[readBit()];switch(typeof t){case"number":return t;case"object":continue}throw new JpegError("invalid huffman sequence")}}function receive(e){let t=0;for(;e>0;){t=t<<1|readBit();e--}return t}function receiveAndExtend(e){if(1===e)return 1===readBit()?1:-1;const t=receive(e);return t>=1<<e-1?t:t+(-1<<e)+1}let d=0;let g,b=0;let w=0;function decodeMcu(e,t,n,a,s){const r=n%c;w=(n/c|0)*e.v+a;const i=r*e.h+s;t(e,getBlockBufferOffset(e,w,i))}function decodeBlock(e,t,n){w=n/e.blocksPerLine|0;const a=n%e.blocksPerLine;t(e,getBlockBufferOffset(e,w,a))}const j=a.length;let k,y,q,v,S,x;x=h?0===r?0===o?function decodeDCFirst(e,t){const n=decodeHuffman(e.huffmanTableDC),a=0===n?0:receiveAndExtend(n)<<l;e.blockData[t]=e.pred+=a}:function decodeDCSuccessive(e,t){e.blockData[t]|=readBit()<<l}:0===o?function decodeACFirst(e,t){if(d>0){d--;return}let n=r;const a=i;for(;n<=a;){const a=decodeHuffman(e.huffmanTableAC),s=15&a,r=a>>4;if(0===s){if(r<15){d=receive(r)+(1<<r)-1;break}n+=16;continue}n+=r;const i=Cn[n];e.blockData[t+i]=receiveAndExtend(s)*(1<<l);n++}}:function decodeACSuccessive(e,t){let n=r;const a=i;let s,o,f=0;for(;n<=a;){const a=t+Cn[n],r=e.blockData[a]<0?-1:1;switch(b){case 0:o=decodeHuffman(e.huffmanTableAC);s=15&o;f=o>>4;if(0===s)if(f<15){d=receive(f)+(1<<f);b=4}else{f=16;b=1}else{if(1!==s)throw new JpegError("invalid ACn encoding");g=receiveAndExtend(s);b=f?2:3}continue;case 1:case 2:if(e.blockData[a])e.blockData[a]+=r*(readBit()<<l);else{f--;0===f&&(b=2===b?3:0)}break;case 3:if(e.blockData[a])e.blockData[a]+=r*(readBit()<<l);else{e.blockData[a]=g<<l;b=0}break;case 4:e.blockData[a]&&(e.blockData[a]+=r*(readBit()<<l))}n++}if(4===b){d--;0===d&&(b=0)}}:function decodeBaseline(e,t){const n=decodeHuffman(e.huffmanTableDC),a=0===n?0:receiveAndExtend(n);e.blockData[t]=e.pred+=a;let s=1;for(;s<64;){const n=decodeHuffman(e.huffmanTableAC),a=15&n,r=n>>4;if(0===a){if(r<15)break;s+=16;continue}s+=r;const i=Cn[s];e.blockData[t+i]=receiveAndExtend(a);s++}};let C,F=0;const T=1===j?a[0].blocksPerLine*a[0].blocksPerColumn:c*n.mcusPerColumn;let H,O;for(;F<=T;){const n=s?Math.min(T-F,s):T;if(n>0){for(y=0;y<j;y++)a[y].pred=0;d=0;if(1===j){k=a[0];for(S=0;S<n;S++){decodeBlock(k,x,F);F++}}else for(S=0;S<n;S++){for(y=0;y<j;y++){k=a[y];H=k.h;O=k.v;for(q=0;q<O;q++)for(v=0;v<H;v++)decodeMcu(k,x,F,q,v)}F++}}p=0;C=findNextFileMarker(e,t);if(!C)break;if(C.invalid){warn(`decodeScan - ${n>0?"unexpected":"excessive"} MCU data, current marker is: ${C.invalid}`);t=C.offset}if(!(C.marker>=65488&&C.marker<=65495))break;t+=2}return t-u}function quantizeAndInverse(e,t,n){const a=e.quantizationTable,s=e.blockData;let r,i,o,l,f,c,h,u,m,p,d,g,b,w,j,k,y;if(!a)throw new JpegError("missing required Quantization Table.");for(let e=0;e<64;e+=8){m=s[t+e];p=s[t+e+1];d=s[t+e+2];g=s[t+e+3];b=s[t+e+4];w=s[t+e+5];j=s[t+e+6];k=s[t+e+7];m*=a[e];if(0!==(p|d|g|b|w|j|k)){p*=a[e+1];d*=a[e+2];g*=a[e+3];b*=a[e+4];w*=a[e+5];j*=a[e+6];k*=a[e+7];r=Rn*m+128>>8;i=Rn*b+128>>8;o=d;l=j;f=Dn*(p-k)+128>>8;u=Dn*(p+k)+128>>8;c=g<<4;h=w<<4;r=r+i+1>>1;i=r-i;y=o*Bn+l*On+128>>8;o=o*On-l*Bn+128>>8;l=y;f=f+h+1>>1;h=f-h;u=u+c+1>>1;c=u-c;r=r+l+1>>1;l=r-l;i=i+o+1>>1;o=i-o;y=f*Hn+u*Tn+2048>>12;f=f*Tn-u*Hn+2048>>12;u=y;y=c*Fn+h*In+2048>>12;c=c*In-h*Fn+2048>>12;h=y;n[e]=r+u;n[e+7]=r-u;n[e+1]=i+h;n[e+6]=i-h;n[e+2]=o+c;n[e+5]=o-c;n[e+3]=l+f;n[e+4]=l-f}else{y=Rn*m+512>>10;n[e]=y;n[e+1]=y;n[e+2]=y;n[e+3]=y;n[e+4]=y;n[e+5]=y;n[e+6]=y;n[e+7]=y}}for(let e=0;e<8;++e){m=n[e];p=n[e+8];d=n[e+16];g=n[e+24];b=n[e+32];w=n[e+40];j=n[e+48];k=n[e+56];if(0!==(p|d|g|b|w|j|k)){r=Rn*m+2048>>12;i=Rn*b+2048>>12;o=d;l=j;f=Dn*(p-k)+2048>>12;u=Dn*(p+k)+2048>>12;c=g;h=w;r=4112+(r+i+1>>1);i=r-i;y=o*Bn+l*On+2048>>12;o=o*On-l*Bn+2048>>12;l=y;f=f+h+1>>1;h=f-h;u=u+c+1>>1;c=u-c;r=r+l+1>>1;l=r-l;i=i+o+1>>1;o=i-o;y=f*Hn+u*Tn+2048>>12;f=f*Tn-u*Hn+2048>>12;u=y;y=c*Fn+h*In+2048>>12;c=c*In-h*Fn+2048>>12;h=y;m=r+u;k=r-u;p=i+h;j=i-h;d=o+c;w=o-c;g=l+f;b=l-f;m<16?m=0:m>=4080?m=255:m>>=4;p<16?p=0:p>=4080?p=255:p>>=4;d<16?d=0:d>=4080?d=255:d>>=4;g<16?g=0:g>=4080?g=255:g>>=4;b<16?b=0:b>=4080?b=255:b>>=4;w<16?w=0:w>=4080?w=255:w>>=4;j<16?j=0:j>=4080?j=255:j>>=4;k<16?k=0:k>=4080?k=255:k>>=4;s[t+e]=m;s[t+e+8]=p;s[t+e+16]=d;s[t+e+24]=g;s[t+e+32]=b;s[t+e+40]=w;s[t+e+48]=j;s[t+e+56]=k}else{y=Rn*m+8192>>14;y=y<-2040?0:y>=2024?255:y+2056>>4;s[t+e]=y;s[t+e+8]=y;s[t+e+16]=y;s[t+e+24]=y;s[t+e+32]=y;s[t+e+40]=y;s[t+e+48]=y;s[t+e+56]=y}}}function buildComponentData(e,t){const n=t.blocksPerLine,a=t.blocksPerColumn,s=new Int16Array(64);for(let e=0;e<a;e++)for(let a=0;a<n;a++){quantizeAndInverse(t,getBlockBufferOffset(t,e,a),s)}return t.blockData}function findNextFileMarker(e,t,n=t){const a=e.length-1;let s=n<t?n:t;if(t>=a)return null;const r=readUint16(e,t);if(r>=65472&&r<=65534)return{invalid:null,marker:r,offset:t};let i=readUint16(e,s);for(;!(i>=65472&&i<=65534);){if(++s>=a)return null;i=readUint16(e,s)}return{invalid:r.toString(16),marker:i,offset:s}}function prepareComponents(e){const t=Math.ceil(e.samplesPerLine/8/e.maxH),n=Math.ceil(e.scanLines/8/e.maxV);for(const a of e.components){const s=Math.ceil(Math.ceil(e.samplesPerLine/8)*a.h/e.maxH),r=Math.ceil(Math.ceil(e.scanLines/8)*a.v/e.maxV),i=t*a.h,o=64*(n*a.v)*(i+1);a.blockData=new Int16Array(o);a.blocksPerLine=s;a.blocksPerColumn=r}e.mcusPerLine=t;e.mcusPerColumn=n}function readDataBlock(e,t){const n=readUint16(e,t);let a=(t+=2)+n-2;const s=findNextFileMarker(e,a,t);if(s?.invalid){warn("readDataBlock - incorrect length, current marker is: "+s.invalid);a=s.offset}const r=e.subarray(t,a);return{appData:r,oldOffset:t,newOffset:t+r.length}}function skipData(e,t){const n=readUint16(e,t),a=(t+=2)+n-2,s=findNextFileMarker(e,a,t);return s?.invalid?s.offset:a}class JpegImage{constructor({decodeTransform:e=null,colorTransform:t=-1}={}){this._decodeTransform=e;this._colorTransform=t}static canUseImageDecoder(e,t=-1){let n=null,a=0,s=null,r=readUint16(e,a);a+=2;if(65496!==r)throw new JpegError("SOI not found");r=readUint16(e,a);a+=2;e:for(;65497!==r;){switch(r){case 65505:const{appData:t,oldOffset:i,newOffset:o}=readDataBlock(e,a);a=o;if(69===t[0]&&120===t[1]&&105===t[2]&&102===t[3]&&0===t[4]&&0===t[5]){if(n)throw new JpegError("Duplicate EXIF-blocks found.");n={exifStart:i+6,exifEnd:o}}r=readUint16(e,a);a+=2;continue;case 65472:case 65473:case 65474:s=e[a+7];break e;case 65535:255!==e[a]&&a--}a=skipData(e,a);r=readUint16(e,a);a+=2}return 4===s||3===s&&0===t?null:n||{}}parse(e,{dnlScanLines:t=null}={}){let n,a,s=0,r=null,i=null,o=0;const l=[],f=[],c=[];let h=readUint16(e,s);s+=2;if(65496!==h)throw new JpegError("SOI not found");h=readUint16(e,s);s+=2;e:for(;65497!==h;){let u,m,p;switch(h){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:const{appData:d,newOffset:g}=readDataBlock(e,s);s=g;65504===h&&74===d[0]&&70===d[1]&&73===d[2]&&70===d[3]&&0===d[4]&&(r={version:{major:d[5],minor:d[6]},densityUnits:d[7],xDensity:d[8]<<8|d[9],yDensity:d[10]<<8|d[11],thumbWidth:d[12],thumbHeight:d[13],thumbData:d.subarray(14,14+3*d[12]*d[13])});65518===h&&65===d[0]&&100===d[1]&&111===d[2]&&98===d[3]&&101===d[4]&&(i={version:d[5]<<8|d[6],flags0:d[7]<<8|d[8],flags1:d[9]<<8|d[10],transformCode:d[11]});break;case 65499:const b=readUint16(e,s);s+=2;const w=b+s-2;let j;for(;s<w;){const t=e[s++],n=new Uint16Array(64);if(t>>4){if(t>>4!=1)throw new JpegError("DQT - invalid table spec");for(m=0;m<64;m++){j=Cn[m];n[j]=readUint16(e,s);s+=2}}else for(m=0;m<64;m++){j=Cn[m];n[j]=e[s++]}l[15&t]=n}break;case 65472:case 65473:case 65474:if(n)throw new JpegError("Only single frame JPEGs supported");s+=2;n={};n.extended=65473===h;n.progressive=65474===h;n.precision=e[s++];const k=readUint16(e,s);s+=2;n.scanLines=t||k;n.samplesPerLine=readUint16(e,s);s+=2;n.components=[];n.componentIds={};const y=e[s++];let q=0,v=0;for(u=0;u<y;u++){const t=e[s],a=e[s+1]>>4,r=15&e[s+1];q<a&&(q=a);v<r&&(v=r);const i=e[s+2];p=n.components.push({h:a,v:r,quantizationId:i,quantizationTable:null});n.componentIds[t]=p-1;s+=3}n.maxH=q;n.maxV=v;prepareComponents(n);break;case 65476:const S=readUint16(e,s);s+=2;for(u=2;u<S;){const t=e[s++],n=new Uint8Array(16);let a=0;for(m=0;m<16;m++,s++)a+=n[m]=e[s];const r=new Uint8Array(a);for(m=0;m<a;m++,s++)r[m]=e[s];u+=17+a;(t>>4?f:c)[15&t]=buildHuffmanTable(n,r)}break;case 65501:s+=2;a=readUint16(e,s);s+=2;break;case 65498:const x=1===++o&&!t;s+=2;const C=e[s++],F=[];for(u=0;u<C;u++){const t=e[s++],a=n.componentIds[t],r=n.components[a];r.index=t;const i=e[s++];r.huffmanTableDC=c[i>>4];r.huffmanTableAC=f[15&i];F.push(r)}const T=e[s++],H=e[s++],O=e[s++];try{s+=decodeScan(e,s,n,F,a,T,H,O>>4,15&O,x)}catch(t){if(t instanceof DNLMarkerError){warn(`${t.message} -- attempting to re-parse the JPEG image.`);return this.parse(e,{dnlScanLines:t.scanLines})}if(t instanceof EOIMarkerError){warn(`${t.message} -- ignoring the rest of the image data.`);break e}throw t}break;case 65500:s+=4;break;case 65535:255!==e[s]&&s--;break;default:const R=findNextFileMarker(e,s-2,s-3);if(R?.invalid){warn("JpegImage.parse - unexpected data, current marker is: "+R.invalid);s=R.offset;break}if(!R||s>=e.length-1){warn("JpegImage.parse - reached the end of the image data without finding an EOI marker (0xFFD9).");break e}throw new JpegError("JpegImage.parse - unknown marker: "+h.toString(16))}h=readUint16(e,s);s+=2}if(!n)throw new JpegError("JpegImage.parse - no frame data found.");this.width=n.samplesPerLine;this.height=n.scanLines;this.jfif=r;this.adobe=i;this.components=[];for(const e of n.components){const t=l[e.quantizationId];t&&(e.quantizationTable=t);this.components.push({index:e.index,output:buildComponentData(0,e),scaleX:e.h/n.maxH,scaleY:e.v/n.maxV,blocksPerLine:e.blocksPerLine,blocksPerColumn:e.blocksPerColumn})}this.numComponents=this.components.length}_getLinearizedBlockData(e,t,n=!1){const a=this.width/e,s=this.height/t;let r,i,o,l,f,c,h,u,m,p,d,g=0;const b=this.components.length,w=e*t*b,j=new Uint8ClampedArray(w),k=new Uint32Array(e),y=4294967288;let q;for(h=0;h<b;h++){r=this.components[h];i=r.scaleX*a;o=r.scaleY*s;g=h;d=r.output;l=r.blocksPerLine+1<<3;if(i!==q){for(f=0;f<e;f++){u=0|f*i;k[f]=(u&y)<<3|7&u}q=i}for(c=0;c<t;c++){u=0|c*o;p=l*(u&y)|(7&u)<<3;for(f=0;f<e;f++){j[g]=d[p+k[f]];g+=b}}}let v=this._decodeTransform;n||4!==b||v||(v=new Int32Array([-256,255,-256,255,-256,255,-256,255]));if(v)for(h=0;h<w;)for(u=0,m=0;u<b;u++,h++,m+=2)j[h]=(j[h]*v[m]>>8)+v[m+1];return j}get _isColorConversionNeeded(){return this.adobe?!!this.adobe.transformCode:3===this.numComponents?0!==this._colorTransform&&(82!==this.components[0].index||71!==this.components[1].index||66!==this.components[2].index):1===this._colorTransform}_convertYccToRgb(e){let t,n,a;for(let s=0,r=e.length;s<r;s+=3){t=e[s];n=e[s+1];a=e[s+2];e[s]=t-179.456+1.402*a;e[s+1]=t+135.459-.344*n-.714*a;e[s+2]=t-226.816+1.772*n}return e}_convertYccToRgba(e,t){for(let n=0,a=0,s=e.length;n<s;n+=3,a+=4){const s=e[n],r=e[n+1],i=e[n+2];t[a]=s-179.456+1.402*i;t[a+1]=s+135.459-.344*r-.714*i;t[a+2]=s-226.816+1.772*r;t[a+3]=255}return t}_convertYcckToRgb(e){this._convertYcckToCmyk(e);return this._convertCmykToRgb(e)}_convertYcckToRgba(e){this._convertYcckToCmyk(e);return this._convertCmykToRgba(e)}_convertYcckToCmyk(e){let t,n,a;for(let s=0,r=e.length;s<r;s+=4){t=e[s];n=e[s+1];a=e[s+2];e[s]=434.456-t-1.402*a;e[s+1]=119.541-t+.344*n+.714*a;e[s+2]=481.816-t-1.772*n}return e}_convertCmykToRgb(e){const t=e.length/4;ColorSpaceUtils.cmyk.getRgbBuffer(e,0,t,e,0,8,0);return e.subarray(0,3*t)}_convertCmykToRgba(e){ColorSpaceUtils.cmyk.getRgbBuffer(e,0,e.length/4,e,0,8,1);if(ColorSpaceUtils.cmyk instanceof DeviceCmykCS)for(let t=3,n=e.length;t<n;t+=4)e[t]=255;return e}getData({width:e,height:t,forceRGBA:n=!1,forceRGB:a=!1,isSourcePDF:s=!1}){if(this.numComponents>4)throw new JpegError("Unsupported color mode");const r=this._getLinearizedBlockData(e,t,s);if(1===this.numComponents&&(n||a)){const e=r.length*(n?4:3),t=new Uint8ClampedArray(e);let a=0;if(n)!function grayToRGBA(e,t){if(FeatureTest.isLittleEndian)for(let n=0,a=e.length;n<a;n++)t[n]=65793*e[n]|4278190080;else for(let n=0,a=e.length;n<a;n++)t[n]=16843008*e[n]|255}(r,new Uint32Array(t.buffer));else for(const e of r){t[a++]=e;t[a++]=e;t[a++]=e}return t}if(3===this.numComponents&&this._isColorConversionNeeded){if(n){const e=new Uint8ClampedArray(r.length/3*4);return this._convertYccToRgba(r,e)}return this._convertYccToRgb(r)}if(4===this.numComponents){if(this._isColorConversionNeeded)return n?this._convertYcckToRgba(r):a?this._convertYcckToRgb(r):this._convertYcckToCmyk(r);if(n)return this._convertCmykToRgba(r);if(a)return this._convertCmykToRgb(r)}return r}}class JpegStream extends DecodeStream{static#T=FeatureTest.isImageDecoderSupported;constructor(e,t,n){super(t);this.stream=e;this.dict=e.dict;this.maybeLength=t;this.params=n}static get canUseImageDecoder(){return shadow(this,"canUseImageDecoder",this.#T?ImageDecoder.isTypeSupported("image/jpeg"):Promise.resolve(!1))}static setOptions({isImageDecoderSupported:e=!1}){this.#T=e}get bytes(){return shadow(this,"bytes",this.stream.getBytes(this.maybeLength))}ensureBuffer(e){}readBlock(){this.decodeImage()}get jpegOptions(){const e={decodeTransform:void 0,colorTransform:void 0},t=this.dict.getArray("D","Decode");if((this.forceRGBA||this.forceRGB)&&Array.isArray(t)){const n=this.dict.get("BPC","BitsPerComponent")||8,a=t.length,s=new Int32Array(a);let r=!1;const i=(1<<n)-1;for(let e=0;e<a;e+=2){s[e]=256*(t[e+1]-t[e])|0;s[e+1]=t[e]*i|0;256===s[e]&&0===s[e+1]||(r=!0)}r&&(e.decodeTransform=s)}if(this.params instanceof Dict){const t=this.params.get("ColorTransform");Number.isInteger(t)&&(e.colorTransform=t)}return shadow(this,"jpegOptions",e)}#N(e){for(let t=0,n=e.length-1;t<n;t++)if(255===e[t]&&216===e[t+1]){t>0&&(e=e.subarray(t));break}return e}decodeImage(e){if(this.eof)return this.buffer;e=this.#N(e||this.bytes);const t=new JpegImage(this.jpegOptions);t.parse(e);const n=t.getData({width:this.drawWidth,height:this.drawHeight,forceRGBA:this.forceRGBA,forceRGB:this.forceRGB,isSourcePDF:!0});this.buffer=n;this.bufferLength=n.length;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}async getTransferableImage(){if(!await JpegStream.canUseImageDecoder)return null;const e=this.jpegOptions;if(e.decodeTransform)return null;let t;try{const n=this.canAsyncDecodeImageFromBuffer&&await this.stream.asyncGetBytes()||this.bytes;if(!n)return null;let a=this.#N(n);const s=JpegImage.canUseImageDecoder(a,e.colorTransform);if(!s)return null;if(s.exifStart){a=a.slice();a.fill(0,s.exifStart,s.exifEnd)}t=new ImageDecoder({data:a,type:"image/jpeg",preferAnimation:!1});return(await t.decode()).image}catch(e){warn(`getTransferableImage - failed: "${e}".`);return null}finally{t?.close()}}get isImageStream(){return!0}}const Mn=async function OpenJPEG(e={}){var t=e,n="./this.program",quit_=(e,t)=>{throw t},a=import.meta.url;try{new URL(".",a).href}catch{}0;var s,r,i,o,l,f,c,h,u=console.log.bind(console),m=console.error.bind(console),p=!1,d=!1;function updateMemoryViews(){var e=o.buffer;l=new Int8Array(e);new Int16Array(e);f=new Uint8Array(e);new Uint16Array(e);c=new Int32Array(e);h=new Uint32Array(e);new Float32Array(e);new Float64Array(e);new BigInt64Array(e);new BigUint64Array(e)}class ExitStatus{name="ExitStatus";constructor(e){this.message=`Program terminated with exit(${e})`;this.status=e}}var g,callRuntimeCallbacks=e=>{for(;e.length>0;)e.shift()(t)},b=[],addOnPostRun=e=>b.push(e),w=[],addOnPreRun=e=>w.push(e),j=!0,k=0,y={},handleException=e=>{if(e instanceof ExitStatus||"unwind"==e)return s;quit_(0,e)},keepRuntimeAlive=()=>j||k>0,_proc_exit=e=>{s=e;if(!keepRuntimeAlive()){t.onExit?.(e);p=!0}quit_(0,new ExitStatus(e))},_exit=(e,t)=>{s=e;_proc_exit(e)},callUserCallback=e=>{if(!p)try{e();(()=>{if(!keepRuntimeAlive())try{_exit(s)}catch(e){handleException(e)}})()}catch(e){handleException(e)}},alignMemory=(e,t)=>Math.ceil(e/t)*t,growMemory=e=>{var t=(e-o.buffer.byteLength+65535)/65536|0;try{o.grow(t);updateMemoryViews();return 1}catch(e){}},q={},getEnvStrings=()=>{if(!getEnvStrings.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.language||"C").replace("-","_")+".UTF-8",_:n||"./this.program"};for(var t in q)void 0===q[t]?delete e[t]:e[t]=q[t];var a=[];for(var t in e)a.push(`${t}=${e[t]}`);getEnvStrings.strings=a}return getEnvStrings.strings},stringToUTF8=(e,t,n)=>((e,t,n,a)=>{if(!(a>0))return 0;for(var s=n,r=n+a-1,i=0;i<e.length;++i){var o=e.codePointAt(i);if(o<=127){if(n>=r)break;t[n++]=o}else if(o<=2047){if(n+1>=r)break;t[n++]=192|o>>6;t[n++]=128|63&o}else if(o<=65535){if(n+2>=r)break;t[n++]=224|o>>12;t[n++]=128|o>>6&63;t[n++]=128|63&o}else{if(n+3>=r)break;t[n++]=240|o>>18;t[n++]=128|o>>12&63;t[n++]=128|o>>6&63;t[n++]=128|63&o;i++}}t[n]=0;return n-s})(e,f,t,n),lengthBytesUTF8=e=>{for(var t=0,n=0;n<e.length;++n){var a=e.charCodeAt(n);if(a<=127)t++;else if(a<=2047)t+=2;else if(a>=55296&&a<=57343){t+=4;++n}else t+=3}return t},v=[null,[],[]],S="undefined"!=typeof TextDecoder?new TextDecoder:void 0,UTF8ArrayToString=(e,t=0,n,a)=>{var s=((e,t,n,a)=>{var s=t+n;if(a)return s;for(;e[t]&&!(t>=s);)++t;return t})(e,t,n,a);if(s-t>16&&e.buffer&&S)return S.decode(e.subarray(t,s));for(var r="";t<s;){var i=e[t++];if(128&i){var o=63&e[t++];if(192!=(224&i)){var l=63&e[t++];if((i=224==(240&i)?(15&i)<<12|o<<6|l:(7&i)<<18|o<<12|l<<6|63&e[t++])<65536)r+=String.fromCharCode(i);else{var f=i-65536;r+=String.fromCharCode(55296|f>>10,56320|1023&f)}}else r+=String.fromCharCode((31&i)<<6|o)}else r+=String.fromCharCode(i)}return r},printChar=(e,t)=>{var n=v[e];if(0===t||10===t){(1===e?u:m)(UTF8ArrayToString(n));n.length=0}else n.push(t)},UTF8ToString=(e,t,n)=>e?UTF8ArrayToString(f,e,t,n):"";t.noExitRuntime&&(j=t.noExitRuntime);t.print&&(u=t.print);t.printErr&&(m=t.printErr);t.wasmBinary&&t.wasmBinary;t.arguments&&t.arguments;t.thisProgram&&(n=t.thisProgram);if(t.preInit){"function"==typeof t.preInit&&(t.preInit=[t.preInit]);for(;t.preInit.length>0;)t.preInit.shift()()}t.writeArrayToMemory=(e,t)=>{l.set(e,t)};var x,C={k:()=>function abort(e){t.onAbort?.(e);m(e="Aborted("+e+")");p=!0;e+=". Build with -sASSERTIONS for more info.";var n=new WebAssembly.RuntimeError(e);i?.(n);throw n}(""),j:()=>{j=!1;k=0},l:(e,t)=>{if(y[e]){clearTimeout(y[e].id);delete y[e]}if(!t)return 0;var n=setTimeout(()=>{delete y[e];callUserCallback(()=>g(e,performance.now()))},t);y[e]={id:n,timeout_ms:t};return 0},f:function _copy_pixels_1(e,n){e>>=2;const a=t.imageData=new Uint8ClampedArray(n),s=c.subarray(e,e+n);a.set(s)},e:function _copy_pixels_3(e,n,a,s){e>>=2;n>>=2;a>>=2;const r=t.imageData=new Uint8ClampedArray(3*s),i=c.subarray(e,e+s),o=c.subarray(n,n+s),l=c.subarray(a,a+s);for(let e=0;e<s;e++){r[3*e]=i[e];r[3*e+1]=o[e];r[3*e+2]=l[e]}},d:function _copy_pixels_4(e,n,a,s,r){e>>=2;n>>=2;a>>=2;s>>=2;const i=t.imageData=new Uint8ClampedArray(4*r),o=c.subarray(e,e+r),l=c.subarray(n,n+r),f=c.subarray(a,a+r),h=c.subarray(s,s+r);for(let e=0;e<r;e++){i[4*e]=o[e];i[4*e+1]=l[e];i[4*e+2]=f[e];i[4*e+3]=h[e]}},m:e=>{var t=f.length,n=2147483648;if((e>>>=0)>n)return!1;for(var a=1;a<=4;a*=2){var s=t*(1+.2/a);s=Math.min(s,e+100663296);var r=Math.min(n,alignMemory(Math.max(e,s),65536));if(growMemory(r))return!0}return!1},o:(e,t)=>{var n=0,a=0;for(var s of getEnvStrings()){var r=t+n;h[e+a>>2]=r;n+=stringToUTF8(s,r,1/0)+1;a+=4}return 0},p:(e,t)=>{var n=getEnvStrings();h[e>>2]=n.length;var a=0;for(var s of n)a+=lengthBytesUTF8(s)+1;h[t>>2]=a;return 0},n:function _fd_seek(e,t,n,a){t=(s=t)<-9007199254740992||s>9007199254740992?NaN:Number(s);var s;return 70},b:(e,t,n,a)=>{for(var s=0,r=0;r<n;r++){var i=h[t>>2],o=h[t+4>>2];t+=8;for(var l=0;l<o;l++)printChar(e,f[i+l]);s+=o}h[a>>2]=s;return 0},q:function _gray_to_rgba(e,n){e>>=2;const a=t.imageData=new Uint8ClampedArray(4*n),s=c.subarray(e,e+n);for(let e=0;e<n;e++){a[4*e]=a[4*e+1]=a[4*e+2]=s[e];a[4*e+3]=255}},h:function _graya_to_rgba(e,n,a){e>>=2;n>>=2;const s=t.imageData=new Uint8ClampedArray(4*a),r=c.subarray(e,e+a),i=c.subarray(n,n+a);for(let e=0;e<a;e++){s[4*e]=s[4*e+1]=s[4*e+2]=r[e];s[4*e+3]=i[e]}},c:function _jsPrintWarning(e){const n=UTF8ToString(e);(t.warn||console.warn)(`OpenJPEG: ${n}`)},i:_proc_exit,g:function _rgb_to_rgba(e,n,a,s){e>>=2;n>>=2;a>>=2;const r=t.imageData=new Uint8ClampedArray(4*s),i=c.subarray(e,e+s),o=c.subarray(n,n+s),l=c.subarray(a,a+s);for(let e=0;e<s;e++){r[4*e]=i[e];r[4*e+1]=o[e];r[4*e+2]=l[e];r[4*e+3]=255}},a:function _storeErrorMessage(e){const n=UTF8ToString(e);t.errorMessages?t.errorMessages+="\n"+n:t.errorMessages=n}};x=await async function createWasm(){function receiveInstance(e,n){x=e.exports;o=x.r;updateMemoryViews();!function assignWasmExports(e){t._malloc=e.t;t._free=e.u;t._jp2_decode=e.v;g=e.w}(x);return x}var e=function getWasmImports(){return{a:C}}();return new Promise((n,a)=>{t.instantiateWasm(e,(e,t)=>{n(receiveInstance(e))})})}();!function run(){!function preRun(){if(t.preRun){"function"==typeof t.preRun&&(t.preRun=[t.preRun]);for(;t.preRun.length;)addOnPreRun(t.preRun.shift())}callRuntimeCallbacks(w)}();function doRun(){t.calledRun=!0;if(!p){!function initRuntime(){d=!0;x.s()}();r?.(t);t.onRuntimeInitialized?.();!function postRun(){if(t.postRun){"function"==typeof t.postRun&&(t.postRun=[t.postRun]);for(;t.postRun.length;)addOnPostRun(t.postRun.shift())}callRuntimeCallbacks(b)}()}}if(t.setStatus){t.setStatus("Running...");setTimeout(()=>{setTimeout(()=>t.setStatus(""),1);doRun()},1)}else doRun()}();return d?t:new Promise((e,t)=>{r=e;i=t})};class JpxError extends en{constructor(e){super(e,"JpxError")}}class JpxImage{static#O=null;static#B=null;static#R=null;static#x=!0;static#D=!0;static#A=null;static setOptions({handler:e,useWasm:t,useWorkerFetch:n,wasmUrl:a}){this.#x=t;this.#D=n;this.#A=a;n||(this.#B=e)}static async#z(e){const t=`${this.#A}openjpeg_nowasm_fallback.js`;let n=null;try{n=(await import( +/*webpackIgnore: true*/ +/*@vite-ignore*/ +t)).default()}catch(e){warn(`JpxImage#getJsModule: ${e}`)}e(n)}static async#M(e,t,n){const a="openjpeg.wasm";try{this.#O||(this.#D?this.#O=await fetchBinaryData(`${this.#A}${a}`):this.#O=await this.#B.sendWithPromise("FetchBinaryData",{type:"wasmFactory",filename:a}));return n((await WebAssembly.instantiate(this.#O,t)).instance)}catch(t){warn(`JpxImage#instantiateWasm: ${t}`);this.#z(e);return null}finally{this.#B=null}}static async decode(e,{numComponents:t=4,isIndexedColormap:n=!1,smaskInData:a=!1,reducePower:s=0}={}){if(!this.#R){const{promise:e,resolve:t}=Promise.withResolvers(),n=[e];this.#x?n.push(Mn({warn,instantiateWasm:this.#M.bind(this,t)})):this.#z(t);this.#R=Promise.race(n)}const r=await this.#R;if(!r)throw new JpxError("OpenJPEG failed to initialize");let i;try{const o=e.length;i=r._malloc(o);r.writeArrayToMemory(e,i);if(r._jp2_decode(i,o,t>0?t:0,!!n,!!a,s)){const{errorMessages:e}=r;if(e){delete r.errorMessages;throw new JpxError(e)}throw new JpxError("Unknown error")}const{imageData:l}=r;r.imageData=null;return l}finally{i&&r._free(i)}}static cleanup(){this.#R=null}static parseImageProperties(e){let t=e.getByte();for(;t>=0;){const n=t;t=e.getByte();if(65361===(n<<8|t)){e.skip(4);const t=e.getInt32()>>>0,n=e.getInt32()>>>0,a=e.getInt32()>>>0,s=e.getInt32()>>>0;e.skip(16);return{width:t-a,height:n-s,bitsPerComponent:8,componentsCount:e.getUint16()}}}throw new JpxError("No size marker found in JPX stream")}}function addState(e,t,n,a,s){let r=e;for(let e=0,n=t.length-1;e<n;e++){const n=t[e];r=r[n]||=[]}r[t.at(-1)]={checkFn:n,iterateFn:a,processFn:s}}const Pn=[];addState(Pn,[we,ke,Pt,je],null,function iterateInlineImageGroup(e,t){const n=e.fnArray,a=(t-(e.iCurr-3))%4;switch(a){case 0:return n[t]===we;case 1:return n[t]===ke;case 2:return n[t]===Pt;case 3:return n[t]===je}throw new Error(`iterateInlineImageGroup - invalid pos: ${a}`)},function foundInlineImageGroup(e,t){const n=e.fnArray,a=e.argsArray,s=e.iCurr,r=s-3,i=s-2,o=s-1,l=Math.min(Math.floor((t-r)/4),200);if(l<10)return t-(t-r)%4;let f=0;const c=[];let h=0,u=1,m=1;for(let e=0;e<l;e++){const t=a[i+(e<<2)],n=a[o+(e<<2)][0];if(u+n.width>1e3){f=Math.max(f,u);m+=h+2;u=0;h=0}c.push({transform:t,x:u,y:m,w:n.width,h:n.height});u+=n.width+2;h=Math.max(h,n.height)}const p=Math.max(f,u)+1,d=m+h+1,g=new Uint8Array(p*d*4),b=p<<2;for(let e=0;e<l;e++){const t=a[o+(e<<2)][0].data,n=c[e].w<<2;let s=0,r=c[e].x+c[e].y*p<<2;g.set(t.subarray(0,n),r-b);for(let a=0,i=c[e].h;a<i;a++){g.set(t.subarray(s,s+n),r);s+=n;r+=b}g.set(t.subarray(s-n,s),r);for(;r>=0;){t[r-4]=t[r];t[r-3]=t[r+1];t[r-2]=t[r+2];t[r-1]=t[r+3];t[r+n]=t[r+n-4];t[r+n+1]=t[r+n-3];t[r+n+2]=t[r+n-2];t[r+n+3]=t[r+n-1];r-=b}}const w={width:p,height:d};if(e.isOffscreenCanvasSupported){const e=new OffscreenCanvas(p,d);e.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(g.buffer),p,d),0,0);w.bitmap=e.transferToImageBitmap();w.data=null}else{w.kind=F;w.data=g}n.splice(r,4*l,Et);a.splice(r,4*l,[w,c]);return r+1});addState(Pn,[we,ke,Rt,je],null,function iterateImageMaskGroup(e,t){const n=e.fnArray,a=(t-(e.iCurr-3))%4;switch(a){case 0:return n[t]===we;case 1:return n[t]===ke;case 2:return n[t]===Rt;case 3:return n[t]===je}throw new Error(`iterateImageMaskGroup - invalid pos: ${a}`)},function foundImageMaskGroup(e,t){const n=e.fnArray,a=e.argsArray,s=e.iCurr,r=s-3,i=s-2,o=s-1;let l=Math.floor((t-r)/4);if(l<10)return t-(t-r)%4;let f,c,h=!1;const u=a[o][0],m=a[i][0],p=a[i][1],d=a[i][2],g=a[i][3];if(p===d){h=!0;f=i+4;let e=o+4;for(let t=1;t<l;t++,f+=4,e+=4){c=a[f];if(a[e][0]!==u||c[0]!==m||c[1]!==p||c[2]!==d||c[3]!==g){t<10?h=!1:l=t;break}}}if(h){l=Math.min(l,1e3);const e=new Float32Array(2*l);f=i;for(let t=0;t<l;t++,f+=4){c=a[f];e[t<<1]=c[4];e[1+(t<<1)]=c[5]}n.splice(r,4*l,zt);a.splice(r,4*l,[u,m,p,d,g,e])}else{l=Math.min(l,100);const e=[];for(let t=0;t<l;t++){c=a[i+(t<<2)];const n=a[o+(t<<2)][0];e.push({data:n.data,width:n.width,height:n.height,interpolate:n.interpolate,count:n.count,transform:c})}n.splice(r,4*l,Dt);a.splice(r,4*l,[e])}return r+1});addState(Pn,[we,ke,Mt,je],function(e){const t=e.argsArray,n=e.iCurr-2;return 0===t[n][1]&&0===t[n][2]},function iterateImageGroup(e,t){const n=e.fnArray,a=e.argsArray,s=(t-(e.iCurr-3))%4;switch(s){case 0:return n[t]===we;case 1:if(n[t]!==ke)return!1;const s=e.iCurr-2,r=a[s][0],i=a[s][3];return a[t][0]===r&&0===a[t][1]&&0===a[t][2]&&a[t][3]===i;case 2:if(n[t]!==Mt)return!1;const o=a[e.iCurr-1][0];return a[t][0]===o;case 3:return n[t]===je}throw new Error(`iterateImageGroup - invalid pos: ${s}`)},function(e,t){const n=e.fnArray,a=e.argsArray,s=e.iCurr,r=s-3,i=s-2,o=a[s-1][0],l=a[i][0],f=a[i][3],c=Math.min(Math.floor((t-r)/4),1e3);if(c<3)return t-(t-r)%4;const h=new Float32Array(2*c);let u=i;for(let e=0;e<c;e++,u+=4){const t=a[u];h[e<<1]=t[4];h[1+(e<<1)]=t[5]}const m=[o,l,f,h];n.splice(r,4*c,Nt);a.splice(r,4*c,m);return r+1});addState(Pn,[Ne,We,Ye,Qe,ze],null,function iterateShowTextGroup(e,t){const n=e.fnArray,a=e.argsArray,s=(t-(e.iCurr-4))%5;switch(s){case 0:return n[t]===Ne;case 1:return n[t]===We;case 2:return n[t]===Ye;case 3:if(n[t]!==Qe)return!1;const s=e.iCurr-3,r=a[s][0],i=a[s][1];return a[t][0]===r&&a[t][1]===i;case 4:return n[t]===ze}throw new Error(`iterateShowTextGroup - invalid pos: ${s}`)},function(e,t){const n=e.fnArray,a=e.argsArray,s=e.iCurr,r=s-4,i=s-3,o=s-2,l=s-1,f=s,c=a[i][0],h=a[i][1];let u=Math.min(Math.floor((t-r)/5),1e3);if(u<3)return t-(t-r)%5;let m=r;if(r>=4&&n[r-4]===n[i]&&n[r-3]===n[o]&&n[r-2]===n[l]&&n[r-1]===n[f]&&a[r-4][0]===c&&a[r-4][1]===h){u++;m-=5}let p=m+4;for(let e=1;e<u;e++){n.splice(p,3);a.splice(p,3);p+=2}return p+1});addState(Pn,[we,ke,Ut,je],e=>{const t=e.argsArray,n=t[e.iCurr-1][0];if(n!==Ie&&n!==Fe&&n!==Oe&&n!==Be&&n!==Re&&n!==De)return!0;const a=t[e.iCurr-2];return 1===a[0]&&0===a[1]&&0===a[2]&&1===a[3]},()=>!1,(e,t)=>{const{fnArray:n,argsArray:a}=e,s=e.iCurr,r=s-3,i=s-2,o=a[s-1],l=a[i],[,[f],c]=o;if(c){Util.scaleMinMax(l,c);for(let e=0,t=f.length;e<t;)switch(f[e++]){case Kt:case Gt:Util.applyTransform(f,l,e);e+=2;break;case Vt:Util.applyTransformToBezier(f,l,e);e+=6}}n.splice(r,4,Ut);a.splice(r,4,o);return r+1});class NullOptimizer{constructor(e){this.queue=e}_optimize(){}push(e,t){this.queue.fnArray.push(e);this.queue.argsArray.push(t);this._optimize()}flush(){}reset(){}}class QueueOptimizer extends NullOptimizer{constructor(e){super(e);this.state=null;this.context={iCurr:0,fnArray:e.fnArray,argsArray:e.argsArray,isOffscreenCanvasSupported:OperatorList.isOffscreenCanvasSupported};this.match=null;this.lastProcessed=0}_optimize(){const e=this.queue.fnArray;let t=this.lastProcessed,n=e.length,a=this.state,s=this.match;if(!a&&!s&&t+1===n&&!Pn[e[t]]){this.lastProcessed=n;return}const r=this.context;for(;t<n;){if(s){if((0,s.iterateFn)(r,t)){t++;continue}t=(0,s.processFn)(r,t+1);n=e.length;s=null;a=null;if(t>=n)break}a=(a||Pn)[e[t]];if(a&&!Array.isArray(a)){r.iCurr=t;t++;if(!a.checkFn||(0,a.checkFn)(r)){s=a;a=null}else a=null}else t++}this.state=a;this.match=s;this.lastProcessed=t}flush(){for(;this.match;){const e=this.queue.fnArray.length;this.lastProcessed=(0,this.match.processFn)(this.context,e);this.match=null;this.state=null;this._optimize()}}reset(){this.state=null;this.match=null;this.lastProcessed=0}}class OperatorList{static CHUNK_SIZE=1e3;static CHUNK_SIZE_ABOUT=this.CHUNK_SIZE-5;static isOffscreenCanvasSupported=!1;constructor(e=0,t){this._streamSink=t;this.fnArray=[];this.argsArray=[];this.optimizer=!t||e&u?new NullOptimizer(this):new QueueOptimizer(this);this.dependencies=new Set;this._totalLength=0;this.weight=0;this._resolved=t?null:Promise.resolve()}static setOptions({isOffscreenCanvasSupported:e}){this.isOffscreenCanvasSupported=e}get length(){return this.argsArray.length}get ready(){return this._resolved||this._streamSink.ready}get totalLength(){return this._totalLength+this.length}addOp(e,t){this.optimizer.push(e,t);this.weight++;this._streamSink&&(this.weight>=OperatorList.CHUNK_SIZE||this.weight>=OperatorList.CHUNK_SIZE_ABOUT&&(e===je||e===ze))&&this.flush()}addImageOps(e,t,n,a=!1){if(a){this.addOp(we);this.addOp(be,[[["SMask",!1]]])}void 0!==n&&this.addOp(St,["OC",n]);this.addOp(e,t);void 0!==n&&this.addOp(xt,[]);a&&this.addOp(je)}addDependency(e){if(!this.dependencies.has(e)){this.dependencies.add(e);this.addOp(fe,[e])}}addDependencies(e){for(const t of e)this.addDependency(t)}addOpList(e){if(e instanceof OperatorList){for(const t of e.dependencies)this.dependencies.add(t);for(let t=0,n=e.length;t<n;t++)this.addOp(e.fnArray[t],e.argsArray[t])}else warn('addOpList - ignoring invalid "opList" parameter.')}getIR(){return{fnArray:this.fnArray,argsArray:this.argsArray,length:this.length}}get _transfers(){const e=[],{fnArray:t,argsArray:n,length:a}=this;for(let s=0;s<a;s++)switch(t[s]){case Pt:case Et:case Rt:{const{bitmap:t,data:a}=n[s][0];(t||a?.buffer)&&e.push(t||a.buffer);break}case Ut:{const[,[t],a]=n[s];t&&e.push(t.buffer,a.buffer);break}case It:const[t,a]=n[s];t&&e.push(t.buffer);a&&e.push(a.buffer);break;case Ye:e.push(n[s][0].buffer)}return e}flush(e=!1,t=null){this.optimizer.flush();const n=this.length;this._totalLength+=n;this._streamSink.enqueue({fnArray:this.fnArray,argsArray:this.argsArray,lastChunk:e,separateAnnots:t,length:n},1,this._transfers);this.dependencies.clear();this.fnArray.length=0;this.argsArray.length=0;this.weight=0;this.optimizer.reset()}}function hexToInt(e,t){let n=0;for(let a=0;a<=t;a++)n=n<<8|e[a];return n>>>0}function hexToStr(e,t){return 1===t?String.fromCharCode(e[0],e[1]):3===t?String.fromCharCode(e[0],e[1],e[2],e[3]):String.fromCharCode(...e.subarray(0,t+1))}function addHex(e,t,n){let a=0;for(let s=n;s>=0;s--){a+=e[s]+t[s];e[s]=255&a;a>>=8}}function incHex(e,t){let n=1;for(let a=t;a>=0&&n>0;a--){n+=e[a];e[a]=255&n;n>>=8}}const En=16;class BinaryCMapStream{constructor(e){this.buffer=e;this.pos=0;this.end=e.length;this.tmpBuf=new Uint8Array(19)}readByte(){return this.pos>=this.end?-1:this.buffer[this.pos++]}readNumber(){let e,t=0;do{const n=this.readByte();if(n<0)throw new FormatError("unexpected EOF in bcmap");e=!(128&n);t=t<<7|127&n}while(!e);return t}readSigned(){const e=this.readNumber();return 1&e?~(e>>>1):e>>>1}readHex(e,t){e.set(this.buffer.subarray(this.pos,this.pos+t+1));this.pos+=t+1}readHexNumber(e,t){let n;const a=this.tmpBuf;let s=0;do{const e=this.readByte();if(e<0)throw new FormatError("unexpected EOF in bcmap");n=!(128&e);a[s++]=127&e}while(!n);let r=t,i=0,o=0;for(;r>=0;){for(;o<8&&a.length>0;){i|=a[--s]<<o;o+=7}e[r]=255&i;r--;i>>=8;o-=8}}readHexSigned(e,t){this.readHexNumber(e,t);const n=1&e[t]?255:0;let a=0;for(let s=0;s<=t;s++){a=(1&a)<<8|e[s];e[s]=a>>1^n}}readString(){const e=this.readNumber(),t=new Array(e);for(let n=0;n<e;n++)t[n]=this.readNumber();return String.fromCharCode(...t)}}class BinaryCMapReader{async process(e,t,n){const a=new BinaryCMapStream(e),s=a.readByte();t.vertical=!!(1&s);let r=null;const i=new Uint8Array(En),o=new Uint8Array(En),l=new Uint8Array(En),f=new Uint8Array(En),c=new Uint8Array(En);let h,u;for(;(u=a.readByte())>=0;){const e=u>>5;if(7===e){switch(31&u){case 0:a.readString();break;case 1:r=a.readString()}continue}const n=!!(16&u),s=15&u;if(s+1>En)throw new Error("BinaryCMapReader.process: Invalid dataSize.");const m=1,p=a.readNumber();switch(e){case 0:a.readHex(i,s);a.readHexNumber(o,s);addHex(o,i,s);t.addCodespaceRange(s+1,hexToInt(i,s),hexToInt(o,s));for(let e=1;e<p;e++){incHex(o,s);a.readHexNumber(i,s);addHex(i,o,s);a.readHexNumber(o,s);addHex(o,i,s);t.addCodespaceRange(s+1,hexToInt(i,s),hexToInt(o,s))}break;case 1:a.readHex(i,s);a.readHexNumber(o,s);addHex(o,i,s);a.readNumber();for(let e=1;e<p;e++){incHex(o,s);a.readHexNumber(i,s);addHex(i,o,s);a.readHexNumber(o,s);addHex(o,i,s);a.readNumber()}break;case 2:a.readHex(l,s);h=a.readNumber();t.mapOne(hexToInt(l,s),h);for(let e=1;e<p;e++){incHex(l,s);if(!n){a.readHexNumber(c,s);addHex(l,c,s)}h=a.readSigned()+(h+1);t.mapOne(hexToInt(l,s),h)}break;case 3:a.readHex(i,s);a.readHexNumber(o,s);addHex(o,i,s);h=a.readNumber();t.mapCidRange(hexToInt(i,s),hexToInt(o,s),h);for(let e=1;e<p;e++){incHex(o,s);if(n)i.set(o);else{a.readHexNumber(i,s);addHex(i,o,s)}a.readHexNumber(o,s);addHex(o,i,s);h=a.readNumber();t.mapCidRange(hexToInt(i,s),hexToInt(o,s),h)}break;case 4:a.readHex(l,m);a.readHex(f,s);t.mapOne(hexToInt(l,m),hexToStr(f,s));for(let e=1;e<p;e++){incHex(l,m);if(!n){a.readHexNumber(c,m);addHex(l,c,m)}incHex(f,s);a.readHexSigned(c,s);addHex(f,c,s);t.mapOne(hexToInt(l,m),hexToStr(f,s))}break;case 5:a.readHex(i,m);a.readHexNumber(o,m);addHex(o,i,m);a.readHex(f,s);t.mapBfRange(hexToInt(i,m),hexToInt(o,m),hexToStr(f,s));for(let e=1;e<p;e++){incHex(o,m);if(n)i.set(o);else{a.readHexNumber(i,m);addHex(i,o,m)}a.readHexNumber(o,m);addHex(o,i,m);a.readHex(f,s);t.mapBfRange(hexToInt(i,m),hexToInt(o,m),hexToStr(f,s))}break;default:throw new Error(`BinaryCMapReader.process - unknown type: ${e}`)}}return r?n(r):t}}class Ascii85Stream extends DecodeStream{constructor(e,t){t&&(t*=.8);super(t);this.stream=e;this.dict=e.dict;this.input=new Uint8Array(5)}readBlock(){const e=this.stream;let t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();if(-1===t||126===t){this.eof=!0;return}const n=this.bufferLength;let a,s;if(122===t){a=this.ensureBuffer(n+4);for(s=0;s<4;++s)a[n+s]=0;this.bufferLength+=4}else{const r=this.input;r[0]=t;for(s=1;s<5;++s){t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();r[s]=t;if(-1===t||126===t)break}a=this.ensureBuffer(n+s-1);this.bufferLength+=s-1;if(s<5){for(;s<5;++s)r[s]=117;this.eof=!0}let i=0;for(s=0;s<5;++s)i=85*i+(r[s]-33);for(s=3;s>=0;--s){a[n+s]=255&i;i>>=8}}}}class AsciiHexStream extends DecodeStream{constructor(e,t){t&&(t*=.5);super(t);this.stream=e;this.dict=e.dict;this.firstDigit=-1}readBlock(){const e=this.stream.getBytes(8e3);if(!e.length){this.eof=!0;return}const t=e.length+1>>1,n=this.ensureBuffer(this.bufferLength+t);let a=this.bufferLength,s=this.firstDigit;for(const t of e){let e;if(t>=48&&t<=57)e=15&t;else{if(!(t>=65&&t<=70||t>=97&&t<=102)){if(62===t){this.eof=!0;break}continue}e=9+(15&t)}if(s<0)s=e;else{n[a++]=s<<4|e;s=-1}}if(s>=0&&this.eof){n[a++]=s<<4;s=-1}this.firstDigit=s;this.bufferLength=a}}let Nn=(()=>{const e=Int32Array.from([256,402,436,468,500,534,566,598,630,662,694,726,758,790,822,854,886,920,952,984,1016,1048,1080]),t=Int32Array.from([1,2,3,4,0,5,17,6,16,7,8,9,10,11,12,13,14,15]),n=Int32Array.from([0,3,2,1,0,0,0,0,0,0,3,3,3,3,3,3]),a=Int32Array.from([0,0,0,0,-1,1,-2,2,-3,3,-1,1,-2,2,-3,3]),s=Int32Array.from([131072,131076,131075,196610,131072,131076,131075,262145,131072,131076,131075,196610,131072,131076,131075,262149]),r=Int32Array.from([1,5,9,13,17,25,33,41,49,65,81,97,113,145,177,209,241,305,369,497,753,1265,2289,4337,8433,16625]),i=Int32Array.from([2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,7,8,9,10,11,12,13,24]),o=Int16Array.from([0,0,0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,7,8,9,10,12,14,24]),l=Int16Array.from([0,0,0,0,0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,7,8,9,10,24]),f=new Int16Array(2816);!function unpackCommandLookupTable(e){const t=new Int32Array(24),n=new Int32Array(24);n[0]=2;for(let e=0;e<23;++e){t[e+1]=t[e]+(1<<o[e]);n[e+1]=n[e]+(1<<l[e])}for(let a=0;a<704;++a){let s=a>>6,r=-4;if(s>=2){s-=2;r=0}const i=(170064>>2*s&3)<<3|a>>3&7,f=(156228>>2*s&3)<<3|7&a,c=n[f],h=r+Math.min(c,5)-2,u=4*a;e[u]=o[i]|l[f]<<8;e[u+1]=t[i];e[u+2]=n[f];e[u+3]=h}}(f);function log2floor(e){let t=-1,n=16,a=e;for(;n>0;){let e=a>>n;if(0!==e){t+=n;a=e}n>>=1}return t+a}function calculateDistanceAlphabetSize(e,t,n){return 16+t+2*(n<<e)}function calculateDistanceAlphabetLimit(e,t,n,a){if(t<a+(2<<n))return makeError(e,-23);const s=4+(t-a>>n),r=log2floor(s)-1;return((r-1<<1|s>>r&1)-1<<n)+(1<<n)+a+16}function initState(e){if(0!==e.runningState)return makeError(e,-26);e.blockTrees=new Int32Array(3091);e.blockTrees[0]=7;e.distRbIdx=3;let t=calculateDistanceAlphabetLimit(e,2147483644,3,120);if(t<0)return t;const n=t;e.distExtraBits=new Int8Array(n);e.distOffset=new Int32Array(n);t=function initBitReader(e){e.byteBuffer=new Int8Array(4160);e.accumulator32=0;e.shortBuffer=new Int16Array(2080);e.bitOffset=32;e.halfOffset=2048;e.endOfStreamReached=0;return prepare(e)}(e);if(t<0)return t;e.runningState=1;return 0}function decodeVarLenUnsignedByte(e){if(e.bitOffset>=16){e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16}if(0!==readFewBits(e,1)){const t=readFewBits(e,3);return 0===t?1:readFewBits(e,t)+(1<<t)}return 0}function readSymbol(e,t,n){let a=e[t];const s=n.accumulator32>>>n.bitOffset;a+=255&s;const r=e[a]>>16,i=65535&e[a];if(r<=8){n.bitOffset+=r;return i}a+=i;a+=(s&(1<<r)-1)>>>8;n.bitOffset+=8+(e[a]>>16);return 65535&e[a]}function readBlockLength(e,t,n){if(n.bitOffset>=16){n.accumulator32=n.shortBuffer[n.halfOffset++]<<16|n.accumulator32>>>16;n.bitOffset-=16}const a=readSymbol(e,t,n),s=i[a];if(n.bitOffset>=16){n.accumulator32=n.shortBuffer[n.halfOffset++]<<16|n.accumulator32>>>16;n.bitOffset-=16}return r[a]+(s<=16?readFewBits(n,s):readManyBits(n,s))}function moveToFront(e,t){let n=t;const a=e[n];for(;n>0;){e[n]=e[n-1];n--}e[0]=a}function readSimpleHuffmanCode(e,t,n,a,s){const r=new Int32Array(t),i=new Int32Array(4),o=1+log2floor(e-1),l=readFewBits(s,2)+1;for(let e=0;e<l;++e){if(s.bitOffset>=16){s.accumulator32=s.shortBuffer[s.halfOffset++]<<16|s.accumulator32>>>16;s.bitOffset-=16}const n=readFewBits(s,o);if(n>=t)return makeError(s,-15);i[e]=n}const f=function checkDupes(e,t,n){for(let a=0;a<n-1;++a)for(let s=a+1;s<n;++s)if(t[a]===t[s])return makeError(e,-7);return 0}(s,i,l);if(f<0)return f;let c=l;4===l&&(c+=readFewBits(s,1));switch(c){case 1:r[i[0]]=1;break;case 2:r[i[0]]=1;r[i[1]]=1;break;case 3:r[i[0]]=1;r[i[1]]=2;r[i[2]]=2;break;case 4:r[i[0]]=2;r[i[1]]=2;r[i[2]]=2;r[i[3]]=2;break;case 5:r[i[0]]=1;r[i[1]]=2;r[i[2]]=3;r[i[3]]=3}return buildHuffmanTable(n,a,8,r,t)}function readComplexHuffmanCode(e,n,a,r,i){const o=new Int32Array(e),l=new Int32Array(18);let f=32,c=0;for(let e=n;e<18;++e){const n=t[e];if(i.bitOffset>=16){i.accumulator32=i.shortBuffer[i.halfOffset++]<<16|i.accumulator32>>>16;i.bitOffset-=16}const a=i.accumulator32>>>i.bitOffset&15;i.bitOffset+=s[a]>>16;const r=65535&s[a];l[n]=r;if(0!==r){f-=32>>r;c++;if(f<=0)break}}if(0!==f&&1!==c)return makeError(i,-4);const h=function readHuffmanCodeLengths(e,t,n,a){let s=0,r=8,i=0,o=0,l=32768;const f=new Int32Array(33);buildHuffmanTable(f,f.length-1,5,e,18);for(;s<t&&l>0;){if(a.halfOffset>2030){const e=readMoreInput(a);if(e<0)return e}if(a.bitOffset>=16){a.accumulator32=a.shortBuffer[a.halfOffset++]<<16|a.accumulator32>>>16;a.bitOffset-=16}const e=a.accumulator32>>>a.bitOffset&31;a.bitOffset+=f[e]>>16;const c=65535&f[e];if(c<16){i=0;n[s++]=c;if(0!==c){r=c;l-=32768>>c}}else{const e=c-14;let f=0;16===c&&(f=r);if(o!==f){i=0;o=f}const h=i;if(i>0){i-=2;i<<=e}if(a.bitOffset>=16){a.accumulator32=a.shortBuffer[a.halfOffset++]<<16|a.accumulator32>>>16;a.bitOffset-=16}i+=readFewBits(a,e)+3;const u=i-h;if(s+u>t)return makeError(a,-2);for(let e=0;e<u;++e)n[s++]=o;0!==o&&(l-=u<<15-o)}}if(0!==l)return makeError(a,-18);n.fill(0,s,t);return 0}(l,e,o,i);return h<0?h:buildHuffmanTable(a,r,8,o,e)}function readHuffmanCode(e,t,n,a,s){if(s.halfOffset>2030){const e=readMoreInput(s);if(e<0)return e}if(s.bitOffset>=16){s.accumulator32=s.shortBuffer[s.halfOffset++]<<16|s.accumulator32>>>16;s.bitOffset-=16}const r=readFewBits(s,2);return 1===r?readSimpleHuffmanCode(e,t,n,a,s):readComplexHuffmanCode(t,r,n,a,s)}function decodeContextMap(t,n,a){let s;if(a.halfOffset>2030){s=readMoreInput(a);if(s<0)return s}const r=decodeVarLenUnsignedByte(a)+1;if(1===r){n.fill(0,0,t);return r}if(a.bitOffset>=16){a.accumulator32=a.shortBuffer[a.halfOffset++]<<16|a.accumulator32>>>16;a.bitOffset-=16}let i=0;0!==readFewBits(a,1)&&(i=readFewBits(a,4)+1);const o=r+i,l=e[o+31>>5],f=new Int32Array(l+1),c=f.length-1;s=readHuffmanCode(o,o,f,c,a);if(s<0)return s;let h=0;for(;h<t;){if(a.halfOffset>2030){s=readMoreInput(a);if(s<0)return s}if(a.bitOffset>=16){a.accumulator32=a.shortBuffer[a.halfOffset++]<<16|a.accumulator32>>>16;a.bitOffset-=16}const e=readSymbol(f,c,a);if(0===e){n[h]=0;h++}else if(e<=i){if(a.bitOffset>=16){a.accumulator32=a.shortBuffer[a.halfOffset++]<<16|a.accumulator32>>>16;a.bitOffset-=16}let s=(1<<e)+readFewBits(a,e);for(;0!==s;){if(h>=t)return makeError(a,-3);n[h]=0;h++;s--}}else{n[h]=e-i;h++}}if(a.bitOffset>=16){a.accumulator32=a.shortBuffer[a.halfOffset++]<<16|a.accumulator32>>>16;a.bitOffset-=16}1===readFewBits(a,1)&&function inverseMoveToFrontTransform(e,t){const n=new Int32Array(256);for(let e=0;e<256;++e)n[e]=e;for(let a=0;a<t;++a){const t=255&e[a];e[a]=n[t];0!==t&&moveToFront(n,t)}}(n,t);return r}function decodeBlockTypeAndLength(e,t,n){const a=e.rings,s=4+2*t;if(e.bitOffset>=16){e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16}let r=readSymbol(e.blockTrees,2*t,e);const i=readBlockLength(e.blockTrees,2*t+1,e);1===r?r=a[s+1]+1:0===r?r=a[s]:r-=2;r>=n&&(r-=n);a[s]=a[s+1];a[s+1]=r;return i}function decodeLiteralBlockSwitch(e){e.literalBlockLength=decodeBlockTypeAndLength(e,0,e.numLiteralBlockTypes);const t=e.rings[5];e.contextMapSlice=t<<6;e.literalTreeIdx=255&e.contextMap[e.contextMapSlice];const n=e.contextModes[t];e.contextLookupOffset1=n<<9;e.contextLookupOffset2=e.contextLookupOffset1+256}function decodeCommandBlockSwitch(e){e.commandBlockLength=decodeBlockTypeAndLength(e,1,e.numCommandBlockTypes);e.commandTreeIdx=e.rings[7]}function decodeDistanceBlockSwitch(e){e.distanceBlockLength=decodeBlockTypeAndLength(e,2,e.numDistanceBlockTypes);e.distContextMapSlice=e.rings[9]<<2}function readNextMetablockHeader(e){if(0!==e.inputEnd){e.nextRunningState=10;e.runningState=12;return 0}e.literalTreeGroup=new Int32Array(0);e.commandTreeGroup=new Int32Array(0);e.distanceTreeGroup=new Int32Array(0);let t;if(e.halfOffset>2030){t=readMoreInput(e);if(t<0)return t}t=function decodeMetaBlockLength(e){if(e.bitOffset>=16){e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16}e.inputEnd=readFewBits(e,1);e.metaBlockLength=0;e.isUncompressed=0;e.isMetadata=0;if(0!==e.inputEnd&&0!==readFewBits(e,1))return 0;const t=readFewBits(e,2)+4;if(7===t){e.isMetadata=1;if(0!==readFewBits(e,1))return makeError(e,-6);const t=readFewBits(e,2);if(0===t)return 0;for(let n=0;n<t;++n){if(e.bitOffset>=16){e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16}const a=readFewBits(e,8);if(0===a&&n+1===t&&t>1)return makeError(e,-8);e.metaBlockLength+=a<<8*n}}else for(let n=0;n<t;++n){if(e.bitOffset>=16){e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16}const a=readFewBits(e,4);if(0===a&&n+1===t&&t>4)return makeError(e,-8);e.metaBlockLength+=a<<4*n}e.metaBlockLength++;0===e.inputEnd&&(e.isUncompressed=readFewBits(e,1));return 0}(e);if(t<0)return t;if(0===e.metaBlockLength&&0===e.isMetadata)return 0;if(0!==e.isUncompressed||0!==e.isMetadata){t=jumpToByteBoundary(e);if(t<0)return t;0===e.isMetadata?e.runningState=6:e.runningState=5}else e.runningState=3;if(0!==e.isMetadata)return 0;e.expectedTotalSize+=e.metaBlockLength;e.expectedTotalSize>1<<30&&(e.expectedTotalSize=1<<30);e.ringBufferSize<e.maxRingBufferSize&&function maybeReallocateRingBuffer(e){let t=e.maxRingBufferSize;if(t>e.expectedTotalSize){const n=e.expectedTotalSize;for(;t>>1>n;)t>>=1;0===e.inputEnd&&t<16384&&e.maxRingBufferSize>=16384&&(t=16384)}if(t<=e.ringBufferSize)return;const n=new Int8Array(t+37),a=e.ringBuffer;0!==a.length&&n.set(a.subarray(0,e.ringBufferSize),0);e.ringBuffer=n;e.ringBufferSize=t}(e);return 0}function readMetablockPartition(e,t,n){let a=e.blockTrees[2*t];if(n<=1){e.blockTrees[2*t+1]=a;e.blockTrees[2*t+2]=a;return 1<<28}const s=n+2;let r=readHuffmanCode(s,s,e.blockTrees,2*t,e);if(r<0)return r;a+=r;e.blockTrees[2*t+1]=a;r=readHuffmanCode(26,26,e.blockTrees,2*t+1,e);if(r<0)return r;a+=r;e.blockTrees[2*t+2]=a;return readBlockLength(e.blockTrees,2*t+1,e)}function readMetablockHuffmanCodesAndContextMaps(e){e.numLiteralBlockTypes=decodeVarLenUnsignedByte(e)+1;let t=readMetablockPartition(e,0,e.numLiteralBlockTypes);if(t<0)return t;e.literalBlockLength=t;e.numCommandBlockTypes=decodeVarLenUnsignedByte(e)+1;t=readMetablockPartition(e,1,e.numCommandBlockTypes);if(t<0)return t;e.commandBlockLength=t;e.numDistanceBlockTypes=decodeVarLenUnsignedByte(e)+1;t=readMetablockPartition(e,2,e.numDistanceBlockTypes);if(t<0)return t;e.distanceBlockLength=t;if(e.halfOffset>2030){t=readMoreInput(e);if(t<0)return t}if(e.bitOffset>=16){e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16}e.distancePostfixBits=readFewBits(e,2);e.numDirectDistanceCodes=readFewBits(e,4)<<e.distancePostfixBits;e.contextModes=new Int8Array(e.numLiteralBlockTypes);let n=0;for(;n<e.numLiteralBlockTypes;){const a=Math.min(n+96,e.numLiteralBlockTypes);for(;n<a;){if(e.bitOffset>=16){e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16}e.contextModes[n]=readFewBits(e,2);n++}if(e.halfOffset>2030){t=readMoreInput(e);if(t<0)return t}}const a=e.numLiteralBlockTypes<<6;e.contextMap=new Int8Array(a);t=decodeContextMap(a,e.contextMap,e);if(t<0)return t;const s=t;e.trivialLiteralContext=1;for(let t=0;t<a;++t)if(e.contextMap[t]!==t>>6){e.trivialLiteralContext=0;break}e.distContextMap=new Int8Array(e.numDistanceBlockTypes<<2);t=decodeContextMap(e.numDistanceBlockTypes<<2,e.distContextMap,e);if(t<0)return t;const r=t;e.literalTreeGroup=new Int32Array(huffmanTreeGroupAllocSize(256,s));t=decodeHuffmanTreeGroup(256,256,s,e,e.literalTreeGroup);if(t<0)return t;e.commandTreeGroup=new Int32Array(huffmanTreeGroupAllocSize(704,e.numCommandBlockTypes));t=decodeHuffmanTreeGroup(704,704,e.numCommandBlockTypes,e,e.commandTreeGroup);if(t<0)return t;let i=calculateDistanceAlphabetSize(e.distancePostfixBits,e.numDirectDistanceCodes,24),o=i;if(1===e.isLargeWindow){i=calculateDistanceAlphabetSize(e.distancePostfixBits,e.numDirectDistanceCodes,62);t=calculateDistanceAlphabetLimit(e,2147483644,e.distancePostfixBits,e.numDirectDistanceCodes);if(t<0)return t;o=t}e.distanceTreeGroup=new Int32Array(huffmanTreeGroupAllocSize(o,r));t=decodeHuffmanTreeGroup(i,o,r,e,e.distanceTreeGroup);if(t<0)return t;!function calculateDistanceLut(e,t){const n=e.distExtraBits,a=e.distOffset,s=e.distancePostfixBits,r=e.numDirectDistanceCodes,i=1<<s;let o=1,l=0,f=16;for(let e=0;e<r;++e){n[f]=0;a[f]=e+1;++f}for(;f<t;){const e=r+((2+l<<o)-4<<s)+1;for(let t=0;t<i;++t){n[f]=o;a[f]=e+t;++f}o+=l;l^=1}}(e,o);e.contextMapSlice=0;e.distContextMapSlice=0;e.contextLookupOffset1=512*e.contextModes[0];e.contextLookupOffset2=e.contextLookupOffset1+256;e.literalTreeIdx=0;e.commandTreeIdx=0;e.rings[4]=1;e.rings[5]=0;e.rings[6]=1;e.rings[7]=0;e.rings[8]=1;e.rings[9]=0;return 0}function copyUncompressedData(e){const t=e.ringBuffer;let n;if(e.metaBlockLength<=0){n=reload(e);if(n<0)return n;e.runningState=2;return 0}const a=Math.min(e.ringBufferSize-e.pos,e.metaBlockLength);n=function copyRawBytes(e,t,n,a){let s=n,r=a;if(7&e.bitOffset)return makeError(e,-30);for(;32!==e.bitOffset&&0!==r;){t[s++]=e.accumulator32>>>e.bitOffset;e.bitOffset+=8;r--}if(0===r)return 0;const i=Math.min(halfAvailable(e),r>>1);if(i>0){const n=e.halfOffset<<1,a=i<<1;t.set(e.byteBuffer.subarray(n,n+a),s);s+=a;r-=a;e.halfOffset+=i}if(0===r)return 0;if(halfAvailable(e)>0){if(e.bitOffset>=16){e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16}for(;0!==r;){t[s++]=e.accumulator32>>>e.bitOffset;e.bitOffset+=8;r--}return checkHealth(e,0)}for(;r>0;){const n=readInput(e,t,s,r);if(n<-1)return n;if(n<=0)return makeError(e,-16);s+=n;r-=n}return 0}(e,t,e.pos,a);if(n<0)return n;e.metaBlockLength-=a;e.pos+=a;if(e.pos===e.ringBufferSize){e.nextRunningState=6;e.runningState=12;return 0}n=reload(e);if(n<0)return n;e.runningState=2;return 0}function writeRingBuffer(e){const t=Math.min(e.outputLength-e.outputUsed,e.ringBufferBytesReady-e.ringBufferBytesWritten);if(0!==t){e.output.set(e.ringBuffer.subarray(e.ringBufferBytesWritten,e.ringBufferBytesWritten+t),e.outputOffset+e.outputUsed);e.outputUsed+=t;e.ringBufferBytesWritten+=t}return e.outputUsed<e.outputLength?0:2}function huffmanTreeGroupAllocSize(t,n){return n+n*e[t+31>>5]}function decodeHuffmanTreeGroup(e,t,n,a,s){let r=n;for(let i=0;i<n;++i){s[i]=r;const n=readHuffmanCode(e,t,s,i,a);if(n<0)return n;r+=n}return 0}function calculateFence(e){let t=e.ringBufferSize;0!==e.isEager&&(t=Math.min(t,e.ringBufferBytesWritten+e.outputLength-e.outputUsed));return t}function doUseDictionary(e,t){if(e.distance>2147483644)return makeError(e,-9);const n=e.distance-e.maxDistance-1-e.cdTotalSize;if(n<0){const t=function initializeCompoundDictionaryCopy(e,t,n){-1===e.cdBlockBits&&function initializeCompoundDictionary(e){e.cdBlockMap=new Int8Array(256);let t=8;for(;e.cdTotalSize-1>>t;)t++;t-=8;e.cdBlockBits=t;let n=0,a=0;for(;n<e.cdTotalSize;){for(;e.cdChunkOffsets[a+1]<n;)a++;e.cdBlockMap[n>>t]=a;n+=1<<t}}(e);let a=e.cdBlockMap[t>>e.cdBlockBits];for(;t>=e.cdChunkOffsets[a+1];)a++;if(e.cdTotalSize>t+n)return makeError(e,-9);e.distRbIdx=e.distRbIdx+1&3;e.rings[e.distRbIdx]=e.distance;e.metaBlockLength-=n;e.cdBrIndex=a;e.cdBrOffset=t-e.cdChunkOffsets[a];e.cdBrLength=n;e.cdBrCopied=0;return 0}(e,-n-1,e.copyLength);if(t<0)return t;e.runningState=14}else{const a=u,s=e.copyLength;if(s>31)return makeError(e,-9);const r=p[s];if(0===r)return makeError(e,-9);let i=m[s];const o=n>>r;i+=(n&(1<<r)-1)*s;const l=c;if(o>=l.numTransforms)return makeError(e,-9);const f=function transformDictionaryWord(e,t,n,a,s,r,i){let o=t;const l=r.triplets,f=r.prefixSuffixStorage,c=r.prefixSuffixHeads,h=3*i,u=l[h],m=l[h+1],p=l[h+2];let d=c[u];const g=c[u+1];let b=c[p];const w=c[p+1];let j=m-11,k=m;(j<1||j>9)&&(j=0);(k<1||k>9)&&(k=0);for(;d!==g;)e[o++]=f[d++];let y=s;j>y&&(j=y);let q=a+j;y-=j;y-=k;let v=y;for(;v>0;){e[o++]=n[q++];v--}if(10===m||11===m){let t=o-y;10===m&&(y=1);for(;y>0;){const n=255&e[t];if(n<192){n>=97&&n<=122&&(e[t]=32^e[t]);t+=1;y-=1}else if(n<224){e[t+1]=32^e[t+1];t+=2;y-=2}else{e[t+2]=5^e[t+2];t+=3;y-=3}}}else if(21===m||22===m){let t=o-y;const n=r.params[i];let a=16777216-(32768&n)+(32767&n);for(;y>0;){let n=1;const s=255&e[t];if(s<128){a+=s;e[t]=127&a}else if(s<192);else if(s<224)if(y>=2){const r=e[t+1];a+=63&r|(31&s)<<6;e[t]=192|a>>6&31;e[t+1]=192&r|63&a;n=2}else n=y;else if(s<240)if(y>=3){const r=e[t+1],i=e[t+2];a+=63&i|(63&r)<<6|(15&s)<<12;e[t]=224|a>>12&15;e[t+1]=192&r|a>>6&63;e[t+2]=192&i|63&a;n=3}else n=y;else if(s<248)if(y>=4){const r=e[t+1],i=e[t+2],o=e[t+3];a+=63&o|(63&i)<<6|(63&r)<<12|(7&s)<<18;e[t]=240|a>>18&7;e[t+1]=192&r|a>>12&63;e[t+2]=192&i|a>>6&63;e[t+3]=192&o|63&a;n=4}else n=y;t+=n;y-=n;21===m&&(y=0)}}for(;b!==w;)e[o++]=f[b++];return o-t}(e.ringBuffer,e.pos,a,i,s,l,o);e.pos+=f;e.metaBlockLength-=f;if(e.pos>=t){e.nextRunningState=4;e.runningState=12;return 0}e.runningState=4}return 0}function copyFromCompoundDictionary(e,t){let n=e.pos;const a=n;for(;e.cdBrLength!==e.cdBrCopied;){const a=t-n,s=e.cdChunkOffsets[e.cdBrIndex+1]-e.cdChunkOffsets[e.cdBrIndex]-e.cdBrOffset;let r=e.cdBrLength-e.cdBrCopied;r>s&&(r=s);r>a&&(r=a);e.ringBuffer.set(e.cdChunks[e.cdBrIndex].subarray(e.cdBrOffset,e.cdBrOffset+r),n);n+=r;e.cdBrOffset+=r;e.cdBrCopied+=r;if(r===s){e.cdBrIndex++;e.cdBrOffset=0}if(n>=t)break}return n-a}function decompress(e){let t;if(0===e.runningState)return makeError(e,-25);if(e.runningState<0)return makeError(e,-28);if(11===e.runningState)return makeError(e,-22);if(1===e.runningState){const t=function decodeWindowBits(e){const t=e.isLargeWindow;e.isLargeWindow=0;if(e.bitOffset>=16){e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16}if(0===readFewBits(e,1))return 16;let n=readFewBits(e,3);if(0!==n)return 17+n;n=readFewBits(e,3);if(0!==n){if(1===n){if(0===t)return-1;e.isLargeWindow=1;if(1===readFewBits(e,1))return-1;n=readFewBits(e,6);return n<10||n>30?-1:n}return 8+n}return 17}(e);if(-1===t)return makeError(e,-11);e.maxRingBufferSize=1<<t;e.maxBackwardDistance=e.maxRingBufferSize-16;e.runningState=2}let s=calculateFence(e),r=e.ringBufferSize-1,i=e.ringBuffer;for(;10!==e.runningState;)switch(e.runningState){case 2:if(e.metaBlockLength<0)return makeError(e,-10);t=readNextMetablockHeader(e);if(t<0)return t;s=calculateFence(e);r=e.ringBufferSize-1;i=e.ringBuffer;continue;case 3:t=readMetablockHuffmanCodesAndContextMaps(e);if(t<0)return t;e.runningState=4;continue;case 4:if(e.metaBlockLength<=0){e.runningState=2;continue}if(e.halfOffset>2030){t=readMoreInput(e);if(t<0)return t}0===e.commandBlockLength&&decodeCommandBlockSwitch(e);e.commandBlockLength--;if(e.bitOffset>=16){e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16}const o=readSymbol(e.commandTreeGroup,e.commandTreeIdx,e)<<2,l=f[o],c=f[o+1],u=f[o+2];e.distanceCode=f[o+3];if(e.bitOffset>=16){e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16}const m=255&l;e.insertLength=c+(m<=16?readFewBits(e,m):readManyBits(e,m));if(e.bitOffset>=16){e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16}const p=l>>8;e.copyLength=u+(p<=16?readFewBits(e,p):readManyBits(e,p));e.j=0;e.runningState=7;continue;case 7:if(0!==e.trivialLiteralContext)for(;e.j<e.insertLength;){if(e.halfOffset>2030){t=readMoreInput(e);if(t<0)return t}0===e.literalBlockLength&&decodeLiteralBlockSwitch(e);e.literalBlockLength--;if(e.bitOffset>=16){e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16}i[e.pos]=readSymbol(e.literalTreeGroup,e.literalTreeIdx,e);e.pos++;e.j++;if(e.pos>=s){e.nextRunningState=7;e.runningState=12;break}}else{let n=255&i[e.pos-1&r],a=255&i[e.pos-2&r];for(;e.j<e.insertLength;){if(e.halfOffset>2030){t=readMoreInput(e);if(t<0)return t}0===e.literalBlockLength&&decodeLiteralBlockSwitch(e);const r=h[e.contextLookupOffset1+n]|h[e.contextLookupOffset2+a],o=255&e.contextMap[e.contextMapSlice+r];e.literalBlockLength--;a=n;if(e.bitOffset>=16){e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16}n=readSymbol(e.literalTreeGroup,o,e);i[e.pos]=n;e.pos++;e.j++;if(e.pos>=s){e.nextRunningState=7;e.runningState=12;break}}}if(7!==e.runningState)continue;e.metaBlockLength-=e.insertLength;if(e.metaBlockLength<=0){e.runningState=4;continue}let d=e.distanceCode;if(d<0)e.distance=e.rings[e.distRbIdx];else{if(e.halfOffset>2030){t=readMoreInput(e);if(t<0)return t}0===e.distanceBlockLength&&decodeDistanceBlockSwitch(e);e.distanceBlockLength--;if(e.bitOffset>=16){e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16}const s=255&e.distContextMap[e.distContextMapSlice+d];d=readSymbol(e.distanceTreeGroup,s,e);if(d<16){const t=e.distRbIdx+n[d]&3;e.distance=e.rings[t]+a[d];if(e.distance<0)return makeError(e,-12)}else{const t=e.distExtraBits[d];let n;if(e.bitOffset+t<=32)n=readFewBits(e,t);else{if(e.bitOffset>=16){e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16}n=t<=16?readFewBits(e,t):readManyBits(e,t)}e.distance=e.distOffset[d]+(n<<e.distancePostfixBits)}}e.maxDistance!==e.maxBackwardDistance&&e.pos<e.maxBackwardDistance?e.maxDistance=e.pos:e.maxDistance=e.maxBackwardDistance;if(e.distance>e.maxDistance){e.runningState=9;continue}if(d>0){e.distRbIdx=e.distRbIdx+1&3;e.rings[e.distRbIdx]=e.distance}if(e.copyLength>e.metaBlockLength)return makeError(e,-9);e.j=0;e.runningState=8;continue;case 8:let g=e.pos-e.distance&r,b=e.pos;const w=e.copyLength-e.j,j=g+w,k=b+w;if(j<r&&k<r){if(w<12||j>b&&k>g){const e=w+3>>2;for(let t=0;t<e;++t){i[b++]=i[g++];i[b++]=i[g++];i[b++]=i[g++];i[b++]=i[g++]}}else i.copyWithin(b,g,j);e.j+=w;e.metaBlockLength-=w;e.pos+=w}else for(;e.j<e.copyLength;){i[e.pos]=i[e.pos-e.distance&r];e.metaBlockLength--;e.pos++;e.j++;if(e.pos>=s){e.nextRunningState=8;e.runningState=12;break}}8===e.runningState&&(e.runningState=4);continue;case 9:t=doUseDictionary(e,s);if(t<0)return t;continue;case 14:e.pos+=copyFromCompoundDictionary(e,s);if(e.pos>=s){e.nextRunningState=14;e.runningState=12;return 2}e.runningState=4;continue;case 5:for(;e.metaBlockLength>0;){if(e.halfOffset>2030){t=readMoreInput(e);if(t<0)return t}if(e.bitOffset>=16){e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16}readFewBits(e,8);e.metaBlockLength--}e.runningState=2;continue;case 6:t=copyUncompressedData(e);if(t<0)return t;continue;case 12:e.ringBufferBytesReady=Math.min(e.pos,e.ringBufferSize);e.runningState=13;continue;case 13:t=writeRingBuffer(e);if(0!==t)return t;e.pos>=e.maxBackwardDistance&&(e.maxDistance=e.maxBackwardDistance);if(e.pos>=e.ringBufferSize){e.pos>e.ringBufferSize&&i.copyWithin(0,e.ringBufferSize,e.pos);e.pos=e.pos&r;e.ringBufferBytesWritten=0}e.runningState=e.nextRunningState;continue;default:return makeError(e,-28)}if(10!==e.runningState)return makeError(e,-29);if(e.metaBlockLength<0)return makeError(e,-10);t=jumpToByteBoundary(e);if(0!==t)return t;t=checkHealth(e,1);return 0!==t?t:1}const c=new function Transforms(e,t,n){this.numTransforms=0;this.triplets=new Int32Array(0);this.prefixSuffixStorage=new Int8Array(0);this.prefixSuffixHeads=new Int32Array(0);this.params=new Int16Array(0);this.numTransforms=e;this.triplets=new Int32Array(3*e);this.params=new Int16Array(e);this.prefixSuffixStorage=new Int8Array(t);this.prefixSuffixHeads=new Int32Array(n+1)}(121,167,50);!function unpackTransforms(e,t,n,a,s){const r=toUtf8Runes(a),i=r.length;let o=1,l=0;for(let n=0;n<i;++n){const a=r[n];35===a?t[o++]=l:e[l++]=a}for(let e=0;e<363;++e)n[e]=s.charCodeAt(e)-32}(c.prefixSuffixStorage,c.prefixSuffixHeads,c.triplets,'# #s #, #e #.# the #.com/# # of # and # in # to #"#">#\n#]# for # a # that #. # with #\'# from # by #. The # on # as # is #ing #\n\t#:#ed #(# at #ly #="# of the #. This #,# not #er #al #=\'#ful #ive #less #est #ize #ous #'," !! ! , *! &! \" ! ) * * - ! # ! #!*! + ,$ ! - % . / # 0 1 . \" 2 3!* 4% ! # / 5 6 7 8 0 1 & $ 9 + : ; < ' != > ?! 4 @ 4 2 & A *# ( B C& ) % ) !*# *-% A +! *. D! %' & E *6 F G% ! *A *% H! D I!+! J!+ K +- *4! A L!*4 M N +6 O!*% +.! K *G P +%( ! G *D +D Q +# *K!*G!+D!+# +G +A +4!+% +K!+4!*D!+K!*K");function getNextKey(e,t){let n=1<<t-1;for(;0!==(e&n);)n>>=1;return(e&n-1)+n}function replicateValue(e,t,n,a,s){let r=a;for(;r>0;){r-=n;e[t+r]=s}}function nextTableBitSize(e,t,n){let a=t,s=1<<a-n;for(;a<15;){s-=e[a];if(s<=0)break;a++;s<<=1}return a-n}function buildHuffmanTable(e,t,n,a,s){const r=e[t],i=new Int32Array(s),o=new Int32Array(16),l=new Int32Array(16);for(let e=0;e<s;++e)o[a[e]]++;l[1]=0;for(let e=1;e<15;++e)l[e+1]=l[e]+o[e];for(let e=0;e<s;++e)0!==a[e]&&(i[l[a[e]]++]=e);let f=n,c=1<<f,h=c;if(1===l[15]){for(let t=0;t<h;++t)e[r+t]=i[0];return h}let u=0,m=0,p=1;for(let t=1;t<=n;++t){p<<=1;for(;o[t]>0;){replicateValue(e,r+u,p,c,t<<16|i[m++]);u=getNextKey(u,t);o[t]--}}const d=h-1;let g=-1,b=r;p=1;for(let t=n+1;t<=15;++t){p<<=1;for(;o[t]>0;){if((u&d)!==g){b+=c;f=nextTableBitSize(o,t,n);c=1<<f;h+=c;g=u&d;e[r+g]=f+n<<16|b-r-g}replicateValue(e,b+(u>>n),p,c,t-n<<16|i[m++]);u=getNextKey(u,t);o[t]--}}return h}function readMoreInput(e){if(0!==e.endOfStreamReached)return halfAvailable(e)>=-2?0:makeError(e,-16);const t=e.halfOffset<<1;let n=4096-t;e.byteBuffer.copyWithin(0,t,4096);e.halfOffset=0;for(;n<4096;){const t=4096-n,a=readInput(e,e.byteBuffer,n,t);if(a<-1)return a;if(a<=0){e.endOfStreamReached=1;e.tailBytes=n;n+=1;break}n+=a}!function bytesToNibbles(e,t){const n=e.byteBuffer,a=t>>1,s=e.shortBuffer;for(let e=0;e<a;++e)s[e]=255&n[2*e]|(255&n[2*e+1])<<8}(e,n);return 0}function checkHealth(e,t){if(0===e.endOfStreamReached)return 0;const n=(e.halfOffset<<1)+(e.bitOffset+7>>3)-4;return n>e.tailBytes?makeError(e,-13):0!==t&&n!==e.tailBytes?makeError(e,-17):0}function readFewBits(e,t){const n=e.accumulator32>>>e.bitOffset&(1<<t)-1;e.bitOffset+=t;return n}function readManyBits(e,t){const n=readFewBits(e,16);e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16;return n|readFewBits(e,t-16)<<16}function prepare(e){if(e.halfOffset>2030){const t=readMoreInput(e);if(0!==t)return t}let t=checkHealth(e,0);if(0!==t)return t;e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16;e.accumulator32=e.shortBuffer[e.halfOffset++]<<16|e.accumulator32>>>16;e.bitOffset-=16;return 0}function reload(e){return 32===e.bitOffset?prepare(e):0}function jumpToByteBoundary(e){const t=32-e.bitOffset&7;if(0!==t){if(0!==readFewBits(e,t))return makeError(e,-5)}return 0}function halfAvailable(e){let t=2048;0!==e.endOfStreamReached&&(t=e.tailBytes+1>>1);return t-e.halfOffset}const h=new Int32Array(2048);!function unpackLookupTable(e,t,n){for(let t=0;t<256;++t){e[t]=63&t;e[512+t]=t>>2;e[1792+t]=2+(t>>6)}for(let n=0;n<128;++n)e[1024+n]=4*(t.charCodeAt(n)-32);for(let t=0;t<64;++t){e[1152+t]=1&t;e[1216+t]=2+(1&t)}let a=1280;for(let t=0;t<19;++t){const s=3&t,r=n.charCodeAt(t)-32;for(let t=0;t<r;++t)e[a++]=s}for(let t=0;t<16;++t){e[1792+t]=1;e[2032+t]=6}e[1792]=0;e[2047]=7;for(let t=0;t<256;++t)e[1536+t]=e[1792+t]<<3}(h," !! ! \"#$##%#$&'##(#)#++++++++++((&*'##,---,---,-----,-----,-----&#'###.///.///./////./////./////&#'# ","A/* ': & : $  @");function State(){this.ringBuffer=new Int8Array(0);this.contextModes=new Int8Array(0);this.contextMap=new Int8Array(0);this.distContextMap=new Int8Array(0);this.distExtraBits=new Int8Array(0);this.output=new Int8Array(0);this.byteBuffer=new Int8Array(0);this.shortBuffer=new Int16Array(0);this.intBuffer=new Int32Array(0);this.rings=new Int32Array(0);this.blockTrees=new Int32Array(0);this.literalTreeGroup=new Int32Array(0);this.commandTreeGroup=new Int32Array(0);this.distanceTreeGroup=new Int32Array(0);this.distOffset=new Int32Array(0);this.accumulator64=0;this.runningState=0;this.nextRunningState=0;this.accumulator32=0;this.bitOffset=0;this.halfOffset=0;this.tailBytes=0;this.endOfStreamReached=0;this.metaBlockLength=0;this.inputEnd=0;this.isUncompressed=0;this.isMetadata=0;this.literalBlockLength=0;this.numLiteralBlockTypes=0;this.commandBlockLength=0;this.numCommandBlockTypes=0;this.distanceBlockLength=0;this.numDistanceBlockTypes=0;this.pos=0;this.maxDistance=0;this.distRbIdx=0;this.trivialLiteralContext=0;this.literalTreeIdx=0;this.commandTreeIdx=0;this.j=0;this.insertLength=0;this.contextMapSlice=0;this.distContextMapSlice=0;this.contextLookupOffset1=0;this.contextLookupOffset2=0;this.distanceCode=0;this.numDirectDistanceCodes=0;this.distancePostfixBits=0;this.distance=0;this.copyLength=0;this.maxBackwardDistance=0;this.maxRingBufferSize=0;this.ringBufferSize=0;this.expectedTotalSize=0;this.outputOffset=0;this.outputLength=0;this.outputUsed=0;this.ringBufferBytesWritten=0;this.ringBufferBytesReady=0;this.isEager=0;this.isLargeWindow=0;this.cdNumChunks=0;this.cdTotalSize=0;this.cdBrIndex=0;this.cdBrOffset=0;this.cdBrLength=0;this.cdBrCopied=0;this.cdChunks=new Array(0);this.cdChunkOffsets=new Int32Array(0);this.cdBlockBits=0;this.cdBlockMap=new Int8Array(0);this.input=new InputStream(new Int8Array(0));this.ringBuffer=new Int8Array(0);this.rings=new Int32Array(10);this.rings[0]=16;this.rings[1]=15;this.rings[2]=11;this.rings[3]=4}let u=new Int8Array(0);const m=new Int32Array(32),p=new Int32Array(32);const d=new Int8Array(122784),g=new Int32Array(25);!function unpackDictionaryData(e,t,n,a,s,r){const i=function toUsAsciiBytes(e){const t=e.length,n=new Int8Array(t);for(let a=0;a<t;++a)n[a]=e.charCodeAt(a);return n}(t+n),o=toUtf8Runes(a);let l=0;const f=o.length>>1;for(let e=0;e<f;++e){const t=o[2*e]-36,n=o[2*e+1]-36;for(let e=0;e<t;++e){i[l]=3^i[l];l++}for(let e=0;e<n;++e){i[l]=236^i[l];l++}}for(let e=0;e<r.length;++e)s[e]=r.charCodeAt(e)-65;e.set(i)}(d,'wjnfgltmojefofewab`h`lgfgbwbpkltlmozpjwf`jwzlsfmivpwojhfeqfftlqhwf{wzfbqlufqalgzolufelqnallhsobzojufojmfkfosklnfpjgfnlqftlqgolmdwkfnujftejmgsbdfgbzpevookfbgwfqnfb`kbqfbeqlnwqvfnbqhbaofvslmkjdkgbwfobmgmftpfufmmf{w`bpfalwkslpwvpfgnbgfkbmgkfqftkbwmbnfOjmhaoldpjyfabpfkfognbhfnbjmvpfq$*#(klogfmgptjwkMftpqfbgtfqfpjdmwbhfkbufdbnfpffm`boosbwktfoosovpnfmvejonsbqwiljmwkjpojpwdllgmffgtbzptfpwilapnjmgboploldlqj`kvpfpobpwwfbnbqnzellghjmdtjoofbpwtbqgafpwejqfSbdfhmltbtbz-smdnlufwkbmolbgdjufpfoemlwfnv`keffgnbmzql`hj`lmlm`follhkjgfgjfgKlnfqvofklpwbib{jmel`ovaobtpofppkboeplnfpv`kylmf233&lmfp`bqfWjnfqb`faovfelvqtffheb`fklsfdbufkbqgolpwtkfmsbqhhfswsbpppkjsqllnKWNOsobmWzsfglmfpbufhffseobdojmhplogejufwllhqbwfwltmivnswkvpgbqh`bqgejofefbqpwbzhjoowkbweboobvwlfufq-`lnwbohpklsulwfgffsnlgfqfpwwvqmalqmabmgefooqlpfvqo+phjmqlof`lnfb`wpbdfpnffwdlog-isdjwfnubqzefowwkfmpfmggqlsUjft`lsz2-3!?,b=pwlsfopfojfpwlvqsb`h-djesbpw`pp<dqbznfbm%dw8qjgfpklwobwfpbjgqlbgubq#effoilkmqj`hslqwebpw$VB.gfbg?,a=sllqajoowzsfV-P-tllgnvpw1s{8JmelqbmhtjgftbmwtbooofbgX3^8sbvotbufpvqf\'+$ tbjwnbppbqnpdlfpdbjmobmdsbjg"..#ol`hvmjwqllwtbohejqntjef{no!plmdwfpw13s{hjmgqltpwlloelmwnbjopbefpwbqnbsp`lqfqbjmeoltabazpsbmpbzp7s{85s{8bqwpellwqfbotjhjkfbwpwfswqjslqd,obhftfbhwlogElqn`bpwebmpabmhufqzqvmpivozwbph2s{8dlbodqftpoltfgdfjg>!pfwp6s{8-ip<73s{je#+pllmpfbwmlmfwvafyfqlpfmwqffgeb`wjmwldjewkbqn2;s{`bnfkjooalogyllnuljgfbpzqjmdejoosfbhjmjw`lpw0s{8ib`hwbdpajwpqloofgjwhmftmfbq?"..dqltIPLMgvwzMbnfpbofzlv#olwpsbjmibyy`logfzfpejpkttt-qjphwbapsqfu23s{qjpf16s{Aovfgjmd033/abooelqgfbqmtjogal{-ebjqob`hufqpsbjqivmfwf`kje+"sj`hfujo\'+! tbqnolqgglfpsvoo/333jgfbgqbtkvdfpslwevmgavqmkqfe`foohfzpwj`hklvqolppevfo21s{pvjwgfboQPP!bdfgdqfzDFW!fbpfbjnpdjqobjgp;s{8mbuzdqjgwjsp :::tbqpobgz`bqp*8#~sks<kfoowbootklnyk9\t),\t#233kboo-\t\tB4s{8svpk`kbw3s{8`qft),?,kbpk46s{eobwqbqf#%%#wfoo`bnslmwlobjgnjppphjswfmwejmfnbofdfwpsolw733/\t\t`lloeffw-sks?aq=fqj`nlpwdvjgafoogfp`kbjqnbwkbwln,jnd% ;1ov`h`fmw3338wjmzdlmfkwnopfoogqvdEQFFmlgfmj`h<jg>olpfmvooubpwtjmgQPP#tfbqqfozaffmpbnfgvhfmbpb`bsftjpkdvoeW109kjwppolwdbwfhj`haovqwkfz26s{$$*8*8!=npjftjmpajqgplqwafwbpffhW2;9lqgpwqffnboo53s{ebqnlupalzpX3^-$*8!SLPWafbqhjgp*8~~nbqzwfmg+VH*rvbgyk9\n.pjy....sqls$*8ojewW2:9uj`fbmgzgfaw=QPPsllomf`haoltW259gllqfuboW249ofwpebjolqbosloomlub`lopdfmf#lxplewqlnfwjooqlpp?k0=slvqebgfsjmh?wq=njmj*"+njmfyk9abqpkfbq33*8njoh#..=jqlmeqfggjphtfmwpljosvwp,ip,klozW119JPAMW139bgbnpffp?k1=iplm$/#$`lmwW129#QPPollsbpjbnllm?,s=plvoOJMFelqw`bqwW279?k2=;3s{"..?:s{8W379njhf975Ymj`fjm`kZlqhqj`fyk9\b$**8svqfnbdfsbqbwlmfalmg904Y\\le\\$^*8333/yk9\vwbmhzbqgaltoavpk965YIbub03s{\t~\t&@0&907YifeeF[SJ`bpkujpbdloepmltyk9rvfq-`pppj`hnfbwnjm-ajmggfookjqfsj`pqfmw905YKWWS.132elwltloeFMG#{al{967YALGZgj`h8\t~\tf{jw906Yubqpafbw$~*8gjfw:::8bmmf~~?,Xj^-Obmdhn.^tjqfwlzpbggppfbobof{8\t\n~f`klmjmf-lqd336*wlmziftppbmgofdpqlle333*#133tjmfdfbqgldpallwdbqz`vwpwzofwfnswjlm-{no`l`hdbmd\'+$-63s{Sk-Gnjp`bobmolbmgfphnjofqzbmvmj{gjp`*8~\tgvpw`ojs*-\t\t43s{.133GUGp4^=?wbsfgfnlj((*tbdffvqlskjolswpklofEBRpbpjm.15WobapsfwpVQO#avoh`llh8~\tKFBGX3^*baaqivbm+2:;ofpkwtjm?,j=plmzdvzpev`hsjsf.\t"331*mgltX2^8X^8\tOld#pbow\t\n\nabmdwqjnabwk*x\t33s{\t~*8hl9\0effpbg=p9,,#X^8wloosovd+*x\tx\t#-ip$133sgvboalbw-ISD*8\t~rvlw*8\t\t$*8\t\t~1327132613251324132;132:13131312131113101317131613151314131;131:130313021301130013071306130513041320132113221323133:133;133413351336133713301331133213332:::2::;2::42::52::62::72::02::12::22::32:;:2:;;2:;42:;52:;62:;72:;02:;12:;22:;32:4:2:4;2:442:452:462:472:402:412:422:432:5:2:5;2:542:552:562:572:502:512:522:532:6:2:6;2:642:652:662:672:602:612:622:632333231720:73333::::`lnln/Mpfpwffpwbsfqlwlglkb`f`bgbb/]lajfmg/Abbp/Aujgb`bpllwqlelqlplollwqb`vbogjilpjgldqbmwjslwfnbgfafbodlrv/Efpwlmbgbwqfpsl`l`bpbabilwlgbpjmlbdvbsvfpvmlpbmwfgj`fovjpfoobnbzlylmbbnlqsjpllaqb`oj`foolgjlpklqb`bpj<[<\\<Q<\\<R<P=l<\\=l=o=n<\\<Q<Y<S<R<R=n<T<[<Q<R<X<R=n<R<Z<Y<R<Q<T=i<q<\\<Y<Y<]=g<P=g<~=g=m<R<^=g<^<R<q<R<R<]<s<R<W<T<Q<T<L<H<q<Y<p=g=n=g<r<Q<T<P<X<\\<{<\\<x<\\<q=o<r<]=n<Y<t<[<Y<U<Q=o<P<P<N=g=o<Z5m5f4O5j5i4K5i4U5o5h4O5d4]4C5f4K5m5e5k5d5h5i5h5o4K5d5h5k4D4_4K5h4I5j5k5f4O5f5n4C5k5h4G5i4D5k5h5d5h5f4D5h4K5f4D5o4X5f4K5i4O5i5j4F4D5f5h5j4A4D5k5i5i4X5d4Xejqpwujgflojdkwtlqognfgjbtkjwf`olpfaob`hqjdkwpnbooallhpsob`fnvpj`ejfoglqgfqsljmwubovfofufowbaofalbqgklvpfdqlvstlqhpzfbqppwbwfwlgbztbwfqpwbqwpwzofgfbwksltfqsklmfmjdkwfqqlqjmsvwbalvwwfqnpwjwofwllopfufmwol`bowjnfpobqdftlqgpdbnfppklqwpsb`fel`vp`ofbqnlgfoaol`hdvjgfqbgjlpkbqftlnfmbdbjmnlmfzjnbdfmbnfpzlvmdojmfpobwfq`lolqdqffmeqlmw%bns8tbw`kelq`fsqj`fqvofpafdjmbewfqujpjwjppvfbqfbpafoltjmgf{wlwboklvqpobafosqjmwsqfppavjowojmhppsffgpwvgzwqbgfelvmgpfmpfvmgfqpkltmelqnpqbmdfbggfgpwjoonlufgwbhfmbalufeobpkej{fglewfmlwkfqujftp`kf`hofdboqjufqjwfnprvj`hpkbsfkvnbmf{jpwdljmdnlujfwkjqgabpj`sfb`fpwbdftjgwkoldjmjgfbptqlwfsbdfpvpfqpgqjufpwlqfaqfbhplvwkulj`fpjwfpnlmwktkfqfavjogtkj`kfbqwkelqvnwkqffpslqwsbqwz@oj`holtfqojufp`obppobzfqfmwqzpwlqzvpbdfplvmg`lvqwzlvq#ajqwkslsvswzsfpbssozJnbdfafjmdvssfqmlwfpfufqzpkltpnfbmpf{wqbnbw`kwqb`hhmltmfbqozafdbmpvsfqsbsfqmlqwkofbqmdjufmmbnfgfmgfgWfqnpsbqwpDqlvsaqbmgvpjmdtlnbmebopfqfbgzbvgjlwbhfptkjof-`ln,ojufg`bpfpgbjoz`kjogdqfbwivgdfwklpfvmjwpmfufqaqlbg`lbpw`lufqbssofejofp`z`ofp`fmfsobmp`oj`htqjwfrvffmsjf`ffnbjoeqbnflogfqsklwlojnjw`b`kf`jujop`boffmwfqwkfnfwkfqfwlv`kalvmgqlzbobphfgtklofpjm`fpwl`h#mbnfebjwkkfbqwfnswzleefqp`lsfltmfgnjdkwboavnwkjmhaollgbqqbznbilqwqvpw`bmlmvmjlm`lvmwubojgpwlmfPwzofOldjmkbsszl``vqofew9eqfpkrvjwfejonpdqbgfmffgpvqabmejdkwabpjpklufqbvwl8qlvwf-kwnonj{fgejmboZlvq#pojgfwlsj`aqltmbolmfgqbtmpsojwqfb`kQjdkwgbwfpnbq`krvlwfdllgpOjmhpglvawbpzm`wkvnaboolt`kjfezlvwkmlufo23s{8pfqufvmwjokbmgp@kf`hPsb`frvfqzibnfpfrvbowtj`f3/333Pwbqwsbmfoplmdpqlvmgfjdkwpkjewtlqwkslpwpofbgptffhpbuljgwkfpfnjofpsobmfpnbqwboskbsobmwnbqhpqbwfpsobzp`objnpbofpwf{wppwbqptqlmd?,k0=wkjmd-lqd,nvowjkfbqgSltfqpwbmgwlhfmplojg+wkjpaqjmdpkjsppwbeewqjfg`boopevoozeb`wpbdfmwWkjp#,,..=bgnjmfdzswFufmw26s{8Fnbjowqvf!`qlpppsfmwaoldpal{!=mlwfgofbuf`kjmbpjyfpdvfpw?,k7=qlalwkfbuzwqvf/pfufmdqbmg`qjnfpjdmpbtbqfgbm`fskbpf=?"..fm\\VP% 0:8133s{\\mbnfobwjmfmilzbib{-bwjlmpnjwkV-P-#klogpsfwfqjmgjbmbu!=`kbjmp`lqf`lnfpgljmdsqjlqPkbqf2::3pqlnbmojpwpibsbmeboopwqjboltmfqbdqff?,k1=bavpfbofqwlsfqb!.,,T`bqgpkjoopwfbnpSklwlwqvwk`ofbm-sks<pbjmwnfwboolvjpnfbmwsqlleaqjfeqlt!=dfmqfwqv`hollhpUbovfEqbnf-mfw,..=\t?wqz#x\tubq#nbhfp`lpwpsobjmbgvowrvfpwwqbjmobalqkfosp`bvpfnbdj`nlwlqwkfjq163s{ofbpwpwfsp@lvmw`lvogdobpppjgfpevmgpklwfobtbqgnlvwknlufpsbqjpdjufpgvw`kwf{bpeqvjwmvoo/X^8wls!=\t?"..SLPW!l`fbm?aq,=eollqpsfbhgfswk#pjyfabmhp`bw`k`kbqw13s{8bojdmgfboptlvog63s{8vqo>!sbqhpnlvpfNlpw#---?,bnlmdaqbjmalgz#mlmf8abpfg`bqqzgqbewqfefqsbdf\\klnf-nfwfqgfobzgqfbnsqlufiljmw?,wq=gqvdp?"..#bsqjojgfboboofmf{b`welqwk`lgfpoldj`Ujft#pffnpaobmhslqwp#+133pbufg\\ojmhdlbopdqbmwdqffhklnfpqjmdpqbwfg03s{8tklpfsbqpf+*8!#Aol`hojmv{ilmfpsj{fo$*8!=*8je+.ofewgbujgklqpfEl`vpqbjpfal{fpWqb`hfnfmw?,fn=abq!=-pq`>wltfqbow>!`baofkfmqz17s{8pfwvsjwbozpkbqsnjmlqwbpwftbmwpwkjp-qfpfwtkffodjqop,`pp,233&8`ovappwveeajaofulwfp#2333hlqfb~*8\tabmgprvfvf>#x~8;3s{8`hjmdx\t\n\nbkfbg`ol`hjqjpkojhf#qbwjlpwbwpElqn!zbkll*X3^8Balvwejmgp?,k2=gfavdwbphpVQO#>`foop~*+*821s{8sqjnfwfoopwvqmp3{533-isd!psbjmafb`kwb{fpnj`qlbmdfo..=?,djewppwfuf.ojmhalgz-~*8\t\nnlvmw#+2::EBR?,qldfqeqbmh@obpp1;s{8effgp?k2=?p`lwwwfpwp11s{8gqjmh*##oftjppkboo 30:8#elq#olufgtbpwf33s{8ib9npjnlm?elmwqfsoznffwpvmwfq`kfbswjdkwAqbmg*#">#gqfpp`ojspqllnplmhfznlajonbjm-Mbnf#sobwfevmmzwqffp`ln,!2-isdtnlgfsbqbnPWBQWofew#jggfm/#132*8\t~\telqn-ujqvp`kbjqwqbmptlqpwSbdfpjwjlmsbw`k?"..\tl.`b`ejqnpwlvqp/333#bpjbmj((*xbglaf$*X3^jg>23alwk8nfmv#-1-nj-smd!hfujm`lb`k@kjogaqv`f1-isdVQO*(-isdpvjwfpoj`fkbqqz213!#ptffwwq=\tmbnf>gjfdlsbdf#ptjpp..=\t\t eee8!=Old-`ln!wqfbwpkffw*#%%#27s{8poffsmwfmwejofgib9ojg>!`Mbnf!tlqpfpklwp.al{.gfowb\t%ow8afbqp97;Y?gbwb.qvqbo?,b=#psfmgabhfqpklsp>#!!8sks!=`wjlm20s{8aqjbmkfoolpjyf>l>&1E#iljmnbzaf?jnd#jnd!=/#eipjnd!#!*X3^NWlsAWzsf!mftozGbmph`yf`kwqbjohmltp?,k6=ebr!=yk.`m23*8\t.2!*8wzsf>aovfpwqvozgbujp-ip$8=\t?"pwffo#zlv#k1=\telqn#ifpvp233&#nfmv-\t\n\ttbofpqjphpvnfmwggjmda.ojhwfb`kdje!#ufdbpgbmphffpwjpkrjspvlnjplaqfgfpgffmwqfwlglpsvfgfb/]lpfpw/Mwjfmfkbpwblwqlpsbqwfglmgfmvfulkb`fqelqnbnjpnlnfilqnvmglbrv/Ag/Abpp/_olbzvgbef`kbwlgbpwbmwlnfmlpgbwlplwqbppjwjlnv`klbklqbovdbqnbzlqfpwlpklqbpwfmfqbmwfpelwlpfpwbpsb/Apmvfubpbovgelqlpnfgjlrvjfmnfpfpslgfq`kjofpfq/Muf`fpgf`jqilp/Efpwbqufmwbdqvslkf`klfoolpwfmdlbnjdl`lpbpmjufodfmwfnjpnbbjqfpivojlwfnbpkb`jbebulqivmjlojaqfsvmwlavfmlbvwlqbaqjoavfmbwf{wlnbqylpbafqojpwbovfdl`/_nlfmfqlivfdlsfq/Vkbafqfpwlzmvm`bnvifqubolqevfqbojaqldvpwbjdvboulwlp`bplpdv/Absvfglplnlpbujplvpwfggfafmml`kfavp`bebowbfvqlppfqjfgj`kl`vqpl`obuf`bpbpof/_msobylobqdllaqbpujpwbbslzlivmwlwqbwbujpwl`qfbq`bnslkfnlp`jm`l`bqdlsjplplqgfmkb`fm/Mqfbgjp`lsfgql`fq`bsvfgbsbsfonfmlq/Vwjo`obqlilqdf`boofslmfqwbqgfmbgjfnbq`bpjdvffoobppjdol`l`kfnlwlpnbgqf`obpfqfpwlmj/]lrvfgbsbpbqabm`lkjilpujbifsbaol/Epwfujfmfqfjmlgfibqelmgl`bmbomlqwfofwqb`bvpbwlnbqnbmlpovmfpbvwlpujoobufmglsfpbqwjslpwfmdbnbq`loofubsbgqfvmjglubnlpylmbpbnalpabmgbnbqjbbavplnv`kbpvajqqjlibujujqdqbgl`kj`bboo/Ailufmgj`kbfpwbmwbofppbojqpvfolsfplpejmfpoobnbavp`l/Epwboofdbmfdqlsobybkvnlqsbdbqivmwbglaofjpobpalopbab/]lkbaobov`kb/mqfbgj`fmivdbqmlwbpuboofboo/M`bqdbglolqbabilfpw/Edvpwlnfmwfnbqjlejqnb`lpwlej`kbsobwbkldbqbqwfpofzfpbrvfonvpflabpfpsl`lpnjwbg`jfol`kj`lnjfgldbmbqpbmwlfwbsbgfafpsobzbqfgfppjfwf`lqwf`lqfbgvgbpgfpflujfilgfpfbbdvbp%rvlw8glnbjm`lnnlmpwbwvpfufmwpnbpwfqpzpwfnb`wjlmabmmfqqfnlufp`qloovsgbwfdolabonfgjvnejowfqmvnafq`kbmdfqfpvowsvaoj`p`qffm`kllpfmlqnbowqbufojppvfpplvq`fwbqdfwpsqjmdnlgvofnlajofptjw`ksklwlpalqgfqqfdjlmjwpfoepl`jbob`wjuf`lovnmqf`lqgelooltwjwof=fjwkfqofmdwkebnjozeqjfmgobzlvwbvwklq`qfbwfqfujftpvnnfqpfqufqsobzfgsobzfqf{sbmgsloj`zelqnbwglvaofsljmwppfqjfpsfqplmojujmdgfpjdmnlmwkpelq`fpvmjrvftfjdkwsflsoffmfqdzmbwvqfpfbq`kejdvqfkbujmd`vpwlnleepfwofwwfqtjmgltpvanjwqfmgfqdqlvspvsolbgkfbowknfwklgujgflpp`klloevwvqfpkbgltgfabwfubovfpLaif`wlwkfqpqjdkwpofbdvf`kqlnfpjnsofmlwj`fpkbqfgfmgjmdpfbplmqfslqwlmojmfprvbqfavwwlmjnbdfpfmbaofnlujmdobwfpwtjmwfqEqbm`fsfqjlgpwqlmdqfsfbwOlmglmgfwbjoelqnfggfnbmgpf`vqfsbppfgwlddofsob`fpgfuj`fpwbwj``jwjfppwqfbnzfooltbwwb`hpwqffweojdkwkjggfmjmel!=lsfmfgvpfevouboofz`bvpfpofbgfqpf`qfwpf`lmggbnbdfpslqwpf{`fswqbwjmdpjdmfgwkjmdpfeef`wejfogppwbwfpleej`fujpvbofgjwlqulovnfQfslqwnvpfvnnlujfpsbqfmwb``fppnlpwoznlwkfq!#jg>!nbqhfwdqlvmg`kbm`fpvqufzafelqfpznalonlnfmwpsff`knlwjlmjmpjgfnbwwfq@fmwfqlaif`wf{jpwpnjggofFvqlsfdqltwkofdb`znbmmfqfmlvdk`bqffqbmptfqlqjdjmslqwbo`ojfmwpfof`wqbmgln`olpfgwlsj`p`lnjmdebwkfqlswjlmpjnsozqbjpfgfp`bsf`klpfm`kvq`kgfejmfqfbplm`lqmfqlvwsvwnfnlqzjeqbnfsloj`fnlgfopMvnafqgvqjmdleefqppwzofphjoofgojpwfg`boofgpjoufqnbqdjmgfofwfafwwfqaqltpfojnjwpDolabopjmdoftjgdfw`fmwfqavgdfwmltqbs`qfgjw`objnpfmdjmfpbefwz`klj`fpsjqjw.pwzofpsqfbgnbhjmdmffgfgqvppjbsofbpff{wfmwP`qjswaqlhfmbooltp`kbqdfgjujgfeb`wlqnfnafq.abpfgwkflqz`lmejdbqlvmgtlqhfgkfosfg@kvq`kjnsb`wpklvogbotbzpoldl!#alwwlnojpw!=*xubq#sqfej{lqbmdfKfbgfq-svpk+`lvsofdbqgfmaqjgdfobvm`kQfujftwbhjmdujpjlmojwwofgbwjmdAvwwlmafbvwzwkfnfpelqdlwPfbq`kbm`klqbonlpwolbgfg@kbmdfqfwvqmpwqjmdqfolbgNlajofjm`lnfpvssozPlvq`flqgfqpujftfg%maps8`lvqpfBalvw#jpobmg?kwno#`llhjfmbnf>!bnbylmnlgfqmbguj`fjm?,b=9#Wkf#gjboldklvpfpAFDJM#Nf{j`lpwbqwp`fmwqfkfjdkwbggjmdJpobmgbppfwpFnsjqfP`kllofeelqwgjqf`wmfbqoznbmvboPfof`w-\t\tLmfiljmfgnfmv!=SkjojsbtbqgpkbmgofjnslqwLeej`fqfdbqgphjoopmbwjlmPslqwpgfdqfftffhoz#+f-d-afkjmggl`wlqolddfgvmjwfg?,a=?,afdjmpsobmwpbppjpwbqwjpwjppvfg033s{`bmbgbbdfm`zp`kfnfqfnbjmAqbyjopbnsofoldl!=afzlmg.p`bofb``fswpfqufgnbqjmfEllwfq`bnfqb?,k2=\t\\elqn!ofbufppwqfpp!#,=\t-dje!#lmolbgolbgfqL{elqgpjpwfqpvqujuojpwfmefnbofGfpjdmpjyf>!bssfbowf{w!=ofufopwkbmhpkjdkfqelq`fgbmjnbobmzlmfBeqj`bbdqffgqf`fmwSflsof?aq#,=tlmgfqsqj`fpwvqmfg#x~8nbjm!=jmojmfpvmgbztqbs!=ebjofg`fmpvpnjmvwfafb`lmrvlwfp263s{fpwbwfqfnlwffnbjo!ojmhfgqjdkw8pjdmboelqnbo2-kwnopjdmvssqjm`feolbw9-smd!#elqvn-B``fppsbsfqpplvmgpf{wfmgKfjdkwpojgfqVWE.;!%bns8#Afelqf-#TjwkpwvgjlltmfqpnbmbdfsqlejwiRvfqzbmmvbosbqbnpalvdkwebnlvpdlldofolmdfqj((*#xjpqbfopbzjmdgf`jgfklnf!=kfbgfqfmpvqfaqbm`ksjf`fpaol`h8pwbwfgwls!=?qb`jmdqfpjyf..%dw8sb`jwzpf{vboavqfbv-isd!#23/333lawbjmwjwofpbnlvmw/#Jm`-`lnfgznfmv!#ozqj`pwlgbz-jmgffg`lvmwz\\oldl-EbnjozollhfgNbqhfwopf#jeSobzfqwvqhfz*8ubq#elqfpwdjujmdfqqlqpGlnbjm~fopfxjmpfqwAold?,ellwfqoldjm-ebpwfqbdfmwp?algz#23s{#3sqbdnbeqjgbzivmjlqgloobqsob`fg`lufqpsovdjm6/333#sbdf!=alpwlm-wfpw+bubwbqwfpwfg\\`lvmwelqvnpp`kfnbjmgf{/ejoofgpkbqfpqfbgfqbofqw+bssfbqPvanjwojmf!=algz!=\t)#WkfWklvdkpffjmdifqpfzMftp?,ufqjezf{sfqwjmivqztjgwk>@llhjfPWBQW#b`qlpp\\jnbdfwkqfbgmbwjufsl`hfwal{!=\tPzpwfn#Gbujg`bm`fqwbaofpsqlufgBsqjo#qfboozgqjufqjwfn!=nlqf!=albqgp`lolqp`bnsvpejqpw##X^8nfgjb-dvjwbqejmjpktjgwk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fgnfppbdfpv``fppebpkjlm?wjwof=`lvmwqzb``lvmw`qfbwfgpwlqjfpqfpvowpqvmmjmdsql`fpptqjwjmdlaif`wpujpjaoftfo`lnfbqwj`ofvmhmltmmfwtlqh`lnsbmzgzmbnj`aqltpfqsqjub`zsqlaofnPfquj`fqfpsf`wgjpsobzqfrvfpwqfpfquftfapjwfkjpwlqzeqjfmgplswjlmptlqhjmdufqpjlmnjoojlm`kbmmfotjmglt-bggqfppujpjwfgtfbwkfq`lqqf`wsqlgv`wfgjqf`welqtbqgzlv#`bmqfnlufgpvaif`w`lmwqlobq`kjuf`vqqfmwqfbgjmdojaqbqzojnjwfgnbmbdfqevqwkfqpvnnbqznb`kjmfnjmvwfpsqjubwf`lmwf{wsqldqbnpl`jfwzmvnafqptqjwwfmfmbaofgwqjddfqplvq`fpolbgjmdfofnfmwsbqwmfqejmboozsfqef`wnfbmjmdpzpwfnphffsjmd`vowvqf%rvlw8/ilvqmbosqlif`wpvqeb`fp%rvlw8f{sjqfpqfujftpabobm`fFmdojpk@lmwfmwwkqlvdkSofbpf#lsjmjlm`lmwb`wbufqbdfsqjnbqzujoobdfPsbmjpkdboofqzgf`ojmfnffwjmdnjppjlmslsvobqrvbojwznfbpvqfdfmfqbopsf`jfppfppjlmpf`wjlmtqjwfqp`lvmwfqjmjwjboqfslqwpejdvqfpnfnafqpklogjmdgjpsvwffbqojfqf{sqfppgjdjwbosj`wvqfBmlwkfqnbqqjfgwqbeej`ofbgjmd`kbmdfg`fmwqbouj`wlqzjnbdfp,qfbplmppwvgjfpefbwvqfojpwjmdnvpw#afp`kllopUfqpjlmvpvboozfsjplgfsobzjmddqltjmdlaujlvplufqobzsqfpfmwb`wjlmp?,vo=\ttqbssfqboqfbgz`fqwbjmqfbojwzpwlqbdfbmlwkfqgfphwlsleefqfgsbwwfqmvmvpvboGjdjwbo`bsjwboTfapjwfebjovqf`lmmf`wqfgv`fgBmgqljggf`bgfpqfdvobq#%bns8#bmjnbopqfofbpfBvwlnbwdfwwjmdnfwklgpmlwkjmdSlsvobq`bswjlmofwwfqp`bswvqfp`jfm`foj`fmpf`kbmdfpFmdobmg>2%bns8Kjpwlqz#>#mft#@fmwqbovsgbwfgPsf`jboMfwtlqhqfrvjqf`lnnfmwtbqmjmd@loofdfwlloabqqfnbjmpaf`bvpffof`wfgGfvwp`kejmbm`ftlqhfqprvj`hozafwtffmf{b`wozpfwwjmdgjpfbpfPl`jfwztfbslmpf{kjajw%ow8"..@lmwqlo`obppfp`lufqfglvwojmfbwwb`hpgfuj`fp+tjmgltsvqslpfwjwof>!Nlajof#hjoojmdpkltjmdJwbojbmgqlssfgkfbujozfeef`wp.2$^*8\t`lmejqn@vqqfmwbgubm`fpkbqjmdlsfmjmdgqbtjmdajoojlmlqgfqfgDfqnbmzqfobwfg?,elqn=jm`ovgftkfwkfqgfejmfgP`jfm`f`bwboldBqwj`ofavwwlmpobqdfpwvmjelqnilvqmfzpjgfabq@kj`bdlklojgbzDfmfqbosbppbdf/%rvlw8bmjnbwfeffojmdbqqjufgsbppjmdmbwvqboqlvdkoz-\t\tWkf#avw#mlwgfmpjwzAqjwbjm@kjmfpfob`h#lewqjavwfJqfobmg!#gbwb.eb`wlqpqf`fjufwkbw#jpOjaqbqzkvpabmgjm#eb`wbeebjqp@kbqofpqbgj`boaqlvdkwejmgjmdobmgjmd9obmd>!qfwvqm#ofbgfqpsobmmfgsqfnjvnsb`hbdfBnfqj`bFgjwjlm^%rvlw8Nfppbdfmffg#wlubovf>!`lnsof{ollhjmdpwbwjlmafojfufpnboofq.nlajofqf`lqgptbmw#wlhjmg#leEjqfel{zlv#bqfpjnjobqpwvgjfgnb{jnvnkfbgjmdqbsjgoz`ojnbwfhjmdglnfnfqdfgbnlvmwpelvmgfgsjlmffqelqnvobgzmbpwzklt#wl#Pvsslqwqfufmvff`lmlnzQfpvowpaqlwkfqplogjfqobqdfoz`boojmd-%rvlw8B``lvmwFgtbqg#pfdnfmwQlafqw#feelqwpSb`jej`ofbqmfgvs#tjwkkfjdkw9tf#kbufBmdfofpmbwjlmp\\pfbq`kbssojfgb`rvjqfnbppjufdqbmwfg9#ebopfwqfbwfgajddfpwafmfejwgqjujmdPwvgjfpnjmjnvnsfqkbspnlqmjmdpfoojmdjp#vpfgqfufqpfubqjbmw#qlof>!njppjmdb`kjfufsqlnlwfpwvgfmwplnflmff{wqfnfqfpwlqfalwwln9fuloufgboo#wkfpjwfnbsfmdojpktbz#wl##Bvdvpwpznalop@lnsbmznbwwfqpnvpj`bobdbjmpwpfqujmd~*+*8\tsbznfmwwqlvaof`lm`fsw`lnsbqfsbqfmwpsobzfqpqfdjlmpnlmjwlq#$$Wkf#tjmmjmdf{solqfbgbswfgDboofqzsqlgv`fbajojwzfmkbm`f`bqffqp*-#Wkf#`loof`wPfbq`k#bm`jfmwf{jpwfgellwfq#kbmgofqsqjmwfg`lmplofFbpwfqmf{slqwptjmgltp@kbmmfojoofdbomfvwqbopvddfpw\\kfbgfqpjdmjmd-kwno!=pfwwofgtfpwfqm`bvpjmd.tfahjw`objnfgIvpwj`f`kbswfquj`wjnpWklnbp#nlyjoobsqlnjpfsbqwjfpfgjwjlmlvwpjgf9ebopf/kvmgqfgLoznsj`\\avwwlmbvwklqpqfb`kfg`kqlmj`gfnbmgppf`lmgpsqlwf`wbglswfgsqfsbqfmfjwkfqdqfbwozdqfbwfqlufqboojnsqluf`lnnbmgpsf`jbopfbq`k-tlqpkjsevmgjmdwklvdkwkjdkfpwjmpwfbgvwjojwzrvbqwfq@vowvqfwfpwjmd`ofbqozf{slpfgAqltpfqojafqbo~#`bw`kSqlif`wf{bnsofkjgf+*8EolqjgbbmptfqpbooltfgFnsfqlqgfefmpfpfqjlvpeqffglnPfufqbo.avwwlmEvqwkfqlvw#le#">#mvoowqbjmfgGfmnbqhuljg+3*,boo-ipsqfufmwQfrvfpwPwfskfm\t\tTkfm#lapfquf?,k1=\tNlgfqm#sqlujgf!#bow>!alqgfqp-\t\tElq#\t\tNbmz#bqwjpwpsltfqfgsfqelqnej`wjlmwzsf#lenfgj`bowj`hfwplsslpfg@lvm`jotjwmfppivpwj`fDflqdf#Afodjvn---?,b=wtjwwfqmlwbaoztbjwjmdtbqebqf#Lwkfq#qbmhjmdskqbpfpnfmwjlmpvqujufp`klobq?,s=\t#@lvmwqzjdmlqfgolpp#leivpw#bpDflqdjbpwqbmdf?kfbg=?pwlssfg2$^*8\tjpobmgpmlwbaofalqgfq9ojpw#le`bqqjfg233/333?,k0=\t#pfufqboaf`lnfppfof`w#tfggjmd33-kwnonlmbq`klee#wkfwfb`kfqkjdkoz#ajloldzojef#lelq#fufmqjpf#le%qbrvl8sovplmfkvmwjmd+wklvdkGlvdobpiljmjmd`jq`ofpElq#wkfBm`jfmwUjfwmbnufkj`ofpv`k#bp`qzpwboubovf#>Tjmgltpfmilzfgb#pnboobppvnfg?b#jg>!elqfjdm#Boo#qjklt#wkfGjpsobzqfwjqfgkltfufqkjggfm8abwwofppffhjmd`bajmfwtbp#mlwollh#bw`lmgv`wdfw#wkfIbmvbqzkbssfmpwvqmjmdb9klufqLmojmf#Eqfm`k#ob`hjmdwzsj`bof{wqb`wfmfnjfpfufm#jedfmfqbwgf`jgfgbqf#mlw,pfbq`kafojfep.jnbdf9ol`bwfgpwbwj`-oldjm!=`lmufqwujlofmwfmwfqfgejqpw!=`jq`vjwEjmobmg`kfnjpwpkf#tbp23s{8!=bp#pv`kgjujgfg?,psbm=tjoo#afojmf#leb#dqfbwnzpwfqz,jmgf{-eboojmdgvf#wl#qbjotbz`loofdfnlmpwfqgfp`fmwjw#tjwkmv`ofbqIftjpk#sqlwfpwAqjwjpkeoltfqpsqfgj`wqfelqnpavwwlm#tkl#tbpof`wvqfjmpwbmwpvj`jgfdfmfqj`sfqjlgpnbqhfwpPl`jbo#ejpkjmd`lnajmfdqbskj`tjmmfqp?aq#,=?az#wkf#MbwvqboSqjub`z`llhjfplvw`lnfqfploufPtfgjpkaqjfeozSfqpjbmpl#nv`k@fmwvqzgfsj`wp`lov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qfe>!,!#qfo>!gfufols`lm`fqwgjbdqbngloobqp`ovpwfqsks<jg>bo`lklo*8~*+*8vpjmd#b=?psbm=ufppfopqfujuboBggqfppbnbwfvqbmgqljgboofdfgjoomfpptbohjmd`fmwfqprvbojeznbw`kfpvmjejfgf{wjm`wGfefmpfgjfg#jm\t\n?"..#`vpwlnpojmhjmdOjwwof#Allh#lefufmjmdnjm-ip<bqf#wkfhlmwbhwwlgbz$p-kwno!#wbqdfw>tfbqjmdBoo#Qjd8\t~*+*8qbjpjmd#Bopl/#`qv`jbobalvw!=gf`obqf..=\t?p`ejqfel{bp#nv`kbssojfpjmgf{/#p/#avw#wzsf#>#\t\t?"..wltbqgpQf`lqgpSqjubwfElqfjdmSqfnjfq`klj`fpUjqwvboqfwvqmp@lnnfmwSltfqfgjmojmf8slufqwz`kbnafqOjujmd#ulovnfpBmwklmzoldjm!#QfobwfgF`lmlnzqfb`kfp`vwwjmddqbujwzojef#jm@kbswfq.pkbgltMlwbaof?,wg=\t#qfwvqmpwbgjvntjgdfwpubqzjmdwqbufopkfog#aztkl#bqftlqh#jmeb`vowzbmdvobqtkl#kbgbjqslqwwltm#le\t\tPlnf#$`oj`h$`kbqdfphfztlqgjw#tjoo`jwz#le+wkjp*8Bmgqft#vmjrvf#`kf`hfglq#nlqf033s{8#qfwvqm8qpjlm>!sovdjmptjwkjm#kfqpfoePwbwjlmEfgfqboufmwvqfsvaojpkpfmw#wlwfmpjlmb`wqfpp`lnf#wlejmdfqpGvhf#lesflsof/f{soljwtkbw#jpkbqnlmzb#nbilq!9!kwwsjm#kjp#nfmv!=\tnlmwkozleej`fq`lvm`jodbjmjmdfufm#jmPvnnbqzgbwf#leolzbowzejwmfppbmg#tbpfnsfqlqpvsqfnfPf`lmg#kfbqjmdQvppjbmolmdfpwBoafqwbobwfqbopfw#le#pnboo!=-bssfmggl#tjwkefgfqboabmh#leafmfbwkGfpsjwf@bsjwbodqlvmgp*/#bmg#sfq`fmwjw#eqln`olpjmd`lmwbjmJmpwfbgejewffmbp#tfoo-zbkll-qfpslmgejdkwfqlap`vqfqfeof`wlqdbmj`>#Nbwk-fgjwjmdlmojmf#sbggjmdb#tkloflmfqqlqzfbq#lefmg#le#abqqjfqtkfm#jwkfbgfq#klnf#leqfpvnfgqfmbnfgpwqlmd=kfbwjmdqfwbjmp`olvgeqtbz#le#Nbq`k#2hmltjmdjm#sbqwAfwtffmofpplmp`olpfpwujqwvboojmhp!=`qlppfgFMG#..=ebnlvp#btbqgfgOj`fmpfKfbowk#ebjqoz#tfbowkznjmjnboBeqj`bm`lnsfwfobafo!=pjmdjmdebqnfqpAqbpjo*gjp`vppqfsob`fDqfdlqzelmw#`lsvqpvfgbssfbqpnbhf#vsqlvmgfgalwk#leaol`hfgpbt#wkfleej`fp`lolvqpje+gl`vtkfm#kffmelq`fsvpk+evBvdvpw#VWE.;!=Ebmwbpzjm#nlpwjmivqfgVpvboozebqnjmd`olpvqflaif`w#gfefm`fvpf#le#Nfgj`bo?algz=\tfujgfmwaf#vpfghfz@lgfpj{wffmJpobnj` 333333fmwjqf#tjgfoz#b`wjuf#+wzsflelmf#`bm`lolq#>psfbhfqf{wfmgpSkzpj`pwfqqbjm?walgz=evmfqboujftjmdnjggof#`qj`hfwsqlskfwpkjewfggl`wlqpQvppfoo#wbqdfw`lnsb`wbodfaqbpl`jbo.avoh#lenbm#bmg?,wg=\t#kf#ofew*-ubo+*ebopf*8oldj`boabmhjmdklnf#wlmbnjmd#Bqjylmb`qfgjwp*8\t~*8\telvmgfqjm#wvqm@loojmpafelqf#Avw#wkf`kbqdfgWjwof!=@bswbjmpsfoofgdlggfppWbd#..=Bggjmd9avw#tbpQf`fmw#sbwjfmwab`h#jm>ebopf%Ojm`lomtf#hmlt@lvmwfqIvgbjpnp`qjsw#bowfqfg$^*8\t##kbp#wkfvm`ofbqFufmw$/alwk#jmmlw#boo\t\t?"..#sob`jmdkbqg#wl#`fmwfqplqw#le`ojfmwppwqffwpAfqmbqgbppfqwpwfmg#wlebmwbpzgltm#jmkbqalvqEqffglniftfoqz,balvw--pfbq`kofdfmgpjp#nbgfnlgfqm#lmoz#lmlmoz#wljnbdf!#ojmfbq#sbjmwfqbmg#mlwqbqfoz#b`qlmzngfojufqpklqwfq33%bns8bp#nbmztjgwk>!,)#?"X@wjwof#>le#wkf#oltfpw#sj`hfg#fp`bsfgvpfp#lesflsofp#Svaoj`Nbwwkftwb`wj`pgbnbdfgtbz#elqobtp#lefbpz#wl#tjmgltpwqlmd##pjnsof~`bw`k+pfufmwkjmelal{tfmw#wlsbjmwfg`jwjyfmJ#glm$wqfwqfbw-#Plnf#tt-!*8\talnajmdnbjowl9nbgf#jm-#Nbmz#`bqqjfpx~8tjtlqh#lepzmlmzngfefbwpebulqfglswj`bosbdfWqbvmofpp#pfmgjmdofew!=?`lnP`lqBoo#wkfiRvfqz-wlvqjpw@obppj`ebopf!#Tjokfonpvavqapdfmvjmfajpklsp-psojw+dolabo#elooltpalgz#lemlnjmbo@lmwb`wpf`vobqofew#wl`kjfeoz.kjggfm.abmmfq?,oj=\t\t-#Tkfm#jm#alwkgjpnjppF{solqfbotbzp#ujb#wkfpsb/]lotfoebqfqvojmd#bqqbmdf`bswbjmkjp#plmqvof#lekf#wllhjwpfoe/>3%bns8+`boofgpbnsofpwl#nbhf`ln,sbdNbqwjm#Hfmmfgzb``fswpevoo#lekbmgofgAfpjgfp,,..=?,baof#wlwbqdfwpfppfm`fkjn#wl#jwp#az#`lnnlm-njmfqbowl#wbhftbzp#wlp-lqd,obgujpfgsfmbowzpjnsof9je#wkfzOfwwfqpb#pklqwKfqafqwpwqjhfp#dqlvsp-ofmdwkeojdkwplufqobspoltoz#ofppfq#pl`jbo#?,s=\t\n\njw#jmwlqbmhfg#qbwf#levo=\t##bwwfnswsbjq#lenbhf#jwHlmwbhwBmwlmjlkbujmd#qbwjmdp#b`wjufpwqfbnpwqbssfg!*-`pp+klpwjofofbg#wlojwwof#dqlvsp/Sj`wvqf..=\t\t#qltp>!#laif`wjmufqpf?ellwfq@vpwlnU=?_,p`qploujmd@kbnafqpobufqztlvmgfgtkfqfbp">#$vmgelq#boosbqwoz#.qjdkw9Bqbajbmab`hfg#`fmwvqzvmjw#lenlajof.Fvqlsf/jp#klnfqjph#legfpjqfg@ojmwlm`lpw#lebdf#le#af`lnf#mlmf#les%rvlw8Njggof#fbg$*X3@qjwj`ppwvgjlp=%`lsz8dqlvs!=bppfnaonbhjmd#sqfppfgtjgdfw-sp9!#<#qfavjowaz#plnfElqnfq#fgjwlqpgfobzfg@bmlmj`kbg#wkfsvpkjmd`obpp>!avw#bqfsbqwjboAbazolmalwwln#`bqqjfq@lnnbmgjwp#vpfBp#tjwk`lvqpfpb#wkjqggfmlwfpbopl#jmKlvpwlm13s{8!=b``vpfgglvaof#dlbo#leEbnlvp#*-ajmg+sqjfpwp#Lmojmfjm#Ivozpw#(#!d`lmpvowgf`jnbokfosevoqfujufgjp#ufqzq$($jswolpjmd#efnbofpjp#boplpwqjmdpgbzp#lebqqjuboevwvqf#?laif`welq`jmdPwqjmd+!#,=\t\n\nkfqf#jpfm`lgfg-##Wkf#aboollmglmf#az,`lnnlmad`lolqobt#le#Jmgjbmbbuljgfgavw#wkf1s{#0s{irvfqz-bewfq#bsloj`z-nfm#bmgellwfq.>#wqvf8elq#vpfp`qffm-Jmgjbm#jnbdf#>ebnjoz/kwws9,,#%maps8gqjufqpfwfqmbopbnf#bpmlwj`fgujftfqp~*+*8\t#jp#nlqfpfbplmpelqnfq#wkf#mftjp#ivpw`lmpfmw#Pfbq`ktbp#wkftkz#wkfpkjssfgaq=?aq=tjgwk9#kfjdkw>nbgf#le`vjpjmfjp#wkbwb#ufqz#Bgnjqbo#ej{fg8mlqnbo#NjppjlmSqfpp/#lmwbqjl`kbqpfwwqz#wl#jmubgfg>!wqvf!psb`jmdjp#nlpwb#nlqf#wlwboozeboo#le~*8\t##jnnfmpfwjnf#jmpfw#lvwpbwjpezwl#ejmggltm#wlolw#le#Sobzfqpjm#Ivmf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b#.alwwlnSqjm`f#bqfb#lenlqf#lepfbq`k\\mbwvqf/ofdboozsfqjlg/obmg#lelq#tjwkjmgv`fgsqlujmdnjppjofol`boozBdbjmpwwkf#tbzh%rvlw8s{8!=\tsvpkfg#babmglmmvnfqbo@fqwbjmJm#wkjpnlqf#jmlq#plnfmbnf#jpbmg/#jm`qltmfgJPAM#3.`qfbwfpL`wlafqnbz#mlw`fmwfq#obwf#jmGfefm`ffmb`wfgtjpk#wlaqlbgoz`llojmdlmolbg>jw-#Wkfqf`lufqNfnafqpkfjdkw#bppvnfp?kwno=\tsflsof-jm#lmf#>tjmgltellwfq\\b#dllg#qfhobnblwkfqp/wl#wkjp\\`llhjfsbmfo!=Olmglm/gfejmfp`qvpkfgabswjpn`lbpwbopwbwvp#wjwof!#nluf#wlolpw#jmafwwfq#jnsojfpqjuboqzpfqufqp#PzpwfnSfqkbspfp#bmg#`lmwfmgeoltjmdobpwfg#qjpf#jmDfmfpjpujft#leqjpjmd#pffn#wlavw#jm#ab`hjmdkf#tjoodjufm#bdjujmd#`jwjfp-eolt#le#Obwfq#boo#avwKjdktbzlmoz#azpjdm#lekf#glfpgjeefqpabwwfqz%bns8obpjmdofpwkqfbwpjmwfdfqwbhf#lmqfevpfg`boofg#>VP%bnsPff#wkfmbwjufpaz#wkjppzpwfn-kfbg#le9klufq/ofpajbmpvqmbnfbmg#boo`lnnlm,kfbgfq\\\\sbqbnpKbqubqg,sj{fo-qfnlubopl#olmdqlof#leiljmwozphzp`qbVmj`lgfaq#,=\tBwobmwbmv`ofvp@lvmwz/svqfoz#`lvmw!=fbpjoz#avjog#blm`oj`hb#djufmsljmwfqk%rvlw8fufmwp#fopf#x\tgjwjlmpmlt#wkf/#tjwk#nbm#tkllqd,Tfalmf#bmg`buboqzKf#gjfgpfbwwof33/333#xtjmgltkbuf#wlje+tjmgbmg#jwpplofoz#n%rvlw8qfmftfgGfwqljwbnlmdpwfjwkfq#wkfn#jmPfmbwlqVp?,b=?Hjmd#leEqb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plufqujftnbdbyjmff`lmlnj`wqbjmjmdsqfppvqfubqjlvp#?pwqlmd=sqlsfqwzpklssjmdwldfwkfqbgubm`fgafkbujlqgltmolbgefbwvqfgellwaboopfof`wfgObmdvbdfgjpwbm`fqfnfnafqwqb`hjmdsbpptlqgnlgjejfgpwvgfmwpgjqf`wozejdkwjmdmlqwkfqmgbwbabpfefpwjuboaqfbhjmdol`bwjlmjmwfqmfwgqlsgltmsqb`wj`ffujgfm`fevm`wjlmnbqqjbdfqfpslmpfsqlaofnpmfdbwjufsqldqbnpbmbozpjpqfofbpfgabmmfq!=svq`kbpfsloj`jfpqfdjlmbo`qfbwjufbqdvnfmwallhnbqhqfefqqfq`kfnj`bogjujpjlm`booab`hpfsbqbwfsqlif`wp`lmeoj`wkbqgtbqfjmwfqfpwgfojufqznlvmwbjmlawbjmfg>#ebopf8elq+ubq#b``fswfg`bsb`jwz`lnsvwfqjgfmwjwzbjq`qbewfnsolzfgsqlslpfgglnfpwj`jm`ovgfpsqlujgfgklpsjwboufqwj`bo`loobspfbssqlb`ksbqwmfqpoldl!=?bgbvdkwfqbvwklq!#`vowvqboebnjojfp,jnbdfp,bppfnaozsltfqevowfb`kjmdejmjpkfggjpwqj`w`qjwj`bo`dj.ajm,svqslpfpqfrvjqfpfof`wjlmaf`lnjmdsqlujgfpb`bgfnj`f{fq`jpfb`wvbooznfgj`jmf`lmpwbmwb``jgfmwNbdbyjmfgl`vnfmwpwbqwjmdalwwln!=lapfqufg9#%rvlw8f{wfmgfgsqfujlvpPlewtbqf`vpwlnfqgf`jpjlmpwqfmdwkgfwbjofgpojdkwozsobmmjmdwf{wbqfb`vqqfm`zfufqzlmfpwqbjdkwwqbmpefqslpjwjufsqlgv`fgkfqjwbdfpkjssjmdbaplovwfqf`fjufgqfofubmwavwwlm!#ujlofm`fbmztkfqfafmfejwpobvm`kfgqf`fmwozboojbm`felooltfgnvowjsofavoofwjmjm`ovgfgl``vqqfgjmwfqmbo\'+wkjp*-qfsvaoj`=?wq=?wg`lmdqfppqf`lqgfgvowjnbwfplovwjlm?vo#jg>!gjp`lufqKlnf?,b=tfapjwfpmfwtlqhpbowklvdkfmwjqfoznfnlqjbonfppbdfp`lmwjmvfb`wjuf!=plnftkbwuj`wlqjbTfpwfqm##wjwof>!Ol`bwjlm`lmwqb`wujpjwlqpGltmolbgtjwklvw#qjdkw!=\tnfbpvqfptjgwk#>#ubqjbaofjmuloufgujqdjmjbmlqnboozkbssfmfgb``lvmwppwbmgjmdmbwjlmboQfdjpwfqsqfsbqfg`lmwqlopb``vqbwfajqwkgbzpwqbwfdzleej`jbodqbskj`p`qjnjmboslppjaoz`lmpvnfqSfqplmbopsfbhjmdubojgbwfb`kjfufg-isd!#,=nb`kjmfp?,k1=\t##hfztlqgpeqjfmgozaqlwkfqp`lnajmfglqjdjmbo`lnslpfgf{sf`wfgbgfrvbwfsbhjpwbmeloolt!#ubovbaof?,obafo=qfobwjufaqjmdjmdjm`qfbpfdlufqmlqsovdjmp,Ojpw#le#Kfbgfq!=!#mbnf>!#+%rvlw8dqbgvbwf?,kfbg=\t`lnnfq`fnbobzpjbgjqf`wlqnbjmwbjm8kfjdkw9p`kfgvof`kbmdjmdab`h#wl#`bwkloj`sbwwfqmp`lolq9# dqfbwfpwpvssojfpqfojbaof?,vo=\t\n\n?pfof`w#`jwjyfmp`olwkjmdtbw`kjmd?oj#jg>!psf`jej``bqqzjmdpfmwfm`f?`fmwfq=`lmwqbpwwkjmhjmd`bw`k+f*plvwkfqmNj`kbfo#nfq`kbmw`bqlvpfosbggjmd9jmwfqjlq-psojw+!ojybwjlmL`wlafq#*xqfwvqmjnsqlufg..%dw8\t\t`lufqbdf`kbjqnbm-smd!#,=pvaif`wpQj`kbqg#tkbwfufqsqlabaozqf`lufqzabpfabooivgdnfmw`lmmf`w--`pp!#,=#tfapjwfqfslqwfggfebvow!,=?,b=\tfof`wqj`p`lwobmg`qfbwjlmrvbmwjwz-#JPAM#3gjg#mlw#jmpwbm`f.pfbq`k.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wof!=slqwbaof-ofmdwk#fojdjaofjmuloufpbwobmwj`lmolbg>!gfebvow-pvssojfgsbznfmwpdolppbqz\t\tBewfq#dvjgbm`f?,wg=?wgfm`lgjmdnjggof!=`bnf#wl#gjpsobzpp`lwwjpkilmbwkbmnbilqjwztjgdfwp-`ojmj`bowkbjobmgwfb`kfqp?kfbg=\t\nbeef`wfgpvsslqwpsljmwfq8wlPwqjmd?,pnboo=lhobklnbtjoo#af#jmufpwlq3!#bow>!klojgbzpQfplvq`foj`fmpfg#+tkj`k#-#Bewfq#`lmpjgfqujpjwjmdf{solqfqsqjnbqz#pfbq`k!#bmgqljg!rvj`hoz#nffwjmdpfpwjnbwf8qfwvqm#8`lolq9 #kfjdkw>bssqlubo/#%rvlw8#`kf`hfg-njm-ip!nbdmfwj`=?,b=?,kelqf`bpw-#Tkjof#wkvqpgbzgufqwjpf%fb`vwf8kbp@obppfubovbwflqgfqjmdf{jpwjmdsbwjfmwp#Lmojmf#`lolqbglLswjlmp!`bnsafoo?"..#fmg?,psbm=??aq#,=\t\\slsvspp`jfm`fp/%rvlw8#rvbojwz#Tjmgltp#bppjdmfgkfjdkw9#?a#`obppof%rvlw8#ubovf>!#@lnsbmzf{bnsofp?jeqbnf#afojfufpsqfpfmwpnbqpkboosbqw#le#sqlsfqoz*-\t\tWkf#wb{lmlnznv`k#le#?,psbm=\t!#gbwb.pqwvdv/Fpp`qlooWl#sqlif`w?kfbg=\tbwwlqmfzfnskbpjppslmplqpebm`zal{tlqog$p#tjogojef`kf`hfg>pfppjlmpsqldqbnns{8elmw.#Sqlif`wilvqmbopafojfufgub`bwjlmwklnsplmojdkwjmdbmg#wkf#psf`jbo#alqgfq>3`kf`hjmd?,walgz=?avwwlm#@lnsofwf`ofbqej{\t?kfbg=\tbqwj`of#?pf`wjlmejmgjmdpqlof#jm#slsvobq##L`wlafqtfapjwf#f{slpvqfvpfg#wl##`kbmdfplsfqbwfg`oj`hjmdfmwfqjmd`lnnbmgpjmelqnfg#mvn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`lvmwqjfprvfpwjlmpfrvjsnfmw`lnnvmjwzbubjobaofkjdkojdkwGWG,{kwnonbqhfwjmdhmltofgdfplnfwkjmd`lmwbjmfqgjqf`wjlmpvap`qjafbgufqwjpf`kbqb`wfq!#ubovf>!?,pfof`w=Bvpwqbojb!#`obpp>!pjwvbwjlmbvwklqjwzelooltjmdsqjnbqjozlsfqbwjlm`kboofmdfgfufolsfgbmlmznlvpevm`wjlm#evm`wjlmp`lnsbmjfppwqv`wvqfbdqffnfmw!#wjwof>!slwfmwjbofgv`bwjlmbqdvnfmwppf`lmgbqz`lszqjdkwobmdvbdfpf{`ovpjuf`lmgjwjlm?,elqn=\tpwbwfnfmwbwwfmwjlmAjldqbskz~#fopf#x\tplovwjlmptkfm#wkf#Bmbozwj`pwfnsobwfpgbmdfqlvppbwfoojwfgl`vnfmwpsvaojpkfqjnslqwbmwsqlwlwzsfjmeovfm`f%qbrvl8?,feef`wjufdfmfqboozwqbmpelqnafbvwjevowqbmpslqwlqdbmjyfgsvaojpkfgsqlnjmfmwvmwjo#wkfwkvnambjoMbwjlmbo#-el`vp+*8lufq#wkf#njdqbwjlmbmmlvm`fgellwfq!=\tf{`fswjlmofpp#wkbmf{sfmpjufelqnbwjlmeqbnftlqhwfqqjwlqzmgj`bwjlm`vqqfmwoz`obppMbnf`qjwj`jpnwqbgjwjlmfopftkfqfBof{bmgfqbssljmwfgnbwfqjbopaqlbg`bpwnfmwjlmfgbeejojbwf?,lswjlm=wqfbwnfmwgjeefqfmw,gfebvow-Sqfpjgfmwlm`oj`h>!ajldqbskzlwkfqtjpfsfqnbmfmwEqbm/KbjpKlooztllgf{sbmpjlmpwbmgbqgp?,pwzof=\tqfgv`wjlmGf`fnafq#sqfefqqfg@bnaqjgdflsslmfmwpAvpjmfpp#`lmevpjlm=\t?wjwof=sqfpfmwfgf{sobjmfgglfp#mlw#tlqogtjgfjmwfqeb`fslpjwjlmpmftpsbsfq?,wbaof=\tnlvmwbjmpojhf#wkf#fppfmwjboejmbm`jbopfof`wjlmb`wjlm>!,babmglmfgFgv`bwjlmsbqpfJmw+pwbajojwzvmbaof#wl?,wjwof=\tqfobwjlmpMlwf#wkbwfeej`jfmwsfqelqnfgwtl#zfbqpPjm`f#wkfwkfqfelqftqbssfq!=bowfqmbwfjm`qfbpfgAbwwof#lesfq`fjufgwqzjmd#wlmf`fppbqzslqwqbzfgfof`wjlmpFojybafwk?,jeqbnf=gjp`lufqzjmpvqbm`fp-ofmdwk8ofdfmgbqzDfldqbskz`bmgjgbwf`lqslqbwfplnfwjnfppfquj`fp-jmkfqjwfg?,pwqlmd=@lnnvmjwzqfojdjlvpol`bwjlmp@lnnjwwffavjogjmdpwkf#tlqogml#olmdfqafdjmmjmdqfefqfm`f`bmmlw#afeqfrvfm`zwzsj`boozjmwl#wkf#qfobwjuf8qf`lqgjmdsqfpjgfmwjmjwjboozwf`kmjrvfwkf#lwkfqjw#`bm#aff{jpwfm`fvmgfqojmfwkjp#wjnfwfofsklmfjwfnp`lsfsqb`wj`fpbgubmwbdf*8qfwvqm#Elq#lwkfqsqlujgjmdgfnl`qb`zalwk#wkf#f{wfmpjufpveefqjmdpvsslqwfg`lnsvwfqp#evm`wjlmsqb`wj`bopbjg#wkbwjw#nbz#afFmdojpk?,eqln#wkf#p`kfgvofggltmolbgp?,obafo=\tpvpsf`wfgnbqdjm9#3psjqjwvbo?,kfbg=\t\tnj`qlplewdqbgvboozgjp`vppfgkf#af`bnff{f`vwjufirvfqz-ipklvpfklog`lmejqnfgsvq`kbpfgojwfqboozgfpwqlzfgvs#wl#wkfubqjbwjlmqfnbjmjmdjw#jp#mlw`fmwvqjfpIbsbmfpf#bnlmd#wkf`lnsofwfgbodlqjwknjmwfqfpwpqfafoojlmvmgfejmfgfm`lvqbdfqfpjybaofjmuloujmdpfmpjwjufvmjufqpbosqlujpjlm+bowklvdkefbwvqjmd`lmgv`wfg*/#tkj`k#`lmwjmvfg.kfbgfq!=Efaqvbqz#mvnfqlvp#lufqeolt9`lnslmfmweqbdnfmwpf{`foofmw`lopsbm>!wf`kmj`bomfbq#wkf#Bgubm`fg#plvq`f#lef{sqfppfgKlmd#Hlmd#Eb`fallhnvowjsof#nf`kbmjpnfofubwjlmleefmpjuf?,elqn=\t\npslmplqfggl`vnfmw-lq#%rvlw8wkfqf#bqfwklpf#tklnlufnfmwpsql`fppfpgjeej`vowpvanjwwfgqf`lnnfmg`lmujm`fgsqlnlwjmd!#tjgwk>!-qfsob`f+`obppj`bo`lbojwjlmkjp#ejqpwgf`jpjlmpbppjpwbmwjmgj`bwfgfulovwjlm.tqbssfq!fmlvdk#wlbolmd#wkfgfojufqfg..=\t?"..Bnfqj`bm#sqlwf`wfgMlufnafq#?,pwzof=?evqmjwvqfJmwfqmfw##lmaovq>!pvpsfmgfgqf`jsjfmwabpfg#lm#Nlqflufq/balojpkfg`loof`wfgtfqf#nbgffnlwjlmbofnfqdfm`zmbqqbwjufbgul`bwfps{8alqgfq`lnnjwwfggjq>!owq!fnsolzffpqfpfbq`k-#pfof`wfgpv``fpplq`vpwlnfqpgjpsobzfgPfswfnafqbgg@obpp+Eb`fallh#pvddfpwfgbmg#obwfqlsfqbwjmdfobalqbwfPlnfwjnfpJmpwjwvwf`fqwbjmozjmpwboofgelooltfqpIfqvpbofnwkfz#kbuf`lnsvwjmddfmfqbwfgsqlujm`fpdvbqbmwffbqajwqbqzqf`ldmjyftbmwfg#wls{8tjgwk9wkflqz#leafkbujlvqTkjof#wkffpwjnbwfgafdbm#wl#jw#af`bnfnbdmjwvgfnvpw#kbufnlqf#wkbmGjqf`wlqzf{wfmpjlmpf`qfwbqzmbwvqboozl``vqqjmdubqjbaofpdjufm#wkfsobwelqn-?,obafo=?ebjofg#wl`lnslvmgphjmgp#le#pl`jfwjfpbolmdpjgf#..%dw8\t\tplvwktfpwwkf#qjdkwqbgjbwjlmnbz#kbuf#vmfp`bsf+pslhfm#jm!#kqfe>!,sqldqbnnflmoz#wkf#`lnf#eqlngjqf`wlqzavqjfg#jm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pnpplnf#wjnfEqjfgqj`ktbp#ejqpwwkf#lmoz#eb`w#wkbwelqn#jg>!sqf`fgjmdWf`kmj`boskzpj`jpwl``vqp#jmmbujdbwlqpf`wjlm!=psbm#jg>!plvdkw#wlafolt#wkfpvqujujmd~?,pwzof=kjp#gfbwkbp#jm#wkf`bvpfg#azsbqwjboozf{jpwjmd#vpjmd#wkftbp#djufmb#ojpw#leofufop#lemlwjlm#leLeej`jbo#gjpnjppfgp`jfmwjpwqfpfnaofpgvsoj`bwff{solpjufqf`lufqfgboo#lwkfqdboofqjfpxsbggjmd9sflsof#leqfdjlm#lebggqfppfpbppl`jbwfjnd#bow>!jm#nlgfqmpklvog#afnfwklg#leqfslqwjmdwjnfpwbnsmffgfg#wlwkf#Dqfbwqfdbqgjmdpffnfg#wlujftfg#bpjnsb`w#lmjgfb#wkbwwkf#Tlqogkfjdkw#lef{sbmgjmdWkfpf#bqf`vqqfmw!=`bqfevooznbjmwbjmp`kbqdf#le@obppj`bobggqfppfgsqfgj`wfgltmfqpkjs?gju#jg>!qjdkw!=\tqfpjgfm`fofbuf#wkf`lmwfmw!=bqf#lewfm##~*+*8\tsqlabaoz#Sqlefpplq.avwwlm!#qfpslmgfgpbzp#wkbwkbg#wl#afsob`fg#jmKvmdbqjbmpwbwvp#lepfqufp#bpVmjufqpbof{f`vwjlmbddqfdbwfelq#tkj`kjmef`wjlmbdqffg#wlkltfufq/#slsvobq!=sob`fg#lm`lmpwqv`wfof`wlqbopznalo#lejm`ovgjmdqfwvqm#wlbq`kjwf`w@kqjpwjbmsqfujlvp#ojujmd#jmfbpjfq#wlsqlefpplq\t%ow8"..#feef`w#lebmbozwj`ptbp#wbhfmtkfqf#wkfwllh#lufqafojfe#jmBeqjhbbmpbp#ebq#bpsqfufmwfgtlqh#tjwkb#psf`jbo?ejfogpfw@kqjpwnbpQfwqjfufg\t\tJm#wkf#ab`h#jmwlmlqwkfbpwnbdbyjmfp=?pwqlmd=`lnnjwwffdlufqmjmddqlvsp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$/#$VB.qfplovwjlmlsfqbwjlmpwfofujpjlmwqbmpobwfgTbpkjmdwlmmbujdbwlq-#>#tjmglt-jnsqfppjlm%ow8aq%dw8ojwfqbwvqfslsvobwjlmad`lolq>! fpsf`jbooz#`lmwfmw>!sqlgv`wjlmmftpofwwfqsqlsfqwjfpgfejmjwjlmofbgfqpkjsWf`kmloldzSbqojbnfmw`lnsbqjplmvo#`obpp>!-jmgf{Le+!`lm`ovpjlmgjp`vppjlm`lnslmfmwpajloldj`boQfulovwjlm\\`lmwbjmfqvmgfqpwllgmlp`qjsw=?sfqnjppjlmfb`k#lwkfqbwnlpskfqf#lmel`vp>!?elqn#jg>!sql`fppjmdwkjp-ubovfdfmfqbwjlm@lmefqfm`fpvapfrvfmwtfoo.hmltmubqjbwjlmpqfsvwbwjlmskfmlnfmlmgjp`jsojmfoldl-smd!#+gl`vnfmw/alvmgbqjfpf{sqfppjlmpfwwofnfmwAb`hdqlvmglvw#le#wkffmwfqsqjpf+!kwwsp9!#vmfp`bsf+!sbpptlqg!#gfnl`qbwj`?b#kqfe>!,tqbssfq!=\tnfnafqpkjsojmdvjpwj`s{8sbggjmdskjolplskzbppjpwbm`fvmjufqpjwzeb`jojwjfpqf`ldmjyfgsqfefqfm`fje#+wzsflenbjmwbjmfgul`bavobqzkzslwkfpjp-pvanjw+*8%bns8maps8bmmlwbwjlmafkjmg#wkfElvmgbwjlmsvaojpkfq!bppvnswjlmjmwqlgv`fg`lqqvswjlmp`jfmwjpwpf{soj`jwozjmpwfbg#legjnfmpjlmp#lm@oj`h>!`lmpjgfqfggfsbqwnfmwl``vsbwjlmpllm#bewfqjmufpwnfmwsqlmlvm`fgjgfmwjejfgf{sfqjnfmwNbmbdfnfmwdfldqbskj`!#kfjdkw>!ojmh#qfo>!-qfsob`f+,gfsqfppjlm`lmefqfm`fsvmjpknfmwfojnjmbwfgqfpjpwbm`fbgbswbwjlmlsslpjwjlmtfoo#hmltmpvssofnfmwgfwfqnjmfgk2#`obpp>!3s{8nbqdjmnf`kbmj`bopwbwjpwj`p`fofaqbwfgDlufqmnfmw\t\tGvqjmd#wgfufolsfqpbqwjej`jbofrvjubofmwlqjdjmbwfg@lnnjppjlmbwwb`knfmw?psbm#jg>!wkfqf#tfqfMfgfqobmgpafzlmg#wkfqfdjpwfqfgilvqmbojpweqfrvfmwozboo#le#wkfobmd>!fm!#?,pwzof=\tbaplovwf8#pvsslqwjmdf{wqfnfoz#nbjmpwqfbn?,pwqlmd=#slsvobqjwzfnsolznfmw?,wbaof=\t#`lopsbm>!?,elqn=\t##`lmufqpjlmbalvw#wkf#?,s=?,gju=jmwfdqbwfg!#obmd>!fmSlqwvdvfpfpvapwjwvwfjmgjujgvbojnslppjaofnvowjnfgjbbonlpw#boos{#plojg# bsbqw#eqlnpvaif`w#wljm#Fmdojpk`qjwj`jyfgf{`fsw#elqdvjgfojmfplqjdjmboozqfnbqhbaofwkf#pf`lmgk1#`obpp>!?b#wjwof>!+jm`ovgjmdsbqbnfwfqpsqlkjajwfg>#!kwws9,,gj`wjlmbqzsfq`fswjlmqfulovwjlmelvmgbwjlms{8kfjdkw9pv``fppevopvsslqwfqpnjoofmmjvnkjp#ebwkfqwkf#%rvlw8ml.qfsfbw8`lnnfq`jbojmgvpwqjbofm`lvqbdfgbnlvmw#le#vmleej`jbofeej`jfm`zQfefqfm`fp`llqgjmbwfgjp`objnfqf{sfgjwjlmgfufolsjmd`bo`vobwfgpjnsojejfgofdjwjnbwfpvapwqjmd+3!#`obpp>!`lnsofwfozjoovpwqbwfejuf#zfbqpjmpwqvnfmwSvaojpkjmd2!#`obpp>!spz`kloldz`lmejgfm`fmvnafq#le#bapfm`f#leel`vpfg#lmiljmfg#wkfpwqv`wvqfpsqfujlvpoz=?,jeqbnf=lm`f#bdbjmavw#qbwkfqjnnjdqbmwple#`lvqpf/b#dqlvs#leOjwfqbwvqfVmojhf#wkf?,b=%maps8\tevm`wjlm#jw#tbp#wkf@lmufmwjlmbvwlnlajofSqlwfpwbmwbddqfppjufbewfq#wkf#Pjnjobqoz/!#,=?,gju=`loof`wjlm\tevm`wjlmujpjajojwzwkf#vpf#leulovmwffqpbwwqb`wjlmvmgfq#wkf#wkqfbwfmfg)?"X@GBWBXjnslqwbm`fjm#dfmfqbowkf#obwwfq?,elqn=\t?,-jmgf{Le+$j#>#38#j#?gjeefqfm`fgfulwfg#wlwqbgjwjlmppfbq`k#elqvowjnbwfozwlvqmbnfmwbwwqjavwfppl.`boofg#~\t?,pwzof=fubovbwjlmfnskbpjyfgb``fppjaof?,pf`wjlm=pv``fppjlmbolmd#tjwkNfbmtkjof/jmgvpwqjfp?,b=?aq#,=kbp#af`lnfbpsf`wp#leWfofujpjlmpveej`jfmwabphfwabooalwk#pjgfp`lmwjmvjmdbm#bqwj`of?jnd#bow>!bgufmwvqfpkjp#nlwkfqnbm`kfpwfqsqjm`jsofpsbqwj`vobq`lnnfmwbqzfeef`wp#legf`jgfg#wl!=?pwqlmd=svaojpkfqpIlvqmbo#legjeej`vowzeb`jojwbwfb``fswbaofpwzof-`pp!\nevm`wjlm#jmmlubwjlm=@lszqjdkwpjwvbwjlmptlvog#kbufavpjmfppfpGj`wjlmbqzpwbwfnfmwplewfm#vpfgsfqpjpwfmwjm#Ibmvbqz`lnsqjpjmd?,wjwof=\t\ngjsolnbwj``lmwbjmjmdsfqelqnjmdf{wfmpjlmpnbz#mlw#af`lm`fsw#le#lm`oj`h>!Jw#jp#boplejmbm`jbo#nbhjmd#wkfOv{fnalvqdbggjwjlmbobqf#`boofgfmdbdfg#jm!p`qjsw!*8avw#jw#tbpfof`wqlmj`lmpvanjw>!\t?"..#Fmg#fof`wqj`boleej`jboozpvddfpwjlmwls#le#wkfvmojhf#wkfBvpwqbojbmLqjdjmboozqfefqfm`fp\t?,kfbg=\tqf`ldmjpfgjmjwjbojyfojnjwfg#wlBof{bmgqjbqfwjqfnfmwBgufmwvqfpelvq#zfbqp\t\t%ow8"..#jm`qfbpjmdgf`lqbwjlmk0#`obpp>!lqjdjmp#lelaojdbwjlmqfdvobwjlm`obppjejfg+evm`wjlm+bgubmwbdfpafjmd#wkf#kjpwlqjbmp?abpf#kqfeqfsfbwfgoztjoojmd#wl`lnsbqbaofgfpjdmbwfgmlnjmbwjlmevm`wjlmbojmpjgf#wkfqfufobwjlmfmg#le#wkfp#elq#wkf#bvwklqjyfgqfevpfg#wlwbhf#sob`fbvwlmlnlvp`lnsqlnjpfslojwj`bo#qfpwbvqbmwwtl#le#wkfEfaqvbqz#1rvbojwz#leptelaif`w-vmgfqpwbmgmfbqoz#bootqjwwfm#azjmwfqujftp!#tjgwk>!2tjwkgqbtboeolbw9ofewjp#vpvbooz`bmgjgbwfpmftpsbsfqpnzpwfqjlvpGfsbqwnfmwafpw#hmltmsbqojbnfmwpvssqfppfg`lmufmjfmwqfnfnafqfggjeefqfmw#pzpwfnbwj`kbp#ofg#wlsqlsbdbmgb`lmwqloofgjmeovfm`fp`fqfnlmjbosql`objnfgSqlwf`wjlmoj#`obpp>!P`jfmwjej``obpp>!ml.wqbgfnbqhpnlqf#wkbm#tjgfpsqfbgOjafqbwjlmwllh#sob`fgbz#le#wkfbp#olmd#bpjnsqjplmfgBggjwjlmbo\t?kfbg=\t?nObalqbwlqzMlufnafq#1f{`fswjlmpJmgvpwqjboubqjfwz#leeolbw9#ofeGvqjmd#wkfbppfppnfmwkbuf#affm#gfbop#tjwkPwbwjpwj`pl``vqqfm`f,vo=?,gju=`ofbqej{!=wkf#svaoj`nbmz#zfbqptkj`k#tfqflufq#wjnf/pzmlmznlvp`lmwfmw!=\tsqfpvnbaozkjp#ebnjozvpfqBdfmw-vmf{sf`wfgjm`ovgjmd#`kboofmdfgb#njmlqjwzvmgfejmfg!afolmdp#wlwbhfm#eqlnjm#L`wlafqslpjwjlm9#pbjg#wl#afqfojdjlvp#Efgfqbwjlm#qltpsbm>!lmoz#b#eftnfbmw#wkbwofg#wl#wkf..=\t?gju#?ejfogpfw=Bq`kajpkls#`obpp>!mlafjmd#vpfgbssqlb`kfpsqjujofdfpmlp`qjsw=\tqfpvowp#jmnbz#af#wkfFbpwfq#fddnf`kbmjpnpqfbplmbaofSlsvobwjlm@loof`wjlmpfof`wfg!=mlp`qjsw=,jmgf{-sksbqqjubo#le.ippgh$**8nbmbdfg#wljm`lnsofwf`bpvbowjfp`lnsofwjlm@kqjpwjbmpPfswfnafq#bqjwknfwj`sql`fgvqfpnjdkw#kbufSqlgv`wjlmjw#bssfbqpSkjolplskzeqjfmgpkjsofbgjmd#wldjujmd#wkfwltbqg#wkfdvbqbmwffggl`vnfmwfg`lolq9 333ujgfl#dbnf`lnnjppjlmqfeof`wjmd`kbmdf#wkfbppl`jbwfgpbmp.pfqjelmhfzsqfpp8#sbggjmd9Kf#tbp#wkfvmgfqozjmdwzsj`booz#/#bmg#wkf#pq`Fofnfmwpv``fppjufpjm`f#wkf#pklvog#af#mfwtlqhjmdb``lvmwjmdvpf#le#wkfoltfq#wkbmpkltp#wkbw?,psbm=\t\n\n`lnsobjmwp`lmwjmvlvprvbmwjwjfpbpwqlmlnfqkf#gjg#mlwgvf#wl#jwpbssojfg#wlbm#bufqbdffeelqwp#wlwkf#evwvqfbwwfnsw#wlWkfqfelqf/`bsbajojwzQfsvaoj`bmtbp#elqnfgFof`wqlmj`hjolnfwfqp`kboofmdfpsvaojpkjmdwkf#elqnfqjmgjdfmlvpgjqf`wjlmppvapjgjbqz`lmpsjqb`zgfwbjop#lebmg#jm#wkfbeelqgbaofpvapwbm`fpqfbplm#elq`lmufmwjlmjwfnwzsf>!baplovwfozpvsslpfgozqfnbjmfg#bbwwqb`wjufwqbufoojmdpfsbqbwfozel`vpfp#lmfofnfmwbqzbssoj`baofelvmg#wkbwpwzofpkffwnbmvp`qjswpwbmgp#elq#ml.qfsfbw+plnfwjnfp@lnnfq`jbojm#Bnfqj`bvmgfqwbhfmrvbqwfq#lebm#f{bnsofsfqplmboozjmgf{-sks<?,avwwlm=\tsfq`fmwbdfafpw.hmltm`qfbwjmd#b!#gjq>!owq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f#jm#wkfnlmjwlqjmdqfslqwfgozwkf#nlgfqmtlqhjmd#lmbooltfg#wltkfqf#wkf#jmmlubwjuf?,b=?,gju=plvmgwqb`hpfbq`kElqnwfmg#wl#afjmsvw#jg>!lsfmjmd#leqfpwqj`wfgbglswfg#azbggqfppjmdwkfloldjbmnfwklgp#leubqjbmw#le@kqjpwjbm#ufqz#obqdfbvwlnlwjufaz#ebq#wkfqbmdf#eqlnsvqpvjw#leeloolt#wkfaqlvdkw#wljm#Fmdobmgbdqff#wkbwb``vpfg#le`lnfp#eqlnsqfufmwjmdgju#pwzof>kjp#lq#kfqwqfnfmglvpeqffgln#le`lm`fqmjmd3#2fn#2fn8Abphfwaboo,pwzof-`ppbm#fbqojfqfufm#bewfq,!#wjwof>!-`ln,jmgf{wbhjmd#wkfsjwwpavqdk`lmwfmw!=?p`qjsw=+ewvqmfg#lvwkbujmd#wkf?,psbm=\t#l``bpjlmboaf`bvpf#jwpwbqwfg#wlskzpj`booz=?,gju=\t##`qfbwfg#az@vqqfmwoz/#ad`lolq>!wbajmgf{>!gjpbpwqlvpBmbozwj`p#bopl#kbp#b=?gju#jg>!?,pwzof=\t?`boofg#elqpjmdfq#bmg-pq`#>#!,,ujlobwjlmpwkjp#sljmw`lmpwbmwozjp#ol`bwfgqf`lqgjmdpg#eqln#wkfmfgfqobmgpslqwvdv/Fp;N;};D;u;F5m4K4]4_7`gfpbqqlool`lnfmwbqjlfgv`b`j/_mpfswjfnaqfqfdjpwqbglgjqf``j/_mvaj`b`j/_msvaoj`jgbgqfpsvfpwbpqfpvowbglpjnslqwbmwfqfpfqubglpbqw/A`volpgjefqfmwfppjdvjfmwfpqfs/Vaoj`bpjwvb`j/_mnjmjpwfqjlsqjub`jgbggjqf`wlqjlelqnb`j/_mslaob`j/_msqfpjgfmwf`lmw','fmjglpb``fplqjlpwf`kmlqbwjsfqplmbofp`bwfdlq/Abfpsf`jbofpgjpslmjaofb`wvbojgbgqfefqfm`jbuboobglojgajaojlwf`bq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5j4[5n4E4K5h5o4F4D4K5h4]4@5h4K4X4F4]5o4K5h5n4C5i5f4U4[5f5opAzWbdMbnf+-isd!#bow>!2s{#plojg# -dje!#bow>!wqbmpsbqfmwjmelqnbwjlmbssoj`bwjlm!#lm`oj`h>!fpwbaojpkfgbgufqwjpjmd-smd!#bow>!fmujqlmnfmwsfqelqnbm`fbssqlsqjbwf%bns8ngbpk8jnnfgjbwfoz?,pwqlmd=?,qbwkfq#wkbmwfnsfqbwvqfgfufolsnfmw`lnsfwjwjlmsob`fklogfqujpjajojwz9`lszqjdkw!=3!#kfjdkw>!fufm#wklvdkqfsob`fnfmwgfpwjmbwjlm@lqslqbwjlm?vo#`obpp>!Bppl`jbwjlmjmgjujgvbopsfqpsf`wjufpfwWjnflvw+vqo+kwws9,,nbwkfnbwj`pnbqdjm.wls9fufmwvbooz#gfp`qjswjlm*#ml.qfsfbw`loof`wjlmp-ISDwkvnasbqwj`jsbwf,kfbg=?algzeolbw9ofew8?oj#`obpp>!kvmgqfgp#le\t\tKltfufq/#`lnslpjwjlm`ofbq9alwk8`llsfqbwjlmtjwkjm#wkf#obafo#elq>!alqgfq.wls9Mft#Yfbobmgqf`lnnfmgfgsklwldqbskzjmwfqfpwjmd%ow8pvs%dw8`lmwqlufqpzMfwkfqobmgpbowfqmbwjufnb{ofmdwk>!ptjwyfqobmgGfufolsnfmwfppfmwjbooz\t\tBowklvdk#?,wf{wbqfb=wkvmgfqajqgqfsqfpfmwfg%bns8mgbpk8psf`vobwjlm`lnnvmjwjfpofdjpobwjlmfof`wqlmj`p\t\n?gju#jg>!joovpwqbwfgfmdjmffqjmdwfqqjwlqjfpbvwklqjwjfpgjpwqjavwfg5!#kfjdkw>!pbmp.pfqje8`bsbaof#le#gjpbssfbqfgjmwfqb`wjufollhjmd#elqjw#tlvog#afBedkbmjpwbmtbp#`qfbwfgNbwk-eollq+pvqqlvmgjmd`bm#bopl#aflapfqubwjlmnbjmwfmbm`ffm`lvmwfqfg?k1#`obpp>!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{-sks<qfnbjmfg#jmwqbmpelqnfgKf#tbp#bopltbp#boqfbgzpwbwjpwj`bojm#ebulq#leNjmjpwqz#lenlufnfmw#leelqnvobwjlmjp#qfrvjqfg?ojmh#qfo>!Wkjp#jp#wkf#?b#kqfe>!,slsvobqjyfgjmuloufg#jmbqf#vpfg#wlbmg#pfufqbonbgf#az#wkfpffnp#wl#afojhfoz#wkbwSbofpwjmjbmmbnfg#bewfqjw#kbg#affmnlpw#`lnnlmwl#qfefq#wlavw#wkjp#jp`lmpf`vwjufwfnslqbqjozJm#dfmfqbo/`lmufmwjlmpwbhfp#sob`fpvagjujpjlmwfqqjwlqjbolsfqbwjlmbosfqnbmfmwoztbp#obqdfozlvwaqfbh#lejm#wkf#sbpwelooltjmd#b#{nomp9ld>!=?b#`obpp>!`obpp>!wf{w@lmufqpjlm#nbz#af#vpfgnbmveb`wvqfbewfq#afjmd`ofbqej{!=\trvfpwjlm#letbp#fof`wfgwl#af`lnf#baf`bvpf#le#plnf#sflsofjmpsjqfg#azpv``fppevo#b#wjnf#tkfmnlqf#`lnnlmbnlmdpw#wkfbm#leej`jbotjgwk9233&8wf`kmloldz/tbp#bglswfgwl#hffs#wkfpfwwofnfmwpojuf#ajqwkpjmgf{-kwno!@lmmf`wj`vwbppjdmfg#wl%bns8wjnfp8b``lvmw#elqbojdm>qjdkwwkf#`lnsbmzbotbzp#affmqfwvqmfg#wljmuloufnfmwAf`bvpf#wkfwkjp#sfqjlg!#mbnf>!r!#`lmejmfg#wlb#qfpvow#leubovf>!!#,=jp#b`wvboozFmujqlmnfmw\t?,kfbg=\t@lmufqpfoz/=\t?gju#jg>!3!#tjgwk>!2jp#sqlabaozkbuf#af`lnf`lmwqloojmdwkf#sqlaofn`jwjyfmp#leslojwj`jbmpqfb`kfg#wkfbp#fbqoz#bp9mlmf8#lufq?wbaof#`fooubojgjwz#legjqf`woz#wllmnlvpfgltmtkfqf#jw#jptkfm#jw#tbpnfnafqp#le#qfobwjlm#wlb``lnnlg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f#wkfaqlvdkw#wkf`bo`vobwjlmeboo#le#wkfwkf#dfmfqbosqb`wj`boozjm#klmlq#leqfofbpfg#jmqfpjgfmwjbobmg#plnf#lehjmd#le#wkfqfb`wjlm#wl2pw#Fbqo#le`vowvqf#bmgsqjm`jsbooz?,wjwof=\t##wkfz#`bm#afab`h#wl#wkfplnf#le#kjpf{slpvqf#wlbqf#pjnjobqelqn#le#wkfbggEbulqjwf`jwjyfmpkjssbqw#jm#wkfsflsof#tjwkjm#sqb`wj`fwl#`lmwjmvf%bns8njmvp8bssqlufg#az#wkf#ejqpw#booltfg#wkfbmg#elq#wkfevm`wjlmjmdsobzjmd#wkfplovwjlm#wlkfjdkw>!3!#jm#kjp#allhnlqf#wkbm#belooltp#wkf`qfbwfg#wkfsqfpfm`f#jm%maps8?,wg=mbwjlmbojpwwkf#jgfb#leb#`kbqb`wfqtfqf#elq`fg#`obpp>!awmgbzp#le#wkfefbwvqfg#jmpkltjmd#wkfjmwfqfpw#jmjm#sob`f#lewvqm#le#wkfwkf#kfbg#leOlqg#le#wkfslojwj`boozkbp#jwp#ltmFgv`bwjlmbobssqlubo#leplnf#le#wkffb`k#lwkfq/afkbujlq#lebmg#af`bvpfbmg#bmlwkfqbssfbqfg#lmqf`lqgfg#jmaob`h%rvlw8nbz#jm`ovgfwkf#tlqog$p`bm#ofbg#wlqfefqp#wl#balqgfq>!3!#dlufqmnfmw#tjmmjmd#wkfqfpvowfg#jm#tkjof#wkf#Tbpkjmdwlm/wkf#pvaif`w`jwz#jm#wkf=?,gju=\t\n\nqfeof`w#wkfwl#`lnsofwfaf`bnf#nlqfqbgjlb`wjufqfif`wfg#aztjwklvw#bmzkjp#ebwkfq/tkj`k#`lvog`lsz#le#wkfwl#jmgj`bwfb#slojwj`bob``lvmwp#le`lmpwjwvwfptlqhfg#tjwkfq?,b=?,oj=le#kjp#ojefb``lnsbmjfg`ojfmwTjgwksqfufmw#wkfOfdjpobwjufgjeefqfmwozwldfwkfq#jmkbp#pfuf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bwfq#wkbmb`kjfufnfmwpfpwbaojpkjmdIbubP`qjsw!#mfufqwkfofpppjdmjej`bm`fAqlbg`bpwjmd=%maps8?,wg=`lmwbjmfq!=\tpv`k#bp#wkf#jmeovfm`f#leb#sbqwj`vobqpq`>$kwws9,,mbujdbwjlm!#kboe#le#wkf#pvapwbmwjbo#%maps8?,gju=bgubmwbdf#legjp`lufqz#leevmgbnfmwbo#nfwqlslojwbmwkf#lsslpjwf!#{no9obmd>!gfojafqbwfozbojdm>`fmwfqfulovwjlm#lesqfpfqubwjlmjnsqlufnfmwpafdjmmjmd#jmIfpvp#@kqjpwSvaoj`bwjlmpgjpbdqffnfmwwf{w.bojdm9q/#evm`wjlm+*pjnjobqjwjfpalgz=?,kwno=jp#`vqqfmwozboskbafwj`bojp#plnfwjnfpwzsf>!jnbdf,nbmz#le#wkf#eolt9kjggfm8bubjobaof#jmgfp`qjaf#wkff{jpwfm`f#leboo#lufq#wkfwkf#Jmwfqmfw\n?vo#`obpp>!jmpwboobwjlmmfjdkalqkllgbqnfg#elq`fpqfgv`jmd#wkf`lmwjmvfp#wlMlmfwkfofpp/wfnsfqbwvqfp\t\n\n?b#kqfe>!`olpf#wl#wkff{bnsofp#le#jp#balvw#wkf+pff#afolt*-!#jg>!pfbq`ksqlefppjlmbojp#bubjobaofwkf#leej`jbo\n\n?,p`qjsw=\t\t\n\n?gju#jg>!b``fofqbwjlmwkqlvdk#wkf#Kboo#le#Ebnfgfp`qjswjlmpwqbmpobwjlmpjmwfqefqfm`f#wzsf>$wf{w,qf`fmw#zfbqpjm#wkf#tlqogufqz#slsvobqxab`hdqlvmg9wqbgjwjlmbo#plnf#le#wkf#`lmmf`wfg#wlf{soljwbwjlmfnfqdfm`f#le`lmpwjwvwjlmB#Kjpwlqz#lepjdmjej`bmw#nbmveb`wvqfgf{sf`wbwjlmp=?mlp`qjsw=?`bm#af#elvmgaf`bvpf#wkf#kbp#mlw#affmmfjdkalvqjmdtjwklvw#wkf#bggfg#wl#wk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`ksqlabaoz#wkfwkjp#bqwj`of+evm`wjlm+*xJw#pklvog#afbm#bdqffnfmwb``jgfmwboozgjeefqp#eqlnBq`kjwf`wvqfafwwfq#hmltmbqqbmdfnfmwpjmeovfm`f#lmbwwfmgfg#wkfjgfmwj`bo#wlplvwk#le#wkfsbpp#wkqlvdk{no!#wjwof>!tfjdkw9alog8`qfbwjmd#wkfgjpsobz9mlmfqfsob`fg#wkf?jnd#pq`>!,jkwwsp9,,ttt-Tlqog#Tbq#JJwfpwjnlmjbopelvmg#jm#wkfqfrvjqfg#wl#bmg#wkbw#wkfafwtffm#wkf#tbp#gfpjdmfg`lmpjpwp#le#`lmpjgfqbaozsvaojpkfg#azwkf#obmdvbdf@lmpfqubwjlm`lmpjpwfg#leqfefq#wl#wkfab`h#wl#wkf#`pp!#nfgjb>!Sflsof#eqln#bubjobaof#lmsqlufg#wl#afpvddfpwjlmp!tbp#hmltm#bpubqjfwjfp#leojhfoz#wl#af`lnsqjpfg#lepvsslqw#wkf#kbmgp#le#wkf`lvsofg#tjwk`lmmf`w#bmg#alqgfq9mlmf8sfqelqnbm`fpafelqf#afjmdobwfq#af`bnf`bo`vobwjlmplewfm#`boofgqfpjgfmwp#lenfbmjmd#wkbw=?oj#`obpp>!fujgfm`f#elqf{sobmbwjlmpfmujqlmnfmwp!=?,b=?,gju=tkj`k#booltpJmwqlgv`wjlmgfufolsfg#azb#tjgf#qbmdflm#afkboe#leubojdm>!wls!sqjm`jsof#lebw#wkf#wjnf/?,mlp`qjsw=pbjg#wl#kbufjm#wkf#ejqpwtkjof#lwkfqpkzslwkfwj`boskjolplskfqpsltfq#le#wkf`lmwbjmfg#jmsfqelqnfg#azjmbajojwz#wltfqf#tqjwwfmpsbm#pwzof>!jmsvw#mbnf>!wkf#rvfpwjlmjmwfmgfg#elqqfif`wjlm#lejnsojfp#wkbwjmufmwfg#wkfwkf#pwbmgbqgtbp#sqlabaozojmh#afwtffmsqlefpplq#lejmwfqb`wjlmp`kbmdjmd#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wl#wkfJm#`lmwqbpw/kltfufq/#bmgjp#wzsj`boozbmg#kjp#tjef+bopl#`boofg=?vo#`obpp>!feef`wjufoz#fuloufg#jmwlpffn#wl#kbuftkj`k#jp#wkfwkfqf#tbp#mlbm#f{`foofmwboo#le#wkfpfgfp`qjafg#azJm#sqb`wj`f/aqlbg`bpwjmd`kbqdfg#tjwkqfeof`wfg#jmpvaif`wfg#wlnjojwbqz#bmgwl#wkf#sljmwf`lmlnj`boozpfwWbqdfwjmdbqf#b`wvboozuj`wlqz#lufq+*8?,p`qjsw=`lmwjmvlvpozqfrvjqfg#elqfulovwjlmbqzbm#feef`wjufmlqwk#le#wkf/#tkj`k#tbp#eqlmw#le#wkflq#lwkfqtjpfplnf#elqn#lekbg#mlw#affmdfmfqbwfg#azjmelqnbwjlm-sfqnjwwfg#wljm`ovgfp#wkfgfufolsnfmw/fmwfqfg#jmwlwkf#sqfujlvp`lmpjpwfmwozbqf#hmltm#bpwkf#ejfog#lewkjp#wzsf#ledjufm#wl#wkfwkf#wjwof#le`lmwbjmp#wkfjmpwbm`fp#lejm#wkf#mlqwkgvf#wl#wkfjqbqf#gfpjdmfg`lqslqbwjlmptbp#wkbw#wkflmf#le#wkfpfnlqf#slsvobqpv``ffgfg#jmpvsslqw#eqlnjm#gjeefqfmwglnjmbwfg#azgfpjdmfg#elqltmfqpkjs#lebmg#slppjaozpwbmgbqgjyfgqfpslmpfWf{wtbp#jmwfmgfgqf`fjufg#wkfbppvnfg#wkbwbqfbp#le#wkfsqjnbqjoz#jmwkf#abpjp#lejm#wkf#pfmpfb``lvmwp#elqgfpwqlzfg#azbw#ofbpw#wtltbp#gf`obqfg`lvog#mlw#afPf`qfwbqz#lebssfbq#wl#afnbqdjm.wls92,]_p(_p(\',df*xwkqlt#f~8wkf#pwbqw#lewtl#pfsbqbwfobmdvbdf#bmgtkl#kbg#affmlsfqbwjlm#legfbwk#le#wkfqfbo#mvnafqp\n?ojmh#qfo>!sqlujgfg#wkfwkf#pwlq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nsqfkfmpjufqfefqp#wl#wkf?,vo=\t?,gju=\tskjolplskj`bool`bwjlm-kqfetbp#svaojpkfgPbm#Eqbm`jp`l+evm`wjlm+*x\t?gju#jg>!nbjmplskjpwj`bwfgnbwkfnbwj`bo#,kfbg=\t?algzpvddfpwp#wkbwgl`vnfmwbwjlm`lm`fmwqbwjlmqfobwjlmpkjspnbz#kbuf#affm+elq#f{bnsof/Wkjp#bqwj`of#jm#plnf#`bpfpsbqwp#le#wkf#gfejmjwjlm#leDqfbw#Aqjwbjm#`foosbggjmd>frvjubofmw#wlsob`fklogfq>!8#elmw.pjyf9#ivpwjej`bwjlmafojfufg#wkbwpveefqfg#eqlnbwwfnswfg#wl#ofbgfq#le#wkf`qjsw!#pq`>!,+evm`wjlm+*#xbqf#bubjobaof\t\n?ojmh#qfo>!#pq`>$kwws9,,jmwfqfpwfg#jm`lmufmwjlmbo#!#bow>!!#,=?,bqf#dfmfqboozkbp#bopl#affmnlpw#slsvobq#`lqqfpslmgjmd`qfgjwfg#tjwkwzof>!alqgfq9?,b=?,psbm=?,-dje!#tjgwk>!?jeqbnf#pq`>!wbaof#`obpp>!jmojmf.aol`h8b``lqgjmd#wl#wldfwkfq#tjwkbssql{jnbwfozsbqojbnfmwbqznlqf#bmg#nlqfgjpsobz9mlmf8wqbgjwjlmboozsqfglnjmbmwoz%maps8%maps8%maps8?,psbm=#`foopsb`jmd>?jmsvw#mbnf>!lq!#`lmwfmw>!`lmwqlufqpjbosqlsfqwz>!ld9,{.pkl`htbuf.gfnlmpwqbwjlmpvqqlvmgfg#azMfufqwkfofpp/tbp#wkf#ejqpw`lmpjgfqbaof#Bowklvdk#wkf#`loobalqbwjlmpklvog#mlw#afsqlslqwjlm#le?psbm#pwzof>!hmltm#bp#wkf#pklqwoz#bewfqelq#jmpwbm`f/gfp`qjafg#bp#,kfbg=\t?algz#pwbqwjmd#tjwkjm`qfbpjmdoz#wkf#eb`w#wkbwgjp`vppjlm#lenjggof#le#wkfbm#jmgjujgvbogjeej`vow#wl#sljmw#le#ujftklnlpf{vbojwzb``fswbm`f#le?,psbm=?,gju=nbmveb`wvqfqplqjdjm#le#wkf`lnnlmoz#vpfgjnslqwbm`f#legfmlnjmbwjlmpab`hdqlvmg9# ofmdwk#le#wkfgfwfqnjmbwjlmb#pjdmjej`bmw!#alqgfq>!3!=qfulovwjlmbqzsqjm`jsofp#lejp#`lmpjgfqfgtbp#gfufolsfgJmgl.Fvqlsfbmuvomfqbaof#wlsqlslmfmwp#lebqf#plnfwjnfp`olpfq#wl#wkfMft#Zlqh#@jwz#mbnf>!pfbq`kbwwqjavwfg#wl`lvqpf#le#wkfnbwkfnbwj`jbmaz#wkf#fmg#lebw#wkf#fmg#le!#alqgfq>!3!#wf`kmloldj`bo-qfnluf@obpp+aqbm`k#le#wkffujgfm`f#wkbw"Xfmgje^..=\tJmpwjwvwf#le#jmwl#b#pjmdofqfpsf`wjufoz-bmg#wkfqfelqfsqlsfqwjfp#lejp#ol`bwfg#jmplnf#le#tkj`kWkfqf#jp#bopl`lmwjmvfg#wl#bssfbqbm`f#le#%bns8mgbpk8#gfp`qjafp#wkf`lmpjgfqbwjlmbvwklq#le#wkfjmgfsfmgfmwozfrvjssfg#tjwkglfp#mlw#kbuf?,b=?b#kqfe>!`lmevpfg#tjwk?ojmh#kqfe>!,bw#wkf#bdf#lebssfbq#jm#wkfWkfpf#jm`ovgfqfdbqgofpp#le`lvog#af#vpfg#pwzof>%rvlw8pfufqbo#wjnfpqfsqfpfmw#wkfalgz=\t?,kwno=wklvdkw#wl#afslsvobwjlm#leslppjajojwjfpsfq`fmwbdf#leb``fpp#wl#wkfbm#bwwfnsw#wlsqlgv`wjlm#leirvfqz,irvfqzwtl#gjeefqfmwafolmd#wl#wkffpwbaojpknfmwqfsob`jmd#wkfgfp`qjswjlm!#gfwfqnjmf#wkfbubjobaof#elqB``lqgjmd#wl#tjgf#qbmdf#le\n?gju#`obpp>!nlqf#`lnnlmozlqdbmjpbwjlmpevm`wjlmbojwztbp#`lnsofwfg#%bns8ngbpk8#sbqwj`jsbwjlmwkf#`kbqb`wfqbm#bggjwjlmbobssfbqp#wl#afeb`w#wkbw#wkfbm#f{bnsof#lepjdmjej`bmwozlmnlvpflufq>!af`bvpf#wkfz#bpzm`#>#wqvf8sqlaofnp#tjwkpffnp#wl#kbufwkf#qfpvow#le#pq`>!kwws9,,ebnjojbq#tjwkslppfppjlm#leevm`wjlm#+*#xwllh#sob`f#jmbmg#plnfwjnfppvapwbmwjbooz?psbm=?,psbm=jp#lewfm#vpfgjm#bm#bwwfnswdqfbw#gfbo#leFmujqlmnfmwbopv``fppevooz#ujqwvbooz#boo13wk#`fmwvqz/sqlefppjlmbopmf`fppbqz#wl#gfwfqnjmfg#az`lnsbwjajojwzaf`bvpf#jw#jpGj`wjlmbqz#lenlgjej`bwjlmpWkf#elooltjmdnbz#qfefq#wl9@lmpfrvfmwoz/Jmwfqmbwjlmbobowklvdk#plnfwkbw#tlvog#aftlqog$p#ejqpw`obppjejfg#bpalwwln#le#wkf+sbqwj`vobqozbojdm>!ofew!#nlpw#`lnnlmozabpjp#elq#wkfelvmgbwjlm#le`lmwqjavwjlmpslsvobqjwz#le`fmwfq#le#wkfwl#qfgv`f#wkfivqjpgj`wjlmpbssql{jnbwjlm#lmnlvpflvw>!Mft#Wfpwbnfmw`loof`wjlm#le?,psbm=?,b=?,jm#wkf#Vmjwfgejon#gjqf`wlq.pwqj`w-gwg!=kbp#affm#vpfgqfwvqm#wl#wkfbowklvdk#wkjp`kbmdf#jm#wkfpfufqbo#lwkfqavw#wkfqf#bqfvmsqf`fgfmwfgjp#pjnjobq#wlfpsf`jbooz#jmtfjdkw9#alog8jp#`boofg#wkf`lnsvwbwjlmbojmgj`bwf#wkbwqfpwqj`wfg#wl\n?nfwb#mbnf>!bqf#wzsj`booz`lmeoj`w#tjwkKltfufq/#wkf#Bm#f{bnsof#le`lnsbqfg#tjwkrvbmwjwjfp#leqbwkfq#wkbm#b`lmpwfoobwjlmmf`fppbqz#elqqfslqwfg#wkbwpsf`jej`bwjlmslojwj`bo#bmg%maps8%maps8?qfefqfm`fp#wlwkf#pbnf#zfbqDlufqmnfmw#ledfmfqbwjlm#lekbuf#mlw#affmpfufqbo#zfbqp`lnnjwnfmw#wl\n\n?vo#`obpp>!ujpvbojybwjlm2:wk#`fmwvqz/sqb`wjwjlmfqpwkbw#kf#tlvogbmg#`lmwjmvfgl``vsbwjlm#lejp#gfejmfg#bp`fmwqf#le#wkfwkf#bnlvmw#le=?gju#pwzof>!frvjubofmw#legjeefqfmwjbwfaqlvdkw#balvwnbqdjm.ofew9#bvwlnbwj`boozwklvdkw#le#bpPlnf#le#wkfpf\t?gju#`obpp>!jmsvw#`obpp>!qfsob`fg#tjwkjp#lmf#le#wkffgv`bwjlm#bmgjmeovfm`fg#azqfsvwbwjlm#bp\t?nfwb#mbnf>!b``lnnlgbwjlm?,gju=\t?,gju=obqdf#sbqw#leJmpwjwvwf#elqwkf#pl.`boofg#bdbjmpw#wkf#Jm#wkjp#`bpf/tbp#bssljmwfg`objnfg#wl#afKltfufq/#wkjpGfsbqwnfmw#lewkf#qfnbjmjmdfeef`w#lm#wkfsbqwj`vobqoz#gfbo#tjwk#wkf\t?gju#pwzof>!bonlpw#botbzpbqf#`vqqfmwozf{sqfppjlm#leskjolplskz#leelq#nlqf#wkbm`jujojybwjlmplm#wkf#jpobmgpfof`wfgJmgf{`bm#qfpvow#jm!#ubovf>!!#,=wkf#pwqv`wvqf#,=?,b=?,gju=Nbmz#le#wkfpf`bvpfg#az#wkfle#wkf#Vmjwfgpsbm#`obpp>!n`bm#af#wqb`fgjp#qfobwfg#wlaf`bnf#lmf#lejp#eqfrvfmwozojujmd#jm#wkfwkflqfwj`boozElooltjmd#wkfQfulovwjlmbqzdlufqmnfmw#jmjp#gfwfqnjmfgwkf#slojwj`bojmwqlgv`fg#jmpveej`jfmw#wlgfp`qjswjlm!=pklqw#pwlqjfppfsbqbwjlm#lebp#wl#tkfwkfqhmltm#elq#jwptbp#jmjwjboozgjpsobz9aol`hjp#bm#f{bnsofwkf#sqjm`jsbo`lmpjpwp#le#bqf`ldmjyfg#bp,algz=?,kwno=b#pvapwbmwjboqf`lmpwqv`wfgkfbg#le#pwbwfqfpjpwbm`f#wlvmgfqdqbgvbwfWkfqf#bqf#wtldqbujwbwjlmbobqf#gfp`qjafgjmwfmwjlmboozpfqufg#bp#wkf`obpp>!kfbgfqlsslpjwjlm#wlevmgbnfmwboozglnjmbwfg#wkfbmg#wkf#lwkfqboojbm`f#tjwktbp#elq`fg#wlqfpsf`wjufoz/bmg#slojwj`bojm#pvsslqw#lesflsof#jm#wkf13wk#`fmwvqz-bmg#svaojpkfgolbg@kbqwafbwwl#vmgfqpwbmgnfnafq#pwbwfpfmujqlmnfmwboejqpw#kboe#le`lvmwqjfp#bmgbq`kjwf`wvqboaf#`lmpjgfqfg`kbqb`wfqjyfg`ofbqJmwfqubobvwklqjwbwjufEfgfqbwjlm#letbp#pv``ffgfgbmg#wkfqf#bqfb#`lmpfrvfm`fwkf#Sqfpjgfmwbopl#jm`ovgfgeqff#plewtbqfpv``fppjlm#legfufolsfg#wkftbp#gfpwqlzfgbtbz#eqln#wkf8\t?,p`qjsw=\t?bowklvdk#wkfzelooltfg#az#bnlqf#sltfqevoqfpvowfg#jm#bVmjufqpjwz#leKltfufq/#nbmzwkf#sqfpjgfmwKltfufq/#plnfjp#wklvdkw#wlvmwjo#wkf#fmgtbp#bmmlvm`fgbqf#jnslqwbmwbopl#jm`ovgfp=?jmsvw#wzsf>wkf#`fmwfq#le#GL#MLW#BOWFQvpfg#wl#qfefqwkfnfp,<plqw>wkbw#kbg#affmwkf#abpjp#elqkbp#gfufolsfgjm#wkf#pvnnfq`lnsbqbwjufozgfp`qjafg#wkfpv`k#bp#wklpfwkf#qfpvowjmdjp#jnslppjaofubqjlvp#lwkfqPlvwk#Beqj`bmkbuf#wkf#pbnffeef`wjufmfppjm#tkj`k#`bpf8#wf{w.bojdm9pwqv`wv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ofpjbpwj`bowkfqf#kbp#affmqfpvowjmd#eqln?,algz=?,kwno=kbp#mfufq#affmwkf#ejqpw#wjnfjm#qfpslmpf#wlbvwlnbwj`booz#?,gju=\t\t?gju#jtbp#`lmpjgfqfgsfq`fmw#le#wkf!#,=?,b=?,gju=`loof`wjlm#le#gfp`fmgfg#eqlnpf`wjlm#le#wkfb``fsw.`kbqpfwwl#af#`lmevpfgnfnafq#le#wkf#sbggjmd.qjdkw9wqbmpobwjlm#lejmwfqsqfwbwjlm#kqfe>$kwws9,,tkfwkfq#lq#mlwWkfqf#bqf#boplwkfqf#bqf#nbmzb#pnboo#mvnafqlwkfq#sbqwp#lejnslppjaof#wl##`obpp>!avwwlmol`bwfg#jm#wkf-#Kltfufq/#wkfbmg#fufmwvboozBw#wkf#fmg#le#af`bvpf#le#jwpqfsqfpfmwp#wkf?elqn#b`wjlm>!#nfwklg>!slpw!jw#jp#slppjaofnlqf#ojhfoz#wlbm#jm`qfbpf#jmkbuf#bopl#affm`lqqfpslmgp#wlbmmlvm`fg#wkbwbojdm>!qjdkw!=nbmz#`lvmwqjfpelq#nbmz#zfbqpfbqojfpw#hmltmaf`bvpf#jw#tbpsw!=?,p`qjsw=#ubojdm>!wls!#jmkbajwbmwp#leelooltjmd#zfbq\t?gju#`obpp>!njoojlm#sflsof`lmwqlufqpjbo#`lm`fqmjmd#wkfbqdvf#wkbw#wkfdlufqmnfmw#bmgb#qfefqfm`f#wlwqbmpefqqfg#wlgfp`qjajmd#wkf#pwzof>!`lolq9bowklvdk#wkfqfafpw#hmltm#elqpvanjw!#mbnf>!nvowjsoj`bwjlmnlqf#wkbm#lmf#qf`ldmjwjlm#le@lvm`jo#le#wkffgjwjlm#le#wkf##?nfwb#mbnf>!Fmwfqwbjmnfmw#btbz#eqln#wkf#8nbqdjm.qjdkw9bw#wkf#wjnf#lejmufpwjdbwjlmp`lmmf`wfg#tjwkbmg#nbmz#lwkfqbowklvdk#jw#jpafdjmmjmd#tjwk#?psbm#`ob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HHIHHGGFF");!function setData(e,t){const n=m,a=p;for(let e=0;e<t.length;++e)a[e]=t[e];let s=0;for(let e=0;e<t.length;++e){n[e]=s;const t=a[e];0!==t&&(s+=e<<(31&t))}for(let e=t.length;e<32;++e)n[e]=s;u=e}(d,g);function InputStream(e){this.data=new Int8Array(0);this.offset=0;this.data=e}function readInput(e,t,n,a){if(null===e.input)return-1;const s=e.input,r=Math.min(s.offset+a,s.data.length),i=r-s.offset;t.set(s.data.subarray(s.offset,r),n);s.offset+=i;return i}function toUtf8Runes(e){const t=e.length,n=new Int32Array(t);for(let a=0;a<t;++a)n[a]=e.charCodeAt(a);return n}function makeError(e,t){if(t>=0)return t;e.runningState>=0&&(e.runningState=t);throw new Error("Brotli error code: "+t)}return function decode(e,t){let n=new State;n.input=new InputStream(e);initState(n);if(t){let e=t.customDictionary;e&&function attachDictionaryChunk(e,t){if(1!==e.runningState)return makeError(e,-24);if(0===e.cdNumChunks){e.cdChunks=new Array(16);e.cdChunkOffsets=new Int32Array(16);e.cdBlockBits=-1}if(15===e.cdNumChunks)return makeError(e,-27);e.cdChunks[e.cdNumChunks]=t;e.cdNumChunks++;e.cdTotalSize+=t.length;e.cdChunkOffsets[e.cdNumChunks]=e.cdTotalSize;return 0}(n,e)}let a=0,s=[];for(;;){let e=new Int8Array(16384);s.push(e);n.output=e;n.outputOffset=0;n.outputLength=16384;n.outputUsed=0;decompress(n);a+=n.outputUsed;if(n.outputUsed<16384)break}!function close(e){if(0===e.runningState)return makeError(e,-25);e.runningState>0&&(e.runningState=11);return 0}(n);!function closeInput(e){e.input=new InputStream(new Int8Array(0))}(n);let r=new Int8Array(a),i=0;for(let e=0;e<s.length;++e){let t=s[e],n=Math.min(a,i+16384)-i;n<16384?r.set(t.subarray(0,n),i):r.set(t,i);i+=n}return r}})();class BrotliStream extends DecodeStream{#L=!0;constructor(e,t){super(t);this.stream=e;this.dict=e.dict}readBlock(){const e=this.stream.getBytes(),t=Nn(new Int8Array(e.buffer,e.byteOffset,e.length));this.buffer=new Uint8Array(t.buffer,t.byteOffset,t.length);this.bufferLength=this.buffer.length;this.eof=!0}async getImageData(e,t){const n=await this.asyncGetBytes();return n?n.length<=e?n:n.subarray(0,e):this.getBytes(e)}async asyncGetBytes(){const{decompressed:e,compressed:t}=await this.asyncGetBytesFromDecompressionStream("brotli");if(e)return e;this.#L=!1;this.stream=new Stream(t,0,t.length,this.stream.dict);this.reset();return null}get isAsync(){return this.#L}}const zn=-1,Ln=[[-1,-1],[-1,-1],[7,8],[7,7],[6,6],[6,6],[6,5],[6,5],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2]],Un=[[-1,-1],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[12,1984],[12,2048],[12,2112],[12,2176],[12,2240],[12,2304],[11,1856],[11,1856],[11,1920],[11,1920],[12,2368],[12,2432],[12,2496],[12,2560]],_n=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[8,29],[8,29],[8,30],[8,30],[8,45],[8,45],[8,46],[8,46],[7,22],[7,22],[7,22],[7,22],[7,23],[7,23],[7,23],[7,23],[8,47],[8,47],[8,48],[8,48],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[7,20],[7,20],[7,20],[7,20],[8,33],[8,33],[8,34],[8,34],[8,35],[8,35],[8,36],[8,36],[8,37],[8,37],[8,38],[8,38],[7,19],[7,19],[7,19],[7,19],[8,31],[8,31],[8,32],[8,32],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[8,53],[8,53],[8,54],[8,54],[7,26],[7,26],[7,26],[7,26],[8,39],[8,39],[8,40],[8,40],[8,41],[8,41],[8,42],[8,42],[8,43],[8,43],[8,44],[8,44],[7,21],[7,21],[7,21],[7,21],[7,28],[7,28],[7,28],[7,28],[8,61],[8,61],[8,62],[8,62],[8,63],[8,63],[8,0],[8,0],[8,320],[8,320],[8,384],[8,384],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[7,27],[7,27],[7,27],[7,27],[8,59],[8,59],[8,60],[8,60],[9,1472],[9,1536],[9,1600],[9,1728],[7,18],[7,18],[7,18],[7,18],[7,24],[7,24],[7,24],[7,24],[8,49],[8,49],[8,50],[8,50],[8,51],[8,51],[8,52],[8,52],[7,25],[7,25],[7,25],[7,25],[8,55],[8,55],[8,56],[8,56],[8,57],[8,57],[8,58],[8,58],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[8,448],[8,448],[8,512],[8,512],[9,704],[9,768],[8,640],[8,640],[8,576],[8,576],[9,832],[9,896],[9,960],[9,1024],[9,1088],[9,1152],[9,1216],[9,1280],[9,1344],[9,1408],[7,256],[7,256],[7,256],[7,256],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7]],Xn=[[-1,-1],[-1,-1],[12,-2],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[11,1792],[11,1792],[12,1984],[12,1984],[12,2048],[12,2048],[12,2112],[12,2112],[12,2176],[12,2176],[12,2240],[12,2240],[12,2304],[12,2304],[11,1856],[11,1856],[11,1856],[11,1856],[11,1920],[11,1920],[11,1920],[11,1920],[12,2368],[12,2368],[12,2432],[12,2432],[12,2496],[12,2496],[12,2560],[12,2560],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[12,52],[12,52],[13,640],[13,704],[13,768],[13,832],[12,55],[12,55],[12,56],[12,56],[13,1280],[13,1344],[13,1408],[13,1472],[12,59],[12,59],[12,60],[12,60],[13,1536],[13,1600],[11,24],[11,24],[11,24],[11,24],[11,25],[11,25],[11,25],[11,25],[13,1664],[13,1728],[12,320],[12,320],[12,384],[12,384],[12,448],[12,448],[13,512],[13,576],[12,53],[12,53],[12,54],[12,54],[13,896],[13,960],[13,1024],[13,1088],[13,1152],[13,1216],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64]],Wn=[[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[11,23],[11,23],[12,50],[12,51],[12,44],[12,45],[12,46],[12,47],[12,57],[12,58],[12,61],[12,256],[10,16],[10,16],[10,16],[10,16],[10,17],[10,17],[10,17],[10,17],[12,48],[12,49],[12,62],[12,63],[12,30],[12,31],[12,32],[12,33],[12,40],[12,41],[11,22],[11,22],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[12,128],[12,192],[12,26],[12,27],[12,28],[12,29],[11,19],[11,19],[11,20],[11,20],[12,34],[12,35],[12,36],[12,37],[12,38],[12,39],[11,21],[11,21],[12,42],[12,43],[10,0],[10,0],[10,0],[10,0],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12]],Kn=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[6,9],[6,8],[5,7],[5,7],[4,6],[4,6],[4,6],[4,6],[4,5],[4,5],[4,5],[4,5],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2]];class CCITTFaxDecoder{constructor(e,t={K:0,EndOfLine:!1,EncodedByteAlign:!1,Columns:1728,Rows:0,EndOfBlock:!0,BlackIs1:!1}){if("function"!=typeof e?.next)throw new Error('CCITTFaxDecoder - invalid "source" parameter.');this.source=e;this.eof=!1;({K:this.encoding,EndOfLine:this.eoline,EncodedByteAlign:this.byteAlign,Columns:this.columns,Rows:this.rows,EndOfBlock:this.eoblock,BlackIs1:this.black}=t);this.codingLine=new Uint32Array(this.columns+1);this.refLine=new Uint32Array(this.columns+2);this.codingLine[0]=this.columns;this.codingPos=0;this.row=0;this.nextLine2D=this.encoding<0;this.inputBits=0;this.inputBuf=0;this.outputBits=0;this.rowsDone=!1;let n;for(;0===(n=this._lookBits(12));)this._eatBits(1);1===n&&this._eatBits(12);if(this.encoding>0){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}}readNextChar(){if(this.eof)return-1;const e=this.refLine,t=this.codingLine,n=this.columns;let a,s,r,i,o;if(0===this.outputBits){this.rowsDone&&(this.eof=!0);if(this.eof)return-1;this.err=!1;let r,o,l;if(this.nextLine2D){for(i=0;t[i]<n;++i)e[i]=t[i];e[i++]=n;e[i]=n;t[0]=0;this.codingPos=0;a=0;s=0;for(;t[this.codingPos]<n;){r=this._getTwoDimCode();switch(r){case 0:this._addPixels(e[a+1],s);e[a+1]<n&&(a+=2);break;case 1:r=o=0;if(s){do{r+=l=this._getBlackCode()}while(l>=64);do{o+=l=this._getWhiteCode()}while(l>=64)}else{do{r+=l=this._getWhiteCode()}while(l>=64);do{o+=l=this._getBlackCode()}while(l>=64)}this._addPixels(t[this.codingPos]+r,s);t[this.codingPos]<n&&this._addPixels(t[this.codingPos]+o,1^s);for(;e[a]<=t[this.codingPos]&&e[a]<n;)a+=2;break;case 7:this._addPixels(e[a]+3,s);s^=1;if(t[this.codingPos]<n){++a;for(;e[a]<=t[this.codingPos]&&e[a]<n;)a+=2}break;case 5:this._addPixels(e[a]+2,s);s^=1;if(t[this.codingPos]<n){++a;for(;e[a]<=t[this.codingPos]&&e[a]<n;)a+=2}break;case 3:this._addPixels(e[a]+1,s);s^=1;if(t[this.codingPos]<n){++a;for(;e[a]<=t[this.codingPos]&&e[a]<n;)a+=2}break;case 2:this._addPixels(e[a],s);s^=1;if(t[this.codingPos]<n){++a;for(;e[a]<=t[this.codingPos]&&e[a]<n;)a+=2}break;case 8:this._addPixelsNeg(e[a]-3,s);s^=1;if(t[this.codingPos]<n){a>0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]<n;)a+=2}break;case 6:this._addPixelsNeg(e[a]-2,s);s^=1;if(t[this.codingPos]<n){a>0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]<n;)a+=2}break;case 4:this._addPixelsNeg(e[a]-1,s);s^=1;if(t[this.codingPos]<n){a>0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]<n;)a+=2}break;case zn:this._addPixels(n,0);this.eof=!0;break;default:info("bad 2d code");this._addPixels(n,0);this.err=!0}}}else{t[0]=0;this.codingPos=0;s=0;for(;t[this.codingPos]<n;){r=0;if(s)do{r+=l=this._getBlackCode()}while(l>=64);else do{r+=l=this._getWhiteCode()}while(l>=64);this._addPixels(t[this.codingPos]+r,s);s^=1}}let f=!1;this.byteAlign&&(this.inputBits&=-8);if(this.eoblock||this.row!==this.rows-1){r=this._lookBits(12);if(this.eoline)for(;r!==zn&&1!==r;){this._eatBits(1);r=this._lookBits(12)}else for(;0===r;){this._eatBits(1);r=this._lookBits(12)}if(1===r){this._eatBits(12);f=!0}else r===zn&&(this.eof=!0)}else this.rowsDone=!0;if(!this.eof&&this.encoding>0&&!this.rowsDone){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}if(this.eoblock&&f&&this.byteAlign){r=this._lookBits(12);if(1===r){this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}if(this.encoding>=0)for(i=0;i<4;++i){r=this._lookBits(12);1!==r&&info("bad rtc code: "+r);this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}}this.eof=!0}}else if(this.err&&this.eoline){for(;;){r=this._lookBits(13);if(r===zn){this.eof=!0;return-1}if(r>>1==1)break;this._eatBits(1)}this._eatBits(12);if(this.encoding>0){this._eatBits(1);this.nextLine2D=!(1&r)}}this.outputBits=t[0]>0?t[this.codingPos=0]:t[this.codingPos=1];this.row++}if(this.outputBits>=8){o=1&this.codingPos?0:255;this.outputBits-=8;if(0===this.outputBits&&t[this.codingPos]<n){this.codingPos++;this.outputBits=t[this.codingPos]-t[this.codingPos-1]}}else{r=8;o=0;do{if("number"!=typeof this.outputBits)throw new FormatError('Invalid /CCITTFaxDecode data, "outputBits" must be a number.');if(this.outputBits>r){o<<=r;1&this.codingPos||(o|=255>>8-r);this.outputBits-=r;r=0}else{o<<=this.outputBits;1&this.codingPos||(o|=255>>8-this.outputBits);r-=this.outputBits;this.outputBits=0;if(t[this.codingPos]<n){this.codingPos++;this.outputBits=t[this.codingPos]-t[this.codingPos-1]}else if(r>0){o<<=r;r=0}}}while(r)}this.black&&(o^=255);return o}_addPixels(e,t){const n=this.codingLine;let a=this.codingPos;if(e>n[a]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&a^t&&++a;n[a]=e}this.codingPos=a}_addPixelsNeg(e,t){const n=this.codingLine;let a=this.codingPos;if(e>n[a]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&a^t&&++a;n[a]=e}else if(e<n[a]){if(e<0){info("invalid code");this.err=!0;e=0}for(;a>0&&e<n[a-1];)--a;n[a]=e}this.codingPos=a}_findTableCode(e,t,n,a){const s=a||0;for(let a=e;a<=t;++a){let e=this._lookBits(a);if(e===zn)return[!0,1,!1];a<t&&(e<<=t-a);if(!s||e>=s){const t=n[e-s];if(t[0]===a){this._eatBits(a);return[!0,t[1],!0]}}}return[!1,0,!1]}_getTwoDimCode(){let e,t=0;if(this.eoblock){t=this._lookBits(7);e=Ln[t];if(e?.[0]>0){this._eatBits(e[0]);return e[1]}}else{const e=this._findTableCode(1,7,Ln);if(e[0]&&e[2])return e[1]}info("Bad two dim code");return zn}_getWhiteCode(){let e,t=0;if(this.eoblock){t=this._lookBits(12);if(t===zn)return 1;e=t>>5?_n[t>>3]:Un[t];if(e[0]>0){this._eatBits(e[0]);return e[1]}}else{let e=this._findTableCode(1,9,_n);if(e[0])return e[1];e=this._findTableCode(11,12,Un);if(e[0])return e[1]}info("bad white code");this._eatBits(1);return 1}_getBlackCode(){let e,t;if(this.eoblock){e=this._lookBits(13);if(e===zn)return 1;t=e>>7?!(e>>9)&&e>>7?Wn[(e>>1)-64]:Kn[e>>7]:Xn[e];if(t[0]>0){this._eatBits(t[0]);return t[1]}}else{let e=this._findTableCode(2,6,Kn);if(e[0])return e[1];e=this._findTableCode(7,12,Wn,64);if(e[0])return e[1];e=this._findTableCode(10,13,Xn);if(e[0])return e[1]}info("bad black code");this._eatBits(1);return 1}_lookBits(e){let t;for(;this.inputBits<e;){if(-1===(t=this.source.next()))return 0===this.inputBits?zn:this.inputBuf<<e-this.inputBits&65535>>16-e;this.inputBuf=this.inputBuf<<8|t;this.inputBits+=8}return this.inputBuf>>this.inputBits-e&65535>>16-e}_eatBits(e){(this.inputBits-=e)<0&&(this.inputBits=0)}}class CCITTFaxStream extends DecodeStream{constructor(e,t,n){super(t);this.stream=e;this.maybeLength=t;this.dict=e.dict;n instanceof Dict||(n=Dict.empty);this.params={K:n.get("K")||0,EndOfLine:!!n.get("EndOfLine"),EncodedByteAlign:!!n.get("EncodedByteAlign"),Columns:n.get("Columns")||1728,Rows:n.get("Rows")||0,EndOfBlock:!!(n.get("EndOfBlock")??1),BlackIs1:!!n.get("BlackIs1")}}get bytes(){return shadow(this,"bytes",this.stream.getBytes(this.maybeLength))}readBlock(){this.decodeImageFallback()}get isImageStream(){return!0}get isAsyncDecoder(){return!0}async decodeImage(e,t,n){if(this.eof)return this.buffer;e||(e=this.stream.isAsync&&await this.stream.asyncGetBytes()||this.bytes);try{this.buffer=await JBig2CCITTFaxWasmImage.decode(e,this.dict.get("W","Width"),this.dict.get("H","Height"),null,this.params)}catch{warn("CCITTFaxStream: Falling back to JS CCITTFax decoder.");return this.decodeImageFallback(e,t)}this.bufferLength=this.buffer.length;this.eof=!0;return this.buffer}decodeImageFallback(e,t){if(this.eof)return this.buffer;const{params:n}=this;if(!e){this.stream.reset();e=this.bytes}let a=0;const s={next:()=>e[a++]??-1};t&&this.buffer.byteLength<t&&(this.buffer=new Uint8Array(t));this.ccittFaxDecoder=new CCITTFaxDecoder(s,n);let r=0;for(;!this.eof;){const e=this.ccittFaxDecoder.readNextChar();if(-1===e){this.eof=!0;break}t||this.ensureBuffer(r+1);this.buffer[r++]=e}this.bufferLength=this.buffer.length;return this.buffer.subarray(0,t||this.bufferLength)}}const Gn=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Vn=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),$n=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),Yn=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],Jn=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];class FlateStream extends DecodeStream{#L=!0;constructor(e,t){super(t);this.stream=e;this.dict=e.dict;const n=e.getByte(),a=e.getByte();if(-1===n||-1===a)throw new FormatError(`Invalid header in flate stream: ${n}, ${a}`);if(8!=(15&n))throw new FormatError(`Unknown compression method in flate stream: ${n}, ${a}`);if(((n<<8)+a)%31!=0)throw new FormatError(`Bad FCHECK in flate stream: ${n}, ${a}`);if(32&a)throw new FormatError(`FDICT bit set in flate stream: ${n}, ${a}`);this.codeSize=0;this.codeBuf=0}async getImageData(e,t){const n=await this.asyncGetBytes();return n?n.length<=e?n:n.subarray(0,e):this.getBytes(e)}async asyncGetBytes(){const{decompressed:e,compressed:t}=await this.asyncGetBytesFromDecompressionStream("deflate");if(e)return e;this.#L=!1;this.stream=new Stream(t,2,t.length,this.stream.dict);this.reset();return null}get isAsync(){return this.#L}getBits(e){const t=this.stream;let n,a=this.codeSize,s=this.codeBuf;for(;a<e;){if(-1===(n=t.getByte()))throw new FormatError("Bad encoding in flate stream");s|=n<<a;a+=8}n=s&(1<<e)-1;this.codeBuf=s>>e;this.codeSize=a-=e;return n}getCode(e){const t=this.stream,n=e[0],a=e[1];let s,r=this.codeSize,i=this.codeBuf;for(;r<a&&-1!==(s=t.getByte());){i|=s<<r;r+=8}const o=n[i&(1<<a)-1],l=o>>16,f=65535&o;if(l<1||r<l)throw new FormatError("Bad encoding in flate stream");this.codeBuf=i>>l;this.codeSize=r-l;return f}generateHuffmanTable(e){const t=e.length;let n,a=0;for(n=0;n<t;++n)e[n]>a&&(a=e[n]);const s=1<<a,r=new Int32Array(s);for(let i=1,o=0,l=2;i<=a;++i,o<<=1,l<<=1)for(let a=0;a<t;++a)if(e[a]===i){let e=0,t=o;for(n=0;n<i;++n){e=e<<1|1&t;t>>=1}for(n=e;n<s;n+=l)r[n]=i<<16|a;++o}return[r,a]}#U(e){info(e);this.eof=!0}readBlock(){let e,t,n;const a=this.stream;try{t=this.getBits(3)}catch(e){this.#U(e.message);return}1&t&&(this.eof=!0);t>>=1;if(0===t){let t;if(-1===(t=a.getByte())){this.#U("Bad block header in flate stream");return}let n=t;if(-1===(t=a.getByte())){this.#U("Bad block header in flate stream");return}n|=t<<8;if(-1===(t=a.getByte())){this.#U("Bad block header in flate stream");return}let s=t;if(-1===(t=a.getByte())){this.#U("Bad block header in flate stream");return}s|=t<<8;if(s!==(65535&~n)&&(0!==n||0!==s))throw new FormatError("Bad uncompressed block length in flate stream");this.codeBuf=0;this.codeSize=0;const r=this.bufferLength,i=r+n;e=this.ensureBuffer(i);this.bufferLength=i;if(0===n)-1===a.peekByte()&&(this.eof=!0);else{const t=a.getBytes(n);e.set(t,r);t.length<n&&(this.eof=!0)}return}let s,r;if(1===t){s=Yn;r=Jn}else{if(2!==t)throw new FormatError("Unknown block type in flate stream");{const e=this.getBits(5)+257,t=this.getBits(5)+1,a=this.getBits(4)+4,i=new Uint8Array(Gn.length);let o;for(o=0;o<a;++o)i[Gn[o]]=this.getBits(3);const l=this.generateHuffmanTable(i);n=0;o=0;const f=e+t,c=new Uint8Array(f);let h,u,m;for(;o<f;){const e=this.getCode(l);if(16===e){h=2;u=3;m=n}else if(17===e){h=3;u=3;m=n=0}else{if(18!==e){c[o++]=n=e;continue}h=7;u=11;m=n=0}let t=this.getBits(h)+u;for(;t-- >0;)c[o++]=m}s=this.generateHuffmanTable(c.subarray(0,e));r=this.generateHuffmanTable(c.subarray(e,f))}}e=this.buffer;let i=e?e.length:0,o=this.bufferLength;for(;;){let t=this.getCode(s);if(t<256){if(o+1>=i){e=this.ensureBuffer(o+1);i=e.length}e[o++]=t;continue}if(256===t){this.bufferLength=o;return}t-=257;t=Vn[t];let a=t>>16;a>0&&(a=this.getBits(a));n=(65535&t)+a;t=this.getCode(r);t=$n[t];a=t>>16;a>0&&(a=this.getBits(a));const l=(65535&t)+a;if(o+n>=i){e=this.ensureBuffer(o+n);i=e.length}for(let t=0;t<n;++t,++o)e[o]=e[o-l]}}}const Qn=[{qe:22017,nmps:1,nlps:1,switchFlag:1},{qe:13313,nmps:2,nlps:6,switchFlag:0},{qe:6145,nmps:3,nlps:9,switchFlag:0},{qe:2753,nmps:4,nlps:12,switchFlag:0},{qe:1313,nmps:5,nlps:29,switchFlag:0},{qe:545,nmps:38,nlps:33,switchFlag:0},{qe:22017,nmps:7,nlps:6,switchFlag:1},{qe:21505,nmps:8,nlps:14,switchFlag:0},{qe:18433,nmps:9,nlps:14,switchFlag:0},{qe:14337,nmps:10,nlps:14,switchFlag:0},{qe:12289,nmps:11,nlps:17,switchFlag:0},{qe:9217,nmps:12,nlps:18,switchFlag:0},{qe:7169,nmps:13,nlps:20,switchFlag:0},{qe:5633,nmps:29,nlps:21,switchFlag:0},{qe:22017,nmps:15,nlps:14,switchFlag:1},{qe:21505,nmps:16,nlps:14,switchFlag:0},{qe:20737,nmps:17,nlps:15,switchFlag:0},{qe:18433,nmps:18,nlps:16,switchFlag:0},{qe:14337,nmps:19,nlps:17,switchFlag:0},{qe:13313,nmps:20,nlps:18,switchFlag:0},{qe:12289,nmps:21,nlps:19,switchFlag:0},{qe:10241,nmps:22,nlps:19,switchFlag:0},{qe:9217,nmps:23,nlps:20,switchFlag:0},{qe:8705,nmps:24,nlps:21,switchFlag:0},{qe:7169,nmps:25,nlps:22,switchFlag:0},{qe:6145,nmps:26,nlps:23,switchFlag:0},{qe:5633,nmps:27,nlps:24,switchFlag:0},{qe:5121,nmps:28,nlps:25,switchFlag:0},{qe:4609,nmps:29,nlps:26,switchFlag:0},{qe:4353,nmps:30,nlps:27,switchFlag:0},{qe:2753,nmps:31,nlps:28,switchFlag:0},{qe:2497,nmps:32,nlps:29,switchFlag:0},{qe:2209,nmps:33,nlps:30,switchFlag:0},{qe:1313,nmps:34,nlps:31,switchFlag:0},{qe:1089,nmps:35,nlps:32,switchFlag:0},{qe:673,nmps:36,nlps:33,switchFlag:0},{qe:545,nmps:37,nlps:34,switchFlag:0},{qe:321,nmps:38,nlps:35,switchFlag:0},{qe:273,nmps:39,nlps:36,switchFlag:0},{qe:133,nmps:40,nlps:37,switchFlag:0},{qe:73,nmps:41,nlps:38,switchFlag:0},{qe:37,nmps:42,nlps:39,switchFlag:0},{qe:21,nmps:43,nlps:40,switchFlag:0},{qe:9,nmps:44,nlps:41,switchFlag:0},{qe:5,nmps:45,nlps:42,switchFlag:0},{qe:1,nmps:45,nlps:43,switchFlag:0},{qe:22017,nmps:46,nlps:46,switchFlag:0}];class ArithmeticDecoder{constructor(e,t,n){this.data=e;this.bp=t;this.dataEnd=n;this.chigh=e[t];this.clow=0;this.byteIn();this.chigh=this.chigh<<7&65535|this.clow>>9&127;this.clow=this.clow<<7&65535;this.ct-=7;this.a=32768}byteIn(){const e=this.data;let t=this.bp;if(255===e[t])if(e[t+1]>143){this.clow+=65280;this.ct=8}else{t++;this.clow+=e[t]<<9;this.ct=7;this.bp=t}else{t++;this.clow+=t<this.dataEnd?e[t]<<8:65280;this.ct=8;this.bp=t}if(this.clow>65535){this.chigh+=this.clow>>16;this.clow&=65535}}readBit(e,t){let n=e[t]>>1,a=1&e[t];const s=Qn[n],r=s.qe;let i,o=this.a-r;if(this.chigh<r)if(o<r){o=r;i=a;n=s.nmps}else{o=r;i=1^a;1===s.switchFlag&&(a=i);n=s.nlps}else{this.chigh-=r;if(32768&o){this.a=o;return a}if(o<r){i=1^a;1===s.switchFlag&&(a=i);n=s.nlps}else{i=a;n=s.nmps}}do{0===this.ct&&this.byteIn();o<<=1;this.chigh=this.chigh<<1&65535|this.clow>>15&1;this.clow=this.clow<<1&65535;this.ct--}while(!(32768&o));this.a=o;e[t]=n<<1|a;return i}}class Jbig2Error extends en{constructor(e){super(e,"Jbig2Error")}}class ContextCache{getContexts(e){return e in this?this[e]:this[e]=new Int8Array(65536)}}class DecodingContext{constructor(e,t,n){this.data=e;this.start=t;this.end=n}get decoder(){return shadow(this,"decoder",new ArithmeticDecoder(this.data,this.start,this.end))}get contextCache(){return shadow(this,"contextCache",new ContextCache)}}function decodeInteger(e,t,n){const a=e.getContexts(t);let s=1;function readBits(e){let t=0;for(let r=0;r<e;r++){const e=n.readBit(a,s);s=s<256?s<<1|e:511&(s<<1|e)|256;t=t<<1|e}return t>>>0}const r=readBits(1),i=readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(32)+4436:readBits(12)+340:readBits(8)+84:readBits(6)+20:readBits(4)+4:readBits(2);let o;0===r?o=i:i>0&&(o=-i);return o>=-2147483648&&o<=mn?o:null}function decodeIAID(e,t,n){const a=e.getContexts("IAID");let s=1;for(let e=0;e<n;e++){s=s<<1|t.readBit(a,s)}return n<31?s&(1<<n)-1:2147483647&s}const Zn=["SymbolDictionary",null,null,null,"IntermediateTextRegion",null,"ImmediateTextRegion","ImmediateLosslessTextRegion",null,null,null,null,null,null,null,null,"PatternDictionary",null,null,null,"IntermediateHalftoneRegion",null,"ImmediateHalftoneRegion","ImmediateLosslessHalftoneRegion",null,null,null,null,null,null,null,null,null,null,null,null,"IntermediateGenericRegion",null,"ImmediateGenericRegion","ImmediateLosslessGenericRegion","IntermediateGenericRefinementRegion",null,"ImmediateGenericRefinementRegion","ImmediateLosslessGenericRefinementRegion",null,null,null,null,"PageInformation","EndOfPage","EndOfStripe","EndOfFile","Profiles","Tables",null,null,null,null,null,null,null,null,"Extension"],ea=[[{x:-1,y:-2},{x:0,y:-2},{x:1,y:-2},{x:-2,y:-1},{x:-1,y:-1},{x:0,y:-1},{x:1,y:-1},{x:2,y:-1},{x:-4,y:0},{x:-3,y:0},{x:-2,y:0},{x:-1,y:0}],[{x:-1,y:-2},{x:0,y:-2},{x:1,y:-2},{x:2,y:-2},{x:-2,y:-1},{x:-1,y:-1},{x:0,y:-1},{x:1,y:-1},{x:2,y:-1},{x:-3,y:0},{x:-2,y:0},{x:-1,y:0}],[{x:-1,y:-2},{x:0,y:-2},{x:1,y:-2},{x:-2,y:-1},{x:-1,y:-1},{x:0,y:-1},{x:1,y:-1},{x:-2,y:0},{x:-1,y:0}],[{x:-3,y:-1},{x:-2,y:-1},{x:-1,y:-1},{x:0,y:-1},{x:1,y:-1},{x:-4,y:0},{x:-3,y:0},{x:-2,y:0},{x:-1,y:0}]],ta=[{coding:[{x:0,y:-1},{x:1,y:-1},{x:-1,y:0}],reference:[{x:0,y:-1},{x:1,y:-1},{x:-1,y:0},{x:0,y:0},{x:1,y:0},{x:-1,y:1},{x:0,y:1},{x:1,y:1}]},{coding:[{x:-1,y:-1},{x:0,y:-1},{x:1,y:-1},{x:-1,y:0}],reference:[{x:0,y:-1},{x:-1,y:0},{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}]}],na=[39717,1941,229,405],aa=[32,8];function decodeBitmap(e,t,n,a,s,r,i,o){if(e){return decodeMMRBitmap(new Reader(o.data,o.start,o.end),t,n,!1)}if(0===a&&!r&&!s&&4===i.length&&3===i[0].x&&-1===i[0].y&&-3===i[1].x&&-1===i[1].y&&2===i[2].x&&-2===i[2].y&&-2===i[3].x&&-2===i[3].y)return function decodeBitmapTemplate0(e,t,n){const a=n.decoder,s=n.contextCache.getContexts("GB"),r=[];let i,o,l,f,c,h,u;for(o=0;o<t;o++){c=r[o]=new Uint8Array(e);h=o<1?c:r[o-1];u=o<2?c:r[o-2];i=u[0]<<13|u[1]<<12|u[2]<<11|h[0]<<7|h[1]<<6|h[2]<<5|h[3]<<4;for(l=0;l<e;l++){c[l]=f=a.readBit(s,i);i=(31735&i)<<1|(l+3<e?u[l+3]<<11:0)|(l+4<e?h[l+4]<<4:0)|f}}return r}(t,n,o);const l=!!r,f=ea[a].concat(i);f.sort((e,t)=>e.y-t.y||e.x-t.x);const c=f.length,h=new Int8Array(c),u=new Int8Array(c),m=[];let p,d,g=0,b=0,w=0,j=0;for(d=0;d<c;d++){h[d]=f[d].x;u[d]=f[d].y;b=Math.min(b,f[d].x);w=Math.max(w,f[d].x);j=Math.min(j,f[d].y);d<c-1&&f[d].y===f[d+1].y&&f[d].x===f[d+1].x-1?g|=1<<c-1-d:m.push(d)}const k=m.length,y=new Int8Array(k),q=new Int8Array(k),v=new Uint16Array(k);for(p=0;p<k;p++){d=m[p];y[p]=f[d].x;q[p]=f[d].y;v[p]=1<<c-1-d}const S=-b,x=-j,C=t-w,F=na[a];let T=new Uint8Array(t);const H=[],O=o.decoder,R=o.contextCache.getContexts("GB");let D,M,E,N,z,L=0,U=0;for(let e=0;e<n;e++){if(s){L^=O.readBit(R,F);if(L){H.push(T);continue}}T=new Uint8Array(T);H.push(T);for(D=0;D<t;D++){if(l&&r[e][D]){T[D]=0;continue}if(D>=S&&D<C&&e>=x){U=U<<1&g;for(d=0;d<k;d++){M=e+q[d];E=D+y[d];N=H[M][E];if(N){N=v[d];U|=N}}}else{U=0;z=c-1;for(d=0;d<c;d++,z--){E=D+h[d];if(E>=0&&E<t){M=e+u[d];if(M>=0){N=H[M][E];N&&(U|=N<<z)}}}}const n=O.readBit(R,U);T[D]=n}}return H}function decodeRefinement(e,t,n,a,s,r,i,o,l){let f=ta[n].coding;0===n&&(f=f.concat([o[0]]));const c=f.length,h=new Int32Array(c),u=new Int32Array(c);let m;for(m=0;m<c;m++){h[m]=f[m].x;u[m]=f[m].y}let p=ta[n].reference;0===n&&(p=p.concat([o[1]]));const d=p.length,g=new Int32Array(d),b=new Int32Array(d);for(m=0;m<d;m++){g[m]=p[m].x;b[m]=p[m].y}const w=a[0].length,j=a.length,k=aa[n],y=[],q=l.decoder,v=l.contextCache.getContexts("GR");let S=0;for(let n=0;n<t;n++){if(i){S^=q.readBit(v,k);if(S)throw new Jbig2Error("prediction is not supported")}const t=new Uint8Array(e);y.push(t);for(let i=0;i<e;i++){let o,l,f=0;for(m=0;m<c;m++){o=n+u[m];l=i+h[m];o<0||l<0||l>=e?f<<=1:f=f<<1|y[o][l]}for(m=0;m<d;m++){o=n+b[m]-r;l=i+g[m]-s;o<0||o>=j||l<0||l>=w?f<<=1:f=f<<1|a[o][l]}const p=q.readBit(v,f);t[i]=p}}return y}function decodeTextRegion(e,t,n,a,s,r,i,o,l,f,c,h,u,m,p,d,g,b,w){if(e&&t)throw new Jbig2Error("refinement with Huffman is not supported");const j=[];let k,y;for(k=0;k<a;k++){y=new Uint8Array(n);s&&y.fill(s);j.push(y)}const q=g.decoder,v=g.contextCache;let S=e?-m.tableDeltaT.decode(w):-decodeInteger(v,"IADT",q),x=0;k=0;for(;k<r;){S+=e?m.tableDeltaT.decode(w):decodeInteger(v,"IADT",q);x+=e?m.tableFirstS.decode(w):decodeInteger(v,"IAFS",q);let a=x;for(;;){let s=0;i>1&&(s=e?w.readBits(b):decodeInteger(v,"IAIT",q));const r=i*S+s,x=e?m.symbolIDTable.decode(w):decodeIAID(v,q,l),C=t&&(e?w.readBit():decodeInteger(v,"IARI",q));let F=o[x],T=F[0].length,H=F.length;if(C){const e=decodeInteger(v,"IARDW",q),t=decodeInteger(v,"IARDH",q);T+=e;H+=t;F=decodeRefinement(T,H,p,F,(e>>1)+decodeInteger(v,"IARDX",q),(t>>1)+decodeInteger(v,"IARDY",q),!1,d,g)}let O=0;f?1&h?O=H-1:a+=H-1:h>1?a+=T-1:O=T-1;const R=r-(1&h?0:H-1),D=a-(2&h?T-1:0);let M,E,N;if(f)for(M=0;M<H;M++){y=j[D+M];if(!y)continue;N=F[M];const e=Math.min(n-R,T);switch(u){case 0:for(E=0;E<e;E++)y[R+E]|=N[E];break;case 2:for(E=0;E<e;E++)y[R+E]^=N[E];break;default:throw new Jbig2Error(`operator ${u} is not supported`)}}else for(E=0;E<H;E++){y=j[R+E];if(y){N=F[E];switch(u){case 0:for(M=0;M<T;M++)y[D+M]|=N[M];break;case 2:for(M=0;M<T;M++)y[D+M]^=N[M];break;default:throw new Jbig2Error(`operator ${u} is not supported`)}}}k++;const z=e?m.tableDeltaS.decode(w):decodeInteger(v,"IADS",q);if(null===z)break;a+=O+z+c}}return j}function readSegmentHeader(e,t){const n={};n.number=readUint32(e,t);const a=e[t+4],s=63&a;if(!Zn[s])throw new Jbig2Error("invalid segment type: "+s);n.type=s;n.typeName=Zn[s];n.deferredNonRetain=!!(128&a);const r=!!(64&a),i=e[t+5];let o=i>>5&7;const l=[31&i];let f=t+6;if(7===o){o=536870911&readUint32(e,f-1);f+=3;let t=o+8>>3;l[0]=e[f++];for(;--t>0;)l.push(e[f++])}else if(5===o||6===o)throw new Jbig2Error("invalid referred-to flags");n.retainBits=l;let c=4;n.number<=256?c=1:n.number<=65536&&(c=2);const h=[];let u,m;for(u=0;u<o;u++){let t;t=1===c?e[f]:2===c?readUint16(e,f):readUint32(e,f);h.push(t);f+=c}n.referredTo=h;if(r){n.pageAssociation=readUint32(e,f);f+=4}else n.pageAssociation=e[f++];n.length=readUint32(e,f);f+=4;if(4294967295===n.length){if(38!==s)throw new Jbig2Error("invalid unknown segment length");{const t=readRegionSegmentInformation(e,f),a=!!(1&e[f+sa]),s=6,r=new Uint8Array(s);if(!a){r[0]=255;r[1]=172}r[2]=t.height>>>24&255;r[3]=t.height>>16&255;r[4]=t.height>>8&255;r[5]=255&t.height;for(u=f,m=e.length;u<m;u++){let t=0;for(;t<s&&r[t]===e[u+t];)t++;if(t===s){n.length=u+s;break}}if(4294967295===n.length)throw new Jbig2Error("segment end was not found")}}n.headerEnd=f;return n}function readSegments(e,t,n,a){const s=[];let r=n;for(;r<a;){const n=readSegmentHeader(t,r);r=n.headerEnd;const a={header:n,data:t};if(!e.randomAccess){a.start=r;r+=n.length;a.end=r}s.push(a);if(51===n.type)break}if(e.randomAccess)for(let e=0,t=s.length;e<t;e++){s[e].start=r;r+=s[e].header.length;s[e].end=r}return s}function readRegionSegmentInformation(e,t){return{width:readUint32(e,t),height:readUint32(e,t+4),x:readUint32(e,t+8),y:readUint32(e,t+12),combinationOperator:7&e[t+16]}}const sa=17;function processSegment(e,t){const n=e.header,a=e.data,s=e.end;let r,i,o,l,f=e.start;switch(n.type){case 0:const e={},t=readUint16(a,f);e.huffman=!!(1&t);e.refinement=!!(2&t);e.huffmanDHSelector=t>>2&3;e.huffmanDWSelector=t>>4&3;e.bitmapSizeSelector=t>>6&1;e.aggregationInstancesSelector=t>>7&1;e.bitmapCodingContextUsed=!!(256&t);e.bitmapCodingContextRetained=!!(512&t);e.template=t>>10&3;e.refinementTemplate=t>>12&1;f+=2;if(!e.huffman){l=0===e.template?4:1;i=[];for(o=0;o<l;o++){i.push({x:readInt8(a,f),y:readInt8(a,f+1)});f+=2}e.at=i}if(e.refinement&&!e.refinementTemplate){i=[];for(o=0;o<2;o++){i.push({x:readInt8(a,f),y:readInt8(a,f+1)});f+=2}e.refinementAt=i}e.numberOfExportedSymbols=readUint32(a,f);f+=4;e.numberOfNewSymbols=readUint32(a,f);f+=4;r=[e,n.number,n.referredTo,a,f,s];break;case 6:case 7:const c={};c.info=readRegionSegmentInformation(a,f);f+=sa;const h=readUint16(a,f);f+=2;c.huffman=!!(1&h);c.refinement=!!(2&h);c.logStripSize=h>>2&3;c.stripSize=1<<c.logStripSize;c.referenceCorner=h>>4&3;c.transposed=!!(64&h);c.combinationOperator=h>>7&3;c.defaultPixelValue=h>>9&1;c.dsOffset=h<<17>>27;c.refinementTemplate=h>>15&1;if(c.huffman){const e=readUint16(a,f);f+=2;c.huffmanFS=3&e;c.huffmanDS=e>>2&3;c.huffmanDT=e>>4&3;c.huffmanRefinementDW=e>>6&3;c.huffmanRefinementDH=e>>8&3;c.huffmanRefinementDX=e>>10&3;c.huffmanRefinementDY=e>>12&3;c.huffmanRefinementSizeSelector=!!(16384&e)}if(c.refinement&&!c.refinementTemplate){i=[];for(o=0;o<2;o++){i.push({x:readInt8(a,f),y:readInt8(a,f+1)});f+=2}c.refinementAt=i}c.numberOfSymbolInstances=readUint32(a,f);f+=4;r=[c,n.referredTo,a,f,s];break;case 16:const u={},m=a[f++];u.mmr=!!(1&m);u.template=m>>1&3;u.patternWidth=a[f++];u.patternHeight=a[f++];u.maxPatternIndex=readUint32(a,f);f+=4;r=[u,n.number,a,f,s];break;case 22:case 23:const p={};p.info=readRegionSegmentInformation(a,f);f+=sa;const d=a[f++];p.mmr=!!(1&d);p.template=d>>1&3;p.enableSkip=!!(8&d);p.combinationOperator=d>>4&7;p.defaultPixelValue=d>>7&1;p.gridWidth=readUint32(a,f);f+=4;p.gridHeight=readUint32(a,f);f+=4;p.gridOffsetX=4294967295&readUint32(a,f);f+=4;p.gridOffsetY=4294967295&readUint32(a,f);f+=4;p.gridVectorX=readUint16(a,f);f+=2;p.gridVectorY=readUint16(a,f);f+=2;r=[p,n.referredTo,a,f,s];break;case 38:case 39:const g={};g.info=readRegionSegmentInformation(a,f);f+=sa;const b=a[f++];g.mmr=!!(1&b);g.template=b>>1&3;g.prediction=!!(8&b);if(!g.mmr){l=0===g.template?4:1;i=[];for(o=0;o<l;o++){i.push({x:readInt8(a,f),y:readInt8(a,f+1)});f+=2}g.at=i}r=[g,a,f,s];break;case 48:const w={width:readUint32(a,f),height:readUint32(a,f+4),resolutionX:readUint32(a,f+8),resolutionY:readUint32(a,f+12)};4294967295===w.height&&delete w.height;const j=a[f+16];readUint16(a,f+17);w.lossless=!!(1&j);w.refinement=!!(2&j);w.defaultPixelValue=j>>2&1;w.combinationOperator=j>>3&3;w.requiresBuffer=!!(32&j);w.combinationOperatorOverride=!!(64&j);r=[w];break;case 49:case 50:case 51:case 62:break;case 53:r=[n.number,a,f,s];break;default:throw new Jbig2Error(`segment type ${n.typeName}(${n.type}) is not implemented`)}const c="on"+n.typeName;c in t&&t[c].apply(t,r)}function processSegments(e,t){for(let n=0,a=e.length;n<a;n++)processSegment(e[n],t)}class SimpleSegmentVisitor{onPageInformation(e){this.currentPageInfo=e;const t=e.width+7>>3,n=new Uint8ClampedArray(t*e.height);e.defaultPixelValue&&n.fill(255);this.buffer=n}drawBitmap(e,t){const n=this.currentPageInfo,a=e.width,s=e.height,r=n.width+7>>3,i=n.combinationOperatorOverride?e.combinationOperator:n.combinationOperator,o=this.buffer,l=128>>(7&e.x);let f,c,h,u,m=e.y*r+(e.x>>3);switch(i){case 0:for(f=0;f<s;f++){h=l;u=m;for(c=0;c<a;c++){t[f][c]&&(o[u]|=h);h>>=1;if(!h){h=128;u++}}m+=r}break;case 2:for(f=0;f<s;f++){h=l;u=m;for(c=0;c<a;c++){t[f][c]&&(o[u]^=h);h>>=1;if(!h){h=128;u++}}m+=r}break;default:throw new Jbig2Error(`operator ${i} is not supported`)}}onImmediateGenericRegion(e,t,n,a){const s=e.info,r=new DecodingContext(t,n,a),i=decodeBitmap(e.mmr,s.width,s.height,e.template,e.prediction,null,e.at,r);this.drawBitmap(s,i)}onImmediateLosslessGenericRegion(){this.onImmediateGenericRegion(...arguments)}onSymbolDictionary(e,t,n,a,s,r){let i,o;if(e.huffman){i=function getSymbolDictionaryHuffmanTables(e,t,n){let a,s,r,i,o=0;switch(e.huffmanDHSelector){case 0:case 1:a=getStandardTable(e.huffmanDHSelector+4);break;case 3:a=getCustomHuffmanTable(o,t,n);o++;break;default:throw new Jbig2Error("invalid Huffman DH selector")}switch(e.huffmanDWSelector){case 0:case 1:s=getStandardTable(e.huffmanDWSelector+2);break;case 3:s=getCustomHuffmanTable(o,t,n);o++;break;default:throw new Jbig2Error("invalid Huffman DW selector")}if(e.bitmapSizeSelector){r=getCustomHuffmanTable(o,t,n);o++}else r=getStandardTable(1);i=e.aggregationInstancesSelector?getCustomHuffmanTable(o,t,n):getStandardTable(1);return{tableDeltaHeight:a,tableDeltaWidth:s,tableBitmapSize:r,tableAggregateInstances:i}}(e,n,this.customTables);o=new Reader(a,s,r)}let l=this.symbols;l||(this.symbols=l={});const f=[];for(const e of n){const t=l[e];t&&f.push(...t)}const c=new DecodingContext(a,s,r);l[t]=function decodeSymbolDictionary(e,t,n,a,s,r,i,o,l,f,c,h){if(e&&t)throw new Jbig2Error("symbol refinement with Huffman is not supported");const u=[];let m=0,p=log2(n.length+a);const d=c.decoder,g=c.contextCache;let b,w;if(e){b=getStandardTable(1);w=[];p=Math.max(p,1)}for(;u.length<a;){m+=e?r.tableDeltaHeight.decode(h):decodeInteger(g,"IADH",d);let a=0,s=0;const b=e?w.length:0;for(;;){const b=e?r.tableDeltaWidth.decode(h):decodeInteger(g,"IADW",d);if(null===b)break;a+=b;s+=a;let j;if(t){const s=decodeInteger(g,"IAAI",d);if(s>1)j=decodeTextRegion(e,t,a,m,0,s,1,n.concat(u),p,0,0,1,0,r,l,f,c,0,h);else{const e=decodeIAID(g,d,p),t=decodeInteger(g,"IARDX",d),s=decodeInteger(g,"IARDY",d);j=decodeRefinement(a,m,l,e<n.length?n[e]:u[e-n.length],t,s,!1,f,c)}u.push(j)}else if(e)w.push(a);else{j=decodeBitmap(!1,a,m,i,!1,null,o,c);u.push(j)}}if(e&&!t){const e=r.tableBitmapSize.decode(h);h.byteAlign();let t;if(0===e)t=readUncompressedBitmap(h,s,m);else{const n=h.end,a=h.position+e;h.end=a;t=decodeMMRBitmap(h,s,m,!1);h.end=n;h.position=a}const n=w.length;if(b===n-1)u.push(t);else{let e,a,s,r,i,o=0;for(e=b;e<n;e++){r=w[e];s=o+r;i=[];for(a=0;a<m;a++)i.push(t[a].subarray(o,s));u.push(i);o=s}}}}const j=[],k=[];let y,q,v=!1;const S=n.length+a;for(;k.length<S;){let t=e?b.decode(h):decodeInteger(g,"IAEX",d);for(;t--;)k.push(v);v=!v}for(y=0,q=n.length;y<q;y++)k[y]&&j.push(n[y]);for(let e=0;e<a;y++,e++)k[y]&&j.push(u[e]);return j}(e.huffman,e.refinement,f,e.numberOfNewSymbols,e.numberOfExportedSymbols,i,e.template,e.at,e.refinementTemplate,e.refinementAt,c,o)}onImmediateTextRegion(e,t,n,a,s){const r=e.info;let i,o;const l=this.symbols,f=[];for(const e of t){const t=l[e];t&&f.push(...t)}const c=log2(f.length);if(e.huffman){o=new Reader(n,a,s);i=function getTextRegionHuffmanTables(e,t,n,a,s){const r=[];for(let e=0;e<=34;e++){const t=s.readBits(4);r.push(new HuffmanLine([e,t,0,0]))}const i=new HuffmanTable(r,!1);r.length=0;for(let e=0;e<a;){const t=i.decode(s);if(t>=32){let n,a,i;switch(t){case 32:if(0===e)throw new Jbig2Error("no previous value in symbol ID table");a=s.readBits(2)+3;n=r[e-1].prefixLength;break;case 33:a=s.readBits(3)+3;n=0;break;case 34:a=s.readBits(7)+11;n=0;break;default:throw new Jbig2Error("invalid code length in symbol ID table")}for(i=0;i<a;i++){r.push(new HuffmanLine([e,n,0,0]));e++}}else{r.push(new HuffmanLine([e,t,0,0]));e++}}s.byteAlign();const o=new HuffmanTable(r,!1);let l,f,c,h=0;switch(e.huffmanFS){case 0:case 1:l=getStandardTable(e.huffmanFS+6);break;case 3:l=getCustomHuffmanTable(h,t,n);h++;break;default:throw new Jbig2Error("invalid Huffman FS selector")}switch(e.huffmanDS){case 0:case 1:case 2:f=getStandardTable(e.huffmanDS+8);break;case 3:f=getCustomHuffmanTable(h,t,n);h++;break;default:throw new Jbig2Error("invalid Huffman DS selector")}switch(e.huffmanDT){case 0:case 1:case 2:c=getStandardTable(e.huffmanDT+11);break;case 3:c=getCustomHuffmanTable(h,t,n);h++;break;default:throw new Jbig2Error("invalid Huffman DT selector")}if(e.refinement)throw new Jbig2Error("refinement with Huffman is not supported");return{symbolIDTable:o,tableFirstS:l,tableDeltaS:f,tableDeltaT:c}}(e,t,this.customTables,f.length,o)}const h=new DecodingContext(n,a,s),u=decodeTextRegion(e.huffman,e.refinement,r.width,r.height,e.defaultPixelValue,e.numberOfSymbolInstances,e.stripSize,f,c,e.transposed,e.dsOffset,e.referenceCorner,e.combinationOperator,i,e.refinementTemplate,e.refinementAt,h,e.logStripSize,o);this.drawBitmap(r,u)}onImmediateLosslessTextRegion(){this.onImmediateTextRegion(...arguments)}onPatternDictionary(e,t,n,a,s){let r=this.patterns;r||(this.patterns=r={});const i=new DecodingContext(n,a,s);r[t]=function decodePatternDictionary(e,t,n,a,s,r){const i=[];if(!e){i.push({x:-t,y:0});0===s&&i.push({x:-3,y:-1},{x:2,y:-2},{x:-2,y:-2})}const o=decodeBitmap(e,(a+1)*t,n,s,!1,null,i,r),l=[];for(let e=0;e<=a;e++){const a=[],s=t*e,r=s+t;for(let e=0;e<n;e++)a.push(o[e].subarray(s,r));l.push(a)}return l}(e.mmr,e.patternWidth,e.patternHeight,e.maxPatternIndex,e.template,i)}onImmediateHalftoneRegion(e,t,n,a,s){const r=this.patterns[t[0]],i=e.info,o=new DecodingContext(n,a,s),l=function decodeHalftoneRegion(e,t,n,a,s,r,i,o,l,f,c,h,u,m,p){if(i)throw new Jbig2Error("skip is not supported");if(0!==o)throw new Jbig2Error(`operator "${o}" is not supported in halftone region`);const d=[];let g,b,w;for(g=0;g<s;g++){w=new Uint8Array(a);r&&w.fill(r);d.push(w)}const j=t.length,k=t[0],y=k[0].length,q=k.length,v=log2(j),S=[];if(!e){S.push({x:n<=1?3:2,y:-1});0===n&&S.push({x:-3,y:-1},{x:2,y:-2},{x:-2,y:-2})}const x=[];let C,F,T,H,O,R,D,M,E,N,z;e&&(C=new Reader(p.data,p.start,p.end));for(g=v-1;g>=0;g--){F=e?decodeMMRBitmap(C,l,f,!0):decodeBitmap(!1,l,f,n,!1,null,S,p);x[g]=F}for(T=0;T<f;T++)for(H=0;H<l;H++){O=0;R=0;for(b=v-1;b>=0;b--){O^=x[b][T][H];R|=O<<b}D=t[R];M=c+T*m+H*u>>8;E=h+T*u-H*m>>8;if(M>=0&&M+y<=a&&E>=0&&E+q<=s)for(g=0;g<q;g++){z=d[E+g];N=D[g];for(b=0;b<y;b++)z[M+b]|=N[b]}else{let e,t;for(g=0;g<q;g++){t=E+g;if(!(t<0||t>=s)){z=d[t];N=D[g];for(b=0;b<y;b++){e=M+b;e>=0&&e<a&&(z[e]|=N[b])}}}}}return d}(e.mmr,r,e.template,i.width,i.height,e.defaultPixelValue,e.enableSkip,e.combinationOperator,e.gridWidth,e.gridHeight,e.gridOffsetX,e.gridOffsetY,e.gridVectorX,e.gridVectorY,o);this.drawBitmap(i,l)}onImmediateLosslessHalftoneRegion(){this.onImmediateHalftoneRegion(...arguments)}onTables(e,t,n,a){let s=this.customTables;s||(this.customTables=s={});s[e]=function decodeTablesSegment(e,t,n){const a=e[t],s=4294967295&readUint32(e,t+1),r=4294967295&readUint32(e,t+5),i=new Reader(e,t+9,n),o=1+(a>>1&7),l=1+(a>>4&7),f=[];let c,h,u=s;do{c=i.readBits(o);h=i.readBits(l);f.push(new HuffmanLine([u,c,h,0]));u+=1<<h}while(u<r);c=i.readBits(o);f.push(new HuffmanLine([s-1,c,32,0,"lower"]));c=i.readBits(o);f.push(new HuffmanLine([r,c,32,0]));if(1&a){c=i.readBits(o);f.push(new HuffmanLine([c,0]))}return new HuffmanTable(f,!1)}(t,n,a)}}class HuffmanLine{constructor(e){if(2===e.length){this.isOOB=!0;this.rangeLow=0;this.prefixLength=e[0];this.rangeLength=0;this.prefixCode=e[1];this.isLowerRange=!1}else{this.isOOB=!1;this.rangeLow=e[0];this.prefixLength=e[1];this.rangeLength=e[2];this.prefixCode=e[3];this.isLowerRange="lower"===e[4]}}}class HuffmanTreeNode{constructor(e){this.children=[];if(e){this.isLeaf=!0;this.rangeLength=e.rangeLength;this.rangeLow=e.rangeLow;this.isLowerRange=e.isLowerRange;this.isOOB=e.isOOB}else this.isLeaf=!1}buildTree(e,t){const n=e.prefixCode>>t&1;if(t<=0)this.children[n]=new HuffmanTreeNode(e);else{let a=this.children[n];a||(this.children[n]=a=new HuffmanTreeNode(null));a.buildTree(e,t-1)}}decodeNode(e){if(this.isLeaf){if(this.isOOB)return null;const t=e.readBits(this.rangeLength);return this.rangeLow+(this.isLowerRange?-t:t)}const t=this.children[e.readBit()];if(!t)throw new Jbig2Error("invalid Huffman data");return t.decodeNode(e)}}class HuffmanTable{constructor(e,t){t||this.assignPrefixCodes(e);this.rootNode=new HuffmanTreeNode(null);for(let t=0,n=e.length;t<n;t++){const n=e[t];n.prefixLength>0&&this.rootNode.buildTree(n,n.prefixLength-1)}}decode(e){return this.rootNode.decodeNode(e)}assignPrefixCodes(e){const t=e.length;let n=0;for(let a=0;a<t;a++)n=Math.max(n,e[a].prefixLength);const a=new Uint32Array(n+1);for(let n=0;n<t;n++)a[e[n].prefixLength]++;let s,r,i,o=1,l=0;a[0]=0;for(;o<=n;){l=l+a[o-1]<<1;s=l;r=0;for(;r<t;){i=e[r];if(i.prefixLength===o){i.prefixCode=s;s++}r++}o++}}}const ra={};function getStandardTable(e){let t,n=ra[e];if(n)return n;switch(e){case 1:t=[[0,1,4,0],[16,2,8,2],[272,3,16,6],[65808,3,32,7]];break;case 2:t=[[0,1,0,0],[1,2,0,2],[2,3,0,6],[3,4,3,14],[11,5,6,30],[75,6,32,62],[6,63]];break;case 3:t=[[-256,8,8,254],[0,1,0,0],[1,2,0,2],[2,3,0,6],[3,4,3,14],[11,5,6,30],[-257,8,32,255,"lower"],[75,7,32,126],[6,62]];break;case 4:t=[[1,1,0,0],[2,2,0,2],[3,3,0,6],[4,4,3,14],[12,5,6,30],[76,5,32,31]];break;case 5:t=[[-255,7,8,126],[1,1,0,0],[2,2,0,2],[3,3,0,6],[4,4,3,14],[12,5,6,30],[-256,7,32,127,"lower"],[76,6,32,62]];break;case 6:t=[[-2048,5,10,28],[-1024,4,9,8],[-512,4,8,9],[-256,4,7,10],[-128,5,6,29],[-64,5,5,30],[-32,4,5,11],[0,2,7,0],[128,3,7,2],[256,3,8,3],[512,4,9,12],[1024,4,10,13],[-2049,6,32,62,"lower"],[2048,6,32,63]];break;case 7:t=[[-1024,4,9,8],[-512,3,8,0],[-256,4,7,9],[-128,5,6,26],[-64,5,5,27],[-32,4,5,10],[0,4,5,11],[32,5,5,28],[64,5,6,29],[128,4,7,12],[256,3,8,1],[512,3,9,2],[1024,3,10,3],[-1025,5,32,30,"lower"],[2048,5,32,31]];break;case 8:t=[[-15,8,3,252],[-7,9,1,508],[-5,8,1,253],[-3,9,0,509],[-2,7,0,124],[-1,4,0,10],[0,2,1,0],[2,5,0,26],[3,6,0,58],[4,3,4,4],[20,6,1,59],[22,4,4,11],[38,4,5,12],[70,5,6,27],[134,5,7,28],[262,6,7,60],[390,7,8,125],[646,6,10,61],[-16,9,32,510,"lower"],[1670,9,32,511],[2,1]];break;case 9:t=[[-31,8,4,252],[-15,9,2,508],[-11,8,2,253],[-7,9,1,509],[-5,7,1,124],[-3,4,1,10],[-1,3,1,2],[1,3,1,3],[3,5,1,26],[5,6,1,58],[7,3,5,4],[39,6,2,59],[43,4,5,11],[75,4,6,12],[139,5,7,27],[267,5,8,28],[523,6,8,60],[779,7,9,125],[1291,6,11,61],[-32,9,32,510,"lower"],[3339,9,32,511],[2,0]];break;case 10:t=[[-21,7,4,122],[-5,8,0,252],[-4,7,0,123],[-3,5,0,24],[-2,2,2,0],[2,5,0,25],[3,6,0,54],[4,7,0,124],[5,8,0,253],[6,2,6,1],[70,5,5,26],[102,6,5,55],[134,6,6,56],[198,6,7,57],[326,6,8,58],[582,6,9,59],[1094,6,10,60],[2118,7,11,125],[-22,8,32,254,"lower"],[4166,8,32,255],[2,2]];break;case 11:t=[[1,1,0,0],[2,2,1,2],[4,4,0,12],[5,4,1,13],[7,5,1,28],[9,5,2,29],[13,6,2,60],[17,7,2,122],[21,7,3,123],[29,7,4,124],[45,7,5,125],[77,7,6,126],[141,7,32,127]];break;case 12:t=[[1,1,0,0],[2,2,0,2],[3,3,1,6],[5,5,0,28],[6,5,1,29],[8,6,1,60],[10,7,0,122],[11,7,1,123],[13,7,2,124],[17,7,3,125],[25,7,4,126],[41,8,5,254],[73,8,32,255]];break;case 13:t=[[1,1,0,0],[2,3,0,4],[3,4,0,12],[4,5,0,28],[5,4,1,13],[7,3,3,5],[15,6,1,58],[17,6,2,59],[21,6,3,60],[29,6,4,61],[45,6,5,62],[77,7,6,126],[141,7,32,127]];break;case 14:t=[[-2,3,0,4],[-1,3,0,5],[0,1,0,0],[1,3,0,6],[2,3,0,7]];break;case 15:t=[[-24,7,4,124],[-8,6,2,60],[-4,5,1,28],[-2,4,0,12],[-1,3,0,4],[0,1,0,0],[1,3,0,5],[2,4,0,13],[3,5,1,29],[5,6,2,61],[9,7,4,125],[-25,7,32,126,"lower"],[25,7,32,127]];break;default:throw new Jbig2Error(`standard table B.${e} does not exist`)}for(let e=0,n=t.length;e<n;e++)t[e]=new HuffmanLine(t[e]);n=new HuffmanTable(t,!0);ra[e]=n;return n}class Reader{constructor(e,t,n){this.data=e;this.start=t;this.end=n;this.position=t;this.shift=-1;this.currentByte=0}readBit(){if(this.shift<0){if(this.position>=this.end)throw new Jbig2Error("end of data while reading bit");this.currentByte=this.data[this.position++];this.shift=7}const e=this.currentByte>>this.shift&1;this.shift--;return e}readBits(e){let t,n=0;for(t=e-1;t>=0;t--)n|=this.readBit()<<t;return n}byteAlign(){this.shift=-1}next(){return this.position>=this.end?-1:this.data[this.position++]}}function getCustomHuffmanTable(e,t,n){let a=0;for(let s=0,r=t.length;s<r;s++){const r=n[t[s]];if(r){if(e===a)return r;a++}}throw new Jbig2Error("can't find custom Huffman table")}function readUncompressedBitmap(e,t,n){const a=[];for(let s=0;s<n;s++){const n=new Uint8Array(t);a.push(n);for(let a=0;a<t;a++)n[a]=e.readBit();e.byteAlign()}return a}function decodeMMRBitmap(e,t,n,a){const s=new CCITTFaxDecoder(e,{K:-1,Columns:t,Rows:n,BlackIs1:!0,EndOfBlock:a}),r=[];let i,o=!1;for(let e=0;e<n;e++){const e=new Uint8Array(t);r.push(e);let n=-1;for(let a=0;a<t;a++){if(n<0){i=s.readNextChar();if(-1===i){i=0;o=!0}n=7}e[a]=i>>n&1;n--}}if(a&&!o){const e=5;for(let t=0;t<e&&-1!==s.readNextChar();t++);}return r}class Jbig2Image{parseChunks(e){return function parseJbig2Chunks(e){const t=new SimpleSegmentVisitor;for(let n=0,a=e.length;n<a;n++){const a=e[n];processSegments(readSegments({},a.data,a.start,a.end),t)}return t.buffer}(e)}parse(e){throw new Error("Not implemented: Jbig2Image.parse")}}class Jbig2Stream extends DecodeStream{constructor(e,t,n){super(t);this.stream=e;this.dict=e.dict;this.maybeLength=t;this.params=n}get bytes(){return shadow(this,"bytes",this.stream.getBytes(this.maybeLength))}ensureBuffer(e){}readBlock(){this.decodeImageFallback()}get isAsyncDecoder(){return!0}get isImageStream(){return!0}async decodeImage(e,t,n){if(this.eof)return this.buffer;e||=this.bytes;try{let t=null;if(this.params instanceof Dict){const e=this.params.get("JBIG2Globals");e instanceof BaseStream&&(t=e.getBytes())}this.buffer=await JBig2CCITTFaxWasmImage.decode(e,this.dict.get("Width"),this.dict.get("Height"),t)}catch{warn("Jbig2Stream: Falling back to JS JBIG2 decoder.");return this.decodeImageFallback(e,t)}this.bufferLength=this.buffer.length;this.eof=!0;return this.buffer}decodeImageFallback(e,t){if(this.eof)return this.buffer;e||=this.bytes;const n=new Jbig2Image,a=[];if(this.params instanceof Dict){const e=this.params.get("JBIG2Globals");if(e instanceof BaseStream){const t=e.getBytes();a.push({data:t,start:0,end:t.length})}}a.push({data:e,start:0,end:e.length});const s=n.parseChunks(a),r=s.length;for(let e=0;e<r;e++)s[e]^=255;this.buffer=s;this.bufferLength=r;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}}class JpxStream extends DecodeStream{constructor(e,t,n){super(t);this.stream=e;this.dict=e.dict;this.maybeLength=t;this.params=n}get bytes(){return shadow(this,"bytes",this.stream.getBytes(this.maybeLength))}ensureBuffer(e){}readBlock(e){unreachable("JpxStream.readBlock")}get isAsyncDecoder(){return!0}async decodeImage(e,t,n){if(this.eof)return this.buffer;e||=this.bytes;this.buffer=await JpxImage.decode(e,n);this.bufferLength=this.buffer.length;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}get isImageStream(){return!0}}class LZWStream extends DecodeStream{constructor(e,t,n){super(t);this.stream=e;this.dict=e.dict;this.cachedData=0;this.bitsCached=0;const a=4096,s={earlyChange:n,codeLength:9,nextCode:258,dictionaryValues:new Uint8Array(a),dictionaryLengths:new Uint16Array(a),dictionaryPrevCodes:new Uint16Array(a),currentSequence:new Uint8Array(a),currentSequenceLength:0};for(let e=0;e<256;++e){s.dictionaryValues[e]=e;s.dictionaryLengths[e]=1}this.lzwState=s}readBits(e){let t=this.bitsCached,n=this.cachedData;for(;t<e;){const e=this.stream.getByte();if(-1===e){this.eof=!0;return null}n=n<<8|e;t+=8}this.bitsCached=t-=e;this.cachedData=n;return n>>>t&(1<<e)-1}readBlock(){let e,t,n,a=1024;const s=this.lzwState;if(!s)return;const r=s.earlyChange;let i=s.nextCode;const o=s.dictionaryValues,l=s.dictionaryLengths,f=s.dictionaryPrevCodes;let c=s.codeLength,h=s.prevCode;const u=s.currentSequence;let m=s.currentSequenceLength,p=0,d=this.bufferLength,g=this.ensureBuffer(this.bufferLength+a);for(e=0;e<512;e++){const e=this.readBits(c),s=m>0;if(e<256){u[0]=e;m=1}else{if(!(e>=258)){if(256===e){c=9;i=258;m=0;continue}this.eof=!0;delete this.lzwState;break}if(e<i){m=l[e];for(t=m-1,n=e;t>=0;t--){u[t]=o[n];n=f[n]}}else u[m++]=u[0]}if(s){f[i]=h;l[i]=l[h]+1;o[i]=u[0];i++;c=i+r&i+r-1?c:0|Math.min(Math.log(i+r)/.6931471805599453+1,12)}h=e;p+=m;if(a<p){do{a+=512}while(a<p);g=this.ensureBuffer(this.bufferLength+a)}for(t=0;t<m;t++)g[d++]=u[t]}s.nextCode=i;s.codeLength=c;s.prevCode=h;s.currentSequenceLength=m;this.bufferLength=d}}class PredictorStream extends DecodeStream{constructor(e,t,n){super(t);if(!(n instanceof Dict))return e;const a=this.predictor=n.get("Predictor")||1;if(a<=1)return e;if(2!==a&&(a<10||a>15))throw new FormatError(`Unsupported predictor: ${a}`);this.readBlock=2===a?this.readBlockTiff:this.readBlockPng;this.stream=e;this.dict=e.dict;const s=this.colors=n.get("Colors")||1,r=this.bits=n.get("BPC","BitsPerComponent")||8,i=this.columns=n.get("Columns")||1;this.pixBytes=s*r+7>>3;this.rowBytes=i*s*r+7>>3;return this}readBlockTiff(){const e=this.rowBytes,t=this.bufferLength,n=this.ensureBuffer(t+e),a=this.bits,s=this.colors,r=this.stream.getBytes(e);this.eof=!r.length;if(this.eof)return;let i,o=0,l=0,f=0,c=0,h=t;if(1===a&&1===s)for(i=0;i<e;++i){let e=r[i]^o;e^=e>>1;e^=e>>2;e^=e>>4;o=(1&e)<<7;n[h++]=e}else if(8===a){for(i=0;i<s;++i)n[h++]=r[i];for(;i<e;++i){n[h]=n[h-s]+r[i];h++}}else if(16===a){const t=2*s;for(i=0;i<t;++i)n[h++]=r[i];for(;i<e;i+=2){const e=((255&r[i])<<8)+(255&r[i+1])+((255&n[h-t])<<8)+(255&n[h-t+1]);n[h++]=e>>8&255;n[h++]=255&e}}else{const e=new Uint8Array(s+1),h=(1<<a)-1;let u=0,m=t;const p=this.columns;for(i=0;i<p;++i)for(let t=0;t<s;++t){if(f<a){o=o<<8|255&r[u++];f+=8}e[t]=e[t]+(o>>f-a)&h;f-=a;l=l<<a|e[t];c+=a;if(c>=8){n[m++]=l>>c-8&255;c-=8}}c>0&&(n[m++]=(l<<8-c)+(o&(1<<8-c)-1))}this.bufferLength+=e}readBlockPng(){const e=this.rowBytes,t=this.pixBytes,n=this.stream.getByte(),a=this.stream.getBytes(e);this.eof=!a.length;if(this.eof)return;const s=this.bufferLength,r=this.ensureBuffer(s+e);let i=r.subarray(s-e,s);0===i.length&&(i=new Uint8Array(e));let o,l,f,c=s;switch(n){case 0:for(o=0;o<e;++o)r[c++]=a[o];break;case 1:for(o=0;o<t;++o)r[c++]=a[o];for(;o<e;++o){r[c]=r[c-t]+a[o]&255;c++}break;case 2:for(o=0;o<e;++o)r[c++]=i[o]+a[o]&255;break;case 3:for(o=0;o<t;++o)r[c++]=(i[o]>>1)+a[o];for(;o<e;++o){r[c]=(i[o]+r[c-t]>>1)+a[o]&255;c++}break;case 4:for(o=0;o<t;++o){l=i[o];f=a[o];r[c++]=l+f}for(;o<e;++o){l=i[o];const e=i[o-t],n=r[c-t],s=n+l-e;let h=s-n;h<0&&(h=-h);let u=s-l;u<0&&(u=-u);let m=s-e;m<0&&(m=-m);f=a[o];r[c++]=h<=u&&h<=m?n+f:u<=m?l+f:e+f}break;default:throw new FormatError(`Unsupported predictor: ${n}`)}this.bufferLength+=e}}class RunLengthStream extends DecodeStream{constructor(e,t){super(t);this.stream=e;this.dict=e.dict}readBlock(){const e=this.stream.getBytes(2);if(!e||e.length<2||128===e[0]){this.eof=!0;return}let t,n=this.bufferLength,a=e[0];if(a<128){t=this.ensureBuffer(n+a+1);t[n++]=e[1];if(a>0){const e=this.stream.getBytes(a);t.set(e,n);n+=a}}else{a=257-a;t=this.ensureBuffer(n+a+1);t.fill(e[1],n,n+a);n+=a}this.bufferLength=n}}class Parser{constructor({lexer:e,xref:t,allowStreams:n=!1,recoveryMode:a=!1}){this.lexer=e;this.xref=t;this.allowStreams=n;this.recoveryMode=a;this.imageCache=Object.create(null);this._imageId=0;this.refill()}refill(){this.buf1=this.lexer.getObj();this.buf2=this.lexer.getObj()}shift(){if(this.buf2 instanceof Cmd&&"ID"===this.buf2.cmd){this.buf1=this.buf2;this.buf2=null}else{this.buf1=this.buf2;this.buf2=this.lexer.getObj()}}tryShift(){try{this.shift();return!0}catch(e){if(e instanceof MissingDataException)throw e;return!1}}getObj(e=null){const t=this.buf1;this.shift();if(t instanceof Cmd)switch(t.cmd){case"BI":return this.makeInlineImage(e);case"[":const n=[];for(;!isCmd(this.buf1,"]")&&this.buf1!==on;)n.push(this.getObj(e));if(this.buf1===on){if(this.recoveryMode)return n;throw new ParserEOFException("End of file inside array.")}this.shift();return n;case"<<":const a=new Dict(this.xref);for(;!isCmd(this.buf1,">>")&&this.buf1!==on;){if(!(this.buf1 instanceof Name)){info("Malformed dictionary: key must be a name object");this.shift();continue}const t=this.buf1.name;this.shift();if(this.buf1===on)break;a.set(t,this.getObj(e))}if(this.buf1===on){if(this.recoveryMode)return a;throw new ParserEOFException("End of file inside dictionary.")}if(isCmd(this.buf2,"stream"))return this.allowStreams?this.makeStream(a,e):a;this.shift();return a;default:return t}if(Number.isInteger(t)){if(Number.isInteger(this.buf1)&&isCmd(this.buf2,"R")){const e=Ref.get(t,this.buf1);this.shift();this.shift();return e}return t}return"string"==typeof t&&e?e.decryptString(t):t}findDefaultInlineStreamEnd(e){const{knownCommands:t}=this.lexer,n=e.pos;let a,s,r=0;for(;-1!==(a=e.getByte());)if(0===r)r=69===a?1:0;else if(1===r)r=73===a?2:0;else if(32===a||10===a||13===a){s=e.pos;const n=e.peekBytes(15),i=n.length;if(0===i)break;for(let e=0;e<i;e++){a=n[e];if((0!==a||0===n[e+1])&&(10!==a&&13!==a&&(a<32||a>127))){r=0;break}}if(2!==r)continue;if(!t){warn("findDefaultInlineStreamEnd - `lexer.knownCommands` is undefined.");continue}const o=new Lexer(new Stream(e.peekBytes(75)),t);o._hexStringWarn=()=>{};let l=0;for(;;){const e=o.getObj();if(e===on){r=0;break}if(e instanceof Cmd){const n=t[e.cmd];if(!n){r=0;break}if(n.variableArgs?l<=n.numArgs:l===n.numArgs)break;l=0;continue}l++}if(2===r)break}else r=0;if(-1===a){warn("findDefaultInlineStreamEnd: Reached the end of the stream without finding a valid EI marker");if(s){warn('... trying to recover by using the last "EI" occurrence.');e.skip(-(e.pos-s))}}let i=4;e.skip(-i);a=e.peekByte();e.skip(i);isWhiteSpace(a)||i--;return e.pos-i-n}findDCTDecodeInlineStreamEnd(e){const t=e.pos;let n,a,s=!1;for(;-1!==(n=e.getByte());)if(255===n){switch(e.getByte()){case 0:break;case 255:e.skip(-1);break;case 217:s=!0;break;case 192:case 193:case 194:case 195:case 197:case 198:case 199:case 201:case 202:case 203:case 205:case 206:case 207:case 196:case 204:case 218:case 219:case 220:case 221:case 222:case 223:case 224:case 225:case 226:case 227:case 228:case 229:case 230:case 231:case 232:case 233:case 234:case 235:case 236:case 237:case 238:case 239:case 254:a=e.getUint16();a>2?e.skip(a-2):e.skip(-2)}if(s)break}const r=e.pos-t;if(-1===n){warn("Inline DCTDecode image stream: EOI marker not found, searching for /EI/ instead.");e.skip(-r);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return r}findASCII85DecodeInlineStreamEnd(e){const t=e.pos;let n;for(;-1!==(n=e.getByte());)if(126===n){const t=e.pos;n=e.peekByte();for(;isWhiteSpace(n);){e.skip();n=e.peekByte()}if(62===n){e.skip();break}if(e.pos>t){const t=e.peekBytes(2);if(69===t[0]&&73===t[1])break}}const a=e.pos-t;if(-1===n){warn("Inline ASCII85Decode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-a);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return a}findASCIIHexDecodeInlineStreamEnd(e){const t=e.pos;let n;for(;-1!==(n=e.getByte())&&62!==n;);const a=e.pos-t;if(-1===n){warn("Inline ASCIIHexDecode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-a);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return a}inlineStreamSkipEI(e){let t,n=0;for(;-1!==(t=e.getByte());)if(0===n)n=69===t?1:0;else if(1===n)n=73===t?2:0;else if(2===n)break}makeInlineImage(e){const t=this.lexer,n=t.stream,a=Object.create(null);let s;for(;!isCmd(this.buf1,"ID")&&this.buf1!==on;){if(!(this.buf1 instanceof Name))throw new FormatError("Dictionary key must be a name object");const t=this.buf1.name;this.shift();if(this.buf1===on)break;a[t]=this.getObj(e)}-1!==t.beginInlineImagePos&&(s=n.pos-t.beginInlineImagePos);const r=this.xref.fetchIfRef(a.F||a.Filter);let i;if(r instanceof Name)i=r.name;else if(Array.isArray(r)){const e=this.xref.fetchIfRef(r[0]);e instanceof Name&&(i=e.name)}const o=n.pos;let l,f;switch(i){case"DCT":case"DCTDecode":l=this.findDCTDecodeInlineStreamEnd(n);break;case"A85":case"ASCII85Decode":l=this.findASCII85DecodeInlineStreamEnd(n);break;case"AHx":case"ASCIIHexDecode":l=this.findASCIIHexDecodeInlineStreamEnd(n);break;default:l=this.findDefaultInlineStreamEnd(n)}if(l<1e3&&s>0){const e=n.pos;n.pos=t.beginInlineImagePos;f=function getInlineImageCacheKey(e){const t=[],n=e.length;let a=0;for(;a<n-1;)t.push(e[a++]<<8|e[a++]);a<n&&t.push(e[a]);return n+"_"+String.fromCharCode.apply(null,t)}(n.getBytes(s+l));n.pos=e;const a=this.imageCache[f];if(void 0!==a){this.buf2=Cmd.get("EI");this.shift();a.reset();return a}}const c=new Dict(this.xref);for(const e in a)c.set(e,a[e]);let h=n.makeSubStream(o,l,c);e&&(h=e.createStream(h,l));h=this.filter(h,c,l);h.dict=c;if(void 0!==f){h.cacheKey="inline_img_"+ ++this._imageId;this.imageCache[f]=h}this.buf2=Cmd.get("EI");this.shift();return h}#_(e){const{stream:t}=this.lexer;t.pos=e;const n=new Uint8Array([101,110,100]),a=n.length,s=[new Uint8Array([115,116,114,101,97,109]),new Uint8Array([115,116,101,97,109]),new Uint8Array([115,116,114,101,97])],r=9-a;for(;t.pos<t.end;){const i=t.peekBytes(2048),o=i.length-9;if(o<=0)break;let l=0;for(;l<o;){let o=0;for(;o<a&&i[l+o]===n[o];)o++;if(o>=a){let a=!1;for(const e of s){const t=e.length;let s=0;for(;s<t&&i[l+o+s]===e[s];)s++;if(s>=r){a=!0;break}if(s>=t){if(isWhiteSpace(i[l+o+s])){info(`Found "${bytesToString([...n,...e])}" when searching for endstream command.`);a=!0}break}}if(a){t.pos+=l;return t.pos-e}}l++}t.pos+=o}return-1}makeStream(e,t){const n=this.lexer;let a=n.stream;n.skipToNextLine();const s=a.pos-1;let r=e.get("Length");if(!Number.isInteger(r)){info(`Bad length "${r&&r.toString()}" in stream.`);r=0}a.pos=s+r;n.nextChar();if(this.tryShift()&&isCmd(this.buf2,"endstream"))this.shift();else{r=this.#_(s);if(r<0)throw new FormatError("Missing endstream command.");n.nextChar();this.shift();this.shift()}this.shift();a=a.makeSubStream(s,r,e);t&&(a=t.createStream(a,r));a=this.filter(a,e,r);a.dict=e;return a}filter(e,t,n){let a=t.get("F","Filter"),s=t.get("DP","DecodeParms");if(a instanceof Name){Array.isArray(s)&&warn("/DecodeParms should not be an Array, when /Filter is a Name.");return this.makeFilter(e,a.name,n,s)}let r=n;if(Array.isArray(a)){const t=a,n=s;for(let i=0,o=t.length;i<o;++i){a=this.xref.fetchIfRef(t[i]);if(!(a instanceof Name))throw new FormatError(`Bad filter name "${a}"`);s=null;Array.isArray(n)&&i in n&&(s=this.xref.fetchIfRef(n[i]));e=this.makeFilter(e,a.name,r,s);r=null}}return e}makeFilter(e,t,n,a){if(0===n){warn(`Empty "${t}" stream.`);return new NullStream}try{switch(t){case"Fl":case"FlateDecode":return a?new PredictorStream(new FlateStream(e,n),n,a):new FlateStream(e,n);case"LZW":case"LZWDecode":let t=1;if(a){a.has("EarlyChange")&&(t=a.get("EarlyChange"));return new PredictorStream(new LZWStream(e,n,t),n,a)}return new LZWStream(e,n,t);case"DCT":case"DCTDecode":return new JpegStream(e,n,a);case"JPX":case"JPXDecode":return new JpxStream(e,n,a);case"A85":case"ASCII85Decode":return new Ascii85Stream(e,n);case"AHx":case"ASCIIHexDecode":return new AsciiHexStream(e,n);case"CCF":case"CCITTFaxDecode":return new CCITTFaxStream(e,n,a);case"RL":case"RunLengthDecode":return new RunLengthStream(e,n);case"JBIG2Decode":return new Jbig2Stream(e,n,a);case"BrotliDecode":return new BrotliStream(e,n)}warn(`Filter "${t}" is not supported.`);return e}catch(e){if(e instanceof MissingDataException)throw e;warn(`Invalid stream: "${e}"`);return new NullStream}}}const ia=[1,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,2,0,0,2,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];function toHexDigit(e){return e>=48&&e<=57?15&e:e>=65&&e<=70||e>=97&&e<=102?9+(15&e):-1}class Lexer{constructor(e,t=null){this.stream=e;this.nextChar();this.strBuf=[];this.knownCommands=t;this._hexStringNumWarn=0;this.beginInlineImagePos=-1}nextChar(){return this.currentChar=this.stream.getByte()}peekChar(){return this.stream.peekByte()}getNumber(){let e=this.currentChar,t=0,n=1;if(45===e){n=-1;e=this.nextChar();45===e&&(e=this.nextChar())}else 43===e&&(e=this.nextChar());if(10===e||13===e)do{e=this.nextChar()}while(10===e||13===e);if(46===e){t=10;e=this.nextChar()}if(e<48||e>57){const t=`Invalid number: ${String.fromCharCode(e)} (charCode ${e})`;if(isWhiteSpace(e)||40===e||60===e||-1===e){info(`Lexer.getNumber - "${t}".`);return 0}throw new FormatError(t)}let a=e-48;for(;(e=this.nextChar())>=0;)if(e>=48&&e<=57){0!==t&&(t*=10);a=10*a+(e-48)}else if(46===e){if(0!==t)break;t=1}else{if(45!==e)break;warn("Badly formatted number: minus sign in the middle")}0!==t&&(a/=t);return n*a}getString(){let e=1,t=!1;const n=this.strBuf;n.length=0;let a=this.nextChar();for(;;){let s=!1;switch(0|a){case-1:warn("Unterminated string");t=!0;break;case 40:++e;n.push("(");break;case 41:if(0===--e){this.nextChar();t=!0}else n.push(")");break;case 92:a=this.nextChar();switch(a){case-1:warn("Unterminated string");t=!0;break;case 110:n.push("\n");break;case 114:n.push("\r");break;case 116:n.push("\t");break;case 98:n.push("\b");break;case 102:n.push("\f");break;case 92:case 40:case 41:n.push(String.fromCharCode(a));break;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:let e=15&a;a=this.nextChar();s=!0;if(a>=48&&a<=55){e=(e<<3)+(15&a);a=this.nextChar();if(a>=48&&a<=55){s=!1;e=(e<<3)+(15&a)}}n.push(String.fromCharCode(e));break;case 13:10===this.peekChar()&&this.nextChar();break;case 10:break;default:n.push(String.fromCharCode(a))}break;default:n.push(String.fromCharCode(a))}if(t)break;s||(a=this.nextChar())}return n.join("")}getName(){let e,t;const n=this.strBuf;n.length=0;for(;(e=this.nextChar())>=0&&!ia[e];)if(35===e){e=this.nextChar();if(ia[e]){warn("Lexer_getName: NUMBER SIGN (#) should be followed by a hexadecimal number.");n.push("#");break}const a=toHexDigit(e);if(-1!==a){t=e;e=this.nextChar();const s=toHexDigit(e);if(-1===s){warn(`Lexer_getName: Illegal digit (${String.fromCharCode(e)}) in hexadecimal number.`);n.push("#",String.fromCharCode(t));if(ia[e])break;n.push(String.fromCharCode(e));continue}n.push(String.fromCharCode(a<<4|s))}else n.push("#",String.fromCharCode(e))}else n.push(String.fromCharCode(e));n.length>127&&warn(`Name token is longer than allowed by the spec: ${n.length}`);return Name.get(n.join(""))}_hexStringWarn(e){5!==this._hexStringNumWarn++?this._hexStringNumWarn>5||warn(`getHexString - ignoring invalid character: ${e}`):warn("getHexString - ignoring additional invalid characters.")}getHexString(){const e=this.strBuf;e.length=0;let t=this.currentChar,n=-1,a=-1;this._hexStringNumWarn=0;for(;;){if(t<0){warn("Unterminated hex string");break}if(62===t){this.nextChar();break}if(1!==ia[t]){a=toHexDigit(t);if(-1===a)this._hexStringWarn(t);else if(-1===n)n=a;else{e.push(String.fromCharCode(n<<4|a));n=-1}t=this.nextChar()}else t=this.nextChar()}-1!==n&&e.push(String.fromCharCode(n<<4));return e.join("")}getObj(){let e=!1,t=this.currentChar;for(;;){if(t<0)return on;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(1!==ia[t])break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return this.getNumber();case 40:return this.getString();case 47:return this.getName();case 91:this.nextChar();return Cmd.get("[");case 93:this.nextChar();return Cmd.get("]");case 60:t=this.nextChar();if(60===t){this.nextChar();return Cmd.get("<<")}return this.getHexString();case 62:t=this.nextChar();if(62===t){this.nextChar();return Cmd.get(">>")}return Cmd.get(">");case 123:this.nextChar();return Cmd.get("{");case 125:this.nextChar();return Cmd.get("}");case 41:this.nextChar();throw new FormatError(`Illegal character: ${t}`)}let n=String.fromCharCode(t);if(t<32||t>127){const e=this.peekChar();if(e>=32&&e<=127){this.nextChar();return Cmd.get(n)}}const a=this.knownCommands;let s=void 0!==a?.[n];for(;(t=this.nextChar())>=0&&!ia[t];){const e=n+String.fromCharCode(t);if(s&&void 0===a[e])break;if(128===n.length)throw new FormatError(`Command token too long: ${n.length}`);n=e;s=void 0!==a?.[n]}if("true"===n)return!0;if("false"===n)return!1;if("null"===n)return null;"BI"===n&&(this.beginInlineImagePos=this.stream.pos);return Cmd.get(n)}skipToNextLine(){let e=this.currentChar;for(;e>=0;){if(13===e){e=this.nextChar();10===e&&this.nextChar();break}if(10===e){this.nextChar();break}e=this.nextChar()}}}class Linearization{static create(e){function getInt(e,t,n=!1){const a=e.get(t);if(Number.isInteger(a)&&(n?a>=0:a>0))return a;throw new Error(`The "${t}" parameter in the linearization dictionary is invalid.`)}const t=new Parser({lexer:new Lexer(e),xref:null}),n=t.getObj(),a=t.getObj(),s=t.getObj(),r=t.getObj();let i,o;if(!(Number.isInteger(n)&&Number.isInteger(a)&&isCmd(s,"obj")&&r instanceof Dict&&"number"==typeof(i=r.get("Linearized"))&&i>0))return null;if((o=getInt(r,"L"))!==e.length)throw new Error('The "L" parameter in the linearization dictionary does not equal the stream length.');return{length:o,hints:function getHints(e){const t=e.get("H");let n;if(Array.isArray(t)&&(2===(n=t.length)||4===n)){for(let e=0;e<n;e++){const n=t[e];if(!(Number.isInteger(n)&&n>0))throw new Error(`Hint (${e}) in the linearization dictionary is invalid.`)}return t}throw new Error("Hint array in the linearization dictionary is invalid.")}(r),objectNumberFirst:getInt(r,"O"),endFirst:getInt(r,"E"),numPages:getInt(r,"N"),mainXRefEntriesOffset:getInt(r,"T"),pageFirst:r.has("P")?getInt(r,"P",!0):0}}}const oa=["Adobe-GB1-UCS2","Adobe-CNS1-UCS2","Adobe-Japan1-UCS2","Adobe-Korea1-UCS2","78-EUC-H","78-EUC-V","78-H","78-RKSJ-H","78-RKSJ-V","78-V","78ms-RKSJ-H","78ms-RKSJ-V","83pv-RKSJ-H","90ms-RKSJ-H","90ms-RKSJ-V","90msp-RKSJ-H","90msp-RKSJ-V","90pv-RKSJ-H","90pv-RKSJ-V","Add-H","Add-RKSJ-H","Add-RKSJ-V","Add-V","Adobe-CNS1-0","Adobe-CNS1-1","Adobe-CNS1-2","Adobe-CNS1-3","Adobe-CNS1-4","Adobe-CNS1-5","Adobe-CNS1-6","Adobe-GB1-0","Adobe-GB1-1","Adobe-GB1-2","Adobe-GB1-3","Adobe-GB1-4","Adobe-GB1-5","Adobe-Japan1-0","Adobe-Japan1-1","Adobe-Japan1-2","Adobe-Japan1-3","Adobe-Japan1-4","Adobe-Japan1-5","Adobe-Japan1-6","Adobe-Korea1-0","Adobe-Korea1-1","Adobe-Korea1-2","B5-H","B5-V","B5pc-H","B5pc-V","CNS-EUC-H","CNS-EUC-V","CNS1-H","CNS1-V","CNS2-H","CNS2-V","ETHK-B5-H","ETHK-B5-V","ETen-B5-H","ETen-B5-V","ETenms-B5-H","ETenms-B5-V","EUC-H","EUC-V","Ext-H","Ext-RKSJ-H","Ext-RKSJ-V","Ext-V","GB-EUC-H","GB-EUC-V","GB-H","GB-V","GBK-EUC-H","GBK-EUC-V","GBK2K-H","GBK2K-V","GBKp-EUC-H","GBKp-EUC-V","GBT-EUC-H","GBT-EUC-V","GBT-H","GBT-V","GBTpc-EUC-H","GBTpc-EUC-V","GBpc-EUC-H","GBpc-EUC-V","H","HKdla-B5-H","HKdla-B5-V","HKdlb-B5-H","HKdlb-B5-V","HKgccs-B5-H","HKgccs-B5-V","HKm314-B5-H","HKm314-B5-V","HKm471-B5-H","HKm471-B5-V","HKscs-B5-H","HKscs-B5-V","Hankaku","Hiragana","KSC-EUC-H","KSC-EUC-V","KSC-H","KSC-Johab-H","KSC-Johab-V","KSC-V","KSCms-UHC-H","KSCms-UHC-HW-H","KSCms-UHC-HW-V","KSCms-UHC-V","KSCpc-EUC-H","KSCpc-EUC-V","Katakana","NWP-H","NWP-V","RKSJ-H","RKSJ-V","Roman","UniCNS-UCS2-H","UniCNS-UCS2-V","UniCNS-UTF16-H","UniCNS-UTF16-V","UniCNS-UTF32-H","UniCNS-UTF32-V","UniCNS-UTF8-H","UniCNS-UTF8-V","UniGB-UCS2-H","UniGB-UCS2-V","UniGB-UTF16-H","UniGB-UTF16-V","UniGB-UTF32-H","UniGB-UTF32-V","UniGB-UTF8-H","UniGB-UTF8-V","UniJIS-UCS2-H","UniJIS-UCS2-HW-H","UniJIS-UCS2-HW-V","UniJIS-UCS2-V","UniJIS-UTF16-H","UniJIS-UTF16-V","UniJIS-UTF32-H","UniJIS-UTF32-V","UniJIS-UTF8-H","UniJIS-UTF8-V","UniJIS2004-UTF16-H","UniJIS2004-UTF16-V","UniJIS2004-UTF32-H","UniJIS2004-UTF32-V","UniJIS2004-UTF8-H","UniJIS2004-UTF8-V","UniJISPro-UCS2-HW-V","UniJISPro-UCS2-V","UniJISPro-UTF8-V","UniJISX0213-UTF32-H","UniJISX0213-UTF32-V","UniJISX02132004-UTF32-H","UniJISX02132004-UTF32-V","UniKS-UCS2-H","UniKS-UCS2-V","UniKS-UTF16-H","UniKS-UTF16-V","UniKS-UTF32-H","UniKS-UTF32-V","UniKS-UTF8-H","UniKS-UTF8-V","V","WP-Symbol"],la=2**24-1;class CMap{constructor(e=!1){this.codespaceRanges=[[],[],[],[]];this.numCodespaceRanges=0;this._map=[];this.name="";this.vertical=!1;this.useCMap=null;this.builtInCMap=e}addCodespaceRange(e,t,n){this.codespaceRanges[e-1].push(t,n);this.numCodespaceRanges++}mapCidRange(e,t,n){if(t-e>la)throw new Error("mapCidRange - ignoring data above MAX_MAP_RANGE.");for(;e<=t;)this._map[e++]=n++}mapBfRange(e,t,n){if(t-e>la)throw new Error("mapBfRange - ignoring data above MAX_MAP_RANGE.");const a=n.length-1;for(;e<=t;){this._map[e++]=n;const t=n.charCodeAt(a)+1;t>255?n=n.substring(0,a-1)+String.fromCharCode(n.charCodeAt(a-1)+1)+"\0":n=n.substring(0,a)+String.fromCharCode(t)}}mapBfRangeToArray(e,t,n){if(t-e>la)throw new Error("mapBfRangeToArray - ignoring data above MAX_MAP_RANGE.");const a=n.length;let s=0;for(;e<=t&&s<a;){this._map[e]=n[s++];++e}}mapOne(e,t){this._map[e]=t}lookup(e){return this._map[e]}contains(e){return void 0!==this._map[e]}forEach(e){const t=this._map,n=t.length;if(n<=65536)for(let a=0;a<n;a++)void 0!==t[a]&&e(a,t[a]);else for(const n in t)e(n,t[n])}charCodeOf(e){const t=this._map;if(t.length<=65536)return t.indexOf(e);for(const n in t)if(t[n]===e)return 0|n;return-1}getMap(){return this._map}readCharCode(e,t,n){let a=0;const s=this.codespaceRanges;for(let r=0,i=s.length;r<i;r++){a=(a<<8|e.charCodeAt(t+r))>>>0;const i=s[r];for(let e=0,t=i.length;e<t;){const t=i[e++],s=i[e++];if(a>=t&&a<=s){n.charcode=a;n.length=r+1;return}}}n.charcode=0;n.length=1}getCharCodeLength(e){const t=this.codespaceRanges;for(let n=0,a=t.length;n<a;n++){const a=t[n];for(let t=0,s=a.length;t<s;){const s=a[t++],r=a[t++];if(e>=s&&e<=r)return n+1}}return 1}get length(){return this._map.length}get isIdentityCMap(){if("Identity-H"!==this.name&&"Identity-V"!==this.name)return!1;if(65536!==this._map.length)return!1;for(let e=0;e<65536;e++)if(this._map[e]!==e)return!1;return!0}}class IdentityCMap extends CMap{constructor(e,t){super();this.vertical=e;this.addCodespaceRange(t,0,65535)}mapCidRange(e,t,n){unreachable("should not call mapCidRange")}mapBfRange(e,t,n){unreachable("should not call mapBfRange")}mapBfRangeToArray(e,t,n){unreachable("should not call mapBfRangeToArray")}mapOne(e,t){unreachable("should not call mapCidOne")}lookup(e){return Number.isInteger(e)&&e<=65535?e:void 0}contains(e){return Number.isInteger(e)&&e<=65535}forEach(e){for(let t=0;t<=65535;t++)e(t,t)}charCodeOf(e){return Number.isInteger(e)&&e<=65535?e:-1}getMap(){const e=new Array(65536);for(let t=0;t<=65535;t++)e[t]=t;return e}get length(){return 65536}get isIdentityCMap(){unreachable("should not access .isIdentityCMap")}}function strToInt(e){let t=0;for(let n=0;n<e.length;n++)t=t<<8|e.charCodeAt(n);return t>>>0}function expectString(e){if("string"!=typeof e)throw new FormatError("Malformed CMap: expected string.")}function expectInt(e){if(!Number.isInteger(e))throw new FormatError("Malformed CMap: expected int.")}function parseBfChar(e,t){for(;;){let n=t.getObj();if(n===on)break;if(isCmd(n,"endbfchar"))return;expectString(n);const a=strToInt(n);n=t.getObj();expectString(n);const s=n;e.mapOne(a,s)}}function parseBfRange(e,t){for(;;){let n=t.getObj();if(n===on)break;if(isCmd(n,"endbfrange"))return;expectString(n);const a=strToInt(n);n=t.getObj();expectString(n);const s=strToInt(n);n=t.getObj();if(Number.isInteger(n)||"string"==typeof n){const t=Number.isInteger(n)?String.fromCharCode(n):n;e.mapBfRange(a,s,t)}else{if(!isCmd(n,"["))break;{n=t.getObj();const r=[];for(;!isCmd(n,"]")&&n!==on;){r.push(n);n=t.getObj()}e.mapBfRangeToArray(a,s,r)}}}throw new FormatError("Invalid bf range.")}function parseCidChar(e,t){for(;;){let n=t.getObj();if(n===on)break;if(isCmd(n,"endcidchar"))return;expectString(n);const a=strToInt(n);n=t.getObj();expectInt(n);const s=n;e.mapOne(a,s)}}function parseCidRange(e,t){for(;;){let n=t.getObj();if(n===on)break;if(isCmd(n,"endcidrange"))return;expectString(n);const a=strToInt(n);n=t.getObj();expectString(n);const s=strToInt(n);n=t.getObj();expectInt(n);const r=n;e.mapCidRange(a,s,r)}}function parseCodespaceRange(e,t){for(;;){let n=t.getObj();if(n===on)break;if(isCmd(n,"endcodespacerange"))return;if("string"!=typeof n)break;const a=strToInt(n);n=t.getObj();if("string"!=typeof n)break;const s=strToInt(n);e.addCodespaceRange(n.length,a,s)}throw new FormatError("Invalid codespace range.")}function parseWMode(e,t){const n=t.getObj();Number.isInteger(n)&&(e.vertical=!!n)}function parseCMapName(e,t){const n=t.getObj();n instanceof Name&&(e.name=n.name)}async function parseCMap(e,t,n,a){let s,r;e:for(;;)try{const n=t.getObj();if(n===on)break;if(n instanceof Name){"WMode"===n.name?parseWMode(e,t):"CMapName"===n.name&&parseCMapName(e,t);s=n}else if(n instanceof Cmd)switch(n.cmd){case"endcmap":break e;case"usecmap":s instanceof Name&&(r=s.name);break;case"begincodespacerange":parseCodespaceRange(e,t);break;case"beginbfchar":parseBfChar(e,t);break;case"begincidchar":parseCidChar(e,t);break;case"beginbfrange":parseBfRange(e,t);break;case"begincidrange":parseCidRange(e,t)}}catch(e){if(e instanceof MissingDataException)throw e;warn("Invalid cMap data: "+e);continue}!a&&r&&(a=r);return a?extendCMap(e,n,a):e}async function extendCMap(e,t,n){e.useCMap=await createBuiltInCMap(n,t);if(0===e.numCodespaceRanges){const t=e.useCMap.codespaceRanges;for(let n=0;n<t.length;n++)e.codespaceRanges[n]=t[n].slice();e.numCodespaceRanges=e.useCMap.numCodespaceRanges}e.useCMap.forEach(function(t,n){e.contains(t)||e.mapOne(t,n)});return e}async function createBuiltInCMap(e,t){if("Identity-H"===e)return new IdentityCMap(!1,2);if("Identity-V"===e)return new IdentityCMap(!0,2);if(!oa.includes(e))throw new Error("Unknown CMap name: "+e);if(!t)throw new Error("Built-in CMap parameters are not provided.");const{cMapData:n,isCompressed:a}=await t(e),s=new CMap(!0);if(a)return(new BinaryCMapReader).process(n,s,e=>extendCMap(s,t,e));const r=new Lexer(new Stream(n));return parseCMap(s,r,t,null)}class CMapFactory{static async create({encoding:e,fetchBuiltInCMap:t,useCMap:n}){if(e instanceof Name)return createBuiltInCMap(e.name,t);if(e instanceof BaseStream){if(e.isAsync){const t=await e.asyncGetBytes();t&&(e=new Stream(t,0,t.length,e.dict))}const a=await parseCMap(new CMap,new Lexer(e),t,n);return a.isIdentityCMap?createBuiltInCMap(a.name,t):a}throw new Error("Encoding required.")}}const fa=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","","asuperior","bsuperior","centsuperior","dsuperior","esuperior","","","","isuperior","","","lsuperior","msuperior","nsuperior","osuperior","","","rsuperior","ssuperior","tsuperior","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdownsmall","centoldstyle","Lslashsmall","","","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","","Dotaccentsmall","","","Macronsmall","","","figuredash","hypheninferior","","","Ogoneksmall","Ringsmall","Cedillasmall","","","","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],ca=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","centoldstyle","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","","threequartersemdash","","questionsmall","","","","","Ethsmall","","","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","","","","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hypheninferior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","asuperior","centsuperior","","","","","Aacutesmall","Agravesmall","Acircumflexsmall","Adieresissmall","Atildesmall","Aringsmall","Ccedillasmall","Eacutesmall","Egravesmall","Ecircumflexsmall","Edieresissmall","Iacutesmall","Igravesmall","Icircumflexsmall","Idieresissmall","Ntildesmall","Oacutesmall","Ogravesmall","Ocircumflexsmall","Odieresissmall","Otildesmall","Uacutesmall","Ugravesmall","Ucircumflexsmall","Udieresissmall","","eightsuperior","fourinferior","threeinferior","sixinferior","eightinferior","seveninferior","Scaronsmall","","centinferior","twoinferior","","Dieresissmall","","Caronsmall","osuperior","fiveinferior","","commainferior","periodinferior","Yacutesmall","","dollarinferior","","","Thornsmall","","nineinferior","zeroinferior","Zcaronsmall","AEsmall","Oslashsmall","questiondownsmall","oneinferior","Lslashsmall","","","","","","","Cedillasmall","","","","","","OEsmall","figuredash","hyphensuperior","","","","","exclamdownsmall","","Ydieresissmall","","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","ninesuperior","zerosuperior","","esuperior","rsuperior","tsuperior","","","isuperior","ssuperior","dsuperior","","","","","","lsuperior","Ogoneksmall","Brevesmall","Macronsmall","bsuperior","nsuperior","msuperior","commasuperior","periodsuperior","Dotaccentsmall","Ringsmall","","","",""],ha=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","space","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron"],ua=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","","endash","dagger","daggerdbl","periodcentered","","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","","questiondown","","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","","ring","cedilla","","hungarumlaut","ogonek","caron","emdash","","","","","","","","","","","","","","","","","AE","","ordfeminine","","","","","Lslash","Oslash","OE","ordmasculine","","","","","","ae","","","","dotlessi","","","lslash","oslash","oe","germandbls","","","",""],ma=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","bullet","Euro","bullet","quotesinglbase","florin","quotedblbase","ellipsis","dagger","daggerdbl","circumflex","perthousand","Scaron","guilsinglleft","OE","bullet","Zcaron","bullet","bullet","quoteleft","quoteright","quotedblleft","quotedblright","bullet","endash","emdash","tilde","trademark","scaron","guilsinglright","oe","bullet","zcaron","Ydieresis","space","exclamdown","cent","sterling","currency","yen","brokenbar","section","dieresis","copyright","ordfeminine","guillemotleft","logicalnot","hyphen","registered","macron","degree","plusminus","twosuperior","threesuperior","acute","mu","paragraph","periodcentered","cedilla","onesuperior","ordmasculine","guillemotright","onequarter","onehalf","threequarters","questiondown","Agrave","Aacute","Acircumflex","Atilde","Adieresis","Aring","AE","Ccedilla","Egrave","Eacute","Ecircumflex","Edieresis","Igrave","Iacute","Icircumflex","Idieresis","Eth","Ntilde","Ograve","Oacute","Ocircumflex","Otilde","Odieresis","multiply","Oslash","Ugrave","Uacute","Ucircumflex","Udieresis","Yacute","Thorn","germandbls","agrave","aacute","acircumflex","atilde","adieresis","aring","ae","ccedilla","egrave","eacute","ecircumflex","edieresis","igrave","iacute","icircumflex","idieresis","eth","ntilde","ograve","oacute","ocircumflex","otilde","odieresis","divide","oslash","ugrave","uacute","ucircumflex","udieresis","yacute","thorn","ydieresis"],pa=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","universal","numbersign","existential","percent","ampersand","suchthat","parenleft","parenright","asteriskmath","plus","comma","minus","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","congruent","Alpha","Beta","Chi","Delta","Epsilon","Phi","Gamma","Eta","Iota","theta1","Kappa","Lambda","Mu","Nu","Omicron","Pi","Theta","Rho","Sigma","Tau","Upsilon","sigma1","Omega","Xi","Psi","Zeta","bracketleft","therefore","bracketright","perpendicular","underscore","radicalex","alpha","beta","chi","delta","epsilon","phi","gamma","eta","iota","phi1","kappa","lambda","mu","nu","omicron","pi","theta","rho","sigma","tau","upsilon","omega1","omega","xi","psi","zeta","braceleft","bar","braceright","similar","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Euro","Upsilon1","minute","lessequal","fraction","infinity","florin","club","diamond","heart","spade","arrowboth","arrowleft","arrowup","arrowright","arrowdown","degree","plusminus","second","greaterequal","multiply","proportional","partialdiff","bullet","divide","notequal","equivalence","approxequal","ellipsis","arrowvertex","arrowhorizex","carriagereturn","aleph","Ifraktur","Rfraktur","weierstrass","circlemultiply","circleplus","emptyset","intersection","union","propersuperset","reflexsuperset","notsubset","propersubset","reflexsubset","element","notelement","angle","gradient","registerserif","copyrightserif","trademarkserif","product","radical","dotmath","logicalnot","logicaland","logicalor","arrowdblboth","arrowdblleft","arrowdblup","arrowdblright","arrowdbldown","lozenge","angleleft","registersans","copyrightsans","trademarksans","summation","parenlefttp","parenleftex","parenleftbt","bracketlefttp","bracketleftex","bracketleftbt","bracelefttp","braceleftmid","braceleftbt","braceex","","angleright","integral","integraltp","integralex","integralbt","parenrighttp","parenrightex","parenrightbt","bracketrighttp","bracketrightex","bracketrightbt","bracerighttp","bracerightmid","bracerightbt",""],da=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","a1","a2","a202","a3","a4","a5","a119","a118","a117","a11","a12","a13","a14","a15","a16","a105","a17","a18","a19","a20","a21","a22","a23","a24","a25","a26","a27","a28","a6","a7","a8","a9","a10","a29","a30","a31","a32","a33","a34","a35","a36","a37","a38","a39","a40","a41","a42","a43","a44","a45","a46","a47","a48","a49","a50","a51","a52","a53","a54","a55","a56","a57","a58","a59","a60","a61","a62","a63","a64","a65","a66","a67","a68","a69","a70","a71","a72","a73","a74","a203","a75","a204","a76","a77","a78","a79","a81","a82","a83","a84","a97","a98","a99","a100","","a89","a90","a93","a94","a91","a92","a205","a85","a206","a86","a87","a88","a95","a96","","","","","","","","","","","","","","","","","","","","a101","a102","a103","a104","a106","a107","a108","a112","a111","a110","a109","a120","a121","a122","a123","a124","a125","a126","a127","a128","a129","a130","a131","a132","a133","a134","a135","a136","a137","a138","a139","a140","a141","a142","a143","a144","a145","a146","a147","a148","a149","a150","a151","a152","a153","a154","a155","a156","a157","a158","a159","a160","a161","a163","a164","a196","a165","a192","a166","a167","a168","a169","a170","a171","a172","a173","a162","a174","a175","a176","a177","a178","a179","a193","a180","a199","a181","a200","a182","","a201","a183","a184","a197","a185","a194","a198","a186","a195","a187","a188","a189","a190","a191",""];function getEncoding(e){switch(e){case"WinAnsiEncoding":return ma;case"StandardEncoding":return ua;case"MacRomanEncoding":return ha;case"SymbolSetEncoding":return pa;case"ZapfDingbatsEncoding":return da;case"ExpertEncoding":return fa;case"MacExpertEncoding":return ca;default:return null}}const ga=getLookupTableFactory(function(e){e.A=65;e.AE=198;e.AEacute=508;e.AEmacron=482;e.AEsmall=63462;e.Aacute=193;e.Aacutesmall=63457;e.Abreve=258;e.Abreveacute=7854;e.Abrevecyrillic=1232;e.Abrevedotbelow=7862;e.Abrevegrave=7856;e.Abrevehookabove=7858;e.Abrevetilde=7860;e.Acaron=461;e.Acircle=9398;e.Acircumflex=194;e.Acircumflexacute=7844;e.Acircumflexdotbelow=7852;e.Acircumflexgrave=7846;e.Acircumflexhookabove=7848;e.Acircumflexsmall=63458;e.Acircumflextilde=7850;e.Acute=63177;e.Acutesmall=63412;e.Acyrillic=1040;e.Adblgrave=512;e.Adieresis=196;e.Adieresiscyrillic=1234;e.Adieresismacron=478;e.Adieresissmall=63460;e.Adotbelow=7840;e.Adotmacron=480;e.Agrave=192;e.Agravesmall=63456;e.Ahookabove=7842;e.Aiecyrillic=1236;e.Ainvertedbreve=514;e.Alpha=913;e.Alphatonos=902;e.Amacron=256;e.Amonospace=65313;e.Aogonek=260;e.Aring=197;e.Aringacute=506;e.Aringbelow=7680;e.Aringsmall=63461;e.Asmall=63329;e.Atilde=195;e.Atildesmall=63459;e.Aybarmenian=1329;e.B=66;e.Bcircle=9399;e.Bdotaccent=7682;e.Bdotbelow=7684;e.Becyrillic=1041;e.Benarmenian=1330;e.Beta=914;e.Bhook=385;e.Blinebelow=7686;e.Bmonospace=65314;e.Brevesmall=63220;e.Bsmall=63330;e.Btopbar=386;e.C=67;e.Caarmenian=1342;e.Cacute=262;e.Caron=63178;e.Caronsmall=63221;e.Ccaron=268;e.Ccedilla=199;e.Ccedillaacute=7688;e.Ccedillasmall=63463;e.Ccircle=9400;e.Ccircumflex=264;e.Cdot=266;e.Cdotaccent=266;e.Cedillasmall=63416;e.Chaarmenian=1353;e.Cheabkhasiancyrillic=1212;e.Checyrillic=1063;e.Chedescenderabkhasiancyrillic=1214;e.Chedescendercyrillic=1206;e.Chedieresiscyrillic=1268;e.Cheharmenian=1347;e.Chekhakassiancyrillic=1227;e.Cheverticalstrokecyrillic=1208;e.Chi=935;e.Chook=391;e.Circumflexsmall=63222;e.Cmonospace=65315;e.Coarmenian=1361;e.Csmall=63331;e.D=68;e.DZ=497;e.DZcaron=452;e.Daarmenian=1332;e.Dafrican=393;e.Dcaron=270;e.Dcedilla=7696;e.Dcircle=9401;e.Dcircumflexbelow=7698;e.Dcroat=272;e.Ddotaccent=7690;e.Ddotbelow=7692;e.Decyrillic=1044;e.Deicoptic=1006;e.Delta=8710;e.Deltagreek=916;e.Dhook=394;e.Dieresis=63179;e.DieresisAcute=63180;e.DieresisGrave=63181;e.Dieresissmall=63400;e.Digammagreek=988;e.Djecyrillic=1026;e.Dlinebelow=7694;e.Dmonospace=65316;e.Dotaccentsmall=63223;e.Dslash=272;e.Dsmall=63332;e.Dtopbar=395;e.Dz=498;e.Dzcaron=453;e.Dzeabkhasiancyrillic=1248;e.Dzecyrillic=1029;e.Dzhecyrillic=1039;e.E=69;e.Eacute=201;e.Eacutesmall=63465;e.Ebreve=276;e.Ecaron=282;e.Ecedillabreve=7708;e.Echarmenian=1333;e.Ecircle=9402;e.Ecircumflex=202;e.Ecircumflexacute=7870;e.Ecircumflexbelow=7704;e.Ecircumflexdotbelow=7878;e.Ecircumflexgrave=7872;e.Ecircumflexhookabove=7874;e.Ecircumflexsmall=63466;e.Ecircumflextilde=7876;e.Ecyrillic=1028;e.Edblgrave=516;e.Edieresis=203;e.Edieresissmall=63467;e.Edot=278;e.Edotaccent=278;e.Edotbelow=7864;e.Efcyrillic=1060;e.Egrave=200;e.Egravesmall=63464;e.Eharmenian=1335;e.Ehookabove=7866;e.Eightroman=8551;e.Einvertedbreve=518;e.Eiotifiedcyrillic=1124;e.Elcyrillic=1051;e.Elevenroman=8554;e.Emacron=274;e.Emacronacute=7702;e.Emacrongrave=7700;e.Emcyrillic=1052;e.Emonospace=65317;e.Encyrillic=1053;e.Endescendercyrillic=1186;e.Eng=330;e.Enghecyrillic=1188;e.Enhookcyrillic=1223;e.Eogonek=280;e.Eopen=400;e.Epsilon=917;e.Epsilontonos=904;e.Ercyrillic=1056;e.Ereversed=398;e.Ereversedcyrillic=1069;e.Escyrillic=1057;e.Esdescendercyrillic=1194;e.Esh=425;e.Esmall=63333;e.Eta=919;e.Etarmenian=1336;e.Etatonos=905;e.Eth=208;e.Ethsmall=63472;e.Etilde=7868;e.Etildebelow=7706;e.Euro=8364;e.Ezh=439;e.Ezhcaron=494;e.Ezhreversed=440;e.F=70;e.Fcircle=9403;e.Fdotaccent=7710;e.Feharmenian=1366;e.Feicoptic=996;e.Fhook=401;e.Fitacyrillic=1138;e.Fiveroman=8548;e.Fmonospace=65318;e.Fourroman=8547;e.Fsmall=63334;e.G=71;e.GBsquare=13191;e.Gacute=500;e.Gamma=915;e.Gammaafrican=404;e.Gangiacoptic=1002;e.Gbreve=286;e.Gcaron=486;e.Gcedilla=290;e.Gcircle=9404;e.Gcircumflex=284;e.Gcommaaccent=290;e.Gdot=288;e.Gdotaccent=288;e.Gecyrillic=1043;e.Ghadarmenian=1346;e.Ghemiddlehookcyrillic=1172;e.Ghestrokecyrillic=1170;e.Gheupturncyrillic=1168;e.Ghook=403;e.Gimarmenian=1331;e.Gjecyrillic=1027;e.Gmacron=7712;e.Gmonospace=65319;e.Grave=63182;e.Gravesmall=63328;e.Gsmall=63335;e.Gsmallhook=667;e.Gstroke=484;e.H=72;e.H18533=9679;e.H18543=9642;e.H18551=9643;e.H22073=9633;e.HPsquare=13259;e.Haabkhasiancyrillic=1192;e.Hadescendercyrillic=1202;e.Hardsigncyrillic=1066;e.Hbar=294;e.Hbrevebelow=7722;e.Hcedilla=7720;e.Hcircle=9405;e.Hcircumflex=292;e.Hdieresis=7718;e.Hdotaccent=7714;e.Hdotbelow=7716;e.Hmonospace=65320;e.Hoarmenian=1344;e.Horicoptic=1e3;e.Hsmall=63336;e.Hungarumlaut=63183;e.Hungarumlautsmall=63224;e.Hzsquare=13200;e.I=73;e.IAcyrillic=1071;e.IJ=306;e.IUcyrillic=1070;e.Iacute=205;e.Iacutesmall=63469;e.Ibreve=300;e.Icaron=463;e.Icircle=9406;e.Icircumflex=206;e.Icircumflexsmall=63470;e.Icyrillic=1030;e.Idblgrave=520;e.Idieresis=207;e.Idieresisacute=7726;e.Idieresiscyrillic=1252;e.Idieresissmall=63471;e.Idot=304;e.Idotaccent=304;e.Idotbelow=7882;e.Iebrevecyrillic=1238;e.Iecyrillic=1045;e.Ifraktur=8465;e.Igrave=204;e.Igravesmall=63468;e.Ihookabove=7880;e.Iicyrillic=1048;e.Iinvertedbreve=522;e.Iishortcyrillic=1049;e.Imacron=298;e.Imacroncyrillic=1250;e.Imonospace=65321;e.Iniarmenian=1339;e.Iocyrillic=1025;e.Iogonek=302;e.Iota=921;e.Iotaafrican=406;e.Iotadieresis=938;e.Iotatonos=906;e.Ismall=63337;e.Istroke=407;e.Itilde=296;e.Itildebelow=7724;e.Izhitsacyrillic=1140;e.Izhitsadblgravecyrillic=1142;e.J=74;e.Jaarmenian=1345;e.Jcircle=9407;e.Jcircumflex=308;e.Jecyrillic=1032;e.Jheharmenian=1355;e.Jmonospace=65322;e.Jsmall=63338;e.K=75;e.KBsquare=13189;e.KKsquare=13261;e.Kabashkircyrillic=1184;e.Kacute=7728;e.Kacyrillic=1050;e.Kadescendercyrillic=1178;e.Kahookcyrillic=1219;e.Kappa=922;e.Kastrokecyrillic=1182;e.Kaverticalstrokecyrillic=1180;e.Kcaron=488;e.Kcedilla=310;e.Kcircle=9408;e.Kcommaaccent=310;e.Kdotbelow=7730;e.Keharmenian=1364;e.Kenarmenian=1343;e.Khacyrillic=1061;e.Kheicoptic=998;e.Khook=408;e.Kjecyrillic=1036;e.Klinebelow=7732;e.Kmonospace=65323;e.Koppacyrillic=1152;e.Koppagreek=990;e.Ksicyrillic=1134;e.Ksmall=63339;e.L=76;e.LJ=455;e.LL=63167;e.Lacute=313;e.Lambda=923;e.Lcaron=317;e.Lcedilla=315;e.Lcircle=9409;e.Lcircumflexbelow=7740;e.Lcommaaccent=315;e.Ldot=319;e.Ldotaccent=319;e.Ldotbelow=7734;e.Ldotbelowmacron=7736;e.Liwnarmenian=1340;e.Lj=456;e.Ljecyrillic=1033;e.Llinebelow=7738;e.Lmonospace=65324;e.Lslash=321;e.Lslashsmall=63225;e.Lsmall=63340;e.M=77;e.MBsquare=13190;e.Macron=63184;e.Macronsmall=63407;e.Macute=7742;e.Mcircle=9410;e.Mdotaccent=7744;e.Mdotbelow=7746;e.Menarmenian=1348;e.Mmonospace=65325;e.Msmall=63341;e.Mturned=412;e.Mu=924;e.N=78;e.NJ=458;e.Nacute=323;e.Ncaron=327;e.Ncedilla=325;e.Ncircle=9411;e.Ncircumflexbelow=7754;e.Ncommaaccent=325;e.Ndotaccent=7748;e.Ndotbelow=7750;e.Nhookleft=413;e.Nineroman=8552;e.Nj=459;e.Njecyrillic=1034;e.Nlinebelow=7752;e.Nmonospace=65326;e.Nowarmenian=1350;e.Nsmall=63342;e.Ntilde=209;e.Ntildesmall=63473;e.Nu=925;e.O=79;e.OE=338;e.OEsmall=63226;e.Oacute=211;e.Oacutesmall=63475;e.Obarredcyrillic=1256;e.Obarreddieresiscyrillic=1258;e.Obreve=334;e.Ocaron=465;e.Ocenteredtilde=415;e.Ocircle=9412;e.Ocircumflex=212;e.Ocircumflexacute=7888;e.Ocircumflexdotbelow=7896;e.Ocircumflexgrave=7890;e.Ocircumflexhookabove=7892;e.Ocircumflexsmall=63476;e.Ocircumflextilde=7894;e.Ocyrillic=1054;e.Odblacute=336;e.Odblgrave=524;e.Odieresis=214;e.Odieresiscyrillic=1254;e.Odieresissmall=63478;e.Odotbelow=7884;e.Ogoneksmall=63227;e.Ograve=210;e.Ogravesmall=63474;e.Oharmenian=1365;e.Ohm=8486;e.Ohookabove=7886;e.Ohorn=416;e.Ohornacute=7898;e.Ohorndotbelow=7906;e.Ohorngrave=7900;e.Ohornhookabove=7902;e.Ohorntilde=7904;e.Ohungarumlaut=336;e.Oi=418;e.Oinvertedbreve=526;e.Omacron=332;e.Omacronacute=7762;e.Omacrongrave=7760;e.Omega=8486;e.Omegacyrillic=1120;e.Omegagreek=937;e.Omegaroundcyrillic=1146;e.Omegatitlocyrillic=1148;e.Omegatonos=911;e.Omicron=927;e.Omicrontonos=908;e.Omonospace=65327;e.Oneroman=8544;e.Oogonek=490;e.Oogonekmacron=492;e.Oopen=390;e.Oslash=216;e.Oslashacute=510;e.Oslashsmall=63480;e.Osmall=63343;e.Ostrokeacute=510;e.Otcyrillic=1150;e.Otilde=213;e.Otildeacute=7756;e.Otildedieresis=7758;e.Otildesmall=63477;e.P=80;e.Pacute=7764;e.Pcircle=9413;e.Pdotaccent=7766;e.Pecyrillic=1055;e.Peharmenian=1354;e.Pemiddlehookcyrillic=1190;e.Phi=934;e.Phook=420;e.Pi=928;e.Piwrarmenian=1363;e.Pmonospace=65328;e.Psi=936;e.Psicyrillic=1136;e.Psmall=63344;e.Q=81;e.Qcircle=9414;e.Qmonospace=65329;e.Qsmall=63345;e.R=82;e.Raarmenian=1356;e.Racute=340;e.Rcaron=344;e.Rcedilla=342;e.Rcircle=9415;e.Rcommaaccent=342;e.Rdblgrave=528;e.Rdotaccent=7768;e.Rdotbelow=7770;e.Rdotbelowmacron=7772;e.Reharmenian=1360;e.Rfraktur=8476;e.Rho=929;e.Ringsmall=63228;e.Rinvertedbreve=530;e.Rlinebelow=7774;e.Rmonospace=65330;e.Rsmall=63346;e.Rsmallinverted=641;e.Rsmallinvertedsuperior=694;e.S=83;e.SF010000=9484;e.SF020000=9492;e.SF030000=9488;e.SF040000=9496;e.SF050000=9532;e.SF060000=9516;e.SF070000=9524;e.SF080000=9500;e.SF090000=9508;e.SF100000=9472;e.SF110000=9474;e.SF190000=9569;e.SF200000=9570;e.SF210000=9558;e.SF220000=9557;e.SF230000=9571;e.SF240000=9553;e.SF250000=9559;e.SF260000=9565;e.SF270000=9564;e.SF280000=9563;e.SF360000=9566;e.SF370000=9567;e.SF380000=9562;e.SF390000=9556;e.SF400000=9577;e.SF410000=9574;e.SF420000=9568;e.SF430000=9552;e.SF440000=9580;e.SF450000=9575;e.SF460000=9576;e.SF470000=9572;e.SF480000=9573;e.SF490000=9561;e.SF500000=9560;e.SF510000=9554;e.SF520000=9555;e.SF530000=9579;e.SF540000=9578;e.Sacute=346;e.Sacutedotaccent=7780;e.Sampigreek=992;e.Scaron=352;e.Scarondotaccent=7782;e.Scaronsmall=63229;e.Scedilla=350;e.Schwa=399;e.Schwacyrillic=1240;e.Schwadieresiscyrillic=1242;e.Scircle=9416;e.Scircumflex=348;e.Scommaaccent=536;e.Sdotaccent=7776;e.Sdotbelow=7778;e.Sdotbelowdotaccent=7784;e.Seharmenian=1357;e.Sevenroman=8550;e.Shaarmenian=1351;e.Shacyrillic=1064;e.Shchacyrillic=1065;e.Sheicoptic=994;e.Shhacyrillic=1210;e.Shimacoptic=1004;e.Sigma=931;e.Sixroman=8549;e.Smonospace=65331;e.Softsigncyrillic=1068;e.Ssmall=63347;e.Stigmagreek=986;e.T=84;e.Tau=932;e.Tbar=358;e.Tcaron=356;e.Tcedilla=354;e.Tcircle=9417;e.Tcircumflexbelow=7792;e.Tcommaaccent=354;e.Tdotaccent=7786;e.Tdotbelow=7788;e.Tecyrillic=1058;e.Tedescendercyrillic=1196;e.Tenroman=8553;e.Tetsecyrillic=1204;e.Theta=920;e.Thook=428;e.Thorn=222;e.Thornsmall=63486;e.Threeroman=8546;e.Tildesmall=63230;e.Tiwnarmenian=1359;e.Tlinebelow=7790;e.Tmonospace=65332;e.Toarmenian=1337;e.Tonefive=444;e.Tonesix=388;e.Tonetwo=423;e.Tretroflexhook=430;e.Tsecyrillic=1062;e.Tshecyrillic=1035;e.Tsmall=63348;e.Twelveroman=8555;e.Tworoman=8545;e.U=85;e.Uacute=218;e.Uacutesmall=63482;e.Ubreve=364;e.Ucaron=467;e.Ucircle=9418;e.Ucircumflex=219;e.Ucircumflexbelow=7798;e.Ucircumflexsmall=63483;e.Ucyrillic=1059;e.Udblacute=368;e.Udblgrave=532;e.Udieresis=220;e.Udieresisacute=471;e.Udieresisbelow=7794;e.Udieresiscaron=473;e.Udieresiscyrillic=1264;e.Udieresisgrave=475;e.Udieresismacron=469;e.Udieresissmall=63484;e.Udotbelow=7908;e.Ugrave=217;e.Ugravesmall=63481;e.Uhookabove=7910;e.Uhorn=431;e.Uhornacute=7912;e.Uhorndotbelow=7920;e.Uhorngrave=7914;e.Uhornhookabove=7916;e.Uhorntilde=7918;e.Uhungarumlaut=368;e.Uhungarumlautcyrillic=1266;e.Uinvertedbreve=534;e.Ukcyrillic=1144;e.Umacron=362;e.Umacroncyrillic=1262;e.Umacrondieresis=7802;e.Umonospace=65333;e.Uogonek=370;e.Upsilon=933;e.Upsilon1=978;e.Upsilonacutehooksymbolgreek=979;e.Upsilonafrican=433;e.Upsilondieresis=939;e.Upsilondieresishooksymbolgreek=980;e.Upsilonhooksymbol=978;e.Upsilontonos=910;e.Uring=366;e.Ushortcyrillic=1038;e.Usmall=63349;e.Ustraightcyrillic=1198;e.Ustraightstrokecyrillic=1200;e.Utilde=360;e.Utildeacute=7800;e.Utildebelow=7796;e.V=86;e.Vcircle=9419;e.Vdotbelow=7806;e.Vecyrillic=1042;e.Vewarmenian=1358;e.Vhook=434;e.Vmonospace=65334;e.Voarmenian=1352;e.Vsmall=63350;e.Vtilde=7804;e.W=87;e.Wacute=7810;e.Wcircle=9420;e.Wcircumflex=372;e.Wdieresis=7812;e.Wdotaccent=7814;e.Wdotbelow=7816;e.Wgrave=7808;e.Wmonospace=65335;e.Wsmall=63351;e.X=88;e.Xcircle=9421;e.Xdieresis=7820;e.Xdotaccent=7818;e.Xeharmenian=1341;e.Xi=926;e.Xmonospace=65336;e.Xsmall=63352;e.Y=89;e.Yacute=221;e.Yacutesmall=63485;e.Yatcyrillic=1122;e.Ycircle=9422;e.Ycircumflex=374;e.Ydieresis=376;e.Ydieresissmall=63487;e.Ydotaccent=7822;e.Ydotbelow=7924;e.Yericyrillic=1067;e.Yerudieresiscyrillic=1272;e.Ygrave=7922;e.Yhook=435;e.Yhookabove=7926;e.Yiarmenian=1349;e.Yicyrillic=1031;e.Yiwnarmenian=1362;e.Ymonospace=65337;e.Ysmall=63353;e.Ytilde=7928;e.Yusbigcyrillic=1130;e.Yusbigiotifiedcyrillic=1132;e.Yuslittlecyrillic=1126;e.Yuslittleiotifiedcyrillic=1128;e.Z=90;e.Zaarmenian=1334;e.Zacute=377;e.Zcaron=381;e.Zcaronsmall=63231;e.Zcircle=9423;e.Zcircumflex=7824;e.Zdot=379;e.Zdotaccent=379;e.Zdotbelow=7826;e.Zecyrillic=1047;e.Zedescendercyrillic=1176;e.Zedieresiscyrillic=1246;e.Zeta=918;e.Zhearmenian=1338;e.Zhebrevecyrillic=1217;e.Zhecyrillic=1046;e.Zhedescendercyrillic=1174;e.Zhedieresiscyrillic=1244;e.Zlinebelow=7828;e.Zmonospace=65338;e.Zsmall=63354;e.Zstroke=437;e.a=97;e.aabengali=2438;e.aacute=225;e.aadeva=2310;e.aagujarati=2694;e.aagurmukhi=2566;e.aamatragurmukhi=2622;e.aarusquare=13059;e.aavowelsignbengali=2494;e.aavowelsigndeva=2366;e.aavowelsigngujarati=2750;e.abbreviationmarkarmenian=1375;e.abbreviationsigndeva=2416;e.abengali=2437;e.abopomofo=12570;e.abreve=259;e.abreveacute=7855;e.abrevecyrillic=1233;e.abrevedotbelow=7863;e.abrevegrave=7857;e.abrevehookabove=7859;e.abrevetilde=7861;e.acaron=462;e.acircle=9424;e.acircumflex=226;e.acircumflexacute=7845;e.acircumflexdotbelow=7853;e.acircumflexgrave=7847;e.acircumflexhookabove=7849;e.acircumflextilde=7851;e.acute=180;e.acutebelowcmb=791;e.acutecmb=769;e.acutecomb=769;e.acutedeva=2388;e.acutelowmod=719;e.acutetonecmb=833;e.acyrillic=1072;e.adblgrave=513;e.addakgurmukhi=2673;e.adeva=2309;e.adieresis=228;e.adieresiscyrillic=1235;e.adieresismacron=479;e.adotbelow=7841;e.adotmacron=481;e.ae=230;e.aeacute=509;e.aekorean=12624;e.aemacron=483;e.afii00208=8213;e.afii08941=8356;e.afii10017=1040;e.afii10018=1041;e.afii10019=1042;e.afii10020=1043;e.afii10021=1044;e.afii10022=1045;e.afii10023=1025;e.afii10024=1046;e.afii10025=1047;e.afii10026=1048;e.afii10027=1049;e.afii10028=1050;e.afii10029=1051;e.afii10030=1052;e.afii10031=1053;e.afii10032=1054;e.afii10033=1055;e.afii10034=1056;e.afii10035=1057;e.afii10036=1058;e.afii10037=1059;e.afii10038=1060;e.afii10039=1061;e.afii10040=1062;e.afii10041=1063;e.afii10042=1064;e.afii10043=1065;e.afii10044=1066;e.afii10045=1067;e.afii10046=1068;e.afii10047=1069;e.afii10048=1070;e.afii10049=1071;e.afii10050=1168;e.afii10051=1026;e.afii10052=1027;e.afii10053=1028;e.afii10054=1029;e.afii10055=1030;e.afii10056=1031;e.afii10057=1032;e.afii10058=1033;e.afii10059=1034;e.afii10060=1035;e.afii10061=1036;e.afii10062=1038;e.afii10063=63172;e.afii10064=63173;e.afii10065=1072;e.afii10066=1073;e.afii10067=1074;e.afii10068=1075;e.afii10069=1076;e.afii10070=1077;e.afii10071=1105;e.afii10072=1078;e.afii10073=1079;e.afii10074=1080;e.afii10075=1081;e.afii10076=1082;e.afii10077=1083;e.afii10078=1084;e.afii10079=1085;e.afii10080=1086;e.afii10081=1087;e.afii10082=1088;e.afii10083=1089;e.afii10084=1090;e.afii10085=1091;e.afii10086=1092;e.afii10087=1093;e.afii10088=1094;e.afii10089=1095;e.afii10090=1096;e.afii10091=1097;e.afii10092=1098;e.afii10093=1099;e.afii10094=1100;e.afii10095=1101;e.afii10096=1102;e.afii10097=1103;e.afii10098=1169;e.afii10099=1106;e.afii10100=1107;e.afii10101=1108;e.afii10102=1109;e.afii10103=1110;e.afii10104=1111;e.afii10105=1112;e.afii10106=1113;e.afii10107=1114;e.afii10108=1115;e.afii10109=1116;e.afii10110=1118;e.afii10145=1039;e.afii10146=1122;e.afii10147=1138;e.afii10148=1140;e.afii10192=63174;e.afii10193=1119;e.afii10194=1123;e.afii10195=1139;e.afii10196=1141;e.afii10831=63175;e.afii10832=63176;e.afii10846=1241;e.afii299=8206;e.afii300=8207;e.afii301=8205;e.afii57381=1642;e.afii57388=1548;e.afii57392=1632;e.afii57393=1633;e.afii57394=1634;e.afii57395=1635;e.afii57396=1636;e.afii57397=1637;e.afii57398=1638;e.afii57399=1639;e.afii57400=1640;e.afii57401=1641;e.afii57403=1563;e.afii57407=1567;e.afii57409=1569;e.afii57410=1570;e.afii57411=1571;e.afii57412=1572;e.afii57413=1573;e.afii57414=1574;e.afii57415=1575;e.afii57416=1576;e.afii57417=1577;e.afii57418=1578;e.afii57419=1579;e.afii57420=1580;e.afii57421=1581;e.afii57422=1582;e.afii57423=1583;e.afii57424=1584;e.afii57425=1585;e.afii57426=1586;e.afii57427=1587;e.afii57428=1588;e.afii57429=1589;e.afii57430=1590;e.afii57431=1591;e.afii57432=1592;e.afii57433=1593;e.afii57434=1594;e.afii57440=1600;e.afii57441=1601;e.afii57442=1602;e.afii57443=1603;e.afii57444=1604;e.afii57445=1605;e.afii57446=1606;e.afii57448=1608;e.afii57449=1609;e.afii57450=1610;e.afii57451=1611;e.afii57452=1612;e.afii57453=1613;e.afii57454=1614;e.afii57455=1615;e.afii57456=1616;e.afii57457=1617;e.afii57458=1618;e.afii57470=1607;e.afii57505=1700;e.afii57506=1662;e.afii57507=1670;e.afii57508=1688;e.afii57509=1711;e.afii57511=1657;e.afii57512=1672;e.afii57513=1681;e.afii57514=1722;e.afii57519=1746;e.afii57534=1749;e.afii57636=8362;e.afii57645=1470;e.afii57658=1475;e.afii57664=1488;e.afii57665=1489;e.afii57666=1490;e.afii57667=1491;e.afii57668=1492;e.afii57669=1493;e.afii57670=1494;e.afii57671=1495;e.afii57672=1496;e.afii57673=1497;e.afii57674=1498;e.afii57675=1499;e.afii57676=1500;e.afii57677=1501;e.afii57678=1502;e.afii57679=1503;e.afii57680=1504;e.afii57681=1505;e.afii57682=1506;e.afii57683=1507;e.afii57684=1508;e.afii57685=1509;e.afii57686=1510;e.afii57687=1511;e.afii57688=1512;e.afii57689=1513;e.afii57690=1514;e.afii57694=64298;e.afii57695=64299;e.afii57700=64331;e.afii57705=64287;e.afii57716=1520;e.afii57717=1521;e.afii57718=1522;e.afii57723=64309;e.afii57793=1460;e.afii57794=1461;e.afii57795=1462;e.afii57796=1467;e.afii57797=1464;e.afii57798=1463;e.afii57799=1456;e.afii57800=1458;e.afii57801=1457;e.afii57802=1459;e.afii57803=1474;e.afii57804=1473;e.afii57806=1465;e.afii57807=1468;e.afii57839=1469;e.afii57841=1471;e.afii57842=1472;e.afii57929=700;e.afii61248=8453;e.afii61289=8467;e.afii61352=8470;e.afii61573=8236;e.afii61574=8237;e.afii61575=8238;e.afii61664=8204;e.afii63167=1645;e.afii64937=701;e.agrave=224;e.agujarati=2693;e.agurmukhi=2565;e.ahiragana=12354;e.ahookabove=7843;e.aibengali=2448;e.aibopomofo=12574;e.aideva=2320;e.aiecyrillic=1237;e.aigujarati=2704;e.aigurmukhi=2576;e.aimatragurmukhi=2632;e.ainarabic=1593;e.ainfinalarabic=65226;e.aininitialarabic=65227;e.ainmedialarabic=65228;e.ainvertedbreve=515;e.aivowelsignbengali=2504;e.aivowelsigndeva=2376;e.aivowelsigngujarati=2760;e.akatakana=12450;e.akatakanahalfwidth=65393;e.akorean=12623;e.alef=1488;e.alefarabic=1575;e.alefdageshhebrew=64304;e.aleffinalarabic=65166;e.alefhamzaabovearabic=1571;e.alefhamzaabovefinalarabic=65156;e.alefhamzabelowarabic=1573;e.alefhamzabelowfinalarabic=65160;e.alefhebrew=1488;e.aleflamedhebrew=64335;e.alefmaddaabovearabic=1570;e.alefmaddaabovefinalarabic=65154;e.alefmaksuraarabic=1609;e.alefmaksurafinalarabic=65264;e.alefmaksurainitialarabic=65267;e.alefmaksuramedialarabic=65268;e.alefpatahhebrew=64302;e.alefqamatshebrew=64303;e.aleph=8501;e.allequal=8780;e.alpha=945;e.alphatonos=940;e.amacron=257;e.amonospace=65345;e.ampersand=38;e.ampersandmonospace=65286;e.ampersandsmall=63270;e.amsquare=13250;e.anbopomofo=12578;e.angbopomofo=12580;e.angbracketleft=12296;e.angbracketright=12297;e.angkhankhuthai=3674;e.angle=8736;e.anglebracketleft=12296;e.anglebracketleftvertical=65087;e.anglebracketright=12297;e.anglebracketrightvertical=65088;e.angleleft=9001;e.angleright=9002;e.angstrom=8491;e.anoteleia=903;e.anudattadeva=2386;e.anusvarabengali=2434;e.anusvaradeva=2306;e.anusvaragujarati=2690;e.aogonek=261;e.apaatosquare=13056;e.aparen=9372;e.apostrophearmenian=1370;e.apostrophemod=700;e.apple=63743;e.approaches=8784;e.approxequal=8776;e.approxequalorimage=8786;e.approximatelyequal=8773;e.araeaekorean=12686;e.araeakorean=12685;e.arc=8978;e.arighthalfring=7834;e.aring=229;e.aringacute=507;e.aringbelow=7681;e.arrowboth=8596;e.arrowdashdown=8675;e.arrowdashleft=8672;e.arrowdashright=8674;e.arrowdashup=8673;e.arrowdblboth=8660;e.arrowdbldown=8659;e.arrowdblleft=8656;e.arrowdblright=8658;e.arrowdblup=8657;e.arrowdown=8595;e.arrowdownleft=8601;e.arrowdownright=8600;e.arrowdownwhite=8681;e.arrowheaddownmod=709;e.arrowheadleftmod=706;e.arrowheadrightmod=707;e.arrowheadupmod=708;e.arrowhorizex=63719;e.arrowleft=8592;e.arrowleftdbl=8656;e.arrowleftdblstroke=8653;e.arrowleftoverright=8646;e.arrowleftwhite=8678;e.arrowright=8594;e.arrowrightdblstroke=8655;e.arrowrightheavy=10142;e.arrowrightoverleft=8644;e.arrowrightwhite=8680;e.arrowtableft=8676;e.arrowtabright=8677;e.arrowup=8593;e.arrowupdn=8597;e.arrowupdnbse=8616;e.arrowupdownbase=8616;e.arrowupleft=8598;e.arrowupleftofdown=8645;e.arrowupright=8599;e.arrowupwhite=8679;e.arrowvertex=63718;e.asciicircum=94;e.asciicircummonospace=65342;e.asciitilde=126;e.asciitildemonospace=65374;e.ascript=593;e.ascriptturned=594;e.asmallhiragana=12353;e.asmallkatakana=12449;e.asmallkatakanahalfwidth=65383;e.asterisk=42;e.asteriskaltonearabic=1645;e.asteriskarabic=1645;e.asteriskmath=8727;e.asteriskmonospace=65290;e.asterisksmall=65121;e.asterism=8258;e.asuperior=63209;e.asymptoticallyequal=8771;e.at=64;e.atilde=227;e.atmonospace=65312;e.atsmall=65131;e.aturned=592;e.aubengali=2452;e.aubopomofo=12576;e.audeva=2324;e.augujarati=2708;e.augurmukhi=2580;e.aulengthmarkbengali=2519;e.aumatragurmukhi=2636;e.auvowelsignbengali=2508;e.auvowelsigndeva=2380;e.auvowelsigngujarati=2764;e.avagrahadeva=2365;e.aybarmenian=1377;e.ayin=1506;e.ayinaltonehebrew=64288;e.ayinhebrew=1506;e.b=98;e.babengali=2476;e.backslash=92;e.backslashmonospace=65340;e.badeva=2348;e.bagujarati=2732;e.bagurmukhi=2604;e.bahiragana=12400;e.bahtthai=3647;e.bakatakana=12496;e.bar=124;e.barmonospace=65372;e.bbopomofo=12549;e.bcircle=9425;e.bdotaccent=7683;e.bdotbelow=7685;e.beamedsixteenthnotes=9836;e.because=8757;e.becyrillic=1073;e.beharabic=1576;e.behfinalarabic=65168;e.behinitialarabic=65169;e.behiragana=12409;e.behmedialarabic=65170;e.behmeeminitialarabic=64671;e.behmeemisolatedarabic=64520;e.behnoonfinalarabic=64621;e.bekatakana=12505;e.benarmenian=1378;e.bet=1489;e.beta=946;e.betasymbolgreek=976;e.betdagesh=64305;e.betdageshhebrew=64305;e.bethebrew=1489;e.betrafehebrew=64332;e.bhabengali=2477;e.bhadeva=2349;e.bhagujarati=2733;e.bhagurmukhi=2605;e.bhook=595;e.bihiragana=12403;e.bikatakana=12499;e.bilabialclick=664;e.bindigurmukhi=2562;e.birusquare=13105;e.blackcircle=9679;e.blackdiamond=9670;e.blackdownpointingtriangle=9660;e.blackleftpointingpointer=9668;e.blackleftpointingtriangle=9664;e.blacklenticularbracketleft=12304;e.blacklenticularbracketleftvertical=65083;e.blacklenticularbracketright=12305;e.blacklenticularbracketrightvertical=65084;e.blacklowerlefttriangle=9699;e.blacklowerrighttriangle=9698;e.blackrectangle=9644;e.blackrightpointingpointer=9658;e.blackrightpointingtriangle=9654;e.blacksmallsquare=9642;e.blacksmilingface=9787;e.blacksquare=9632;e.blackstar=9733;e.blackupperlefttriangle=9700;e.blackupperrighttriangle=9701;e.blackuppointingsmalltriangle=9652;e.blackuppointingtriangle=9650;e.blank=9251;e.blinebelow=7687;e.block=9608;e.bmonospace=65346;e.bobaimaithai=3610;e.bohiragana=12412;e.bokatakana=12508;e.bparen=9373;e.bqsquare=13251;e.braceex=63732;e.braceleft=123;e.braceleftbt=63731;e.braceleftmid=63730;e.braceleftmonospace=65371;e.braceleftsmall=65115;e.bracelefttp=63729;e.braceleftvertical=65079;e.braceright=125;e.bracerightbt=63742;e.bracerightmid=63741;e.bracerightmonospace=65373;e.bracerightsmall=65116;e.bracerighttp=63740;e.bracerightvertical=65080;e.bracketleft=91;e.bracketleftbt=63728;e.bracketleftex=63727;e.bracketleftmonospace=65339;e.bracketlefttp=63726;e.bracketright=93;e.bracketrightbt=63739;e.bracketrightex=63738;e.bracketrightmonospace=65341;e.bracketrighttp=63737;e.breve=728;e.brevebelowcmb=814;e.brevecmb=774;e.breveinvertedbelowcmb=815;e.breveinvertedcmb=785;e.breveinverteddoublecmb=865;e.bridgebelowcmb=810;e.bridgeinvertedbelowcmb=826;e.brokenbar=166;e.bstroke=384;e.bsuperior=63210;e.btopbar=387;e.buhiragana=12406;e.bukatakana=12502;e.bullet=8226;e.bulletinverse=9688;e.bulletoperator=8729;e.bullseye=9678;e.c=99;e.caarmenian=1390;e.cabengali=2458;e.cacute=263;e.cadeva=2330;e.cagujarati=2714;e.cagurmukhi=2586;e.calsquare=13192;e.candrabindubengali=2433;e.candrabinducmb=784;e.candrabindudeva=2305;e.candrabindugujarati=2689;e.capslock=8682;e.careof=8453;e.caron=711;e.caronbelowcmb=812;e.caroncmb=780;e.carriagereturn=8629;e.cbopomofo=12568;e.ccaron=269;e.ccedilla=231;e.ccedillaacute=7689;e.ccircle=9426;e.ccircumflex=265;e.ccurl=597;e.cdot=267;e.cdotaccent=267;e.cdsquare=13253;e.cedilla=184;e.cedillacmb=807;e.cent=162;e.centigrade=8451;e.centinferior=63199;e.centmonospace=65504;e.centoldstyle=63394;e.centsuperior=63200;e.chaarmenian=1401;e.chabengali=2459;e.chadeva=2331;e.chagujarati=2715;e.chagurmukhi=2587;e.chbopomofo=12564;e.cheabkhasiancyrillic=1213;e.checkmark=10003;e.checyrillic=1095;e.chedescenderabkhasiancyrillic=1215;e.chedescendercyrillic=1207;e.chedieresiscyrillic=1269;e.cheharmenian=1395;e.chekhakassiancyrillic=1228;e.cheverticalstrokecyrillic=1209;e.chi=967;e.chieuchacirclekorean=12919;e.chieuchaparenkorean=12823;e.chieuchcirclekorean=12905;e.chieuchkorean=12618;e.chieuchparenkorean=12809;e.chochangthai=3594;e.chochanthai=3592;e.chochingthai=3593;e.chochoethai=3596;e.chook=392;e.cieucacirclekorean=12918;e.cieucaparenkorean=12822;e.cieuccirclekorean=12904;e.cieuckorean=12616;e.cieucparenkorean=12808;e.cieucuparenkorean=12828;e.circle=9675;e.circlecopyrt=169;e.circlemultiply=8855;e.circleot=8857;e.circleplus=8853;e.circlepostalmark=12342;e.circlewithlefthalfblack=9680;e.circlewithrighthalfblack=9681;e.circumflex=710;e.circumflexbelowcmb=813;e.circumflexcmb=770;e.clear=8999;e.clickalveolar=450;e.clickdental=448;e.clicklateral=449;e.clickretroflex=451;e.club=9827;e.clubsuitblack=9827;e.clubsuitwhite=9831;e.cmcubedsquare=13220;e.cmonospace=65347;e.cmsquaredsquare=13216;e.coarmenian=1409;e.colon=58;e.colonmonetary=8353;e.colonmonospace=65306;e.colonsign=8353;e.colonsmall=65109;e.colontriangularhalfmod=721;e.colontriangularmod=720;e.comma=44;e.commaabovecmb=787;e.commaaboverightcmb=789;e.commaaccent=63171;e.commaarabic=1548;e.commaarmenian=1373;e.commainferior=63201;e.commamonospace=65292;e.commareversedabovecmb=788;e.commareversedmod=701;e.commasmall=65104;e.commasuperior=63202;e.commaturnedabovecmb=786;e.commaturnedmod=699;e.compass=9788;e.congruent=8773;e.contourintegral=8750;e.control=8963;e.controlACK=6;e.controlBEL=7;e.controlBS=8;e.controlCAN=24;e.controlCR=13;e.controlDC1=17;e.controlDC2=18;e.controlDC3=19;e.controlDC4=20;e.controlDEL=127;e.controlDLE=16;e.controlEM=25;e.controlENQ=5;e.controlEOT=4;e.controlESC=27;e.controlETB=23;e.controlETX=3;e.controlFF=12;e.controlFS=28;e.controlGS=29;e.controlHT=9;e.controlLF=10;e.controlNAK=21;e.controlNULL=0;e.controlRS=30;e.controlSI=15;e.controlSO=14;e.controlSOT=2;e.controlSTX=1;e.controlSUB=26;e.controlSYN=22;e.controlUS=31;e.controlVT=11;e.copyright=169;e.copyrightsans=63721;e.copyrightserif=63193;e.cornerbracketleft=12300;e.cornerbracketlefthalfwidth=65378;e.cornerbracketleftvertical=65089;e.cornerbracketright=12301;e.cornerbracketrighthalfwidth=65379;e.cornerbracketrightvertical=65090;e.corporationsquare=13183;e.cosquare=13255;e.coverkgsquare=13254;e.cparen=9374;e.cruzeiro=8354;e.cstretched=663;e.curlyand=8911;e.curlyor=8910;e.currency=164;e.cyrBreve=63185;e.cyrFlex=63186;e.cyrbreve=63188;e.cyrflex=63189;e.d=100;e.daarmenian=1380;e.dabengali=2470;e.dadarabic=1590;e.dadeva=2342;e.dadfinalarabic=65214;e.dadinitialarabic=65215;e.dadmedialarabic=65216;e.dagesh=1468;e.dageshhebrew=1468;e.dagger=8224;e.daggerdbl=8225;e.dagujarati=2726;e.dagurmukhi=2598;e.dahiragana=12384;e.dakatakana=12480;e.dalarabic=1583;e.dalet=1491;e.daletdagesh=64307;e.daletdageshhebrew=64307;e.dalethebrew=1491;e.dalfinalarabic=65194;e.dammaarabic=1615;e.dammalowarabic=1615;e.dammatanaltonearabic=1612;e.dammatanarabic=1612;e.danda=2404;e.dargahebrew=1447;e.dargalefthebrew=1447;e.dasiapneumatacyrilliccmb=1157;e.dblGrave=63187;e.dblanglebracketleft=12298;e.dblanglebracketleftvertical=65085;e.dblanglebracketright=12299;e.dblanglebracketrightvertical=65086;e.dblarchinvertedbelowcmb=811;e.dblarrowleft=8660;e.dblarrowright=8658;e.dbldanda=2405;e.dblgrave=63190;e.dblgravecmb=783;e.dblintegral=8748;e.dbllowline=8215;e.dbllowlinecmb=819;e.dbloverlinecmb=831;e.dblprimemod=698;e.dblverticalbar=8214;e.dblverticallineabovecmb=782;e.dbopomofo=12553;e.dbsquare=13256;e.dcaron=271;e.dcedilla=7697;e.dcircle=9427;e.dcircumflexbelow=7699;e.dcroat=273;e.ddabengali=2465;e.ddadeva=2337;e.ddagujarati=2721;e.ddagurmukhi=2593;e.ddalarabic=1672;e.ddalfinalarabic=64393;e.dddhadeva=2396;e.ddhabengali=2466;e.ddhadeva=2338;e.ddhagujarati=2722;e.ddhagurmukhi=2594;e.ddotaccent=7691;e.ddotbelow=7693;e.decimalseparatorarabic=1643;e.decimalseparatorpersian=1643;e.decyrillic=1076;e.degree=176;e.dehihebrew=1453;e.dehiragana=12391;e.deicoptic=1007;e.dekatakana=12487;e.deleteleft=9003;e.deleteright=8998;e.delta=948;e.deltaturned=397;e.denominatorminusonenumeratorbengali=2552;e.dezh=676;e.dhabengali=2471;e.dhadeva=2343;e.dhagujarati=2727;e.dhagurmukhi=2599;e.dhook=599;e.dialytikatonos=901;e.dialytikatonoscmb=836;e.diamond=9830;e.diamondsuitwhite=9826;e.dieresis=168;e.dieresisacute=63191;e.dieresisbelowcmb=804;e.dieresiscmb=776;e.dieresisgrave=63192;e.dieresistonos=901;e.dihiragana=12386;e.dikatakana=12482;e.dittomark=12291;e.divide=247;e.divides=8739;e.divisionslash=8725;e.djecyrillic=1106;e.dkshade=9619;e.dlinebelow=7695;e.dlsquare=13207;e.dmacron=273;e.dmonospace=65348;e.dnblock=9604;e.dochadathai=3598;e.dodekthai=3604;e.dohiragana=12393;e.dokatakana=12489;e.dollar=36;e.dollarinferior=63203;e.dollarmonospace=65284;e.dollaroldstyle=63268;e.dollarsmall=65129;e.dollarsuperior=63204;e.dong=8363;e.dorusquare=13094;e.dotaccent=729;e.dotaccentcmb=775;e.dotbelowcmb=803;e.dotbelowcomb=803;e.dotkatakana=12539;e.dotlessi=305;e.dotlessj=63166;e.dotlessjstrokehook=644;e.dotmath=8901;e.dottedcircle=9676;e.doubleyodpatah=64287;e.doubleyodpatahhebrew=64287;e.downtackbelowcmb=798;e.downtackmod=725;e.dparen=9375;e.dsuperior=63211;e.dtail=598;e.dtopbar=396;e.duhiragana=12389;e.dukatakana=12485;e.dz=499;e.dzaltone=675;e.dzcaron=454;e.dzcurl=677;e.dzeabkhasiancyrillic=1249;e.dzecyrillic=1109;e.dzhecyrillic=1119;e.e=101;e.eacute=233;e.earth=9793;e.ebengali=2447;e.ebopomofo=12572;e.ebreve=277;e.ecandradeva=2317;e.ecandragujarati=2701;e.ecandravowelsigndeva=2373;e.ecandravowelsigngujarati=2757;e.ecaron=283;e.ecedillabreve=7709;e.echarmenian=1381;e.echyiwnarmenian=1415;e.ecircle=9428;e.ecircumflex=234;e.ecircumflexacute=7871;e.ecircumflexbelow=7705;e.ecircumflexdotbelow=7879;e.ecircumflexgrave=7873;e.ecircumflexhookabove=7875;e.ecircumflextilde=7877;e.ecyrillic=1108;e.edblgrave=517;e.edeva=2319;e.edieresis=235;e.edot=279;e.edotaccent=279;e.edotbelow=7865;e.eegurmukhi=2575;e.eematragurmukhi=2631;e.efcyrillic=1092;e.egrave=232;e.egujarati=2703;e.eharmenian=1383;e.ehbopomofo=12573;e.ehiragana=12360;e.ehookabove=7867;e.eibopomofo=12575;e.eight=56;e.eightarabic=1640;e.eightbengali=2542;e.eightcircle=9319;e.eightcircleinversesansserif=10129;e.eightdeva=2414;e.eighteencircle=9329;e.eighteenparen=9349;e.eighteenperiod=9369;e.eightgujarati=2798;e.eightgurmukhi=2670;e.eighthackarabic=1640;e.eighthangzhou=12328;e.eighthnotebeamed=9835;e.eightideographicparen=12839;e.eightinferior=8328;e.eightmonospace=65304;e.eightoldstyle=63288;e.eightparen=9339;e.eightperiod=9359;e.eightpersian=1784;e.eightroman=8567;e.eightsuperior=8312;e.eightthai=3672;e.einvertedbreve=519;e.eiotifiedcyrillic=1125;e.ekatakana=12456;e.ekatakanahalfwidth=65396;e.ekonkargurmukhi=2676;e.ekorean=12628;e.elcyrillic=1083;e.element=8712;e.elevencircle=9322;e.elevenparen=9342;e.elevenperiod=9362;e.elevenroman=8570;e.ellipsis=8230;e.ellipsisvertical=8942;e.emacron=275;e.emacronacute=7703;e.emacrongrave=7701;e.emcyrillic=1084;e.emdash=8212;e.emdashvertical=65073;e.emonospace=65349;e.emphasismarkarmenian=1371;e.emptyset=8709;e.enbopomofo=12579;e.encyrillic=1085;e.endash=8211;e.endashvertical=65074;e.endescendercyrillic=1187;e.eng=331;e.engbopomofo=12581;e.enghecyrillic=1189;e.enhookcyrillic=1224;e.enspace=8194;e.eogonek=281;e.eokorean=12627;e.eopen=603;e.eopenclosed=666;e.eopenreversed=604;e.eopenreversedclosed=606;e.eopenreversedhook=605;e.eparen=9376;e.epsilon=949;e.epsilontonos=941;e.equal=61;e.equalmonospace=65309;e.equalsmall=65126;e.equalsuperior=8316;e.equivalence=8801;e.erbopomofo=12582;e.ercyrillic=1088;e.ereversed=600;e.ereversedcyrillic=1101;e.escyrillic=1089;e.esdescendercyrillic=1195;e.esh=643;e.eshcurl=646;e.eshortdeva=2318;e.eshortvowelsigndeva=2374;e.eshreversedloop=426;e.eshsquatreversed=645;e.esmallhiragana=12359;e.esmallkatakana=12455;e.esmallkatakanahalfwidth=65386;e.estimated=8494;e.esuperior=63212;e.eta=951;e.etarmenian=1384;e.etatonos=942;e.eth=240;e.etilde=7869;e.etildebelow=7707;e.etnahtafoukhhebrew=1425;e.etnahtafoukhlefthebrew=1425;e.etnahtahebrew=1425;e.etnahtalefthebrew=1425;e.eturned=477;e.eukorean=12641;e.euro=8364;e.evowelsignbengali=2503;e.evowelsigndeva=2375;e.evowelsigngujarati=2759;e.exclam=33;e.exclamarmenian=1372;e.exclamdbl=8252;e.exclamdown=161;e.exclamdownsmall=63393;e.exclammonospace=65281;e.exclamsmall=63265;e.existential=8707;e.ezh=658;e.ezhcaron=495;e.ezhcurl=659;e.ezhreversed=441;e.ezhtail=442;e.f=102;e.fadeva=2398;e.fagurmukhi=2654;e.fahrenheit=8457;e.fathaarabic=1614;e.fathalowarabic=1614;e.fathatanarabic=1611;e.fbopomofo=12552;e.fcircle=9429;e.fdotaccent=7711;e.feharabic=1601;e.feharmenian=1414;e.fehfinalarabic=65234;e.fehinitialarabic=65235;e.fehmedialarabic=65236;e.feicoptic=997;e.female=9792;e.ff=64256;e.f_f=64256;e.ffi=64259;e.f_f_i=64259;e.ffl=64260;e.f_f_l=64260;e.fi=64257;e.f_i=64257;e.fifteencircle=9326;e.fifteenparen=9346;e.fifteenperiod=9366;e.figuredash=8210;e.filledbox=9632;e.filledrect=9644;e.finalkaf=1498;e.finalkafdagesh=64314;e.finalkafdageshhebrew=64314;e.finalkafhebrew=1498;e.finalmem=1501;e.finalmemhebrew=1501;e.finalnun=1503;e.finalnunhebrew=1503;e.finalpe=1507;e.finalpehebrew=1507;e.finaltsadi=1509;e.finaltsadihebrew=1509;e.firsttonechinese=713;e.fisheye=9673;e.fitacyrillic=1139;e.five=53;e.fivearabic=1637;e.fivebengali=2539;e.fivecircle=9316;e.fivecircleinversesansserif=10126;e.fivedeva=2411;e.fiveeighths=8541;e.fivegujarati=2795;e.fivegurmukhi=2667;e.fivehackarabic=1637;e.fivehangzhou=12325;e.fiveideographicparen=12836;e.fiveinferior=8325;e.fivemonospace=65301;e.fiveoldstyle=63285;e.fiveparen=9336;e.fiveperiod=9356;e.fivepersian=1781;e.fiveroman=8564;e.fivesuperior=8309;e.fivethai=3669;e.fl=64258;e.f_l=64258;e.florin=402;e.fmonospace=65350;e.fmsquare=13209;e.fofanthai=3615;e.fofathai=3613;e.fongmanthai=3663;e.forall=8704;e.four=52;e.fourarabic=1636;e.fourbengali=2538;e.fourcircle=9315;e.fourcircleinversesansserif=10125;e.fourdeva=2410;e.fourgujarati=2794;e.fourgurmukhi=2666;e.fourhackarabic=1636;e.fourhangzhou=12324;e.fourideographicparen=12835;e.fourinferior=8324;e.fourmonospace=65300;e.fournumeratorbengali=2551;e.fouroldstyle=63284;e.fourparen=9335;e.fourperiod=9355;e.fourpersian=1780;e.fourroman=8563;e.foursuperior=8308;e.fourteencircle=9325;e.fourteenparen=9345;e.fourteenperiod=9365;e.fourthai=3668;e.fourthtonechinese=715;e.fparen=9377;e.fraction=8260;e.franc=8355;e.g=103;e.gabengali=2455;e.gacute=501;e.gadeva=2327;e.gafarabic=1711;e.gaffinalarabic=64403;e.gafinitialarabic=64404;e.gafmedialarabic=64405;e.gagujarati=2711;e.gagurmukhi=2583;e.gahiragana=12364;e.gakatakana=12460;e.gamma=947;e.gammalatinsmall=611;e.gammasuperior=736;e.gangiacoptic=1003;e.gbopomofo=12557;e.gbreve=287;e.gcaron=487;e.gcedilla=291;e.gcircle=9430;e.gcircumflex=285;e.gcommaaccent=291;e.gdot=289;e.gdotaccent=289;e.gecyrillic=1075;e.gehiragana=12370;e.gekatakana=12466;e.geometricallyequal=8785;e.gereshaccenthebrew=1436;e.gereshhebrew=1523;e.gereshmuqdamhebrew=1437;e.germandbls=223;e.gershayimaccenthebrew=1438;e.gershayimhebrew=1524;e.getamark=12307;e.ghabengali=2456;e.ghadarmenian=1394;e.ghadeva=2328;e.ghagujarati=2712;e.ghagurmukhi=2584;e.ghainarabic=1594;e.ghainfinalarabic=65230;e.ghaininitialarabic=65231;e.ghainmedialarabic=65232;e.ghemiddlehookcyrillic=1173;e.ghestrokecyrillic=1171;e.gheupturncyrillic=1169;e.ghhadeva=2394;e.ghhagurmukhi=2650;e.ghook=608;e.ghzsquare=13203;e.gihiragana=12366;e.gikatakana=12462;e.gimarmenian=1379;e.gimel=1490;e.gimeldagesh=64306;e.gimeldageshhebrew=64306;e.gimelhebrew=1490;e.gjecyrillic=1107;e.glottalinvertedstroke=446;e.glottalstop=660;e.glottalstopinverted=662;e.glottalstopmod=704;e.glottalstopreversed=661;e.glottalstopreversedmod=705;e.glottalstopreversedsuperior=740;e.glottalstopstroke=673;e.glottalstopstrokereversed=674;e.gmacron=7713;e.gmonospace=65351;e.gohiragana=12372;e.gokatakana=12468;e.gparen=9378;e.gpasquare=13228;e.gradient=8711;e.grave=96;e.gravebelowcmb=790;e.gravecmb=768;e.gravecomb=768;e.gravedeva=2387;e.gravelowmod=718;e.gravemonospace=65344;e.gravetonecmb=832;e.greater=62;e.greaterequal=8805;e.greaterequalorless=8923;e.greatermonospace=65310;e.greaterorequivalent=8819;e.greaterorless=8823;e.greateroverequal=8807;e.greatersmall=65125;e.gscript=609;e.gstroke=485;e.guhiragana=12368;e.guillemotleft=171;e.guillemotright=187;e.guilsinglleft=8249;e.guilsinglright=8250;e.gukatakana=12464;e.guramusquare=13080;e.gysquare=13257;e.h=104;e.haabkhasiancyrillic=1193;e.haaltonearabic=1729;e.habengali=2489;e.hadescendercyrillic=1203;e.hadeva=2361;e.hagujarati=2745;e.hagurmukhi=2617;e.haharabic=1581;e.hahfinalarabic=65186;e.hahinitialarabic=65187;e.hahiragana=12399;e.hahmedialarabic=65188;e.haitusquare=13098;e.hakatakana=12495;e.hakatakanahalfwidth=65418;e.halantgurmukhi=2637;e.hamzaarabic=1569;e.hamzalowarabic=1569;e.hangulfiller=12644;e.hardsigncyrillic=1098;e.harpoonleftbarbup=8636;e.harpoonrightbarbup=8640;e.hasquare=13258;e.hatafpatah=1458;e.hatafpatah16=1458;e.hatafpatah23=1458;e.hatafpatah2f=1458;e.hatafpatahhebrew=1458;e.hatafpatahnarrowhebrew=1458;e.hatafpatahquarterhebrew=1458;e.hatafpatahwidehebrew=1458;e.hatafqamats=1459;e.hatafqamats1b=1459;e.hatafqamats28=1459;e.hatafqamats34=1459;e.hatafqamatshebrew=1459;e.hatafqamatsnarrowhebrew=1459;e.hatafqamatsquarterhebrew=1459;e.hatafqamatswidehebrew=1459;e.hatafsegol=1457;e.hatafsegol17=1457;e.hatafsegol24=1457;e.hatafsegol30=1457;e.hatafsegolhebrew=1457;e.hatafsegolnarrowhebrew=1457;e.hatafsegolquarterhebrew=1457;e.hatafsegolwidehebrew=1457;e.hbar=295;e.hbopomofo=12559;e.hbrevebelow=7723;e.hcedilla=7721;e.hcircle=9431;e.hcircumflex=293;e.hdieresis=7719;e.hdotaccent=7715;e.hdotbelow=7717;e.he=1492;e.heart=9829;e.heartsuitblack=9829;e.heartsuitwhite=9825;e.hedagesh=64308;e.hedageshhebrew=64308;e.hehaltonearabic=1729;e.heharabic=1607;e.hehebrew=1492;e.hehfinalaltonearabic=64423;e.hehfinalalttwoarabic=65258;e.hehfinalarabic=65258;e.hehhamzaabovefinalarabic=64421;e.hehhamzaaboveisolatedarabic=64420;e.hehinitialaltonearabic=64424;e.hehinitialarabic=65259;e.hehiragana=12408;e.hehmedialaltonearabic=64425;e.hehmedialarabic=65260;e.heiseierasquare=13179;e.hekatakana=12504;e.hekatakanahalfwidth=65421;e.hekutaarusquare=13110;e.henghook=615;e.herutusquare=13113;e.het=1495;e.hethebrew=1495;e.hhook=614;e.hhooksuperior=689;e.hieuhacirclekorean=12923;e.hieuhaparenkorean=12827;e.hieuhcirclekorean=12909;e.hieuhkorean=12622;e.hieuhparenkorean=12813;e.hihiragana=12402;e.hikatakana=12498;e.hikatakanahalfwidth=65419;e.hiriq=1460;e.hiriq14=1460;e.hiriq21=1460;e.hiriq2d=1460;e.hiriqhebrew=1460;e.hiriqnarrowhebrew=1460;e.hiriqquarterhebrew=1460;e.hiriqwidehebrew=1460;e.hlinebelow=7830;e.hmonospace=65352;e.hoarmenian=1392;e.hohipthai=3627;e.hohiragana=12411;e.hokatakana=12507;e.hokatakanahalfwidth=65422;e.holam=1465;e.holam19=1465;e.holam26=1465;e.holam32=1465;e.holamhebrew=1465;e.holamnarrowhebrew=1465;e.holamquarterhebrew=1465;e.holamwidehebrew=1465;e.honokhukthai=3630;e.hookabovecomb=777;e.hookcmb=777;e.hookpalatalizedbelowcmb=801;e.hookretroflexbelowcmb=802;e.hoonsquare=13122;e.horicoptic=1001;e.horizontalbar=8213;e.horncmb=795;e.hotsprings=9832;e.house=8962;e.hparen=9379;e.hsuperior=688;e.hturned=613;e.huhiragana=12405;e.huiitosquare=13107;e.hukatakana=12501;e.hukatakanahalfwidth=65420;e.hungarumlaut=733;e.hungarumlautcmb=779;e.hv=405;e.hyphen=45;e.hypheninferior=63205;e.hyphenmonospace=65293;e.hyphensmall=65123;e.hyphensuperior=63206;e.hyphentwo=8208;e.i=105;e.iacute=237;e.iacyrillic=1103;e.ibengali=2439;e.ibopomofo=12583;e.ibreve=301;e.icaron=464;e.icircle=9432;e.icircumflex=238;e.icyrillic=1110;e.idblgrave=521;e.ideographearthcircle=12943;e.ideographfirecircle=12939;e.ideographicallianceparen=12863;e.ideographiccallparen=12858;e.ideographiccentrecircle=12965;e.ideographicclose=12294;e.ideographiccomma=12289;e.ideographiccommaleft=65380;e.ideographiccongratulationparen=12855;e.ideographiccorrectcircle=12963;e.ideographicearthparen=12847;e.ideographicenterpriseparen=12861;e.ideographicexcellentcircle=12957;e.ideographicfestivalparen=12864;e.ideographicfinancialcircle=12950;e.ideographicfinancialparen=12854;e.ideographicfireparen=12843;e.ideographichaveparen=12850;e.ideographichighcircle=12964;e.ideographiciterationmark=12293;e.ideographiclaborcircle=12952;e.ideographiclaborparen=12856;e.ideographicleftcircle=12967;e.ideographiclowcircle=12966;e.ideographicmedicinecircle=12969;e.ideographicmetalparen=12846;e.ideographicmoonparen=12842;e.ideographicnameparen=12852;e.ideographicperiod=12290;e.ideographicprintcircle=12958;e.ideographicreachparen=12867;e.ideographicrepresentparen=12857;e.ideographicresourceparen=12862;e.ideographicrightcircle=12968;e.ideographicsecretcircle=12953;e.ideographicselfparen=12866;e.ideographicsocietyparen=12851;e.ideographicspace=12288;e.ideographicspecialparen=12853;e.ideographicstockparen=12849;e.ideographicstudyparen=12859;e.ideographicsunparen=12848;e.ideographicsuperviseparen=12860;e.ideographicwaterparen=12844;e.ideographicwoodparen=12845;e.ideographiczero=12295;e.ideographmetalcircle=12942;e.ideographmooncircle=12938;e.ideographnamecircle=12948;e.ideographsuncircle=12944;e.ideographwatercircle=12940;e.ideographwoodcircle=12941;e.ideva=2311;e.idieresis=239;e.idieresisacute=7727;e.idieresiscyrillic=1253;e.idotbelow=7883;e.iebrevecyrillic=1239;e.iecyrillic=1077;e.ieungacirclekorean=12917;e.ieungaparenkorean=12821;e.ieungcirclekorean=12903;e.ieungkorean=12615;e.ieungparenkorean=12807;e.igrave=236;e.igujarati=2695;e.igurmukhi=2567;e.ihiragana=12356;e.ihookabove=7881;e.iibengali=2440;e.iicyrillic=1080;e.iideva=2312;e.iigujarati=2696;e.iigurmukhi=2568;e.iimatragurmukhi=2624;e.iinvertedbreve=523;e.iishortcyrillic=1081;e.iivowelsignbengali=2496;e.iivowelsigndeva=2368;e.iivowelsigngujarati=2752;e.ij=307;e.ikatakana=12452;e.ikatakanahalfwidth=65394;e.ikorean=12643;e.ilde=732;e.iluyhebrew=1452;e.imacron=299;e.imacroncyrillic=1251;e.imageorapproximatelyequal=8787;e.imatragurmukhi=2623;e.imonospace=65353;e.increment=8710;e.infinity=8734;e.iniarmenian=1387;e.integral=8747;e.integralbottom=8993;e.integralbt=8993;e.integralex=63733;e.integraltop=8992;e.integraltp=8992;e.intersection=8745;e.intisquare=13061;e.invbullet=9688;e.invcircle=9689;e.invsmileface=9787;e.iocyrillic=1105;e.iogonek=303;e.iota=953;e.iotadieresis=970;e.iotadieresistonos=912;e.iotalatin=617;e.iotatonos=943;e.iparen=9380;e.irigurmukhi=2674;e.ismallhiragana=12355;e.ismallkatakana=12451;e.ismallkatakanahalfwidth=65384;e.issharbengali=2554;e.istroke=616;e.isuperior=63213;e.iterationhiragana=12445;e.iterationkatakana=12541;e.itilde=297;e.itildebelow=7725;e.iubopomofo=12585;e.iucyrillic=1102;e.ivowelsignbengali=2495;e.ivowelsigndeva=2367;e.ivowelsigngujarati=2751;e.izhitsacyrillic=1141;e.izhitsadblgravecyrillic=1143;e.j=106;e.jaarmenian=1393;e.jabengali=2460;e.jadeva=2332;e.jagujarati=2716;e.jagurmukhi=2588;e.jbopomofo=12560;e.jcaron=496;e.jcircle=9433;e.jcircumflex=309;e.jcrossedtail=669;e.jdotlessstroke=607;e.jecyrillic=1112;e.jeemarabic=1580;e.jeemfinalarabic=65182;e.jeeminitialarabic=65183;e.jeemmedialarabic=65184;e.jeharabic=1688;e.jehfinalarabic=64395;e.jhabengali=2461;e.jhadeva=2333;e.jhagujarati=2717;e.jhagurmukhi=2589;e.jheharmenian=1403;e.jis=12292;e.jmonospace=65354;e.jparen=9381;e.jsuperior=690;e.k=107;e.kabashkircyrillic=1185;e.kabengali=2453;e.kacute=7729;e.kacyrillic=1082;e.kadescendercyrillic=1179;e.kadeva=2325;e.kaf=1499;e.kafarabic=1603;e.kafdagesh=64315;e.kafdageshhebrew=64315;e.kaffinalarabic=65242;e.kafhebrew=1499;e.kafinitialarabic=65243;e.kafmedialarabic=65244;e.kafrafehebrew=64333;e.kagujarati=2709;e.kagurmukhi=2581;e.kahiragana=12363;e.kahookcyrillic=1220;e.kakatakana=12459;e.kakatakanahalfwidth=65398;e.kappa=954;e.kappasymbolgreek=1008;e.kapyeounmieumkorean=12657;e.kapyeounphieuphkorean=12676;e.kapyeounpieupkorean=12664;e.kapyeounssangpieupkorean=12665;e.karoriisquare=13069;e.kashidaautoarabic=1600;e.kashidaautonosidebearingarabic=1600;e.kasmallkatakana=12533;e.kasquare=13188;e.kasraarabic=1616;e.kasratanarabic=1613;e.kastrokecyrillic=1183;e.katahiraprolongmarkhalfwidth=65392;e.kaverticalstrokecyrillic=1181;e.kbopomofo=12558;e.kcalsquare=13193;e.kcaron=489;e.kcedilla=311;e.kcircle=9434;e.kcommaaccent=311;e.kdotbelow=7731;e.keharmenian=1412;e.kehiragana=12369;e.kekatakana=12465;e.kekatakanahalfwidth=65401;e.kenarmenian=1391;e.kesmallkatakana=12534;e.kgreenlandic=312;e.khabengali=2454;e.khacyrillic=1093;e.khadeva=2326;e.khagujarati=2710;e.khagurmukhi=2582;e.khaharabic=1582;e.khahfinalarabic=65190;e.khahinitialarabic=65191;e.khahmedialarabic=65192;e.kheicoptic=999;e.khhadeva=2393;e.khhagurmukhi=2649;e.khieukhacirclekorean=12920;e.khieukhaparenkorean=12824;e.khieukhcirclekorean=12906;e.khieukhkorean=12619;e.khieukhparenkorean=12810;e.khokhaithai=3586;e.khokhonthai=3589;e.khokhuatthai=3587;e.khokhwaithai=3588;e.khomutthai=3675;e.khook=409;e.khorakhangthai=3590;e.khzsquare=13201;e.kihiragana=12365;e.kikatakana=12461;e.kikatakanahalfwidth=65399;e.kiroguramusquare=13077;e.kiromeetorusquare=13078;e.kirosquare=13076;e.kiyeokacirclekorean=12910;e.kiyeokaparenkorean=12814;e.kiyeokcirclekorean=12896;e.kiyeokkorean=12593;e.kiyeokparenkorean=12800;e.kiyeoksioskorean=12595;e.kjecyrillic=1116;e.klinebelow=7733;e.klsquare=13208;e.kmcubedsquare=13222;e.kmonospace=65355;e.kmsquaredsquare=13218;e.kohiragana=12371;e.kohmsquare=13248;e.kokaithai=3585;e.kokatakana=12467;e.kokatakanahalfwidth=65402;e.kooposquare=13086;e.koppacyrillic=1153;e.koreanstandardsymbol=12927;e.koroniscmb=835;e.kparen=9382;e.kpasquare=13226;e.ksicyrillic=1135;e.ktsquare=13263;e.kturned=670;e.kuhiragana=12367;e.kukatakana=12463;e.kukatakanahalfwidth=65400;e.kvsquare=13240;e.kwsquare=13246;e.l=108;e.labengali=2482;e.lacute=314;e.ladeva=2354;e.lagujarati=2738;e.lagurmukhi=2610;e.lakkhangyaothai=3653;e.lamaleffinalarabic=65276;e.lamalefhamzaabovefinalarabic=65272;e.lamalefhamzaaboveisolatedarabic=65271;e.lamalefhamzabelowfinalarabic=65274;e.lamalefhamzabelowisolatedarabic=65273;e.lamalefisolatedarabic=65275;e.lamalefmaddaabovefinalarabic=65270;e.lamalefmaddaaboveisolatedarabic=65269;e.lamarabic=1604;e.lambda=955;e.lambdastroke=411;e.lamed=1500;e.lameddagesh=64316;e.lameddageshhebrew=64316;e.lamedhebrew=1500;e.lamfinalarabic=65246;e.lamhahinitialarabic=64714;e.laminitialarabic=65247;e.lamjeeminitialarabic=64713;e.lamkhahinitialarabic=64715;e.lamlamhehisolatedarabic=65010;e.lammedialarabic=65248;e.lammeemhahinitialarabic=64904;e.lammeeminitialarabic=64716;e.largecircle=9711;e.lbar=410;e.lbelt=620;e.lbopomofo=12556;e.lcaron=318;e.lcedilla=316;e.lcircle=9435;e.lcircumflexbelow=7741;e.lcommaaccent=316;e.ldot=320;e.ldotaccent=320;e.ldotbelow=7735;e.ldotbelowmacron=7737;e.leftangleabovecmb=794;e.lefttackbelowcmb=792;e.less=60;e.lessequal=8804;e.lessequalorgreater=8922;e.lessmonospace=65308;e.lessorequivalent=8818;e.lessorgreater=8822;e.lessoverequal=8806;e.lesssmall=65124;e.lezh=622;e.lfblock=9612;e.lhookretroflex=621;e.lira=8356;e.liwnarmenian=1388;e.lj=457;e.ljecyrillic=1113;e.ll=63168;e.lladeva=2355;e.llagujarati=2739;e.llinebelow=7739;e.llladeva=2356;e.llvocalicbengali=2529;e.llvocalicdeva=2401;e.llvocalicvowelsignbengali=2531;e.llvocalicvowelsigndeva=2403;e.lmiddletilde=619;e.lmonospace=65356;e.lmsquare=13264;e.lochulathai=3628;e.logicaland=8743;e.logicalnot=172;e.logicalnotreversed=8976;e.logicalor=8744;e.lolingthai=3621;e.longs=383;e.lowlinecenterline=65102;e.lowlinecmb=818;e.lowlinedashed=65101;e.lozenge=9674;e.lparen=9383;e.lslash=322;e.lsquare=8467;e.lsuperior=63214;e.ltshade=9617;e.luthai=3622;e.lvocalicbengali=2444;e.lvocalicdeva=2316;e.lvocalicvowelsignbengali=2530;e.lvocalicvowelsigndeva=2402;e.lxsquare=13267;e.m=109;e.mabengali=2478;e.macron=175;e.macronbelowcmb=817;e.macroncmb=772;e.macronlowmod=717;e.macronmonospace=65507;e.macute=7743;e.madeva=2350;e.magujarati=2734;e.magurmukhi=2606;e.mahapakhhebrew=1444;e.mahapakhlefthebrew=1444;e.mahiragana=12414;e.maichattawalowleftthai=63637;e.maichattawalowrightthai=63636;e.maichattawathai=3659;e.maichattawaupperleftthai=63635;e.maieklowleftthai=63628;e.maieklowrightthai=63627;e.maiekthai=3656;e.maiekupperleftthai=63626;e.maihanakatleftthai=63620;e.maihanakatthai=3633;e.maitaikhuleftthai=63625;e.maitaikhuthai=3655;e.maitholowleftthai=63631;e.maitholowrightthai=63630;e.maithothai=3657;e.maithoupperleftthai=63629;e.maitrilowleftthai=63634;e.maitrilowrightthai=63633;e.maitrithai=3658;e.maitriupperleftthai=63632;e.maiyamokthai=3654;e.makatakana=12510;e.makatakanahalfwidth=65423;e.male=9794;e.mansyonsquare=13127;e.maqafhebrew=1470;e.mars=9794;e.masoracirclehebrew=1455;e.masquare=13187;e.mbopomofo=12551;e.mbsquare=13268;e.mcircle=9436;e.mcubedsquare=13221;e.mdotaccent=7745;e.mdotbelow=7747;e.meemarabic=1605;e.meemfinalarabic=65250;e.meeminitialarabic=65251;e.meemmedialarabic=65252;e.meemmeeminitialarabic=64721;e.meemmeemisolatedarabic=64584;e.meetorusquare=13133;e.mehiragana=12417;e.meizierasquare=13182;e.mekatakana=12513;e.mekatakanahalfwidth=65426;e.mem=1502;e.memdagesh=64318;e.memdageshhebrew=64318;e.memhebrew=1502;e.menarmenian=1396;e.merkhahebrew=1445;e.merkhakefulahebrew=1446;e.merkhakefulalefthebrew=1446;e.merkhalefthebrew=1445;e.mhook=625;e.mhzsquare=13202;e.middledotkatakanahalfwidth=65381;e.middot=183;e.mieumacirclekorean=12914;e.mieumaparenkorean=12818;e.mieumcirclekorean=12900;e.mieumkorean=12609;e.mieumpansioskorean=12656;e.mieumparenkorean=12804;e.mieumpieupkorean=12654;e.mieumsioskorean=12655;e.mihiragana=12415;e.mikatakana=12511;e.mikatakanahalfwidth=65424;e.minus=8722;e.minusbelowcmb=800;e.minuscircle=8854;e.minusmod=727;e.minusplus=8723;e.minute=8242;e.miribaarusquare=13130;e.mirisquare=13129;e.mlonglegturned=624;e.mlsquare=13206;e.mmcubedsquare=13219;e.mmonospace=65357;e.mmsquaredsquare=13215;e.mohiragana=12418;e.mohmsquare=13249;e.mokatakana=12514;e.mokatakanahalfwidth=65427;e.molsquare=13270;e.momathai=3617;e.moverssquare=13223;e.moverssquaredsquare=13224;e.mparen=9384;e.mpasquare=13227;e.mssquare=13235;e.msuperior=63215;e.mturned=623;e.mu=181;e.mu1=181;e.muasquare=13186;e.muchgreater=8811;e.muchless=8810;e.mufsquare=13196;e.mugreek=956;e.mugsquare=13197;e.muhiragana=12416;e.mukatakana=12512;e.mukatakanahalfwidth=65425;e.mulsquare=13205;e.multiply=215;e.mumsquare=13211;e.munahhebrew=1443;e.munahlefthebrew=1443;e.musicalnote=9834;e.musicalnotedbl=9835;e.musicflatsign=9837;e.musicsharpsign=9839;e.mussquare=13234;e.muvsquare=13238;e.muwsquare=13244;e.mvmegasquare=13241;e.mvsquare=13239;e.mwmegasquare=13247;e.mwsquare=13245;e.n=110;e.nabengali=2472;e.nabla=8711;e.nacute=324;e.nadeva=2344;e.nagujarati=2728;e.nagurmukhi=2600;e.nahiragana=12394;e.nakatakana=12490;e.nakatakanahalfwidth=65413;e.napostrophe=329;e.nasquare=13185;e.nbopomofo=12555;e.nbspace=160;e.ncaron=328;e.ncedilla=326;e.ncircle=9437;e.ncircumflexbelow=7755;e.ncommaaccent=326;e.ndotaccent=7749;e.ndotbelow=7751;e.nehiragana=12397;e.nekatakana=12493;e.nekatakanahalfwidth=65416;e.newsheqelsign=8362;e.nfsquare=13195;e.ngabengali=2457;e.ngadeva=2329;e.ngagujarati=2713;e.ngagurmukhi=2585;e.ngonguthai=3591;e.nhiragana=12435;e.nhookleft=626;e.nhookretroflex=627;e.nieunacirclekorean=12911;e.nieunaparenkorean=12815;e.nieuncieuckorean=12597;e.nieuncirclekorean=12897;e.nieunhieuhkorean=12598;e.nieunkorean=12596;e.nieunpansioskorean=12648;e.nieunparenkorean=12801;e.nieunsioskorean=12647;e.nieuntikeutkorean=12646;e.nihiragana=12395;e.nikatakana=12491;e.nikatakanahalfwidth=65414;e.nikhahitleftthai=63641;e.nikhahitthai=3661;e.nine=57;e.ninearabic=1641;e.ninebengali=2543;e.ninecircle=9320;e.ninecircleinversesansserif=10130;e.ninedeva=2415;e.ninegujarati=2799;e.ninegurmukhi=2671;e.ninehackarabic=1641;e.ninehangzhou=12329;e.nineideographicparen=12840;e.nineinferior=8329;e.ninemonospace=65305;e.nineoldstyle=63289;e.nineparen=9340;e.nineperiod=9360;e.ninepersian=1785;e.nineroman=8568;e.ninesuperior=8313;e.nineteencircle=9330;e.nineteenparen=9350;e.nineteenperiod=9370;e.ninethai=3673;e.nj=460;e.njecyrillic=1114;e.nkatakana=12531;e.nkatakanahalfwidth=65437;e.nlegrightlong=414;e.nlinebelow=7753;e.nmonospace=65358;e.nmsquare=13210;e.nnabengali=2467;e.nnadeva=2339;e.nnagujarati=2723;e.nnagurmukhi=2595;e.nnnadeva=2345;e.nohiragana=12398;e.nokatakana=12494;e.nokatakanahalfwidth=65417;e.nonbreakingspace=160;e.nonenthai=3603;e.nonuthai=3609;e.noonarabic=1606;e.noonfinalarabic=65254;e.noonghunnaarabic=1722;e.noonghunnafinalarabic=64415;e.nooninitialarabic=65255;e.noonjeeminitialarabic=64722;e.noonjeemisolatedarabic=64587;e.noonmedialarabic=65256;e.noonmeeminitialarabic=64725;e.noonmeemisolatedarabic=64590;e.noonnoonfinalarabic=64653;e.notcontains=8716;e.notelement=8713;e.notelementof=8713;e.notequal=8800;e.notgreater=8815;e.notgreaternorequal=8817;e.notgreaternorless=8825;e.notidentical=8802;e.notless=8814;e.notlessnorequal=8816;e.notparallel=8742;e.notprecedes=8832;e.notsubset=8836;e.notsucceeds=8833;e.notsuperset=8837;e.nowarmenian=1398;e.nparen=9385;e.nssquare=13233;e.nsuperior=8319;e.ntilde=241;e.nu=957;e.nuhiragana=12396;e.nukatakana=12492;e.nukatakanahalfwidth=65415;e.nuktabengali=2492;e.nuktadeva=2364;e.nuktagujarati=2748;e.nuktagurmukhi=2620;e.numbersign=35;e.numbersignmonospace=65283;e.numbersignsmall=65119;e.numeralsigngreek=884;e.numeralsignlowergreek=885;e.numero=8470;e.nun=1504;e.nundagesh=64320;e.nundageshhebrew=64320;e.nunhebrew=1504;e.nvsquare=13237;e.nwsquare=13243;e.nyabengali=2462;e.nyadeva=2334;e.nyagujarati=2718;e.nyagurmukhi=2590;e.o=111;e.oacute=243;e.oangthai=3629;e.obarred=629;e.obarredcyrillic=1257;e.obarreddieresiscyrillic=1259;e.obengali=2451;e.obopomofo=12571;e.obreve=335;e.ocandradeva=2321;e.ocandragujarati=2705;e.ocandravowelsigndeva=2377;e.ocandravowelsigngujarati=2761;e.ocaron=466;e.ocircle=9438;e.ocircumflex=244;e.ocircumflexacute=7889;e.ocircumflexdotbelow=7897;e.ocircumflexgrave=7891;e.ocircumflexhookabove=7893;e.ocircumflextilde=7895;e.ocyrillic=1086;e.odblacute=337;e.odblgrave=525;e.odeva=2323;e.odieresis=246;e.odieresiscyrillic=1255;e.odotbelow=7885;e.oe=339;e.oekorean=12634;e.ogonek=731;e.ogonekcmb=808;e.ograve=242;e.ogujarati=2707;e.oharmenian=1413;e.ohiragana=12362;e.ohookabove=7887;e.ohorn=417;e.ohornacute=7899;e.ohorndotbelow=7907;e.ohorngrave=7901;e.ohornhookabove=7903;e.ohorntilde=7905;e.ohungarumlaut=337;e.oi=419;e.oinvertedbreve=527;e.okatakana=12458;e.okatakanahalfwidth=65397;e.okorean=12631;e.olehebrew=1451;e.omacron=333;e.omacronacute=7763;e.omacrongrave=7761;e.omdeva=2384;e.omega=969;e.omega1=982;e.omegacyrillic=1121;e.omegalatinclosed=631;e.omegaroundcyrillic=1147;e.omegatitlocyrillic=1149;e.omegatonos=974;e.omgujarati=2768;e.omicron=959;e.omicrontonos=972;e.omonospace=65359;e.one=49;e.onearabic=1633;e.onebengali=2535;e.onecircle=9312;e.onecircleinversesansserif=10122;e.onedeva=2407;e.onedotenleader=8228;e.oneeighth=8539;e.onefitted=63196;e.onegujarati=2791;e.onegurmukhi=2663;e.onehackarabic=1633;e.onehalf=189;e.onehangzhou=12321;e.oneideographicparen=12832;e.oneinferior=8321;e.onemonospace=65297;e.onenumeratorbengali=2548;e.oneoldstyle=63281;e.oneparen=9332;e.oneperiod=9352;e.onepersian=1777;e.onequarter=188;e.oneroman=8560;e.onesuperior=185;e.onethai=3665;e.onethird=8531;e.oogonek=491;e.oogonekmacron=493;e.oogurmukhi=2579;e.oomatragurmukhi=2635;e.oopen=596;e.oparen=9386;e.openbullet=9702;e.option=8997;e.ordfeminine=170;e.ordmasculine=186;e.orthogonal=8735;e.oshortdeva=2322;e.oshortvowelsigndeva=2378;e.oslash=248;e.oslashacute=511;e.osmallhiragana=12361;e.osmallkatakana=12457;e.osmallkatakanahalfwidth=65387;e.ostrokeacute=511;e.osuperior=63216;e.otcyrillic=1151;e.otilde=245;e.otildeacute=7757;e.otildedieresis=7759;e.oubopomofo=12577;e.overline=8254;e.overlinecenterline=65098;e.overlinecmb=773;e.overlinedashed=65097;e.overlinedblwavy=65100;e.overlinewavy=65099;e.overscore=175;e.ovowelsignbengali=2507;e.ovowelsigndeva=2379;e.ovowelsigngujarati=2763;e.p=112;e.paampssquare=13184;e.paasentosquare=13099;e.pabengali=2474;e.pacute=7765;e.padeva=2346;e.pagedown=8671;e.pageup=8670;e.pagujarati=2730;e.pagurmukhi=2602;e.pahiragana=12401;e.paiyannoithai=3631;e.pakatakana=12497;e.palatalizationcyrilliccmb=1156;e.palochkacyrillic=1216;e.pansioskorean=12671;e.paragraph=182;e.parallel=8741;e.parenleft=40;e.parenleftaltonearabic=64830;e.parenleftbt=63725;e.parenleftex=63724;e.parenleftinferior=8333;e.parenleftmonospace=65288;e.parenleftsmall=65113;e.parenleftsuperior=8317;e.parenlefttp=63723;e.parenleftvertical=65077;e.parenright=41;e.parenrightaltonearabic=64831;e.parenrightbt=63736;e.parenrightex=63735;e.parenrightinferior=8334;e.parenrightmonospace=65289;e.parenrightsmall=65114;e.parenrightsuperior=8318;e.parenrighttp=63734;e.parenrightvertical=65078;e.partialdiff=8706;e.paseqhebrew=1472;e.pashtahebrew=1433;e.pasquare=13225;e.patah=1463;e.patah11=1463;e.patah1d=1463;e.patah2a=1463;e.patahhebrew=1463;e.patahnarrowhebrew=1463;e.patahquarterhebrew=1463;e.patahwidehebrew=1463;e.pazerhebrew=1441;e.pbopomofo=12550;e.pcircle=9439;e.pdotaccent=7767;e.pe=1508;e.pecyrillic=1087;e.pedagesh=64324;e.pedageshhebrew=64324;e.peezisquare=13115;e.pefinaldageshhebrew=64323;e.peharabic=1662;e.peharmenian=1402;e.pehebrew=1508;e.pehfinalarabic=64343;e.pehinitialarabic=64344;e.pehiragana=12410;e.pehmedialarabic=64345;e.pekatakana=12506;e.pemiddlehookcyrillic=1191;e.perafehebrew=64334;e.percent=37;e.percentarabic=1642;e.percentmonospace=65285;e.percentsmall=65130;e.period=46;e.periodarmenian=1417;e.periodcentered=183;e.periodhalfwidth=65377;e.periodinferior=63207;e.periodmonospace=65294;e.periodsmall=65106;e.periodsuperior=63208;e.perispomenigreekcmb=834;e.perpendicular=8869;e.perthousand=8240;e.peseta=8359;e.pfsquare=13194;e.phabengali=2475;e.phadeva=2347;e.phagujarati=2731;e.phagurmukhi=2603;e.phi=966;e.phi1=981;e.phieuphacirclekorean=12922;e.phieuphaparenkorean=12826;e.phieuphcirclekorean=12908;e.phieuphkorean=12621;e.phieuphparenkorean=12812;e.philatin=632;e.phinthuthai=3642;e.phisymbolgreek=981;e.phook=421;e.phophanthai=3614;e.phophungthai=3612;e.phosamphaothai=3616;e.pi=960;e.pieupacirclekorean=12915;e.pieupaparenkorean=12819;e.pieupcieuckorean=12662;e.pieupcirclekorean=12901;e.pieupkiyeokkorean=12658;e.pieupkorean=12610;e.pieupparenkorean=12805;e.pieupsioskiyeokkorean=12660;e.pieupsioskorean=12612;e.pieupsiostikeutkorean=12661;e.pieupthieuthkorean=12663;e.pieuptikeutkorean=12659;e.pihiragana=12404;e.pikatakana=12500;e.pisymbolgreek=982;e.piwrarmenian=1411;e.planckover2pi=8463;e.planckover2pi1=8463;e.plus=43;e.plusbelowcmb=799;e.pluscircle=8853;e.plusminus=177;e.plusmod=726;e.plusmonospace=65291;e.plussmall=65122;e.plussuperior=8314;e.pmonospace=65360;e.pmsquare=13272;e.pohiragana=12413;e.pointingindexdownwhite=9759;e.pointingindexleftwhite=9756;e.pointingindexrightwhite=9758;e.pointingindexupwhite=9757;e.pokatakana=12509;e.poplathai=3611;e.postalmark=12306;e.postalmarkface=12320;e.pparen=9387;e.precedes=8826;e.prescription=8478;e.primemod=697;e.primereversed=8245;e.product=8719;e.projective=8965;e.prolongedkana=12540;e.propellor=8984;e.propersubset=8834;e.propersuperset=8835;e.proportion=8759;e.proportional=8733;e.psi=968;e.psicyrillic=1137;e.psilipneumatacyrilliccmb=1158;e.pssquare=13232;e.puhiragana=12407;e.pukatakana=12503;e.pvsquare=13236;e.pwsquare=13242;e.q=113;e.qadeva=2392;e.qadmahebrew=1448;e.qafarabic=1602;e.qaffinalarabic=65238;e.qafinitialarabic=65239;e.qafmedialarabic=65240;e.qamats=1464;e.qamats10=1464;e.qamats1a=1464;e.qamats1c=1464;e.qamats27=1464;e.qamats29=1464;e.qamats33=1464;e.qamatsde=1464;e.qamatshebrew=1464;e.qamatsnarrowhebrew=1464;e.qamatsqatanhebrew=1464;e.qamatsqatannarrowhebrew=1464;e.qamatsqatanquarterhebrew=1464;e.qamatsqatanwidehebrew=1464;e.qamatsquarterhebrew=1464;e.qamatswidehebrew=1464;e.qarneyparahebrew=1439;e.qbopomofo=12561;e.qcircle=9440;e.qhook=672;e.qmonospace=65361;e.qof=1511;e.qofdagesh=64327;e.qofdageshhebrew=64327;e.qofhebrew=1511;e.qparen=9388;e.quarternote=9833;e.qubuts=1467;e.qubuts18=1467;e.qubuts25=1467;e.qubuts31=1467;e.qubutshebrew=1467;e.qubutsnarrowhebrew=1467;e.qubutsquarterhebrew=1467;e.qubutswidehebrew=1467;e.question=63;e.questionarabic=1567;e.questionarmenian=1374;e.questiondown=191;e.questiondownsmall=63423;e.questiongreek=894;e.questionmonospace=65311;e.questionsmall=63295;e.quotedbl=34;e.quotedblbase=8222;e.quotedblleft=8220;e.quotedblmonospace=65282;e.quotedblprime=12318;e.quotedblprimereversed=12317;e.quotedblright=8221;e.quoteleft=8216;e.quoteleftreversed=8219;e.quotereversed=8219;e.quoteright=8217;e.quoterightn=329;e.quotesinglbase=8218;e.quotesingle=39;e.quotesinglemonospace=65287;e.r=114;e.raarmenian=1404;e.rabengali=2480;e.racute=341;e.radeva=2352;e.radical=8730;e.radicalex=63717;e.radoverssquare=13230;e.radoverssquaredsquare=13231;e.radsquare=13229;e.rafe=1471;e.rafehebrew=1471;e.ragujarati=2736;e.ragurmukhi=2608;e.rahiragana=12425;e.rakatakana=12521;e.rakatakanahalfwidth=65431;e.ralowerdiagonalbengali=2545;e.ramiddlediagonalbengali=2544;e.ramshorn=612;e.ratio=8758;e.rbopomofo=12566;e.rcaron=345;e.rcedilla=343;e.rcircle=9441;e.rcommaaccent=343;e.rdblgrave=529;e.rdotaccent=7769;e.rdotbelow=7771;e.rdotbelowmacron=7773;e.referencemark=8251;e.reflexsubset=8838;e.reflexsuperset=8839;e.registered=174;e.registersans=63720;e.registerserif=63194;e.reharabic=1585;e.reharmenian=1408;e.rehfinalarabic=65198;e.rehiragana=12428;e.rekatakana=12524;e.rekatakanahalfwidth=65434;e.resh=1512;e.reshdageshhebrew=64328;e.reshhebrew=1512;e.reversedtilde=8765;e.reviahebrew=1431;e.reviamugrashhebrew=1431;e.revlogicalnot=8976;e.rfishhook=638;e.rfishhookreversed=639;e.rhabengali=2525;e.rhadeva=2397;e.rho=961;e.rhook=637;e.rhookturned=635;e.rhookturnedsuperior=693;e.rhosymbolgreek=1009;e.rhotichookmod=734;e.rieulacirclekorean=12913;e.rieulaparenkorean=12817;e.rieulcirclekorean=12899;e.rieulhieuhkorean=12608;e.rieulkiyeokkorean=12602;e.rieulkiyeoksioskorean=12649;e.rieulkorean=12601;e.rieulmieumkorean=12603;e.rieulpansioskorean=12652;e.rieulparenkorean=12803;e.rieulphieuphkorean=12607;e.rieulpieupkorean=12604;e.rieulpieupsioskorean=12651;e.rieulsioskorean=12605;e.rieulthieuthkorean=12606;e.rieultikeutkorean=12650;e.rieulyeorinhieuhkorean=12653;e.rightangle=8735;e.righttackbelowcmb=793;e.righttriangle=8895;e.rihiragana=12426;e.rikatakana=12522;e.rikatakanahalfwidth=65432;e.ring=730;e.ringbelowcmb=805;e.ringcmb=778;e.ringhalfleft=703;e.ringhalfleftarmenian=1369;e.ringhalfleftbelowcmb=796;e.ringhalfleftcentered=723;e.ringhalfright=702;e.ringhalfrightbelowcmb=825;e.ringhalfrightcentered=722;e.rinvertedbreve=531;e.rittorusquare=13137;e.rlinebelow=7775;e.rlongleg=636;e.rlonglegturned=634;e.rmonospace=65362;e.rohiragana=12429;e.rokatakana=12525;e.rokatakanahalfwidth=65435;e.roruathai=3619;e.rparen=9389;e.rrabengali=2524;e.rradeva=2353;e.rragurmukhi=2652;e.rreharabic=1681;e.rrehfinalarabic=64397;e.rrvocalicbengali=2528;e.rrvocalicdeva=2400;e.rrvocalicgujarati=2784;e.rrvocalicvowelsignbengali=2500;e.rrvocalicvowelsigndeva=2372;e.rrvocalicvowelsigngujarati=2756;e.rsuperior=63217;e.rtblock=9616;e.rturned=633;e.rturnedsuperior=692;e.ruhiragana=12427;e.rukatakana=12523;e.rukatakanahalfwidth=65433;e.rupeemarkbengali=2546;e.rupeesignbengali=2547;e.rupiah=63197;e.ruthai=3620;e.rvocalicbengali=2443;e.rvocalicdeva=2315;e.rvocalicgujarati=2699;e.rvocalicvowelsignbengali=2499;e.rvocalicvowelsigndeva=2371;e.rvocalicvowelsigngujarati=2755;e.s=115;e.sabengali=2488;e.sacute=347;e.sacutedotaccent=7781;e.sadarabic=1589;e.sadeva=2360;e.sadfinalarabic=65210;e.sadinitialarabic=65211;e.sadmedialarabic=65212;e.sagujarati=2744;e.sagurmukhi=2616;e.sahiragana=12373;e.sakatakana=12469;e.sakatakanahalfwidth=65403;e.sallallahoualayhewasallamarabic=65018;e.samekh=1505;e.samekhdagesh=64321;e.samekhdageshhebrew=64321;e.samekhhebrew=1505;e.saraaathai=3634;e.saraaethai=3649;e.saraaimaimalaithai=3652;e.saraaimaimuanthai=3651;e.saraamthai=3635;e.saraathai=3632;e.saraethai=3648;e.saraiileftthai=63622;e.saraiithai=3637;e.saraileftthai=63621;e.saraithai=3636;e.saraothai=3650;e.saraueeleftthai=63624;e.saraueethai=3639;e.saraueleftthai=63623;e.sarauethai=3638;e.sarauthai=3640;e.sarauuthai=3641;e.sbopomofo=12569;e.scaron=353;e.scarondotaccent=7783;e.scedilla=351;e.schwa=601;e.schwacyrillic=1241;e.schwadieresiscyrillic=1243;e.schwahook=602;e.scircle=9442;e.scircumflex=349;e.scommaaccent=537;e.sdotaccent=7777;e.sdotbelow=7779;e.sdotbelowdotaccent=7785;e.seagullbelowcmb=828;e.second=8243;e.secondtonechinese=714;e.section=167;e.seenarabic=1587;e.seenfinalarabic=65202;e.seeninitialarabic=65203;e.seenmedialarabic=65204;e.segol=1462;e.segol13=1462;e.segol1f=1462;e.segol2c=1462;e.segolhebrew=1462;e.segolnarrowhebrew=1462;e.segolquarterhebrew=1462;e.segoltahebrew=1426;e.segolwidehebrew=1462;e.seharmenian=1405;e.sehiragana=12379;e.sekatakana=12475;e.sekatakanahalfwidth=65406;e.semicolon=59;e.semicolonarabic=1563;e.semicolonmonospace=65307;e.semicolonsmall=65108;e.semivoicedmarkkana=12444;e.semivoicedmarkkanahalfwidth=65439;e.sentisquare=13090;e.sentosquare=13091;e.seven=55;e.sevenarabic=1639;e.sevenbengali=2541;e.sevencircle=9318;e.sevencircleinversesansserif=10128;e.sevendeva=2413;e.seveneighths=8542;e.sevengujarati=2797;e.sevengurmukhi=2669;e.sevenhackarabic=1639;e.sevenhangzhou=12327;e.sevenideographicparen=12838;e.seveninferior=8327;e.sevenmonospace=65303;e.sevenoldstyle=63287;e.sevenparen=9338;e.sevenperiod=9358;e.sevenpersian=1783;e.sevenroman=8566;e.sevensuperior=8311;e.seventeencircle=9328;e.seventeenparen=9348;e.seventeenperiod=9368;e.seventhai=3671;e.sfthyphen=173;e.shaarmenian=1399;e.shabengali=2486;e.shacyrillic=1096;e.shaddaarabic=1617;e.shaddadammaarabic=64609;e.shaddadammatanarabic=64606;e.shaddafathaarabic=64608;e.shaddakasraarabic=64610;e.shaddakasratanarabic=64607;e.shade=9618;e.shadedark=9619;e.shadelight=9617;e.shademedium=9618;e.shadeva=2358;e.shagujarati=2742;e.shagurmukhi=2614;e.shalshelethebrew=1427;e.shbopomofo=12565;e.shchacyrillic=1097;e.sheenarabic=1588;e.sheenfinalarabic=65206;e.sheeninitialarabic=65207;e.sheenmedialarabic=65208;e.sheicoptic=995;e.sheqel=8362;e.sheqelhebrew=8362;e.sheva=1456;e.sheva115=1456;e.sheva15=1456;e.sheva22=1456;e.sheva2e=1456;e.shevahebrew=1456;e.shevanarrowhebrew=1456;e.shevaquarterhebrew=1456;e.shevawidehebrew=1456;e.shhacyrillic=1211;e.shimacoptic=1005;e.shin=1513;e.shindagesh=64329;e.shindageshhebrew=64329;e.shindageshshindot=64300;e.shindageshshindothebrew=64300;e.shindageshsindot=64301;e.shindageshsindothebrew=64301;e.shindothebrew=1473;e.shinhebrew=1513;e.shinshindot=64298;e.shinshindothebrew=64298;e.shinsindot=64299;e.shinsindothebrew=64299;e.shook=642;e.sigma=963;e.sigma1=962;e.sigmafinal=962;e.sigmalunatesymbolgreek=1010;e.sihiragana=12375;e.sikatakana=12471;e.sikatakanahalfwidth=65404;e.siluqhebrew=1469;e.siluqlefthebrew=1469;e.similar=8764;e.sindothebrew=1474;e.siosacirclekorean=12916;e.siosaparenkorean=12820;e.sioscieuckorean=12670;e.sioscirclekorean=12902;e.sioskiyeokkorean=12666;e.sioskorean=12613;e.siosnieunkorean=12667;e.siosparenkorean=12806;e.siospieupkorean=12669;e.siostikeutkorean=12668;e.six=54;e.sixarabic=1638;e.sixbengali=2540;e.sixcircle=9317;e.sixcircleinversesansserif=10127;e.sixdeva=2412;e.sixgujarati=2796;e.sixgurmukhi=2668;e.sixhackarabic=1638;e.sixhangzhou=12326;e.sixideographicparen=12837;e.sixinferior=8326;e.sixmonospace=65302;e.sixoldstyle=63286;e.sixparen=9337;e.sixperiod=9357;e.sixpersian=1782;e.sixroman=8565;e.sixsuperior=8310;e.sixteencircle=9327;e.sixteencurrencydenominatorbengali=2553;e.sixteenparen=9347;e.sixteenperiod=9367;e.sixthai=3670;e.slash=47;e.slashmonospace=65295;e.slong=383;e.slongdotaccent=7835;e.smileface=9786;e.smonospace=65363;e.sofpasuqhebrew=1475;e.softhyphen=173;e.softsigncyrillic=1100;e.sohiragana=12381;e.sokatakana=12477;e.sokatakanahalfwidth=65407;e.soliduslongoverlaycmb=824;e.solidusshortoverlaycmb=823;e.sorusithai=3625;e.sosalathai=3624;e.sosothai=3595;e.sosuathai=3626;e.space=32;e.spacehackarabic=32;e.spade=9824;e.spadesuitblack=9824;e.spadesuitwhite=9828;e.sparen=9390;e.squarebelowcmb=827;e.squarecc=13252;e.squarecm=13213;e.squarediagonalcrosshatchfill=9641;e.squarehorizontalfill=9636;e.squarekg=13199;e.squarekm=13214;e.squarekmcapital=13262;e.squareln=13265;e.squarelog=13266;e.squaremg=13198;e.squaremil=13269;e.squaremm=13212;e.squaremsquared=13217;e.squareorthogonalcrosshatchfill=9638;e.squareupperlefttolowerrightfill=9639;e.squareupperrighttolowerleftfill=9640;e.squareverticalfill=9637;e.squarewhitewithsmallblack=9635;e.srsquare=13275;e.ssabengali=2487;e.ssadeva=2359;e.ssagujarati=2743;e.ssangcieuckorean=12617;e.ssanghieuhkorean=12677;e.ssangieungkorean=12672;e.ssangkiyeokkorean=12594;e.ssangnieunkorean=12645;e.ssangpieupkorean=12611;e.ssangsioskorean=12614;e.ssangtikeutkorean=12600;e.ssuperior=63218;e.sterling=163;e.sterlingmonospace=65505;e.strokelongoverlaycmb=822;e.strokeshortoverlaycmb=821;e.subset=8834;e.subsetnotequal=8842;e.subsetorequal=8838;e.succeeds=8827;e.suchthat=8715;e.suhiragana=12377;e.sukatakana=12473;e.sukatakanahalfwidth=65405;e.sukunarabic=1618;e.summation=8721;e.sun=9788;e.superset=8835;e.supersetnotequal=8843;e.supersetorequal=8839;e.svsquare=13276;e.syouwaerasquare=13180;e.t=116;e.tabengali=2468;e.tackdown=8868;e.tackleft=8867;e.tadeva=2340;e.tagujarati=2724;e.tagurmukhi=2596;e.taharabic=1591;e.tahfinalarabic=65218;e.tahinitialarabic=65219;e.tahiragana=12383;e.tahmedialarabic=65220;e.taisyouerasquare=13181;e.takatakana=12479;e.takatakanahalfwidth=65408;e.tatweelarabic=1600;e.tau=964;e.tav=1514;e.tavdages=64330;e.tavdagesh=64330;e.tavdageshhebrew=64330;e.tavhebrew=1514;e.tbar=359;e.tbopomofo=12554;e.tcaron=357;e.tccurl=680;e.tcedilla=355;e.tcheharabic=1670;e.tchehfinalarabic=64379;e.tchehinitialarabic=64380;e.tchehmedialarabic=64381;e.tcircle=9443;e.tcircumflexbelow=7793;e.tcommaaccent=355;e.tdieresis=7831;e.tdotaccent=7787;e.tdotbelow=7789;e.tecyrillic=1090;e.tedescendercyrillic=1197;e.teharabic=1578;e.tehfinalarabic=65174;e.tehhahinitialarabic=64674;e.tehhahisolatedarabic=64524;e.tehinitialarabic=65175;e.tehiragana=12390;e.tehjeeminitialarabic=64673;e.tehjeemisolatedarabic=64523;e.tehmarbutaarabic=1577;e.tehmarbutafinalarabic=65172;e.tehmedialarabic=65176;e.tehmeeminitialarabic=64676;e.tehmeemisolatedarabic=64526;e.tehnoonfinalarabic=64627;e.tekatakana=12486;e.tekatakanahalfwidth=65411;e.telephone=8481;e.telephoneblack=9742;e.telishagedolahebrew=1440;e.telishaqetanahebrew=1449;e.tencircle=9321;e.tenideographicparen=12841;e.tenparen=9341;e.tenperiod=9361;e.tenroman=8569;e.tesh=679;e.tet=1496;e.tetdagesh=64312;e.tetdageshhebrew=64312;e.tethebrew=1496;e.tetsecyrillic=1205;e.tevirhebrew=1435;e.tevirlefthebrew=1435;e.thabengali=2469;e.thadeva=2341;e.thagujarati=2725;e.thagurmukhi=2597;e.thalarabic=1584;e.thalfinalarabic=65196;e.thanthakhatlowleftthai=63640;e.thanthakhatlowrightthai=63639;e.thanthakhatthai=3660;e.thanthakhatupperleftthai=63638;e.theharabic=1579;e.thehfinalarabic=65178;e.thehinitialarabic=65179;e.thehmedialarabic=65180;e.thereexists=8707;e.therefore=8756;e.theta=952;e.theta1=977;e.thetasymbolgreek=977;e.thieuthacirclekorean=12921;e.thieuthaparenkorean=12825;e.thieuthcirclekorean=12907;e.thieuthkorean=12620;e.thieuthparenkorean=12811;e.thirteencircle=9324;e.thirteenparen=9344;e.thirteenperiod=9364;e.thonangmonthothai=3601;e.thook=429;e.thophuthaothai=3602;e.thorn=254;e.thothahanthai=3607;e.thothanthai=3600;e.thothongthai=3608;e.thothungthai=3606;e.thousandcyrillic=1154;e.thousandsseparatorarabic=1644;e.thousandsseparatorpersian=1644;e.three=51;e.threearabic=1635;e.threebengali=2537;e.threecircle=9314;e.threecircleinversesansserif=10124;e.threedeva=2409;e.threeeighths=8540;e.threegujarati=2793;e.threegurmukhi=2665;e.threehackarabic=1635;e.threehangzhou=12323;e.threeideographicparen=12834;e.threeinferior=8323;e.threemonospace=65299;e.threenumeratorbengali=2550;e.threeoldstyle=63283;e.threeparen=9334;e.threeperiod=9354;e.threepersian=1779;e.threequarters=190;e.threequartersemdash=63198;e.threeroman=8562;e.threesuperior=179;e.threethai=3667;e.thzsquare=13204;e.tihiragana=12385;e.tikatakana=12481;e.tikatakanahalfwidth=65409;e.tikeutacirclekorean=12912;e.tikeutaparenkorean=12816;e.tikeutcirclekorean=12898;e.tikeutkorean=12599;e.tikeutparenkorean=12802;e.tilde=732;e.tildebelowcmb=816;e.tildecmb=771;e.tildecomb=771;e.tildedoublecmb=864;e.tildeoperator=8764;e.tildeoverlaycmb=820;e.tildeverticalcmb=830;e.timescircle=8855;e.tipehahebrew=1430;e.tipehalefthebrew=1430;e.tippigurmukhi=2672;e.titlocyrilliccmb=1155;e.tiwnarmenian=1407;e.tlinebelow=7791;e.tmonospace=65364;e.toarmenian=1385;e.tohiragana=12392;e.tokatakana=12488;e.tokatakanahalfwidth=65412;e.tonebarextrahighmod=741;e.tonebarextralowmod=745;e.tonebarhighmod=742;e.tonebarlowmod=744;e.tonebarmidmod=743;e.tonefive=445;e.tonesix=389;e.tonetwo=424;e.tonos=900;e.tonsquare=13095;e.topatakthai=3599;e.tortoiseshellbracketleft=12308;e.tortoiseshellbracketleftsmall=65117;e.tortoiseshellbracketleftvertical=65081;e.tortoiseshellbracketright=12309;e.tortoiseshellbracketrightsmall=65118;e.tortoiseshellbracketrightvertical=65082;e.totaothai=3605;e.tpalatalhook=427;e.tparen=9391;e.trademark=8482;e.trademarksans=63722;e.trademarkserif=63195;e.tretroflexhook=648;e.triagdn=9660;e.triaglf=9668;e.triagrt=9658;e.triagup=9650;e.ts=678;e.tsadi=1510;e.tsadidagesh=64326;e.tsadidageshhebrew=64326;e.tsadihebrew=1510;e.tsecyrillic=1094;e.tsere=1461;e.tsere12=1461;e.tsere1e=1461;e.tsere2b=1461;e.tserehebrew=1461;e.tserenarrowhebrew=1461;e.tserequarterhebrew=1461;e.tserewidehebrew=1461;e.tshecyrillic=1115;e.tsuperior=63219;e.ttabengali=2463;e.ttadeva=2335;e.ttagujarati=2719;e.ttagurmukhi=2591;e.tteharabic=1657;e.ttehfinalarabic=64359;e.ttehinitialarabic=64360;e.ttehmedialarabic=64361;e.tthabengali=2464;e.tthadeva=2336;e.tthagujarati=2720;e.tthagurmukhi=2592;e.tturned=647;e.tuhiragana=12388;e.tukatakana=12484;e.tukatakanahalfwidth=65410;e.tusmallhiragana=12387;e.tusmallkatakana=12483;e.tusmallkatakanahalfwidth=65391;e.twelvecircle=9323;e.twelveparen=9343;e.twelveperiod=9363;e.twelveroman=8571;e.twentycircle=9331;e.twentyhangzhou=21316;e.twentyparen=9351;e.twentyperiod=9371;e.two=50;e.twoarabic=1634;e.twobengali=2536;e.twocircle=9313;e.twocircleinversesansserif=10123;e.twodeva=2408;e.twodotenleader=8229;e.twodotleader=8229;e.twodotleadervertical=65072;e.twogujarati=2792;e.twogurmukhi=2664;e.twohackarabic=1634;e.twohangzhou=12322;e.twoideographicparen=12833;e.twoinferior=8322;e.twomonospace=65298;e.twonumeratorbengali=2549;e.twooldstyle=63282;e.twoparen=9333;e.twoperiod=9353;e.twopersian=1778;e.tworoman=8561;e.twostroke=443;e.twosuperior=178;e.twothai=3666;e.twothirds=8532;e.u=117;e.uacute=250;e.ubar=649;e.ubengali=2441;e.ubopomofo=12584;e.ubreve=365;e.ucaron=468;e.ucircle=9444;e.ucircumflex=251;e.ucircumflexbelow=7799;e.ucyrillic=1091;e.udattadeva=2385;e.udblacute=369;e.udblgrave=533;e.udeva=2313;e.udieresis=252;e.udieresisacute=472;e.udieresisbelow=7795;e.udieresiscaron=474;e.udieresiscyrillic=1265;e.udieresisgrave=476;e.udieresismacron=470;e.udotbelow=7909;e.ugrave=249;e.ugujarati=2697;e.ugurmukhi=2569;e.uhiragana=12358;e.uhookabove=7911;e.uhorn=432;e.uhornacute=7913;e.uhorndotbelow=7921;e.uhorngrave=7915;e.uhornhookabove=7917;e.uhorntilde=7919;e.uhungarumlaut=369;e.uhungarumlautcyrillic=1267;e.uinvertedbreve=535;e.ukatakana=12454;e.ukatakanahalfwidth=65395;e.ukcyrillic=1145;e.ukorean=12636;e.umacron=363;e.umacroncyrillic=1263;e.umacrondieresis=7803;e.umatragurmukhi=2625;e.umonospace=65365;e.underscore=95;e.underscoredbl=8215;e.underscoremonospace=65343;e.underscorevertical=65075;e.underscorewavy=65103;e.union=8746;e.universal=8704;e.uogonek=371;e.uparen=9392;e.upblock=9600;e.upperdothebrew=1476;e.upsilon=965;e.upsilondieresis=971;e.upsilondieresistonos=944;e.upsilonlatin=650;e.upsilontonos=973;e.uptackbelowcmb=797;e.uptackmod=724;e.uragurmukhi=2675;e.uring=367;e.ushortcyrillic=1118;e.usmallhiragana=12357;e.usmallkatakana=12453;e.usmallkatakanahalfwidth=65385;e.ustraightcyrillic=1199;e.ustraightstrokecyrillic=1201;e.utilde=361;e.utildeacute=7801;e.utildebelow=7797;e.uubengali=2442;e.uudeva=2314;e.uugujarati=2698;e.uugurmukhi=2570;e.uumatragurmukhi=2626;e.uuvowelsignbengali=2498;e.uuvowelsigndeva=2370;e.uuvowelsigngujarati=2754;e.uvowelsignbengali=2497;e.uvowelsigndeva=2369;e.uvowelsigngujarati=2753;e.v=118;e.vadeva=2357;e.vagujarati=2741;e.vagurmukhi=2613;e.vakatakana=12535;e.vav=1493;e.vavdagesh=64309;e.vavdagesh65=64309;e.vavdageshhebrew=64309;e.vavhebrew=1493;e.vavholam=64331;e.vavholamhebrew=64331;e.vavvavhebrew=1520;e.vavyodhebrew=1521;e.vcircle=9445;e.vdotbelow=7807;e.vecyrillic=1074;e.veharabic=1700;e.vehfinalarabic=64363;e.vehinitialarabic=64364;e.vehmedialarabic=64365;e.vekatakana=12537;e.venus=9792;e.verticalbar=124;e.verticallineabovecmb=781;e.verticallinebelowcmb=809;e.verticallinelowmod=716;e.verticallinemod=712;e.vewarmenian=1406;e.vhook=651;e.vikatakana=12536;e.viramabengali=2509;e.viramadeva=2381;e.viramagujarati=2765;e.visargabengali=2435;e.visargadeva=2307;e.visargagujarati=2691;e.vmonospace=65366;e.voarmenian=1400;e.voicediterationhiragana=12446;e.voicediterationkatakana=12542;e.voicedmarkkana=12443;e.voicedmarkkanahalfwidth=65438;e.vokatakana=12538;e.vparen=9393;e.vtilde=7805;e.vturned=652;e.vuhiragana=12436;e.vukatakana=12532;e.w=119;e.wacute=7811;e.waekorean=12633;e.wahiragana=12431;e.wakatakana=12527;e.wakatakanahalfwidth=65436;e.wakorean=12632;e.wasmallhiragana=12430;e.wasmallkatakana=12526;e.wattosquare=13143;e.wavedash=12316;e.wavyunderscorevertical=65076;e.wawarabic=1608;e.wawfinalarabic=65262;e.wawhamzaabovearabic=1572;e.wawhamzaabovefinalarabic=65158;e.wbsquare=13277;e.wcircle=9446;e.wcircumflex=373;e.wdieresis=7813;e.wdotaccent=7815;e.wdotbelow=7817;e.wehiragana=12433;e.weierstrass=8472;e.wekatakana=12529;e.wekorean=12638;e.weokorean=12637;e.wgrave=7809;e.whitebullet=9702;e.whitecircle=9675;e.whitecircleinverse=9689;e.whitecornerbracketleft=12302;e.whitecornerbracketleftvertical=65091;e.whitecornerbracketright=12303;e.whitecornerbracketrightvertical=65092;e.whitediamond=9671;e.whitediamondcontainingblacksmalldiamond=9672;e.whitedownpointingsmalltriangle=9663;e.whitedownpointingtriangle=9661;e.whiteleftpointingsmalltriangle=9667;e.whiteleftpointingtriangle=9665;e.whitelenticularbracketleft=12310;e.whitelenticularbracketright=12311;e.whiterightpointingsmalltriangle=9657;e.whiterightpointingtriangle=9655;e.whitesmallsquare=9643;e.whitesmilingface=9786;e.whitesquare=9633;e.whitestar=9734;e.whitetelephone=9743;e.whitetortoiseshellbracketleft=12312;e.whitetortoiseshellbracketright=12313;e.whiteuppointingsmalltriangle=9653;e.whiteuppointingtriangle=9651;e.wihiragana=12432;e.wikatakana=12528;e.wikorean=12639;e.wmonospace=65367;e.wohiragana=12434;e.wokatakana=12530;e.wokatakanahalfwidth=65382;e.won=8361;e.wonmonospace=65510;e.wowaenthai=3623;e.wparen=9394;e.wring=7832;e.wsuperior=695;e.wturned=653;e.wynn=447;e.x=120;e.xabovecmb=829;e.xbopomofo=12562;e.xcircle=9447;e.xdieresis=7821;e.xdotaccent=7819;e.xeharmenian=1389;e.xi=958;e.xmonospace=65368;e.xparen=9395;e.xsuperior=739;e.y=121;e.yaadosquare=13134;e.yabengali=2479;e.yacute=253;e.yadeva=2351;e.yaekorean=12626;e.yagujarati=2735;e.yagurmukhi=2607;e.yahiragana=12420;e.yakatakana=12516;e.yakatakanahalfwidth=65428;e.yakorean=12625;e.yamakkanthai=3662;e.yasmallhiragana=12419;e.yasmallkatakana=12515;e.yasmallkatakanahalfwidth=65388;e.yatcyrillic=1123;e.ycircle=9448;e.ycircumflex=375;e.ydieresis=255;e.ydotaccent=7823;e.ydotbelow=7925;e.yeharabic=1610;e.yehbarreearabic=1746;e.yehbarreefinalarabic=64431;e.yehfinalarabic=65266;e.yehhamzaabovearabic=1574;e.yehhamzaabovefinalarabic=65162;e.yehhamzaaboveinitialarabic=65163;e.yehhamzaabovemedialarabic=65164;e.yehinitialarabic=65267;e.yehmedialarabic=65268;e.yehmeeminitialarabic=64733;e.yehmeemisolatedarabic=64600;e.yehnoonfinalarabic=64660;e.yehthreedotsbelowarabic=1745;e.yekorean=12630;e.yen=165;e.yenmonospace=65509;e.yeokorean=12629;e.yeorinhieuhkorean=12678;e.yerahbenyomohebrew=1450;e.yerahbenyomolefthebrew=1450;e.yericyrillic=1099;e.yerudieresiscyrillic=1273;e.yesieungkorean=12673;e.yesieungpansioskorean=12675;e.yesieungsioskorean=12674;e.yetivhebrew=1434;e.ygrave=7923;e.yhook=436;e.yhookabove=7927;e.yiarmenian=1397;e.yicyrillic=1111;e.yikorean=12642;e.yinyang=9775;e.yiwnarmenian=1410;e.ymonospace=65369;e.yod=1497;e.yoddagesh=64313;e.yoddageshhebrew=64313;e.yodhebrew=1497;e.yodyodhebrew=1522;e.yodyodpatahhebrew=64287;e.yohiragana=12424;e.yoikorean=12681;e.yokatakana=12520;e.yokatakanahalfwidth=65430;e.yokorean=12635;e.yosmallhiragana=12423;e.yosmallkatakana=12519;e.yosmallkatakanahalfwidth=65390;e.yotgreek=1011;e.yoyaekorean=12680;e.yoyakorean=12679;e.yoyakthai=3618;e.yoyingthai=3597;e.yparen=9396;e.ypogegrammeni=890;e.ypogegrammenigreekcmb=837;e.yr=422;e.yring=7833;e.ysuperior=696;e.ytilde=7929;e.yturned=654;e.yuhiragana=12422;e.yuikorean=12684;e.yukatakana=12518;e.yukatakanahalfwidth=65429;e.yukorean=12640;e.yusbigcyrillic=1131;e.yusbigiotifiedcyrillic=1133;e.yuslittlecyrillic=1127;e.yuslittleiotifiedcyrillic=1129;e.yusmallhiragana=12421;e.yusmallkatakana=12517;e.yusmallkatakanahalfwidth=65389;e.yuyekorean=12683;e.yuyeokorean=12682;e.yyabengali=2527;e.yyadeva=2399;e.z=122;e.zaarmenian=1382;e.zacute=378;e.zadeva=2395;e.zagurmukhi=2651;e.zaharabic=1592;e.zahfinalarabic=65222;e.zahinitialarabic=65223;e.zahiragana=12374;e.zahmedialarabic=65224;e.zainarabic=1586;e.zainfinalarabic=65200;e.zakatakana=12470;e.zaqefgadolhebrew=1429;e.zaqefqatanhebrew=1428;e.zarqahebrew=1432;e.zayin=1494;e.zayindagesh=64310;e.zayindageshhebrew=64310;e.zayinhebrew=1494;e.zbopomofo=12567;e.zcaron=382;e.zcircle=9449;e.zcircumflex=7825;e.zcurl=657;e.zdot=380;e.zdotaccent=380;e.zdotbelow=7827;e.zecyrillic=1079;e.zedescendercyrillic=1177;e.zedieresiscyrillic=1247;e.zehiragana=12380;e.zekatakana=12476;e.zero=48;e.zeroarabic=1632;e.zerobengali=2534;e.zerodeva=2406;e.zerogujarati=2790;e.zerogurmukhi=2662;e.zerohackarabic=1632;e.zeroinferior=8320;e.zeromonospace=65296;e.zerooldstyle=63280;e.zeropersian=1776;e.zerosuperior=8304;e.zerothai=3664;e.zerowidthjoiner=65279;e.zerowidthnonjoiner=8204;e.zerowidthspace=8203;e.zeta=950;e.zhbopomofo=12563;e.zhearmenian=1386;e.zhebrevecyrillic=1218;e.zhecyrillic=1078;e.zhedescendercyrillic=1175;e.zhedieresiscyrillic=1245;e.zihiragana=12376;e.zikatakana=12472;e.zinorhebrew=1454;e.zlinebelow=7829;e.zmonospace=65370;e.zohiragana=12382;e.zokatakana=12478;e.zparen=9397;e.zretroflexhook=656;e.zstroke=438;e.zuhiragana=12378;e.zukatakana=12474;e[".notdef"]=0;e.angbracketleftbig=9001;e.angbracketleftBig=9001;e.angbracketleftbigg=9001;e.angbracketleftBigg=9001;e.angbracketrightBig=9002;e.angbracketrightbig=9002;e.angbracketrightBigg=9002;e.angbracketrightbigg=9002;e.arrowhookleft=8618;e.arrowhookright=8617;e.arrowlefttophalf=8636;e.arrowleftbothalf=8637;e.arrownortheast=8599;e.arrownorthwest=8598;e.arrowrighttophalf=8640;e.arrowrightbothalf=8641;e.arrowsoutheast=8600;e.arrowsouthwest=8601;e.backslashbig=8726;e.backslashBig=8726;e.backslashBigg=8726;e.backslashbigg=8726;e.bardbl=8214;e.bracehtipdownleft=65079;e.bracehtipdownright=65079;e.bracehtipupleft=65080;e.bracehtipupright=65080;e.braceleftBig=123;e.braceleftbig=123;e.braceleftbigg=123;e.braceleftBigg=123;e.bracerightBig=125;e.bracerightbig=125;e.bracerightbigg=125;e.bracerightBigg=125;e.bracketleftbig=91;e.bracketleftBig=91;e.bracketleftbigg=91;e.bracketleftBigg=91;e.bracketrightBig=93;e.bracketrightbig=93;e.bracketrightbigg=93;e.bracketrightBigg=93;e.ceilingleftbig=8968;e.ceilingleftBig=8968;e.ceilingleftBigg=8968;e.ceilingleftbigg=8968;e.ceilingrightbig=8969;e.ceilingrightBig=8969;e.ceilingrightbigg=8969;e.ceilingrightBigg=8969;e.circledotdisplay=8857;e.circledottext=8857;e.circlemultiplydisplay=8855;e.circlemultiplytext=8855;e.circleplusdisplay=8853;e.circleplustext=8853;e.contintegraldisplay=8750;e.contintegraltext=8750;e.coproductdisplay=8720;e.coproducttext=8720;e.floorleftBig=8970;e.floorleftbig=8970;e.floorleftbigg=8970;e.floorleftBigg=8970;e.floorrightbig=8971;e.floorrightBig=8971;e.floorrightBigg=8971;e.floorrightbigg=8971;e.hatwide=770;e.hatwider=770;e.hatwidest=770;e.intercal=7488;e.integraldisplay=8747;e.integraltext=8747;e.intersectiondisplay=8898;e.intersectiontext=8898;e.logicalanddisplay=8743;e.logicalandtext=8743;e.logicalordisplay=8744;e.logicalortext=8744;e.parenleftBig=40;e.parenleftbig=40;e.parenleftBigg=40;e.parenleftbigg=40;e.parenrightBig=41;e.parenrightbig=41;e.parenrightBigg=41;e.parenrightbigg=41;e.prime=8242;e.productdisplay=8719;e.producttext=8719;e.radicalbig=8730;e.radicalBig=8730;e.radicalBigg=8730;e.radicalbigg=8730;e.radicalbt=8730;e.radicaltp=8730;e.radicalvertex=8730;e.slashbig=47;e.slashBig=47;e.slashBigg=47;e.slashbigg=47;e.summationdisplay=8721;e.summationtext=8721;e.tildewide=732;e.tildewider=732;e.tildewidest=732;e.uniondisplay=8899;e.unionmultidisplay=8846;e.unionmultitext=8846;e.unionsqdisplay=8852;e.unionsqtext=8852;e.uniontext=8899;e.vextenddouble=8741;e.vextendsingle=8739}),ba=getLookupTableFactory(function(e){e.space=32;e.a1=9985;e.a2=9986;e.a202=9987;e.a3=9988;e.a4=9742;e.a5=9990;e.a119=9991;e.a118=9992;e.a117=9993;e.a11=9755;e.a12=9758;e.a13=9996;e.a14=9997;e.a15=9998;e.a16=9999;e.a105=1e4;e.a17=10001;e.a18=10002;e.a19=10003;e.a20=10004;e.a21=10005;e.a22=10006;e.a23=10007;e.a24=10008;e.a25=10009;e.a26=10010;e.a27=10011;e.a28=10012;e.a6=10013;e.a7=10014;e.a8=10015;e.a9=10016;e.a10=10017;e.a29=10018;e.a30=10019;e.a31=10020;e.a32=10021;e.a33=10022;e.a34=10023;e.a35=9733;e.a36=10025;e.a37=10026;e.a38=10027;e.a39=10028;e.a40=10029;e.a41=10030;e.a42=10031;e.a43=10032;e.a44=10033;e.a45=10034;e.a46=10035;e.a47=10036;e.a48=10037;e.a49=10038;e.a50=10039;e.a51=10040;e.a52=10041;e.a53=10042;e.a54=10043;e.a55=10044;e.a56=10045;e.a57=10046;e.a58=10047;e.a59=10048;e.a60=10049;e.a61=10050;e.a62=10051;e.a63=10052;e.a64=10053;e.a65=10054;e.a66=10055;e.a67=10056;e.a68=10057;e.a69=10058;e.a70=10059;e.a71=9679;e.a72=10061;e.a73=9632;e.a74=10063;e.a203=10064;e.a75=10065;e.a204=10066;e.a76=9650;e.a77=9660;e.a78=9670;e.a79=10070;e.a81=9687;e.a82=10072;e.a83=10073;e.a84=10074;e.a97=10075;e.a98=10076;e.a99=10077;e.a100=10078;e.a101=10081;e.a102=10082;e.a103=10083;e.a104=10084;e.a106=10085;e.a107=10086;e.a108=10087;e.a112=9827;e.a111=9830;e.a110=9829;e.a109=9824;e.a120=9312;e.a121=9313;e.a122=9314;e.a123=9315;e.a124=9316;e.a125=9317;e.a126=9318;e.a127=9319;e.a128=9320;e.a129=9321;e.a130=10102;e.a131=10103;e.a132=10104;e.a133=10105;e.a134=10106;e.a135=10107;e.a136=10108;e.a137=10109;e.a138=10110;e.a139=10111;e.a140=10112;e.a141=10113;e.a142=10114;e.a143=10115;e.a144=10116;e.a145=10117;e.a146=10118;e.a147=10119;e.a148=10120;e.a149=10121;e.a150=10122;e.a151=10123;e.a152=10124;e.a153=10125;e.a154=10126;e.a155=10127;e.a156=10128;e.a157=10129;e.a158=10130;e.a159=10131;e.a160=10132;e.a161=8594;e.a163=8596;e.a164=8597;e.a196=10136;e.a165=10137;e.a192=10138;e.a166=10139;e.a167=10140;e.a168=10141;e.a169=10142;e.a170=10143;e.a171=10144;e.a172=10145;e.a173=10146;e.a162=10147;e.a174=10148;e.a175=10149;e.a176=10150;e.a177=10151;e.a178=10152;e.a179=10153;e.a193=10154;e.a180=10155;e.a199=10156;e.a181=10157;e.a200=10158;e.a182=10159;e.a201=10161;e.a183=10162;e.a184=10163;e.a197=10164;e.a185=10165;e.a194=10166;e.a198=10167;e.a186=10168;e.a195=10169;e.a187=10170;e.a188=10171;e.a189=10172;e.a190=10173;e.a191=10174;e.a89=10088;e.a90=10089;e.a93=10090;e.a94=10091;e.a91=10092;e.a92=10093;e.a205=10094;e.a85=10095;e.a206=10096;e.a86=10097;e.a87=10098;e.a88=10099;e.a95=10100;e.a96=10101;e[".notdef"]=0}),wa=getLookupTableFactory(function(e){e[63721]=169;e[63193]=169;e[63720]=174;e[63194]=174;e[63722]=8482;e[63195]=8482;e[63729]=9127;e[63730]=9128;e[63731]=9129;e[63740]=9131;e[63741]=9132;e[63742]=9133;e[63726]=9121;e[63727]=9122;e[63728]=9123;e[63737]=9124;e[63738]=9125;e[63739]=9126;e[63723]=9115;e[63724]=9116;e[63725]=9117;e[63734]=9118;e[63735]=9119;e[63736]=9120});function getUnicodeForGlyph(e,t){let n=t[e];if(void 0!==n)return n;if(!e)return-1;if("u"===e[0]){const t=e.length;let a;if(7===t&&"n"===e[1]&&"i"===e[2])a=e.substring(3);else{if(!(t>=5&&t<=7))return-1;a=e.substring(1)}if(a===a.toUpperCase()){n=parseInt(a,16);if(n>=0)return n}}return-1}const ja=[[0,127],[128,255],[256,383],[384,591],[592,687,7424,7551,7552,7615],[688,767,42752,42783],[768,879,7616,7679],[880,1023],[11392,11519],[1024,1279,1280,1327,11744,11775,42560,42655],[1328,1423],[1424,1535],[42240,42559],[1536,1791,1872,1919],[1984,2047],[2304,2431],[2432,2559],[2560,2687],[2688,2815],[2816,2943],[2944,3071],[3072,3199],[3200,3327],[3328,3455],[3584,3711],[3712,3839],[4256,4351,11520,11567],[6912,7039],[4352,4607],[7680,7935,11360,11391,42784,43007],[7936,8191],[8192,8303,11776,11903],[8304,8351],[8352,8399],[8400,8447],[8448,8527],[8528,8591],[8592,8703,10224,10239,10496,10623,11008,11263],[8704,8959,10752,11007,10176,10223,10624,10751],[8960,9215],[9216,9279],[9280,9311],[9312,9471],[9472,9599],[9600,9631],[9632,9727],[9728,9983],[9984,10175],[12288,12351],[12352,12447],[12448,12543,12784,12799],[12544,12591,12704,12735],[12592,12687],[43072,43135],[12800,13055],[13056,13311],[44032,55215],[55296,57343],[67840,67871],[19968,40959,11904,12031,12032,12255,12272,12287,13312,19903,131072,173791,12688,12703],[57344,63743],[12736,12783,63744,64255,194560,195103],[64256,64335],[64336,65023],[65056,65071],[65040,65055],[65104,65135],[65136,65279],[65280,65519],[65520,65535],[3840,4095],[1792,1871],[1920,1983],[3456,3583],[4096,4255],[4608,4991,4992,5023,11648,11743],[5024,5119],[5120,5759],[5760,5791],[5792,5887],[6016,6143],[6144,6319],[10240,10495],[40960,42127],[5888,5919,5920,5951,5952,5983,5984,6015],[66304,66351],[66352,66383],[66560,66639],[118784,119039,119040,119295,119296,119375],[119808,120831],[1044480,1048573],[65024,65039,917760,917999],[917504,917631],[6400,6479],[6480,6527],[6528,6623],[6656,6687],[11264,11359],[11568,11647],[19904,19967],[43008,43055],[65536,65663,65664,65791,65792,65855],[65856,65935],[66432,66463],[66464,66527],[66640,66687],[66688,66735],[67584,67647],[68096,68191],[119552,119647],[73728,74751,74752,74879],[119648,119679],[7040,7103],[7168,7247],[7248,7295],[43136,43231],[43264,43311],[43312,43359],[43520,43615],[65936,65999],[66e3,66047],[66208,66271,66176,66207,67872,67903],[127024,127135,126976,127023]];function getUnicodeRangeFor(e,t=-1){if(-1!==t){const n=ja[t];for(let a=0,s=n.length;a<s;a+=2)if(e>=n[a]&&e<=n[a+1])return t}for(let t=0,n=ja.length;t<n;t++){const n=ja[t];for(let a=0,s=n.length;a<s;a+=2)if(e>=n[a]&&e<=n[a+1])return t}return-1}const ka=new RegExp("^(\\s)|(\\p{Mn})|(\\p{Cf})$","u"),ya=new Map;const qa=!0,va=1,Sa=2,xa=4,Aa=32,Ca=[".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","nonbreakingspace","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron","Lslash","lslash","Scaron","scaron","Zcaron","zcaron","brokenbar","Eth","eth","Yacute","yacute","Thorn","thorn","minus","multiply","onesuperior","twosuperior","threesuperior","onehalf","onequarter","threequarters","franc","Gbreve","gbreve","Idotaccent","Scedilla","scedilla","Cacute","cacute","Ccaron","ccaron","dcroat"];function recoverGlyphName(e,t){if(void 0!==t[e])return e;const n=getUnicodeForGlyph(e,t);if(-1!==n)for(const e in t)if(t[e]===n)return e;info("Unable to recover a standard glyph name for: "+e);return e}function type1FontGlyphMapping(e,t,n){const a=Object.create(null);let s,r,i;const o=!!(e.flags&xa);if(e.isInternalFont){i=t;for(r=0;r<i.length;r++){s=n.indexOf(i[r]);a[r]=s>=0?s:0}}else if(e.baseEncodingName){i=getEncoding(e.baseEncodingName);for(r=0;r<i.length;r++){s=n.indexOf(i[r]);a[r]=s>=0?s:0}}else if(o)for(r in t)a[r]=t[r];else{i=ua;for(r=0;r<i.length;r++){s=n.indexOf(i[r]);a[r]=s>=0?s:0}}const l=e.differences;let f;if(l)for(r in l){const e=l[r];s=n.indexOf(e);if(-1===s){f||(f=ga());const t=recoverGlyphName(e,f);t!==e&&(s=n.indexOf(t))}a[r]=s>=0?s:0}return a}function normalizeFontName(e){return e.replaceAll(/[,_]/g,"-").replaceAll(/\s/g,"")}const Ia=getLookupTableFactory(e=>{e[8211]=65074;e[8212]=65073;e[8229]=65072;e[8230]=65049;e[12289]=65041;e[12290]=65042;e[12296]=65087;e[12297]=65088;e[12298]=65085;e[12299]=65086;e[12300]=65089;e[12301]=65090;e[12302]=65091;e[12303]=65092;e[12304]=65083;e[12305]=65084;e[12308]=65081;e[12309]=65082;e[12310]=65047;e[12311]=65048;e[65103]=65076;e[65281]=65045;e[65288]=65077;e[65289]=65078;e[65292]=65040;e[65306]=65043;e[65307]=65044;e[65311]=65046;e[65339]=65095;e[65341]=65096;e[65343]=65075;e[65371]=65079;e[65373]=65080});const Fa=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron"],Ta=[".notdef","space","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],Ha=[".notdef","space","dollaroldstyle","dollarsuperior","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","hyphensuperior","colonmonetary","onefitted","rupiah","centoldstyle","figuredash","hypheninferior","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior"],Oa=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall","001.000","001.001","001.002","001.003","Black","Bold","Book","Light","Medium","Regular","Roman","Semibold"],Ba=391,Ra=[null,{id:"hstem",min:2,stackClearing:!0,stem:!0},null,{id:"vstem",min:2,stackClearing:!0,stem:!0},{id:"vmoveto",min:1,stackClearing:!0},{id:"rlineto",min:2,resetStack:!0},{id:"hlineto",min:1,resetStack:!0},{id:"vlineto",min:1,resetStack:!0},{id:"rrcurveto",min:6,resetStack:!0},null,{id:"callsubr",min:1},{id:"return",min:0},null,null,{id:"endchar",min:0,stackClearing:!0},null,null,null,{id:"hstemhm",min:2,stackClearing:!0,stem:!0},{id:"hintmask",min:0,stackClearing:!0},{id:"cntrmask",min:0,stackClearing:!0},{id:"rmoveto",min:2,stackClearing:!0},{id:"hmoveto",min:1,stackClearing:!0},{id:"vstemhm",min:2,stackClearing:!0,stem:!0},{id:"rcurveline",min:8,resetStack:!0},{id:"rlinecurve",min:8,resetStack:!0},{id:"vvcurveto",min:4,resetStack:!0},{id:"hhcurveto",min:4,resetStack:!0},null,{id:"callgsubr",min:1},{id:"vhcurveto",min:4,resetStack:!0},{id:"hvcurveto",min:4,resetStack:!0}],Da=[null,null,null,{id:"and",min:2,stackDelta:-1},{id:"or",min:2,stackDelta:-1},{id:"not",min:1,stackDelta:0},null,null,null,{id:"abs",min:1,stackDelta:0},{id:"add",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]+e[t-1]}},{id:"sub",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]-e[t-1]}},{id:"div",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]/e[t-1]}},null,{id:"neg",min:1,stackDelta:0,stackFn(e,t){e[t-1]=-e[t-1]}},{id:"eq",min:2,stackDelta:-1},null,null,{id:"drop",min:1,stackDelta:-1},null,{id:"put",min:2,stackDelta:-2},{id:"get",min:1,stackDelta:0},{id:"ifelse",min:4,stackDelta:-3},{id:"random",min:0,stackDelta:1},{id:"mul",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]*e[t-1]}},null,{id:"sqrt",min:1,stackDelta:0},{id:"dup",min:1,stackDelta:1},{id:"exch",min:2,stackDelta:0},{id:"index",min:2,stackDelta:0},{id:"roll",min:3,stackDelta:-2},null,null,null,{id:"hflex",min:7,resetStack:!0},{id:"flex",min:13,resetStack:!0},{id:"hflex1",min:9,resetStack:!0},{id:"flex1",min:11,resetStack:!0}];class CFFParser{constructor(e,t,n){this.bytes=e.getBytes();this.properties=t;this.seacAnalysisEnabled=!!n}parse(){const e=this.properties,t=new CFF;this.cff=t;const n=this.parseHeader(),a=this.parseIndex(n.endPos),s=this.parseIndex(a.endPos),r=this.parseIndex(s.endPos),i=this.parseIndex(r.endPos),o=this.parseDict(s.obj.get(0)),l=this.createDict(CFFTopDict,o,t.strings);t.header=n.obj;t.names=this.parseNameIndex(a.obj);t.strings=this.parseStringIndex(r.obj);t.topDict=l;t.globalSubrIndex=i.obj;this.parsePrivateDict(t.topDict);t.isCIDFont=l.hasName("ROS");const f=l.getByName("CharStrings"),c=this.parseIndex(f).obj;t.charStringCount=c.count;const h=l.getByName("FontMatrix");h&&(e.fontMatrix=h);const u=l.getByName("FontBBox");if(u){e.ascent=Math.max(u[3],u[1]);e.descent=Math.min(u[1],u[3]);e.ascentScaled=!0}let m,p;if(t.isCIDFont){const e=this.parseIndex(l.getByName("FDArray")).obj;for(let n=0,a=e.count;n<a;++n){const a=e.get(n),s=this.createDict(CFFTopDict,this.parseDict(a),t.strings);this.parsePrivateDict(s);t.fdArray.push(s)}p=null;m=this.parseCharsets(l.getByName("charset"),c.count,t.strings,!0);t.fdSelect=this.parseFDSelect(l.getByName("FDSelect"),c.count)}else{m=this.parseCharsets(l.getByName("charset"),c.count,t.strings,!1);p=this.parseEncoding(l.getByName("Encoding"),e,t.strings,m.charset)}t.charset=m;t.encoding=p;const d=this.parseCharStrings({charStrings:c,localSubrIndex:l.privateDict.subrsIndex,globalSubrIndex:i.obj,fdSelect:t.fdSelect,fdArray:t.fdArray,privateDict:l.privateDict});t.charStrings=d.charStrings;t.seacs=d.seacs;t.widths=d.widths;return t}parseHeader(){let e=this.bytes;const t=e.length;let n=0;for(;n<t&&1!==e[n];)++n;if(n>=t)throw new FormatError("Invalid CFF header");if(0!==n){info("cff data is shifted");e=e.subarray(n);this.bytes=e}const a=e[0],s=e[1],r=e[2],i=e[3];return{obj:new CFFHeader(a,s,r,i),endPos:r}}parseDict(e){let t=0;function parseOperand(){let n=e[t++];if(30===n)return function parseFloatOperand(){let n="";const a=15,s=["0","1","2","3","4","5","6","7","8","9",".","E","E-",null,"-"],r=e.length;for(;t<r;){const r=e[t++],i=r>>4,o=15&r;if(i===a)break;n+=s[i];if(o===a)break;n+=s[o]}return parseFloat(n)}();if(28===n){n=readInt16(e,t);t+=2;return n}if(29===n){n=e[t++];n=n<<8|e[t++];n=n<<8|e[t++];n=n<<8|e[t++];return n}if(n>=32&&n<=246)return n-139;if(n>=247&&n<=250)return 256*(n-247)+e[t++]+108;if(n>=251&&n<=254)return-256*(n-251)-e[t++]-108;warn('CFFParser_parseDict: "'+n+'" is a reserved command.');return NaN}let n=[];const a=[];t=0;const s=e.length;for(;t<s;){let s=e[t];if(s<=21){12===s&&(s=s<<8|e[++t]);a.push([s,n]);n=[];++t}else n.push(parseOperand())}return a}parseIndex(e){const t=new CFFIndex,n=this.bytes,a=n[e++]<<8|n[e++],s=[];let r,i,o=e;if(0!==a){const t=n[e++],l=e+(a+1)*t-1;for(r=0,i=a+1;r<i;++r){let a=0;for(let s=0;s<t;++s){a<<=8;a+=n[e++]}s.push(l+a)}o=s[a]}for(r=0,i=s.length-1;r<i;++r){const e=s[r],a=s[r+1];t.add(n.subarray(e,a))}return{obj:t,endPos:o}}parseNameIndex(e){const t=[];for(let n=0,a=e.count;n<a;++n){const a=e.get(n);t.push(bytesToString(a))}return t}parseStringIndex(e){const t=new CFFStrings;for(let n=0,a=e.count;n<a;++n){const a=e.get(n);t.add(bytesToString(a))}return t}createDict(e,t,n){const a=new e(n);for(const[e,n]of t)a.setByKey(e,n);return a}parseCharString(e,t,n,a){if(!t||e.callDepth>10)return!1;let s=e.stackSize;const r=e.stack;let i=t.length;for(let o=0;o<i;){const l=t[o++];let f=null;if(12===l){const e=t[o++];if(0===e){t[o-2]=139;t[o-1]=22;s=0}else f=Da[e]}else if(28===l){r[s]=readInt16(t,o);o+=2;s++}else if(14===l){if(s>=4){s-=4;if(this.seacAnalysisEnabled){e.seac=r.slice(s,s+4);return!1}}f=Ra[l]}else if(l>=32&&l<=246){r[s]=l-139;s++}else if(l>=247&&l<=254){r[s]=l<251?(l-247<<8)+t[o]+108:-(l-251<<8)-t[o]-108;o++;s++}else if(255===l){r[s]=(t[o]<<24|t[o+1]<<16|t[o+2]<<8|t[o+3])/65536;o+=4;s++}else if(19===l||20===l){e.hints+=s>>1;if(0===e.hints){t.copyWithin(o-1,o,-1);o-=1;i-=1;continue}o+=e.hints+7>>3;s%=2;f=Ra[l]}else{if(10===l||29===l){const t=10===l?n:a;if(!t){f=Ra[l];warn("Missing subrsIndex for "+f.id);return!1}let i=32768;t.count<1240?i=107:t.count<33900&&(i=1131);const o=r[--s]+i;if(o<0||o>=t.count||isNaN(o)){f=Ra[l];warn("Out of bounds subrIndex for "+f.id);return!1}e.stackSize=s;e.callDepth++;if(!this.parseCharString(e,t.get(o),n,a))return!1;e.callDepth--;s=e.stackSize;continue}if(11===l){e.stackSize=s;return!0}if(0===l&&o===t.length){t[o-1]=14;f=Ra[14]}else{if(9===l){t.copyWithin(o-1,o,-1);o-=1;i-=1;continue}f=Ra[l]}}if(f){if(f.stem){e.hints+=s>>1;if(3===l||23===l)e.hasVStems=!0;else if(e.hasVStems&&(1===l||18===l)){warn("CFF stem hints are in wrong order");t[o-1]=1===l?3:23}}if(s<f.min){warn("Not enough parameters for "+f.id+"; actual: "+s+", expected: "+f.min);if(0===s){t[o-1]=14;return!0}return!1}if(e.firstStackClearing&&f.stackClearing){e.firstStackClearing=!1;s-=f.min;s>=2&&f.stem?s%=2:s>1&&warn("Found too many parameters for stack-clearing command");s>0&&(e.width=r[s-1])}if("stackDelta"in f){"stackFn"in f&&f.stackFn(r,s);s+=f.stackDelta}else(f.stackClearing||f.resetStack)&&(s=0)}}i<t.length&&t.fill(14,i);e.stackSize=s;return!0}parseCharStrings({charStrings:e,localSubrIndex:t,globalSubrIndex:n,fdSelect:a,fdArray:s,privateDict:r}){const i=[],o=[],l=e.count;for(let f=0;f<l;f++){const l=e.get(f),c={callDepth:0,stackSize:0,stack:[],hints:0,firstStackClearing:!0,seac:null,width:null,hasVStems:!1};let h=!0,u=null,m=r;if(a&&s.length){const e=a.getFDIndex(f);if(-1===e){warn("Glyph index is not in fd select.");h=!1}if(e>=s.length){warn("Invalid fd index for glyph index.");h=!1}if(h){m=s[e].privateDict;u=m.subrsIndex}}else t&&(u=t);h&&(h=this.parseCharString(c,l,u,n));if(null!==c.width){const e=m.getByName("nominalWidthX");o[f]=e+c.width}else{const e=m.getByName("defaultWidthX");o[f]=e}null!==c.seac&&(i[f]=c.seac);h||e.set(f,new Uint8Array([14]))}return{charStrings:e,seacs:i,widths:o}}emptyPrivateDictionary(e){const t=this.createDict(CFFPrivateDict,[],e.strings);e.setByKey(18,[0,0]);e.privateDict=t}parsePrivateDict(e){if(!e.hasName("Private")){this.emptyPrivateDictionary(e);return}const t=e.getByName("Private");if(!Array.isArray(t)||2!==t.length){e.removeByName("Private");return}const n=t[0],a=t[1];if(0===n||a>=this.bytes.length){this.emptyPrivateDictionary(e);return}const s=a+n,r=this.bytes.subarray(a,s),i=this.parseDict(r),o=this.createDict(CFFPrivateDict,i,e.strings);e.privateDict=o;0===o.getByName("ExpansionFactor")&&o.setByName("ExpansionFactor",.06);if(!o.getByName("Subrs"))return;const l=o.getByName("Subrs"),f=a+l;if(0===l||f>=this.bytes.length){this.emptyPrivateDictionary(e);return}const c=this.parseIndex(f);o.subrsIndex=c.obj}parseCharsets(e,t,n,a){if(0===e)return new CFFCharset(!0,Ea.ISO_ADOBE,Fa);if(1===e)return new CFFCharset(!0,Ea.EXPERT,Ta);if(2===e)return new CFFCharset(!0,Ea.EXPERT_SUBSET,Ha);const s=this.bytes,r=e,i=s[e++],o=[a?0:".notdef"];let l,f,c;t-=1;switch(i){case 0:for(c=0;c<t;c++){l=s[e++]<<8|s[e++];o.push(a?l:n.get(l))}break;case 1:for(;o.length<=t;){l=s[e++]<<8|s[e++];f=s[e++];for(c=0;c<=f;c++)o.push(a?l++:n.get(l++))}break;case 2:for(;o.length<=t;){l=s[e++]<<8|s[e++];f=s[e++]<<8|s[e++];for(c=0;c<=f;c++)o.push(a?l++:n.get(l++))}break;default:throw new FormatError("Unknown charset format")}const h=e,u=s.subarray(r,h);return new CFFCharset(!1,i,o,u)}parseEncoding(e,t,n,a){const s=Object.create(null),r=this.bytes;let i,o,l,f=!1,c=null;if(0===e||1===e){f=!0;i=e;const t=e?fa:ua;for(o=0,l=a.length;o<l;o++){const e=t.indexOf(a[o]);-1!==e&&(s[e]=o)}}else{const t=e;i=r[e++];switch(127&i){case 0:const t=r[e++];for(o=1;o<=t;o++)s[r[e++]]=o;break;case 1:const n=r[e++];let a=1;for(o=0;o<n;o++){const t=r[e++],n=r[e++];for(let e=t;e<=t+n;e++)s[e]=a++}break;default:throw new FormatError(`Unknown encoding format: ${i} in CFF`)}const l=e;if(128&i){r[t]&=127;!function readSupplement(){const t=r[e++];for(o=0;o<t;o++){const t=r[e++],i=(r[e++]<<8)+(255&r[e++]);s[t]=a.indexOf(n.get(i))}}()}c=r.subarray(t,l)}i&=127;return new CFFEncoding(f,i,s,c)}parseFDSelect(e,t){const n=this.bytes,a=n[e++],s=[];let r;switch(a){case 0:for(r=0;r<t;++r){const t=n[e++];s.push(t)}break;case 3:const i=n[e++]<<8|n[e++];for(r=0;r<i;++r){let t=n[e++]<<8|n[e++];if(0===r&&0!==t){warn("parseFDSelect: The first range must have a first GID of 0 -- trying to recover.");t=0}const a=n[e++],i=n[e]<<8|n[e+1];for(let e=t;e<i;++e)s.push(a)}e+=2;break;default:throw new FormatError(`parseFDSelect: Unknown format "${a}".`)}if(s.length!==t)throw new FormatError("parseFDSelect: Invalid font data.");return new CFFFDSelect(a,s)}}class CFF{header=null;names=[];topDict=null;strings=new CFFStrings;globalSubrIndex=null;encoding=null;charset=null;charStrings=null;fdArray=[];fdSelect=null;isCIDFont=!1;charStringCount=0;duplicateFirstGlyph(){if(this.charStrings.count>=65535){warn("Not enough space in charstrings to duplicate first glyph.");return}const e=this.charStrings.get(0);this.charStrings.add(e);this.isCIDFont&&this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0])}hasGlyphId(e){if(e<0||e>=this.charStrings.count)return!1;return this.charStrings.get(e).length>0}}class CFFHeader{constructor(e,t,n,a){this.major=e;this.minor=t;this.hdrSize=n;this.offSize=a}}class CFFStrings{strings=[];get(e){return e>=0&&e<=390?Oa[e]:e-Ba<=this.strings.length?this.strings[e-Ba]:Oa[0]}getSID(e){let t=Oa.indexOf(e);if(-1!==t)return t;t=this.strings.indexOf(e);return-1!==t?t+Ba:-1}add(e){this.strings.push(e)}get count(){return this.strings.length}}class CFFIndex{objects=[];length=0;add(e){this.length+=e.length;this.objects.push(e)}set(e,t){this.length+=t.length-this.objects[e].length;this.objects[e]=t}get(e){return this.objects[e]}get count(){return this.objects.length}}class CFFDict{constructor(e,t){this.keyToNameMap=e.keyToNameMap;this.nameToKeyMap=e.nameToKeyMap;this.defaults=e.defaults;this.types=e.types;this.opcodes=e.opcodes;this.order=e.order;this.strings=t;this.values=Object.create(null)}setByKey(e,t){if(!(e in this.keyToNameMap))return!1;if(0===t.length)return!0;for(const n of t)if(isNaN(n)){warn(`Invalid CFFDict value: "${t}" for key "${e}".`);return!0}const n=this.types[e];"num"!==n&&"sid"!==n&&"offset"!==n||(t=t[0]);this.values[e]=t;return!0}setByName(e,t){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name "${e}"`);this.values[this.nameToKeyMap[e]]=t}hasName(e){return this.nameToKeyMap[e]in this.values}getByName(e){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name ${e}"`);const t=this.nameToKeyMap[e];return t in this.values?this.values[t]:this.defaults[t]}removeByName(e){delete this.values[this.nameToKeyMap[e]]}static createTables(e){const t={keyToNameMap:{},nameToKeyMap:{},defaults:{},types:{},opcodes:{},order:[]};for(const n of e){const e=Array.isArray(n[0])?(n[0][0]<<8)+n[0][1]:n[0];t.keyToNameMap[e]=n[1];t.nameToKeyMap[n[1]]=e;t.types[e]=n[2];t.defaults[e]=n[3];t.opcodes[e]=Array.isArray(n[0])?n[0]:[n[0]];t.order.push(e)}return t}}const Ma=[[[12,30],"ROS",["sid","sid","num"],null],[[12,20],"SyntheticBase","num",null],[0,"version","sid",null],[1,"Notice","sid",null],[[12,0],"Copyright","sid",null],[2,"FullName","sid",null],[3,"FamilyName","sid",null],[4,"Weight","sid",null],[[12,1],"isFixedPitch","num",0],[[12,2],"ItalicAngle","num",0],[[12,3],"UnderlinePosition","num",-100],[[12,4],"UnderlineThickness","num",50],[[12,5],"PaintType","num",0],[[12,6],"CharstringType","num",2],[[12,7],"FontMatrix",["num","num","num","num","num","num"],[.001,0,0,.001,0,0]],[13,"UniqueID","num",null],[5,"FontBBox",["num","num","num","num"],[0,0,0,0]],[[12,8],"StrokeWidth","num",0],[14,"XUID","array",null],[15,"charset","offset",0],[16,"Encoding","offset",0],[17,"CharStrings","offset",0],[18,"Private",["offset","offset"],null],[[12,21],"PostScript","sid",null],[[12,22],"BaseFontName","sid",null],[[12,23],"BaseFontBlend","delta",null],[[12,31],"CIDFontVersion","num",0],[[12,32],"CIDFontRevision","num",0],[[12,33],"CIDFontType","num",0],[[12,34],"CIDCount","num",8720],[[12,35],"UIDBase","num",null],[[12,37],"FDSelect","offset",null],[[12,36],"FDArray","offset",null],[[12,38],"FontName","sid",null]];class CFFTopDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(Ma))}constructor(e){super(CFFTopDict.tables,e);this.privateDict=null}}const Pa=[[6,"BlueValues","delta",null],[7,"OtherBlues","delta",null],[8,"FamilyBlues","delta",null],[9,"FamilyOtherBlues","delta",null],[[12,9],"BlueScale","num",.039625],[[12,10],"BlueShift","num",7],[[12,11],"BlueFuzz","num",1],[10,"StdHW","num",null],[11,"StdVW","num",null],[[12,12],"StemSnapH","delta",null],[[12,13],"StemSnapV","delta",null],[[12,14],"ForceBold","num",0],[[12,17],"LanguageGroup","num",0],[[12,18],"ExpansionFactor","num",.06],[[12,19],"initialRandomSeed","num",0],[20,"defaultWidthX","num",0],[21,"nominalWidthX","num",0],[19,"Subrs","offset",null]];class CFFPrivateDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(Pa))}constructor(e){super(CFFPrivateDict.tables,e);this.subrsIndex=null}}const Ea={ISO_ADOBE:0,EXPERT:1,EXPERT_SUBSET:2};class CFFCharset{constructor(e,t,n,a){this.predefined=e;this.format=t;this.charset=n;this.raw=a}}class CFFEncoding{constructor(e,t,n,a){this.predefined=e;this.format=t;this.encoding=n;this.raw=a}}class CFFFDSelect{constructor(e,t){this.format=e;this.fdSelect=t}getFDIndex(e){return e<0||e>=this.fdSelect.length?-1:this.fdSelect[e]}}class CFFOffsetTracker{offsets=Object.create(null);isTracking(e){return e in this.offsets}track(e,t){if(e in this.offsets)throw new FormatError(`Already tracking location of ${e}`);this.offsets[e]=t}offset(e){for(const t in this.offsets)this.offsets[t]+=e}setEntryLocation(e,t,n){if(!(e in this.offsets))throw new FormatError(`Not tracking location of ${e}`);const a=n.data,s=this.offsets[e];for(let e=0,n=t.length;e<n;++e){const n=5*e+s,r=n+1,i=n+2,o=n+3,l=n+4;if(29!==a[n]||0!==a[r]||0!==a[i]||0!==a[o]||0!==a[l])throw new FormatError("writing to an offset that is not empty");const f=t[e];a[n]=29;a[r]=f>>24&255;a[i]=f>>16&255;a[o]=f>>8&255;a[l]=255&f}}}class CFFCompiler{constructor(e){this.cff=e}compile(){const e=this.cff,t={data:[],length:0,add(e){try{this.data.push(...e)}catch{this.data=this.data.concat(e)}this.length=this.data.length}},n=this.compileHeader(e.header);t.add(n);const a=this.compileNameIndex(e.names);t.add(a);if(e.isCIDFont&&e.topDict.hasName("FontMatrix")){const t=e.topDict.getByName("FontMatrix");e.topDict.removeByName("FontMatrix");for(const n of e.fdArray){let e=t.slice(0);n.hasName("FontMatrix")&&(e=Util.transform(e,n.getByName("FontMatrix")));n.setByName("FontMatrix",e)}}const s=e.topDict.getByName("XUID");s?.length>16&&e.topDict.removeByName("XUID");e.topDict.setByName("charset",0);let r=this.compileTopDicts([e.topDict],t.length,e.isCIDFont);t.add(r.output);const i=r.trackers[0],o=this.compileStringIndex(e.strings.strings);t.add(o);const l=this.compileIndex(e.globalSubrIndex);t.add(l);if(e.encoding&&e.topDict.hasName("Encoding"))if(e.encoding.predefined)i.setEntryLocation("Encoding",[e.encoding.format],t);else{const n=this.compileEncoding(e.encoding);i.setEntryLocation("Encoding",[t.length],t);t.add(n)}const f=this.compileCharset(e.charset,e.charStrings.count,e.strings,e.isCIDFont);i.setEntryLocation("charset",[t.length],t);t.add(f);const c=this.compileCharStrings(e.charStrings);i.setEntryLocation("CharStrings",[t.length],t);t.add(c);if(e.isCIDFont){i.setEntryLocation("FDSelect",[t.length],t);const n=this.compileFDSelect(e.fdSelect);t.add(n);r=this.compileTopDicts(e.fdArray,t.length,!0);i.setEntryLocation("FDArray",[t.length],t);t.add(r.output);const a=r.trackers;this.compilePrivateDicts(e.fdArray,a,t)}this.compilePrivateDicts([e.topDict],[i],t);t.add([0]);return t.data}encodeNumber(e){return Number.isInteger(e)?this.encodeInteger(e):this.encodeFloat(e)}static get EncodeFloatRegExp(){return shadow(this,"EncodeFloatRegExp",/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/)}encodeFloat(e){let t=e.toString();const n=CFFCompiler.EncodeFloatRegExp.exec(t);if(n){const a=parseFloat("1e"+((n[2]?+n[2]:0)+n[1].length));t=(Math.round(e*a)/a).toString()}let a,s,r="";for(a=0,s=t.length;a<s;++a){const e=t[a];r+="e"===e?"-"===t[++a]?"c":"b":"."===e?"a":"-"===e?"e":e}r+=1&r.length?"f":"ff";const i=[30];for(a=0,s=r.length;a<s;a+=2)i.push(parseInt(r.substring(a,a+2),16));return i}encodeInteger(e){let t;t=e>=-107&&e<=107?[e+139]:e>=108&&e<=1131?[247+((e-=108)>>8),255&e]:e>=-1131&&e<=-108?[251+((e=-e-108)>>8),255&e]:e>=-32768&&e<=32767?[28,e>>8&255,255&e]:[29,e>>24&255,e>>16&255,e>>8&255,255&e];return t}compileHeader(e){return[e.major,e.minor,4,e.offSize]}compileNameIndex(e){const t=new CFFIndex;for(const n of e){const e=Math.min(n.length,127);let a=new Array(e);for(let t=0;t<e;t++){let e=n[t];(e<"!"||e>"~"||"["===e||"]"===e||"("===e||")"===e||"{"===e||"}"===e||"<"===e||">"===e||"/"===e||"%"===e)&&(e="_");a[t]=e}a=a.join("");""===a&&(a="Bad_Font_Name");t.add(stringToBytes(a))}return this.compileIndex(t)}compileTopDicts(e,t,n){const a=[];let s=new CFFIndex;for(const r of e){if(n){r.removeByName("CIDFontVersion");r.removeByName("CIDFontRevision");r.removeByName("CIDFontType");r.removeByName("CIDCount");r.removeByName("UIDBase")}const e=new CFFOffsetTracker,i=this.compileDict(r,e);a.push(e);s.add(i);e.offset(t)}s=this.compileIndex(s,a);return{trackers:a,output:s}}compilePrivateDicts(e,t,n){for(let a=0,s=e.length;a<s;++a){const s=e[a],r=s.privateDict;if(!r||!s.hasName("Private"))throw new FormatError("There must be a private dictionary.");const i=new CFFOffsetTracker,o=this.compileDict(r,i);let l=n.length;i.offset(l);o.length||(l=0);t[a].setEntryLocation("Private",[o.length,l],n);n.add(o);if(r.subrsIndex&&r.hasName("Subrs")){const e=this.compileIndex(r.subrsIndex);i.setEntryLocation("Subrs",[o.length],n);n.add(e)}}}compileDict(e,t){const n=[];for(const a of e.order){if(!(a in e.values))continue;let s=e.values[a],r=e.types[a];Array.isArray(r)||(r=[r]);Array.isArray(s)||(s=[s]);if(0!==s.length){for(let i=0,o=r.length;i<o;++i){const o=r[i],l=s[i];switch(o){case"num":case"sid":n.push(...this.encodeNumber(l));break;case"offset":const r=e.keyToNameMap[a];t.isTracking(r)||t.track(r,n.length);n.push(29,0,0,0,0);break;case"array":case"delta":n.push(...this.encodeNumber(l));for(let e=1,t=s.length;e<t;++e)n.push(...this.encodeNumber(s[e]));break;default:throw new FormatError(`Unknown data type of ${o}`)}}n.push(...e.opcodes[a])}}return n}compileStringIndex(e){const t=new CFFIndex;for(const n of e)t.add(stringToBytes(n));return this.compileIndex(t)}compileCharStrings(e){const t=new CFFIndex;for(let n=0;n<e.count;n++){const a=e.get(n);0!==a.length?t.add(a):t.add(new Uint8Array([139,14]))}return this.compileIndex(t)}compileCharset(e,t,n,a){let s;const r=t-1;if(a){const e=r-1;s=new Uint8Array([2,0,1,e>>8&255,255&e])}else{s=new Uint8Array(1+2*r);s[0]=0;let t=0;const a=e.charset.length;let i=!1;for(let r=1;r<s.length;r+=2){let o=0;if(t<a){const a=e.charset[t++];o=n.getSID(a);if(-1===o){o=0;if(!i){i=!0;warn(`Couldn't find ${a} in CFF strings`)}}}s[r]=o>>8&255;s[r+1]=255&o}}return this.compileTypedArray(s)}compileEncoding(e){return this.compileTypedArray(e.raw)}compileFDSelect(e){const t=e.format;let n,a;switch(t){case 0:n=new Uint8Array(1+e.fdSelect.length);n[0]=t;for(a=0;a<e.fdSelect.length;a++)n[a+1]=e.fdSelect[a];break;case 3:const s=0;let r=e.fdSelect[0];const i=[t,0,0,s>>8&255,255&s,r];for(a=1;a<e.fdSelect.length;a++){const t=e.fdSelect[a];if(t!==r){i.push(a>>8&255,255&a,t);r=t}}const o=(i.length-3)/3;i[1]=o>>8&255;i[2]=255&o;i.push(a>>8&255,255&a);n=new Uint8Array(i)}return this.compileTypedArray(n)}compileTypedArray(e){return Array.from(e)}compileIndex(e,t=[]){const n=e.objects,a=n.length;if(0===a)return[0,0];const s=[a>>8&255,255&a];let r,i,o=1;for(r=0;r<a;++r)o+=n[r].length;i=o<256?1:o<65536?2:o<16777216?3:4;s.push(i);let l=1;for(r=0;r<a+1;r++){1===i?s.push(255&l):2===i?s.push(l>>8&255,255&l):3===i?s.push(l>>16&255,l>>8&255,255&l):s.push(l>>>24&255,l>>16&255,l>>8&255,255&l);n[r]&&(l+=n[r].length)}for(r=0;r<a;r++){t[r]&&t[r].offset(s.length);s.push(...n[r])}return s}}const Na=getLookupTableFactory(function(e){e["Times-Roman"]="Times-Roman";e.Helvetica="Helvetica";e.Courier="Courier";e.Symbol="Symbol";e["Times-Bold"]="Times-Bold";e["Helvetica-Bold"]="Helvetica-Bold";e["Courier-Bold"]="Courier-Bold";e.ZapfDingbats="ZapfDingbats";e["Times-Italic"]="Times-Italic";e["Helvetica-Oblique"]="Helvetica-Oblique";e["Courier-Oblique"]="Courier-Oblique";e["Times-BoldItalic"]="Times-BoldItalic";e["Helvetica-BoldOblique"]="Helvetica-BoldOblique";e["Courier-BoldOblique"]="Courier-BoldOblique";e.ArialNarrow="Helvetica";e["ArialNarrow-Bold"]="Helvetica-Bold";e["ArialNarrow-BoldItalic"]="Helvetica-BoldOblique";e["ArialNarrow-Italic"]="Helvetica-Oblique";e.ArialBlack="Helvetica";e["ArialBlack-Bold"]="Helvetica-Bold";e["ArialBlack-BoldItalic"]="Helvetica-BoldOblique";e["ArialBlack-Italic"]="Helvetica-Oblique";e["Arial-Black"]="Helvetica";e["Arial-Black-Bold"]="Helvetica-Bold";e["Arial-Black-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Black-Italic"]="Helvetica-Oblique";e.Arial="Helvetica";e["Arial-Bold"]="Helvetica-Bold";e["Arial-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Italic"]="Helvetica-Oblique";e.ArialMT="Helvetica";e["Arial-BoldItalicMT"]="Helvetica-BoldOblique";e["Arial-BoldMT"]="Helvetica-Bold";e["Arial-ItalicMT"]="Helvetica-Oblique";e["Arial-BoldItalicMT-BoldItalic"]="Helvetica-BoldOblique";e["Arial-BoldMT-Bold"]="Helvetica-Bold";e["Arial-ItalicMT-Italic"]="Helvetica-Oblique";e.ArialUnicodeMS="Helvetica";e["ArialUnicodeMS-Bold"]="Helvetica-Bold";e["ArialUnicodeMS-BoldItalic"]="Helvetica-BoldOblique";e["ArialUnicodeMS-Italic"]="Helvetica-Oblique";e["Courier-BoldItalic"]="Courier-BoldOblique";e["Courier-Italic"]="Courier-Oblique";e.CourierNew="Courier";e["CourierNew-Bold"]="Courier-Bold";e["CourierNew-BoldItalic"]="Courier-BoldOblique";e["CourierNew-Italic"]="Courier-Oblique";e["CourierNewPS-BoldItalicMT"]="Courier-BoldOblique";e["CourierNewPS-BoldMT"]="Courier-Bold";e["CourierNewPS-ItalicMT"]="Courier-Oblique";e.CourierNewPSMT="Courier";e["Helvetica-BoldItalic"]="Helvetica-BoldOblique";e["Helvetica-Italic"]="Helvetica-Oblique";e["HelveticaLTStd-Bold"]="Helvetica-Bold";e["Symbol-Bold"]="Symbol";e["Symbol-BoldItalic"]="Symbol";e["Symbol-Italic"]="Symbol";e.TimesNewRoman="Times-Roman";e["TimesNewRoman-Bold"]="Times-Bold";e["TimesNewRoman-BoldItalic"]="Times-BoldItalic";e["TimesNewRoman-Italic"]="Times-Italic";e.TimesNewRomanPS="Times-Roman";e["TimesNewRomanPS-Bold"]="Times-Bold";e["TimesNewRomanPS-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPS-BoldItalicMT"]="Times-BoldItalic";e["TimesNewRomanPS-BoldMT"]="Times-Bold";e["TimesNewRomanPS-Italic"]="Times-Italic";e["TimesNewRomanPS-ItalicMT"]="Times-Italic";e.TimesNewRomanPSMT="Times-Roman";e["TimesNewRomanPSMT-Bold"]="Times-Bold";e["TimesNewRomanPSMT-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPSMT-Italic"]="Times-Italic"}),za=getLookupTableFactory(function(e){e.Courier="FoxitFixed.pfb";e["Courier-Bold"]="FoxitFixedBold.pfb";e["Courier-BoldOblique"]="FoxitFixedBoldItalic.pfb";e["Courier-Oblique"]="FoxitFixedItalic.pfb";e.Helvetica="LiberationSans-Regular.ttf";e["Helvetica-Bold"]="LiberationSans-Bold.ttf";e["Helvetica-BoldOblique"]="LiberationSans-BoldItalic.ttf";e["Helvetica-Oblique"]="LiberationSans-Italic.ttf";e["Times-Roman"]="FoxitSerif.pfb";e["Times-Bold"]="FoxitSerifBold.pfb";e["Times-BoldItalic"]="FoxitSerifBoldItalic.pfb";e["Times-Italic"]="FoxitSerifItalic.pfb";e.Symbol="FoxitSymbol.pfb";e.ZapfDingbats="FoxitDingbats.pfb";e["LiberationSans-Regular"]="LiberationSans-Regular.ttf";e["LiberationSans-Bold"]="LiberationSans-Bold.ttf";e["LiberationSans-Italic"]="LiberationSans-Italic.ttf";e["LiberationSans-BoldItalic"]="LiberationSans-BoldItalic.ttf"}),La=getLookupTableFactory(function(e){e.Calibri="Helvetica";e["Calibri-Bold"]="Helvetica-Bold";e["Calibri-BoldItalic"]="Helvetica-BoldOblique";e["Calibri-Italic"]="Helvetica-Oblique";e.CenturyGothic="Helvetica";e["CenturyGothic-Bold"]="Helvetica-Bold";e["CenturyGothic-BoldItalic"]="Helvetica-BoldOblique";e["CenturyGothic-Italic"]="Helvetica-Oblique";e.ComicSansMS="Comic Sans MS";e["ComicSansMS-Bold"]="Comic Sans MS-Bold";e["ComicSansMS-BoldItalic"]="Comic Sans MS-BoldItalic";e["ComicSansMS-Italic"]="Comic Sans MS-Italic";e.GillSansMT="Helvetica";e["GillSansMT-Bold"]="Helvetica-Bold";e["GillSansMT-BoldItalic"]="Helvetica-BoldOblique";e["GillSansMT-Italic"]="Helvetica-Oblique";e.Impact="Helvetica";e["ItcSymbol-Bold"]="Helvetica-Bold";e["ItcSymbol-BoldItalic"]="Helvetica-BoldOblique";e["ItcSymbol-Book"]="Helvetica";e["ItcSymbol-BookItalic"]="Helvetica-Oblique";e["ItcSymbol-Medium"]="Helvetica";e["ItcSymbol-MediumItalic"]="Helvetica-Oblique";e.LucidaConsole="Courier";e["LucidaConsole-Bold"]="Courier-Bold";e["LucidaConsole-BoldItalic"]="Courier-BoldOblique";e["LucidaConsole-Italic"]="Courier-Oblique";e["LucidaSans-Demi"]="Helvetica-Bold";e["MS-Gothic"]="MS Gothic";e["MS-Gothic-Bold"]="MS Gothic-Bold";e["MS-Gothic-BoldItalic"]="MS Gothic-BoldItalic";e["MS-Gothic-Italic"]="MS Gothic-Italic";e["MS-Mincho"]="MS Mincho";e["MS-Mincho-Bold"]="MS Mincho-Bold";e["MS-Mincho-BoldItalic"]="MS Mincho-BoldItalic";e["MS-Mincho-Italic"]="MS Mincho-Italic";e["MS-PGothic"]="MS PGothic";e["MS-PGothic-Bold"]="MS PGothic-Bold";e["MS-PGothic-BoldItalic"]="MS PGothic-BoldItalic";e["MS-PGothic-Italic"]="MS PGothic-Italic";e["MS-PMincho"]="MS PMincho";e["MS-PMincho-Bold"]="MS PMincho-Bold";e["MS-PMincho-BoldItalic"]="MS PMincho-BoldItalic";e["MS-PMincho-Italic"]="MS PMincho-Italic";e.NuptialScript="Times-Italic";e.SegoeUISymbol="Helvetica"}),Ua=getLookupTableFactory(function(e){e["Adobe Jenson"]=!0;e["Adobe Text"]=!0;e.Albertus=!0;e.Aldus=!0;e.Alexandria=!0;e.Algerian=!0;e["American Typewriter"]=!0;e.Antiqua=!0;e.Apex=!0;e.Arno=!0;e.Aster=!0;e.Aurora=!0;e.Baskerville=!0;e.Bell=!0;e.Bembo=!0;e["Bembo Schoolbook"]=!0;e.Benguiat=!0;e["Berkeley Old Style"]=!0;e["Bernhard Modern"]=!0;e["Berthold City"]=!0;e.Bodoni=!0;e["Bauer Bodoni"]=!0;e["Book Antiqua"]=!0;e.Bookman=!0;e["Bordeaux Roman"]=!0;e["Californian FB"]=!0;e.Calisto=!0;e.Calvert=!0;e.Capitals=!0;e.Cambria=!0;e.Cartier=!0;e.Caslon=!0;e.Catull=!0;e.Centaur=!0;e["Century Old Style"]=!0;e["Century Schoolbook"]=!0;e.Chaparral=!0;e["Charis SIL"]=!0;e.Cheltenham=!0;e["Cholla Slab"]=!0;e.Clarendon=!0;e.Clearface=!0;e.Cochin=!0;e.Colonna=!0;e["Computer Modern"]=!0;e["Concrete Roman"]=!0;e.Constantia=!0;e["Cooper Black"]=!0;e.Corona=!0;e.Ecotype=!0;e.Egyptienne=!0;e.Elephant=!0;e.Excelsior=!0;e.Fairfield=!0;e["FF Scala"]=!0;e.Folkard=!0;e.Footlight=!0;e.FreeSerif=!0;e["Friz Quadrata"]=!0;e.Garamond=!0;e.Gentium=!0;e.Georgia=!0;e.Gloucester=!0;e["Goudy Old Style"]=!0;e["Goudy Schoolbook"]=!0;e["Goudy Pro Font"]=!0;e.Granjon=!0;e["Guardian Egyptian"]=!0;e.Heather=!0;e.Hercules=!0;e["High Tower Text"]=!0;e.Hiroshige=!0;e["Hoefler Text"]=!0;e["Humana Serif"]=!0;e.Imprint=!0;e["Ionic No. 5"]=!0;e.Janson=!0;e.Joanna=!0;e.Korinna=!0;e.Lexicon=!0;e.LiberationSerif=!0;e["Liberation Serif"]=!0;e["Linux Libertine"]=!0;e.Literaturnaya=!0;e.Lucida=!0;e["Lucida Bright"]=!0;e.Melior=!0;e.Memphis=!0;e.Miller=!0;e.Minion=!0;e.Modern=!0;e["Mona Lisa"]=!0;e["Mrs Eaves"]=!0;e["MS Serif"]=!0;e["Museo Slab"]=!0;e["New York"]=!0;e["Nimbus Roman"]=!0;e["NPS Rawlinson Roadway"]=!0;e.NuptialScript=!0;e.Palatino=!0;e.Perpetua=!0;e.Plantin=!0;e["Plantin Schoolbook"]=!0;e.Playbill=!0;e["Poor Richard"]=!0;e["Rawlinson Roadway"]=!0;e.Renault=!0;e.Requiem=!0;e.Rockwell=!0;e.Roman=!0;e["Rotis Serif"]=!0;e.Sabon=!0;e.Scala=!0;e.Seagull=!0;e.Sistina=!0;e.Souvenir=!0;e.STIX=!0;e["Stone Informal"]=!0;e["Stone Serif"]=!0;e.Sylfaen=!0;e.Times=!0;e.Trajan=!0;e["Trinité"]=!0;e["Trump Mediaeval"]=!0;e.Utopia=!0;e["Vale Type"]=!0;e["Bitstream Vera"]=!0;e["Vera Serif"]=!0;e.Versailles=!0;e.Wanted=!0;e.Weiss=!0;e["Wide Latin"]=!0;e.Windsor=!0;e.XITS=!0}),_a=getLookupTableFactory(function(e){e.Dingbats=!0;e.Symbol=!0;e.ZapfDingbats=!0;e.Wingdings=!0;e["Wingdings-Bold"]=!0;e["Wingdings-Regular"]=!0}),Xa=getLookupTableFactory(function(e){e[2]=10;e[3]=32;e[4]=33;e[5]=34;e[6]=35;e[7]=36;e[8]=37;e[9]=38;e[10]=39;e[11]=40;e[12]=41;e[13]=42;e[14]=43;e[15]=44;e[16]=45;e[17]=46;e[18]=47;e[19]=48;e[20]=49;e[21]=50;e[22]=51;e[23]=52;e[24]=53;e[25]=54;e[26]=55;e[27]=56;e[28]=57;e[29]=58;e[30]=894;e[31]=60;e[32]=61;e[33]=62;e[34]=63;e[35]=64;e[36]=65;e[37]=66;e[38]=67;e[39]=68;e[40]=69;e[41]=70;e[42]=71;e[43]=72;e[44]=73;e[45]=74;e[46]=75;e[47]=76;e[48]=77;e[49]=78;e[50]=79;e[51]=80;e[52]=81;e[53]=82;e[54]=83;e[55]=84;e[56]=85;e[57]=86;e[58]=87;e[59]=88;e[60]=89;e[61]=90;e[62]=91;e[63]=92;e[64]=93;e[65]=94;e[66]=95;e[67]=96;e[68]=97;e[69]=98;e[70]=99;e[71]=100;e[72]=101;e[73]=102;e[74]=103;e[75]=104;e[76]=105;e[77]=106;e[78]=107;e[79]=108;e[80]=109;e[81]=110;e[82]=111;e[83]=112;e[84]=113;e[85]=114;e[86]=115;e[87]=116;e[88]=117;e[89]=118;e[90]=119;e[91]=120;e[92]=121;e[93]=122;e[94]=123;e[95]=124;e[96]=125;e[97]=126;e[98]=196;e[99]=197;e[100]=199;e[101]=201;e[102]=209;e[103]=214;e[104]=220;e[105]=225;e[106]=224;e[107]=226;e[108]=228;e[109]=227;e[110]=229;e[111]=231;e[112]=233;e[113]=232;e[114]=234;e[115]=235;e[116]=237;e[117]=236;e[118]=238;e[119]=239;e[120]=241;e[121]=243;e[122]=242;e[123]=244;e[124]=246;e[125]=245;e[126]=250;e[127]=249;e[128]=251;e[129]=252;e[130]=8224;e[131]=176;e[132]=162;e[133]=163;e[134]=167;e[135]=8226;e[136]=182;e[137]=223;e[138]=174;e[139]=169;e[140]=8482;e[141]=180;e[142]=168;e[143]=8800;e[144]=198;e[145]=216;e[146]=8734;e[147]=177;e[148]=8804;e[149]=8805;e[150]=165;e[151]=181;e[152]=8706;e[153]=8721;e[154]=8719;e[156]=8747;e[157]=170;e[158]=186;e[159]=8486;e[160]=230;e[161]=248;e[162]=191;e[163]=161;e[164]=172;e[165]=8730;e[166]=402;e[167]=8776;e[168]=8710;e[169]=171;e[170]=187;e[171]=8230;e[179]=8220;e[180]=8221;e[181]=8216;e[182]=8217;e[200]=193;e[203]=205;e[207]=211;e[210]=218;e[223]=711;e[224]=321;e[225]=322;e[226]=352;e[227]=353;e[228]=381;e[229]=382;e[233]=221;e[234]=253;e[252]=263;e[253]=268;e[254]=269;e[258]=258;e[260]=260;e[261]=261;e[265]=280;e[266]=281;e[267]=282;e[268]=283;e[269]=313;e[275]=323;e[276]=324;e[278]=328;e[283]=344;e[284]=345;e[285]=346;e[286]=347;e[292]=367;e[295]=377;e[296]=378;e[298]=380;e[305]=963;e[306]=964;e[307]=966;e[308]=8215;e[309]=8252;e[310]=8319;e[311]=8359;e[312]=8592;e[313]=8593;e[337]=9552;e[493]=1039;e[494]=1040;e[570]=1040;e[571]=1041;e[572]=1042;e[573]=1043;e[574]=1044;e[575]=1045;e[576]=1046;e[577]=1047;e[578]=1048;e[579]=1049;e[580]=1050;e[581]=1051;e[582]=1052;e[583]=1053;e[584]=1054;e[585]=1055;e[586]=1056;e[587]=1057;e[588]=1058;e[589]=1059;e[590]=1060;e[591]=1061;e[592]=1062;e[593]=1063;e[594]=1064;e[595]=1065;e[596]=1066;e[597]=1067;e[598]=1068;e[599]=1069;e[600]=1070;e[601]=1071;e[602]=1072;e[603]=1073;e[604]=1074;e[605]=1075;e[606]=1076;e[607]=1077;e[608]=1078;e[609]=1079;e[610]=1080;e[611]=1081;e[612]=1082;e[613]=1083;e[614]=1084;e[615]=1085;e[616]=1086;e[617]=1087;e[618]=1088;e[619]=1089;e[620]=1090;e[621]=1091;e[622]=1092;e[623]=1093;e[624]=1094;e[625]=1095;e[626]=1096;e[627]=1097;e[628]=1098;e[629]=1099;e[630]=1100;e[631]=1101;e[632]=1102;e[633]=1103;e[672]=1488;e[673]=1489;e[674]=1490;e[675]=1491;e[676]=1492;e[677]=1493;e[678]=1494;e[679]=1495;e[680]=1496;e[681]=1497;e[682]=1498;e[683]=1499;e[684]=1500;e[685]=1501;e[686]=1502;e[687]=1503;e[688]=1504;e[689]=1505;e[690]=1506;e[691]=1507;e[692]=1508;e[693]=1509;e[694]=1510;e[695]=1511;e[696]=1512;e[697]=1513;e[698]=1514;e[705]=1524;e[706]=8362;e[710]=64288;e[711]=64298;e[759]=1617;e[761]=1776;e[763]=1778;e[775]=1652;e[777]=1764;e[778]=1780;e[779]=1781;e[780]=1782;e[782]=771;e[783]=64726;e[786]=8363;e[788]=8532;e[790]=768;e[791]=769;e[792]=768;e[795]=803;e[797]=64336;e[798]=64337;e[799]=64342;e[800]=64343;e[801]=64344;e[802]=64345;e[803]=64362;e[804]=64363;e[805]=64364;e[2424]=7821;e[2425]=7822;e[2426]=7823;e[2427]=7824;e[2428]=7825;e[2429]=7826;e[2430]=7827;e[2433]=7682;e[2678]=8045;e[2679]=8046;e[2830]=1552;e[2838]=686;e[2840]=751;e[2842]=753;e[2843]=754;e[2844]=755;e[2846]=757;e[2856]=767;e[2857]=848;e[2858]=849;e[2862]=853;e[2863]=854;e[2864]=855;e[2865]=861;e[2866]=862;e[2906]=7460;e[2908]=7462;e[2909]=7463;e[2910]=7464;e[2912]=7466;e[2913]=7467;e[2914]=7468;e[2916]=7470;e[2917]=7471;e[2918]=7472;e[2920]=7474;e[2921]=7475;e[2922]=7476;e[2924]=7478;e[2925]=7479;e[2926]=7480;e[2928]=7482;e[2929]=7483;e[2930]=7484;e[2932]=7486;e[2933]=7487;e[2934]=7488;e[2936]=7490;e[2937]=7491;e[2938]=7492;e[2940]=7494;e[2941]=7495;e[2942]=7496;e[2944]=7498;e[2946]=7500;e[2948]=7502;e[2950]=7504;e[2951]=7505;e[2952]=7506;e[2954]=7508;e[2955]=7509;e[2956]=7510;e[2958]=7512;e[2959]=7513;e[2960]=7514;e[2962]=7516;e[2963]=7517;e[2964]=7518;e[2966]=7520;e[2967]=7521;e[2968]=7522;e[2970]=7524;e[2971]=7525;e[2972]=7526;e[2974]=7528;e[2975]=7529;e[2976]=7530;e[2978]=1537;e[2979]=1538;e[2980]=1539;e[2982]=1549;e[2983]=1551;e[2984]=1552;e[2986]=1554;e[2987]=1555;e[2988]=1556;e[2990]=1623;e[2991]=1624;e[2995]=1775;e[2999]=1791;e[3002]=64290;e[3003]=64291;e[3004]=64292;e[3006]=64294;e[3007]=64295;e[3008]=64296;e[3011]=1900;e[3014]=8223;e[3015]=8244;e[3017]=7532;e[3018]=7533;e[3019]=7534;e[3075]=7590;e[3076]=7591;e[3079]=7594;e[3080]=7595;e[3083]=7598;e[3084]=7599;e[3087]=7602;e[3088]=7603;e[3091]=7606;e[3092]=7607;e[3095]=7610;e[3096]=7611;e[3099]=7614;e[3100]=7615;e[3103]=7618;e[3104]=7619;e[3107]=8337;e[3108]=8338;e[3116]=1884;e[3119]=1885;e[3120]=1885;e[3123]=1886;e[3124]=1886;e[3127]=1887;e[3128]=1887;e[3131]=1888;e[3132]=1888;e[3135]=1889;e[3136]=1889;e[3139]=1890;e[3140]=1890;e[3143]=1891;e[3144]=1891;e[3147]=1892;e[3148]=1892;e[3153]=580;e[3154]=581;e[3157]=584;e[3158]=585;e[3161]=588;e[3162]=589;e[3165]=891;e[3166]=892;e[3169]=1274;e[3170]=1275;e[3173]=1278;e[3174]=1279;e[3181]=7622;e[3182]=7623;e[3282]=11799;e[3316]=578;e[3379]=42785;e[3393]=1159;e[3416]=8377}),Wa=getLookupTableFactory(function(e){e[227]=322;e[264]=261;e[291]=346}),Ka=getLookupTableFactory(function(e){e[1]=32;e[4]=65;e[5]=192;e[6]=193;e[9]=196;e[17]=66;e[18]=67;e[21]=268;e[24]=68;e[28]=69;e[29]=200;e[30]=201;e[32]=282;e[38]=70;e[39]=71;e[44]=72;e[47]=73;e[48]=204;e[49]=205;e[58]=74;e[60]=75;e[62]=76;e[68]=77;e[69]=78;e[75]=79;e[76]=210;e[80]=214;e[87]=80;e[89]=81;e[90]=82;e[92]=344;e[94]=83;e[97]=352;e[100]=84;e[104]=85;e[109]=220;e[115]=86;e[116]=87;e[121]=88;e[122]=89;e[124]=221;e[127]=90;e[129]=381;e[258]=97;e[259]=224;e[260]=225;e[263]=228;e[268]=261;e[271]=98;e[272]=99;e[273]=263;e[275]=269;e[282]=100;e[286]=101;e[287]=232;e[288]=233;e[290]=283;e[295]=281;e[296]=102;e[336]=103;e[346]=104;e[349]=105;e[350]=236;e[351]=237;e[361]=106;e[364]=107;e[367]=108;e[371]=322;e[373]=109;e[374]=110;e[381]=111;e[382]=242;e[383]=243;e[386]=246;e[393]=112;e[395]=113;e[396]=114;e[398]=345;e[400]=115;e[401]=347;e[403]=353;e[410]=116;e[437]=117;e[442]=252;e[448]=118;e[449]=119;e[454]=120;e[455]=121;e[457]=253;e[460]=122;e[462]=382;e[463]=380;e[853]=44;e[855]=58;e[856]=46;e[876]=47;e[878]=45;e[882]=45;e[894]=40;e[895]=41;e[896]=91;e[897]=93;e[923]=64;e[940]=163;e[1004]=48;e[1005]=49;e[1006]=50;e[1007]=51;e[1008]=52;e[1009]=53;e[1010]=54;e[1011]=55;e[1012]=56;e[1013]=57;e[1081]=37;e[1085]=43;e[1086]=45});function getStandardFontName(e){const t=normalizeFontName(e);return Na()[t]}function isKnownFontName(e){const t=normalizeFontName(e);return!!(Na()[t]||La()[t]||Ua()[t]||_a()[t])}class ToUnicodeMap{constructor(e=[]){this._map=e}get length(){return this._map.length}forEach(e){for(const t in this._map)e(t,this._map[t].codePointAt(0))}has(e){return void 0!==this._map[e]}get(e){return this._map[e]}charCodeOf(e){const t=this._map;if(t.length<=65536)return t.indexOf(e);for(const n in t)if(t[n]===e)return 0|n;return-1}amend(e){for(const t in e)this._map[t]=e[t]}}class IdentityToUnicodeMap{constructor(e,t){this.firstChar=e;this.lastChar=t}get length(){return this.lastChar+1-this.firstChar}forEach(e){for(let t=this.firstChar,n=this.lastChar;t<=n;t++)e(t,t)}has(e){return this.firstChar<=e&&e<=this.lastChar}get(e){if(this.firstChar<=e&&e<=this.lastChar)return String.fromCharCode(e)}charCodeOf(e){return Number.isInteger(e)&&e>=this.firstChar&&e<=this.lastChar?e:-1}amend(e){unreachable("Should not call amend()")}}class CFFFont{constructor(e,t){this.properties=t;const n=new CFFParser(e,t,qa);this.cff=n.parse();this.cff.duplicateFirstGlyph();const a=new CFFCompiler(this.cff);this.seacs=this.cff.seacs;try{this.data=a.compile()}catch{warn("Failed to compile font "+t.loadedName);this.data=e}this._createBuiltInEncoding()}get numGlyphs(){return this.cff.charStrings.count}getCharset(){return this.cff.charset.charset}getGlyphMapping(){const e=this.cff,t=this.properties,{cidToGidMap:n,cMap:a}=t,s=e.charset.charset;let r,i;if(t.composite){let t,o;if(n?.length>0){t=Object.create(null);for(let e=0,a=n.length;e<a;e++){const a=n[e];void 0!==a&&(t[a]=e)}}r=Object.create(null);if(e.isCIDFont)for(i=0;i<s.length;i++){const e=s[i];o=a.charCodeOf(e);void 0!==t?.[o]&&(o=t[o]);r[o]=i}else for(i=0;i<e.charStrings.count;i++){o=a.charCodeOf(i);r[o]=i}return r}let o=e.encoding?e.encoding.encoding:null;t.isInternalFont&&(o=t.defaultEncoding);r=type1FontGlyphMapping(t,o,s);return r}hasGlyphId(e){return this.cff.hasGlyphId(e)}_createBuiltInEncoding(){const{charset:e,encoding:t}=this.cff;if(!e||!t)return;const n=e.charset,a=t.encoding,s=[];for(const e in a){const t=a[e];if(t>=0){const a=n[t];a&&(s[e]=a)}}s.length>0&&(this.properties.builtInEncoding=s)}}function getFloat214(e,t){return readInt16(e,t)/16384}function getSubroutineBias(e){const t=e.length;let n=32768;t<1240?n=107:t<33900&&(n=1131);return n}function parseCmap(e,t,n){const a=1===readUint16(e,t+2)?readUint32(e,t+8):readUint32(e,t+16),s=readUint16(e,t+a);let r,i,o;if(4===s){readUint16(e,t+a+2);const n=readUint16(e,t+a+6)>>1;i=t+a+14;r=[];for(o=0;o<n;o++,i+=2)r[o]={end:readUint16(e,i)};i+=2;for(o=0;o<n;o++,i+=2)r[o].start=readUint16(e,i);for(o=0;o<n;o++,i+=2)r[o].idDelta=readUint16(e,i);for(o=0;o<n;o++,i+=2){let t=readUint16(e,i);if(0!==t){r[o].ids=[];for(let n=0,a=r[o].end-r[o].start+1;n<a;n++){r[o].ids[n]=readUint16(e,i+t);t+=2}}}return r}if(12===s){const n=readUint32(e,t+a+12);i=t+a+16;r=[];for(o=0;o<n;o++){t=readUint32(e,i);r.push({start:t,end:readUint32(e,i+4),idDelta:readUint32(e,i+8)-t});i+=12}return r}throw new FormatError(`unsupported cmap: ${s}`)}function parseCff(e,t,n,a){const s=new CFFParser(new Stream(e,t,n-t),{},a).parse();return{glyphs:s.charStrings.objects,subrs:s.topDict.privateDict?.subrsIndex?.objects,gsubrs:s.globalSubrIndex?.objects,isCFFCIDFont:s.isCIDFont,fdSelect:s.fdSelect,fdArray:s.fdArray}}function lookupCmap(e,t){const n=t.codePointAt(0);let a=0,s=0,r=e.length-1;for(;s<r;){const t=s+r+1>>1;n<e[t].start?r=t-1:s=t}e[s].start<=n&&n<=e[s].end&&(a=e[s].idDelta+(e[s].ids?e[s].ids[n-e[s].start]:n)&65535);return{charCode:n,glyphId:a}}function compileGlyf(e,t,n){function moveTo(e,n){i&&t.add(Gt,i);i=[e,n];t.add(Kt,[e,n])}function lineTo(e,n){t.add(Gt,[e,n])}function quadraticCurveTo(e,n,a,s){t.add($t,[e,n,a,s])}let a=0;const s=readInt16(e,a);let r,i=null,o=0,l=0;a+=10;if(s<0)do{r=readUint16(e,a);const s=readUint16(e,a+2);a+=4;let i,f;if(1&r){if(2&r){i=readInt16(e,a);f=readInt16(e,a+2)}else{i=readUint16(e,a);f=readUint16(e,a+2)}a+=4}else if(2&r){i=readInt8(e,a++);f=readInt8(e,a++)}else{i=e[a++];f=e[a++]}if(2&r){o=i;l=f}else{o=0;l=0}let c=1,h=1,u=0,m=0;if(8&r){c=h=getFloat214(e,a);a+=2}else if(64&r){c=getFloat214(e,a);h=getFloat214(e,a+2);a+=4}else if(128&r){c=getFloat214(e,a);u=getFloat214(e,a+2);m=getFloat214(e,a+4);h=getFloat214(e,a+6);a+=8}const p=n.glyphs[s];if(p){t.save();t.transform([c,u,m,h,o,l]);compileGlyf(p,t,n);t.restore()}}while(32&r);else{const t=[];let n,i;for(n=0;n<s;n++){t.push(readUint16(e,a));a+=2}a+=2+readUint16(e,a);const f=t.at(-1)+1,c=[];for(;c.length<f;){r=e[a++];let t=1;8&r&&(t+=e[a++]);for(;t-- >0;)c.push({flags:r})}for(n=0;n<f;n++){switch(18&c[n].flags){case 0:o+=readInt16(e,a);a+=2;break;case 2:o-=e[a++];break;case 18:o+=e[a++]}c[n].x=o}for(n=0;n<f;n++){switch(36&c[n].flags){case 0:l+=readInt16(e,a);a+=2;break;case 4:l-=e[a++];break;case 36:l+=e[a++]}c[n].y=l}let h=0;for(a=0;a<s;a++){const e=t[a],s=c.slice(h,e+1);if(1&s[0].flags)s.push(s[0]);else if(1&s.at(-1).flags)s.unshift(s.at(-1));else{const e={flags:1,x:(s[0].x+s.at(-1).x)/2,y:(s[0].y+s.at(-1).y)/2};s.unshift(e);s.push(e)}moveTo(s[0].x,s[0].y);for(n=1,i=s.length;n<i;n++)if(1&s[n].flags)lineTo(s[n].x,s[n].y);else if(1&s[n+1].flags){quadraticCurveTo(s[n].x,s[n].y,s[n+1].x,s[n+1].y);n++}else quadraticCurveTo(s[n].x,s[n].y,(s[n].x+s[n+1].x)/2,(s[n].y+s[n+1].y)/2);h=e+1}}}function compileCharString(e,t,n,a){function moveTo(e,n){l&&t.add(Gt,l);l=[e,n];t.add(Kt,[e,n])}function lineTo(e,n){t.add(Gt,[e,n])}function bezierCurveTo(e,n,a,s,r,i){t.add(Vt,[e,n,a,s,r,i])}const s=[];let r=0,i=0,o=0,l=null;!function parse(e){let l=0;for(;l<e.length;){let f,c,h,u,m,p,d,g,b,w=!1,j=e[l++];switch(j){case 1:case 3:case 18:case 23:o+=s.length>>1;w=!0;break;case 4:i+=s.pop();moveTo(r,i);w=!0;break;case 5:for(;s.length>0;){r+=s.shift();i+=s.shift();lineTo(r,i)}break;case 6:for(;s.length>0;){r+=s.shift();lineTo(r,i);if(0===s.length)break;i+=s.shift();lineTo(r,i)}break;case 7:for(;s.length>0;){i+=s.shift();lineTo(r,i);if(0===s.length)break;r+=s.shift();lineTo(r,i)}break;case 8:for(;s.length>0;){f=r+s.shift();h=i+s.shift();c=f+s.shift();u=h+s.shift();r=c+s.shift();i=u+s.shift();bezierCurveTo(f,h,c,u,r,i)}break;case 10:g=s.pop();b=null;if(n.isCFFCIDFont){const e=n.fdSelect.getFDIndex(a);if(e>=0&&e<n.fdArray.length){const t=n.fdArray[e];let a;t.privateDict?.subrsIndex&&(a=t.privateDict.subrsIndex.objects);if(a){g+=getSubroutineBias(a);b=a[g]}}else warn("Invalid fd index for glyph index.")}else b=n.subrs[g+n.subrsBias];b&&parse(b);break;case 11:return;case 12:j=e[l++];switch(j){case 34:f=r+s.shift();c=f+s.shift();m=i+s.shift();r=c+s.shift();bezierCurveTo(f,i,c,m,r,m);f=r+s.shift();c=f+s.shift();r=c+s.shift();bezierCurveTo(f,m,c,i,r,i);break;case 35:f=r+s.shift();h=i+s.shift();c=f+s.shift();u=h+s.shift();r=c+s.shift();i=u+s.shift();bezierCurveTo(f,h,c,u,r,i);f=r+s.shift();h=i+s.shift();c=f+s.shift();u=h+s.shift();r=c+s.shift();i=u+s.shift();bezierCurveTo(f,h,c,u,r,i);s.pop();break;case 36:f=r+s.shift();m=i+s.shift();c=f+s.shift();p=m+s.shift();r=c+s.shift();bezierCurveTo(f,m,c,p,r,p);f=r+s.shift();c=f+s.shift();d=p+s.shift();r=c+s.shift();bezierCurveTo(f,p,c,d,r,i);break;case 37:const e=r,t=i;f=r+s.shift();h=i+s.shift();c=f+s.shift();u=h+s.shift();r=c+s.shift();i=u+s.shift();bezierCurveTo(f,h,c,u,r,i);f=r+s.shift();h=i+s.shift();c=f+s.shift();u=h+s.shift();r=c;i=u;Math.abs(r-e)>Math.abs(i-t)?r+=s.shift():i+=s.shift();bezierCurveTo(f,h,c,u,r,i);break;default:throw new FormatError(`unknown operator: 12 ${j}`)}break;case 14:if(s.length>=4){const e=s.pop(),a=s.pop();i=s.pop();r=s.pop();t.save();t.translate(r,i);let o=lookupCmap(n.cmap,String.fromCharCode(n.glyphNameMap[ua[e]]));compileCharString(n.glyphs[o.glyphId],t,n,o.glyphId);t.restore();o=lookupCmap(n.cmap,String.fromCharCode(n.glyphNameMap[ua[a]]));compileCharString(n.glyphs[o.glyphId],t,n,o.glyphId)}return;case 19:case 20:o+=s.length>>1;l+=o+7>>3;w=!0;break;case 21:i+=s.pop();r+=s.pop();moveTo(r,i);w=!0;break;case 22:r+=s.pop();moveTo(r,i);w=!0;break;case 24:for(;s.length>2;){f=r+s.shift();h=i+s.shift();c=f+s.shift();u=h+s.shift();r=c+s.shift();i=u+s.shift();bezierCurveTo(f,h,c,u,r,i)}r+=s.shift();i+=s.shift();lineTo(r,i);break;case 25:for(;s.length>6;){r+=s.shift();i+=s.shift();lineTo(r,i)}f=r+s.shift();h=i+s.shift();c=f+s.shift();u=h+s.shift();r=c+s.shift();i=u+s.shift();bezierCurveTo(f,h,c,u,r,i);break;case 26:s.length%2&&(r+=s.shift());for(;s.length>0;){f=r;h=i+s.shift();c=f+s.shift();u=h+s.shift();r=c;i=u+s.shift();bezierCurveTo(f,h,c,u,r,i)}break;case 27:s.length%2&&(i+=s.shift());for(;s.length>0;){f=r+s.shift();h=i;c=f+s.shift();u=h+s.shift();r=c+s.shift();i=u;bezierCurveTo(f,h,c,u,r,i)}break;case 28:s.push(readInt16(e,l));l+=2;break;case 29:g=s.pop()+n.gsubrsBias;b=n.gsubrs[g];b&&parse(b);break;case 30:for(;s.length>0;){f=r;h=i+s.shift();c=f+s.shift();u=h+s.shift();r=c+s.shift();i=u+(1===s.length?s.shift():0);bezierCurveTo(f,h,c,u,r,i);if(0===s.length)break;f=r+s.shift();h=i;c=f+s.shift();u=h+s.shift();i=u+s.shift();r=c+(1===s.length?s.shift():0);bezierCurveTo(f,h,c,u,r,i)}break;case 31:for(;s.length>0;){f=r+s.shift();h=i;c=f+s.shift();u=h+s.shift();i=u+s.shift();r=c+(1===s.length?s.shift():0);bezierCurveTo(f,h,c,u,r,i);if(0===s.length)break;f=r;h=i+s.shift();c=f+s.shift();u=h+s.shift();r=c+s.shift();i=u+(1===s.length?s.shift():0);bezierCurveTo(f,h,c,u,r,i)}break;default:if(j<32)throw new FormatError(`unknown operator: ${j}`);if(j<247)s.push(j-139);else if(j<251)s.push(256*(j-247)+e[l++]+108);else if(j<255)s.push(256*-(j-251)-e[l++]-108);else{s.push((e[l]<<24|e[l+1]<<16|e[l+2]<<8|e[l+3])/65536);l+=4}}w&&(s.length=0)}}(e)}class Commands{cmds=[];transformStack=[];currentTransform=[1,0,0,1,0,0];add(e,t){if(t){const{currentTransform:n}=this;for(let e=0,a=t.length;e<a;e+=2)Util.applyTransform(t,n,e);this.cmds.push(e,...t)}else this.cmds.push(e)}transform(e){this.currentTransform=Util.transform(this.currentTransform,e)}translate(e,t){this.transform([1,0,0,1,e,t])}save(){this.transformStack.push(this.currentTransform.slice())}restore(){this.currentTransform=this.transformStack.pop()||[1,0,0,1,0,0]}getPath(){return new(FeatureTest.isFloat16ArraySupported?Float16Array:Float32Array)(this.cmds)}}class CompiledFont{constructor(e){this.fontMatrix=e;this.compiledGlyphs=Object.create(null);this.compiledCharCodeToGlyphId=Object.create(null)}getPathJs(e){const{charCode:t,glyphId:n}=lookupCmap(this.cmap,e);let a,s=this.compiledGlyphs[n];if(void 0===s){try{s=this.compileGlyph(this.glyphs[n],n)}catch(e){s="";a=e}this.compiledGlyphs[n]=s}this.compiledCharCodeToGlyphId[t]??=n;if(a)throw a;return s}compileGlyph(e,n){if(!e?.length||14===e[0])return"";let a=this.fontMatrix;if(this.isCFFCIDFont){const e=this.fdSelect.getFDIndex(n);if(e>=0&&e<this.fdArray.length){a=this.fdArray[e].getByName("FontMatrix")||t}else warn("Invalid fd index for glyph index.")}assert(isNumberArray(a,6),"Expected a valid fontMatrix.");const s=new Commands;s.transform(a.slice());this.compileGlyphImpl(e,s,n);s.add(Yt);return s.getPath()}compileGlyphImpl(){unreachable("Children classes should implement this.")}hasBuiltPath(e){const{charCode:t,glyphId:n}=lookupCmap(this.cmap,e);return void 0!==this.compiledGlyphs[n]&&void 0!==this.compiledCharCodeToGlyphId[t]}}class TrueTypeCompiled extends CompiledFont{constructor(e,t,n){super(n||[488e-6,0,0,488e-6,0,0]);this.glyphs=e;this.cmap=t}compileGlyphImpl(e,t){compileGlyf(e,t,this)}}class Type2Compiled extends CompiledFont{constructor(e,t,n){super(n||[.001,0,0,.001,0,0]);this.glyphs=e.glyphs;this.gsubrs=e.gsubrs||[];this.subrs=e.subrs||[];this.cmap=t;this.glyphNameMap=ga();this.gsubrsBias=getSubroutineBias(this.gsubrs);this.subrsBias=getSubroutineBias(this.subrs);this.isCFFCIDFont=e.isCFFCIDFont;this.fdSelect=e.fdSelect;this.fdArray=e.fdArray}compileGlyphImpl(e,t,n){compileCharString(e,t,this,n)}}class FontRendererFactory{static create(e,t){const n=new Uint8Array(e.data);let a,s,r,i,o,l;const f=readUint16(n,4);for(let e=0,c=12;e<f;e++,c+=16){const e=bytesToString(n.subarray(c,c+4)),f=readUint32(n,c+8),h=readUint32(n,c+12);switch(e){case"cmap":a=parseCmap(n,f);break;case"glyf":s=n.subarray(f,f+h);break;case"loca":r=n.subarray(f,f+h);break;case"head":l=readUint16(n,f+18);o=readUint16(n,f+50);break;case"CFF ":i=parseCff(n,f,f+h,t)}}if(s){const t=l?[1/l,0,0,1/l,0,0]:e.fontMatrix;return new TrueTypeCompiled(function parseGlyfTable(e,t,n){let a,s;if(n){a=4;s=readUint32}else{a=2;s=(e,t)=>2*readUint16(e,t)}const r=[];let i=s(t,0);for(let n=a;n<t.length;n+=a){const a=s(t,n);r.push(e.subarray(i,a));i=a}return r}(s,r,o),a,t)}return new Type2Compiled(i,a,e.fontMatrix)}}const Ga=getLookupTableFactory(function(e){e.Courier=600;e["Courier-Bold"]=600;e["Courier-BoldOblique"]=600;e["Courier-Oblique"]=600;e.Helvetica=getLookupTableFactory(function(e){e.space=278;e.exclam=278;e.quotedbl=355;e.numbersign=556;e.dollar=556;e.percent=889;e.ampersand=667;e.quoteright=222;e.parenleft=333;e.parenright=333;e.asterisk=389;e.plus=584;e.comma=278;e.hyphen=333;e.period=278;e.slash=278;e.zero=556;e.one=556;e.two=556;e.three=556;e.four=556;e.five=556;e.six=556;e.seven=556;e.eight=556;e.nine=556;e.colon=278;e.semicolon=278;e.less=584;e.equal=584;e.greater=584;e.question=556;e.at=1015;e.A=667;e.B=667;e.C=722;e.D=722;e.E=667;e.F=611;e.G=778;e.H=722;e.I=278;e.J=500;e.K=667;e.L=556;e.M=833;e.N=722;e.O=778;e.P=667;e.Q=778;e.R=722;e.S=667;e.T=611;e.U=722;e.V=667;e.W=944;e.X=667;e.Y=667;e.Z=611;e.bracketleft=278;e.backslash=278;e.bracketright=278;e.asciicircum=469;e.underscore=556;e.quoteleft=222;e.a=556;e.b=556;e.c=500;e.d=556;e.e=556;e.f=278;e.g=556;e.h=556;e.i=222;e.j=222;e.k=500;e.l=222;e.m=833;e.n=556;e.o=556;e.p=556;e.q=556;e.r=333;e.s=500;e.t=278;e.u=556;e.v=500;e.w=722;e.x=500;e.y=500;e.z=500;e.braceleft=334;e.bar=260;e.braceright=334;e.asciitilde=584;e.exclamdown=333;e.cent=556;e.sterling=556;e.fraction=167;e.yen=556;e.florin=556;e.section=556;e.currency=556;e.quotesingle=191;e.quotedblleft=333;e.guillemotleft=556;e.guilsinglleft=333;e.guilsinglright=333;e.fi=500;e.fl=500;e.endash=556;e.dagger=556;e.daggerdbl=556;e.periodcentered=278;e.paragraph=537;e.bullet=350;e.quotesinglbase=222;e.quotedblbase=333;e.quotedblright=333;e.guillemotright=556;e.ellipsis=1e3;e.perthousand=1e3;e.questiondown=611;e.grave=333;e.acute=333;e.circumflex=333;e.tilde=333;e.macron=333;e.breve=333;e.dotaccent=333;e.dieresis=333;e.ring=333;e.cedilla=333;e.hungarumlaut=333;e.ogonek=333;e.caron=333;e.emdash=1e3;e.AE=1e3;e.ordfeminine=370;e.Lslash=556;e.Oslash=778;e.OE=1e3;e.ordmasculine=365;e.ae=889;e.dotlessi=278;e.lslash=222;e.oslash=611;e.oe=944;e.germandbls=611;e.Idieresis=278;e.eacute=556;e.abreve=556;e.uhungarumlaut=556;e.ecaron=556;e.Ydieresis=667;e.divide=584;e.Yacute=667;e.Acircumflex=667;e.aacute=556;e.Ucircumflex=722;e.yacute=500;e.scommaaccent=500;e.ecircumflex=556;e.Uring=722;e.Udieresis=722;e.aogonek=556;e.Uacute=722;e.uogonek=556;e.Edieresis=667;e.Dcroat=722;e.commaaccent=250;e.copyright=737;e.Emacron=667;e.ccaron=500;e.aring=556;e.Ncommaaccent=722;e.lacute=222;e.agrave=556;e.Tcommaaccent=611;e.Cacute=722;e.atilde=556;e.Edotaccent=667;e.scaron=500;e.scedilla=500;e.iacute=278;e.lozenge=471;e.Rcaron=722;e.Gcommaaccent=778;e.ucircumflex=556;e.acircumflex=556;e.Amacron=667;e.rcaron=333;e.ccedilla=500;e.Zdotaccent=611;e.Thorn=667;e.Omacron=778;e.Racute=722;e.Sacute=667;e.dcaron=643;e.Umacron=722;e.uring=556;e.threesuperior=333;e.Ograve=778;e.Agrave=667;e.Abreve=667;e.multiply=584;e.uacute=556;e.Tcaron=611;e.partialdiff=476;e.ydieresis=500;e.Nacute=722;e.icircumflex=278;e.Ecircumflex=667;e.adieresis=556;e.edieresis=556;e.cacute=500;e.nacute=556;e.umacron=556;e.Ncaron=722;e.Iacute=278;e.plusminus=584;e.brokenbar=260;e.registered=737;e.Gbreve=778;e.Idotaccent=278;e.summation=600;e.Egrave=667;e.racute=333;e.omacron=556;e.Zacute=611;e.Zcaron=611;e.greaterequal=549;e.Eth=722;e.Ccedilla=722;e.lcommaaccent=222;e.tcaron=317;e.eogonek=556;e.Uogonek=722;e.Aacute=667;e.Adieresis=667;e.egrave=556;e.zacute=500;e.iogonek=222;e.Oacute=778;e.oacute=556;e.amacron=556;e.sacute=500;e.idieresis=278;e.Ocircumflex=778;e.Ugrave=722;e.Delta=612;e.thorn=556;e.twosuperior=333;e.Odieresis=778;e.mu=556;e.igrave=278;e.ohungarumlaut=556;e.Eogonek=667;e.dcroat=556;e.threequarters=834;e.Scedilla=667;e.lcaron=299;e.Kcommaaccent=667;e.Lacute=556;e.trademark=1e3;e.edotaccent=556;e.Igrave=278;e.Imacron=278;e.Lcaron=556;e.onehalf=834;e.lessequal=549;e.ocircumflex=556;e.ntilde=556;e.Uhungarumlaut=722;e.Eacute=667;e.emacron=556;e.gbreve=556;e.onequarter=834;e.Scaron=667;e.Scommaaccent=667;e.Ohungarumlaut=778;e.degree=400;e.ograve=556;e.Ccaron=722;e.ugrave=556;e.radical=453;e.Dcaron=722;e.rcommaaccent=333;e.Ntilde=722;e.otilde=556;e.Rcommaaccent=722;e.Lcommaaccent=556;e.Atilde=667;e.Aogonek=667;e.Aring=667;e.Otilde=778;e.zdotaccent=500;e.Ecaron=667;e.Iogonek=278;e.kcommaaccent=500;e.minus=584;e.Icircumflex=278;e.ncaron=556;e.tcommaaccent=278;e.logicalnot=584;e.odieresis=556;e.udieresis=556;e.notequal=549;e.gcommaaccent=556;e.eth=556;e.zcaron=500;e.ncommaaccent=556;e.onesuperior=333;e.imacron=278;e.Euro=556});e["Helvetica-Bold"]=getLookupTableFactory(function(e){e.space=278;e.exclam=333;e.quotedbl=474;e.numbersign=556;e.dollar=556;e.percent=889;e.ampersand=722;e.quoteright=278;e.parenleft=333;e.parenright=333;e.asterisk=389;e.plus=584;e.comma=278;e.hyphen=333;e.period=278;e.slash=278;e.zero=556;e.one=556;e.two=556;e.three=556;e.four=556;e.five=556;e.six=556;e.seven=556;e.eight=556;e.nine=556;e.colon=333;e.semicolon=333;e.less=584;e.equal=584;e.greater=584;e.question=611;e.at=975;e.A=722;e.B=722;e.C=722;e.D=722;e.E=667;e.F=611;e.G=778;e.H=722;e.I=278;e.J=556;e.K=722;e.L=611;e.M=833;e.N=722;e.O=778;e.P=667;e.Q=778;e.R=722;e.S=667;e.T=611;e.U=722;e.V=667;e.W=944;e.X=667;e.Y=667;e.Z=611;e.bracketleft=333;e.backslash=278;e.bracketright=333;e.asciicircum=584;e.underscore=556;e.quoteleft=278;e.a=556;e.b=611;e.c=556;e.d=611;e.e=556;e.f=333;e.g=611;e.h=611;e.i=278;e.j=278;e.k=556;e.l=278;e.m=889;e.n=611;e.o=611;e.p=611;e.q=611;e.r=389;e.s=556;e.t=333;e.u=611;e.v=556;e.w=778;e.x=556;e.y=556;e.z=500;e.braceleft=389;e.bar=280;e.braceright=389;e.asciitilde=584;e.exclamdown=333;e.cent=556;e.sterling=556;e.fraction=167;e.yen=556;e.florin=556;e.section=556;e.currency=556;e.quotesingle=238;e.quotedblleft=500;e.guillemotleft=556;e.guilsinglleft=333;e.guilsinglright=333;e.fi=611;e.fl=611;e.endash=556;e.dagger=556;e.daggerdbl=556;e.periodcentered=278;e.paragraph=556;e.bullet=350;e.quotesinglbase=278;e.quotedblbase=500;e.quotedblright=500;e.guillemotright=556;e.ellipsis=1e3;e.perthousand=1e3;e.questiondown=611;e.grave=333;e.acute=333;e.circumflex=333;e.tilde=333;e.macron=333;e.breve=333;e.dotaccent=333;e.dieresis=333;e.ring=333;e.cedilla=333;e.hungarumlaut=333;e.ogonek=333;e.caron=333;e.emdash=1e3;e.AE=1e3;e.ordfeminine=370;e.Lslash=611;e.Oslash=778;e.OE=1e3;e.ordmasculine=365;e.ae=889;e.dotlessi=278;e.lslash=278;e.oslash=611;e.oe=944;e.germandbls=611;e.Idieresis=278;e.eacute=556;e.abreve=556;e.uhungarumlaut=611;e.ecaron=556;e.Ydieresis=667;e.divide=584;e.Yacute=667;e.Acircumflex=722;e.aacute=556;e.Ucircumflex=722;e.yacute=556;e.scommaaccent=556;e.ecircumflex=556;e.Uring=722;e.Udieresis=722;e.aogonek=556;e.Uacute=722;e.uogonek=611;e.Edieresis=667;e.Dcroat=722;e.commaaccent=250;e.copyright=737;e.Emacron=667;e.ccaron=556;e.aring=556;e.Ncommaaccent=722;e.lacute=278;e.agrave=556;e.Tcommaaccent=611;e.Cacute=722;e.atilde=556;e.Edotaccent=667;e.scaron=556;e.scedilla=556;e.iacute=278;e.lozenge=494;e.Rcaron=722;e.Gcommaaccent=778;e.ucircumflex=611;e.acircumflex=556;e.Amacron=722;e.rcaron=389;e.ccedilla=556;e.Zdotaccent=611;e.Thorn=667;e.Omacron=778;e.Racute=722;e.Sacute=667;e.dcaron=743;e.Umacron=722;e.uring=611;e.threesuperior=333;e.Ograve=778;e.Agrave=722;e.Abreve=722;e.multiply=584;e.uacute=611;e.Tcaron=611;e.partialdiff=494;e.ydieresis=556;e.Nacute=722;e.icircumflex=278;e.Ecircumflex=667;e.adieresis=556;e.edieresis=556;e.cacute=556;e.nacute=611;e.umacron=611;e.Ncaron=722;e.Iacute=278;e.plusminus=584;e.brokenbar=280;e.registered=737;e.Gbreve=778;e.Idotaccent=278;e.summation=600;e.Egrave=667;e.racute=389;e.omacron=611;e.Zacute=611;e.Zcaron=611;e.greaterequal=549;e.Eth=722;e.Ccedilla=722;e.lcommaaccent=278;e.tcaron=389;e.eogonek=556;e.Uogonek=722;e.Aacute=722;e.Adieresis=722;e.egrave=556;e.zacute=500;e.iogonek=278;e.Oacute=778;e.oacute=611;e.amacron=556;e.sacute=556;e.idieresis=278;e.Ocircumflex=778;e.Ugrave=722;e.Delta=612;e.thorn=611;e.twosuperior=333;e.Odieresis=778;e.mu=611;e.igrave=278;e.ohungarumlaut=611;e.Eogonek=667;e.dcroat=611;e.threequarters=834;e.Scedilla=667;e.lcaron=400;e.Kcommaaccent=722;e.Lacute=611;e.trademark=1e3;e.edotaccent=556;e.Igrave=278;e.Imacron=278;e.Lcaron=611;e.onehalf=834;e.lessequal=549;e.ocircumflex=611;e.ntilde=611;e.Uhungarumlaut=722;e.Eacute=667;e.emacron=556;e.gbreve=611;e.onequarter=834;e.Scaron=667;e.Scommaaccent=667;e.Ohungarumlaut=778;e.degree=400;e.ograve=611;e.Ccaron=722;e.ugrave=611;e.radical=549;e.Dcaron=722;e.rcommaaccent=389;e.Ntilde=722;e.otilde=611;e.Rcommaaccent=722;e.Lcommaaccent=611;e.Atilde=722;e.Aogonek=722;e.Aring=722;e.Otilde=778;e.zdotaccent=500;e.Ecaron=667;e.Iogonek=278;e.kcommaaccent=556;e.minus=584;e.Icircumflex=278;e.ncaron=611;e.tcommaaccent=333;e.logicalnot=584;e.odieresis=611;e.udieresis=611;e.notequal=549;e.gcommaaccent=611;e.eth=611;e.zcaron=500;e.ncommaaccent=611;e.onesuperior=333;e.imacron=278;e.Euro=556});e["Helvetica-BoldOblique"]=getLookupTableFactory(function(e){e.space=278;e.exclam=333;e.quotedbl=474;e.numbersign=556;e.dollar=556;e.percent=889;e.ampersand=722;e.quoteright=278;e.parenleft=333;e.parenright=333;e.asterisk=389;e.plus=584;e.comma=278;e.hyphen=333;e.period=278;e.slash=278;e.zero=556;e.one=556;e.two=556;e.three=556;e.four=556;e.five=556;e.six=556;e.seven=556;e.eight=556;e.nine=556;e.colon=333;e.semicolon=333;e.less=584;e.equal=584;e.greater=584;e.question=611;e.at=975;e.A=722;e.B=722;e.C=722;e.D=722;e.E=667;e.F=611;e.G=778;e.H=722;e.I=278;e.J=556;e.K=722;e.L=611;e.M=833;e.N=722;e.O=778;e.P=667;e.Q=778;e.R=722;e.S=667;e.T=611;e.U=722;e.V=667;e.W=944;e.X=667;e.Y=667;e.Z=611;e.bracketleft=333;e.backslash=278;e.bracketright=333;e.asciicircum=584;e.underscore=556;e.quoteleft=278;e.a=556;e.b=611;e.c=556;e.d=611;e.e=556;e.f=333;e.g=611;e.h=611;e.i=278;e.j=278;e.k=556;e.l=278;e.m=889;e.n=611;e.o=611;e.p=611;e.q=611;e.r=389;e.s=556;e.t=333;e.u=611;e.v=556;e.w=778;e.x=556;e.y=556;e.z=500;e.braceleft=389;e.bar=280;e.braceright=389;e.asciitilde=584;e.exclamdown=333;e.cent=556;e.sterling=556;e.fraction=167;e.yen=556;e.florin=556;e.section=556;e.currency=556;e.quotesingle=238;e.quotedblleft=500;e.guillemotleft=556;e.guilsinglleft=333;e.guilsinglright=333;e.fi=611;e.fl=611;e.endash=556;e.dagger=556;e.daggerdbl=556;e.periodcentered=278;e.paragraph=556;e.bullet=350;e.quotesinglbase=278;e.quotedblbase=500;e.quotedblright=500;e.guillemotright=556;e.ellipsis=1e3;e.perthousand=1e3;e.questiondown=611;e.grave=333;e.acute=333;e.circumflex=333;e.tilde=333;e.macron=333;e.breve=333;e.dotaccent=333;e.dieresis=333;e.ring=333;e.cedilla=333;e.hungarumlaut=333;e.ogonek=333;e.caron=333;e.emdash=1e3;e.AE=1e3;e.ordfeminine=370;e.Lslash=611;e.Oslash=778;e.OE=1e3;e.ordmasculine=365;e.ae=889;e.dotlessi=278;e.lslash=278;e.oslash=611;e.oe=944;e.germandbls=611;e.Idieresis=278;e.eacute=556;e.abreve=556;e.uhungarumlaut=611;e.ecaron=556;e.Ydieresis=667;e.divide=584;e.Yacute=667;e.Acircumflex=722;e.aacute=556;e.Ucircumflex=722;e.yacute=556;e.scommaaccent=556;e.ecircumflex=556;e.Uring=722;e.Udieresis=722;e.aogonek=556;e.Uacute=722;e.uogonek=611;e.Edieresis=667;e.Dcroat=722;e.commaaccent=250;e.copyright=737;e.Emacron=667;e.ccaron=556;e.aring=556;e.Ncommaaccent=722;e.lacute=278;e.agrave=556;e.Tcommaaccent=611;e.Cacute=722;e.atilde=556;e.Edotaccent=667;e.scaron=556;e.scedilla=556;e.iacute=278;e.lozenge=494;e.Rcaron=722;e.Gcommaaccent=778;e.ucircumflex=611;e.acircumflex=556;e.Amacron=722;e.rcaron=389;e.ccedilla=556;e.Zdotaccent=611;e.Thorn=667;e.Omacron=778;e.Racute=722;e.Sacute=667;e.dcaron=743;e.Umacron=722;e.uring=611;e.threesuperior=333;e.Ograve=778;e.Agrave=722;e.Abreve=722;e.multiply=584;e.uacute=611;e.Tcaron=611;e.partialdiff=494;e.ydieresis=556;e.Nacute=722;e.icircumflex=278;e.Ecircumflex=667;e.adieresis=556;e.edieresis=556;e.cacute=556;e.nacute=611;e.umacron=611;e.Ncaron=722;e.Iacute=278;e.plusminus=584;e.brokenbar=280;e.registered=737;e.Gbreve=778;e.Idotaccent=278;e.summation=600;e.Egrave=667;e.racute=389;e.omacron=611;e.Zacute=611;e.Zcaron=611;e.greaterequal=549;e.Eth=722;e.Ccedilla=722;e.lcommaaccent=278;e.tcaron=389;e.eogonek=556;e.Uogonek=722;e.Aacute=722;e.Adieresis=722;e.egrave=556;e.zacute=500;e.iogonek=278;e.Oacute=778;e.oacute=611;e.amacron=556;e.sacute=556;e.idieresis=278;e.Ocircumflex=778;e.Ugrave=722;e.Delta=612;e.thorn=611;e.twosuperior=333;e.Odieresis=778;e.mu=611;e.igrave=278;e.ohungarumlaut=611;e.Eogonek=667;e.dcroat=611;e.threequarters=834;e.Scedilla=667;e.lcaron=400;e.Kcommaaccent=722;e.Lacute=611;e.trademark=1e3;e.edotaccent=556;e.Igrave=278;e.Imacron=278;e.Lcaron=611;e.onehalf=834;e.lessequal=549;e.ocircumflex=611;e.ntilde=611;e.Uhungarumlaut=722;e.Eacute=667;e.emacron=556;e.gbreve=611;e.onequarter=834;e.Scaron=667;e.Scommaaccent=667;e.Ohungarumlaut=778;e.degree=400;e.ograve=611;e.Ccaron=722;e.ugrave=611;e.radical=549;e.Dcaron=722;e.rcommaaccent=389;e.Ntilde=722;e.otilde=611;e.Rcommaaccent=722;e.Lcommaaccent=611;e.Atilde=722;e.Aogonek=722;e.Aring=722;e.Otilde=778;e.zdotaccent=500;e.Ecaron=667;e.Iogonek=278;e.kcommaaccent=556;e.minus=584;e.Icircumflex=278;e.ncaron=611;e.tcommaaccent=333;e.logicalnot=584;e.odieresis=611;e.udieresis=611;e.notequal=549;e.gcommaaccent=611;e.eth=611;e.zcaron=500;e.ncommaaccent=611;e.onesuperior=333;e.imacron=278;e.Euro=556});e["Helvetica-Oblique"]=getLookupTableFactory(function(e){e.space=278;e.exclam=278;e.quotedbl=355;e.numbersign=556;e.dollar=556;e.percent=889;e.ampersand=667;e.quoteright=222;e.parenleft=333;e.parenright=333;e.asterisk=389;e.plus=584;e.comma=278;e.hyphen=333;e.period=278;e.slash=278;e.zero=556;e.one=556;e.two=556;e.three=556;e.four=556;e.five=556;e.six=556;e.seven=556;e.eight=556;e.nine=556;e.colon=278;e.semicolon=278;e.less=584;e.equal=584;e.greater=584;e.question=556;e.at=1015;e.A=667;e.B=667;e.C=722;e.D=722;e.E=667;e.F=611;e.G=778;e.H=722;e.I=278;e.J=500;e.K=667;e.L=556;e.M=833;e.N=722;e.O=778;e.P=667;e.Q=778;e.R=722;e.S=667;e.T=611;e.U=722;e.V=667;e.W=944;e.X=667;e.Y=667;e.Z=611;e.bracketleft=278;e.backslash=278;e.bracketright=278;e.asciicircum=469;e.underscore=556;e.quoteleft=222;e.a=556;e.b=556;e.c=500;e.d=556;e.e=556;e.f=278;e.g=556;e.h=556;e.i=222;e.j=222;e.k=500;e.l=222;e.m=833;e.n=556;e.o=556;e.p=556;e.q=556;e.r=333;e.s=500;e.t=278;e.u=556;e.v=500;e.w=722;e.x=500;e.y=500;e.z=500;e.braceleft=334;e.bar=260;e.braceright=334;e.asciitilde=584;e.exclamdown=333;e.cent=556;e.sterling=556;e.fraction=167;e.yen=556;e.florin=556;e.section=556;e.currency=556;e.quotesingle=191;e.quotedblleft=333;e.guillemotleft=556;e.guilsinglleft=333;e.guilsinglright=333;e.fi=500;e.fl=500;e.endash=556;e.dagger=556;e.daggerdbl=556;e.periodcentered=278;e.paragraph=537;e.bullet=350;e.quotesinglbase=222;e.quotedblbase=333;e.quotedblright=333;e.guillemotright=556;e.ellipsis=1e3;e.perthousand=1e3;e.questiondown=611;e.grave=333;e.acute=333;e.circumflex=333;e.tilde=333;e.macron=333;e.breve=333;e.dotaccent=333;e.dieresis=333;e.ring=333;e.cedilla=333;e.hungarumlaut=333;e.ogonek=333;e.caron=333;e.emdash=1e3;e.AE=1e3;e.ordfeminine=370;e.Lslash=556;e.Oslash=778;e.OE=1e3;e.ordmasculine=365;e.ae=889;e.dotlessi=278;e.lslash=222;e.oslash=611;e.oe=944;e.germandbls=611;e.Idieresis=278;e.eacute=556;e.abreve=556;e.uhungarumlaut=556;e.ecaron=556;e.Ydieresis=667;e.divide=584;e.Yacute=667;e.Acircumflex=667;e.aacute=556;e.Ucircumflex=722;e.yacute=500;e.scommaaccent=500;e.ecircumflex=556;e.Uring=722;e.Udieresis=722;e.aogonek=556;e.Uacute=722;e.uogonek=556;e.Edieresis=667;e.Dcroat=722;e.commaaccent=250;e.copyright=737;e.Emacron=667;e.ccaron=500;e.aring=556;e.Ncommaaccent=722;e.lacute=222;e.agrave=556;e.Tcommaaccent=611;e.Cacute=722;e.atilde=556;e.Edotaccent=667;e.scaron=500;e.scedilla=500;e.iacute=278;e.lozenge=471;e.Rcaron=722;e.Gcommaaccent=778;e.ucircumflex=556;e.acircumflex=556;e.Amacron=667;e.rcaron=333;e.ccedilla=500;e.Zdotaccent=611;e.Thorn=667;e.Omacron=778;e.Racute=722;e.Sacute=667;e.dcaron=643;e.Umacron=722;e.uring=556;e.threesuperior=333;e.Ograve=778;e.Agrave=667;e.Abreve=667;e.multiply=584;e.uacute=556;e.Tcaron=611;e.partialdiff=476;e.ydieresis=500;e.Nacute=722;e.icircumflex=278;e.Ecircumflex=667;e.adieresis=556;e.edieresis=556;e.cacute=500;e.nacute=556;e.umacron=556;e.Ncaron=722;e.Iacute=278;e.plusminus=584;e.brokenbar=260;e.registered=737;e.Gbreve=778;e.Idotaccent=278;e.summation=600;e.Egrave=667;e.racute=333;e.omacron=556;e.Zacute=611;e.Zcaron=611;e.greaterequal=549;e.Eth=722;e.Ccedilla=722;e.lcommaaccent=222;e.tcaron=317;e.eogonek=556;e.Uogonek=722;e.Aacute=667;e.Adieresis=667;e.egrave=556;e.zacute=500;e.iogonek=222;e.Oacute=778;e.oacute=556;e.amacron=556;e.sacute=500;e.idieresis=278;e.Ocircumflex=778;e.Ugrave=722;e.Delta=612;e.thorn=556;e.twosuperior=333;e.Odieresis=778;e.mu=556;e.igrave=278;e.ohungarumlaut=556;e.Eogonek=667;e.dcroat=556;e.threequarters=834;e.Scedilla=667;e.lcaron=299;e.Kcommaaccent=667;e.Lacute=556;e.trademark=1e3;e.edotaccent=556;e.Igrave=278;e.Imacron=278;e.Lcaron=556;e.onehalf=834;e.lessequal=549;e.ocircumflex=556;e.ntilde=556;e.Uhungarumlaut=722;e.Eacute=667;e.emacron=556;e.gbreve=556;e.onequarter=834;e.Scaron=667;e.Scommaaccent=667;e.Ohungarumlaut=778;e.degree=400;e.ograve=556;e.Ccaron=722;e.ugrave=556;e.radical=453;e.Dcaron=722;e.rcommaaccent=333;e.Ntilde=722;e.otilde=556;e.Rcommaaccent=722;e.Lcommaaccent=556;e.Atilde=667;e.Aogonek=667;e.Aring=667;e.Otilde=778;e.zdotaccent=500;e.Ecaron=667;e.Iogonek=278;e.kcommaaccent=500;e.minus=584;e.Icircumflex=278;e.ncaron=556;e.tcommaaccent=278;e.logicalnot=584;e.odieresis=556;e.udieresis=556;e.notequal=549;e.gcommaaccent=556;e.eth=556;e.zcaron=500;e.ncommaaccent=556;e.onesuperior=333;e.imacron=278;e.Euro=556});e.Symbol=getLookupTableFactory(function(e){e.space=250;e.exclam=333;e.universal=713;e.numbersign=500;e.existential=549;e.percent=833;e.ampersand=778;e.suchthat=439;e.parenleft=333;e.parenright=333;e.asteriskmath=500;e.plus=549;e.comma=250;e.minus=549;e.period=250;e.slash=278;e.zero=500;e.one=500;e.two=500;e.three=500;e.four=500;e.five=500;e.six=500;e.seven=500;e.eight=500;e.nine=500;e.colon=278;e.semicolon=278;e.less=549;e.equal=549;e.greater=549;e.question=444;e.congruent=549;e.Alpha=722;e.Beta=667;e.Chi=722;e.Delta=612;e.Epsilon=611;e.Phi=763;e.Gamma=603;e.Eta=722;e.Iota=333;e.theta1=631;e.Kappa=722;e.Lambda=686;e.Mu=889;e.Nu=722;e.Omicron=722;e.Pi=768;e.Theta=741;e.Rho=556;e.Sigma=592;e.Tau=611;e.Upsilon=690;e.sigma1=439;e.Omega=768;e.Xi=645;e.Psi=795;e.Zeta=611;e.bracketleft=333;e.therefore=863;e.bracketright=333;e.perpendicular=658;e.underscore=500;e.radicalex=500;e.alpha=631;e.beta=549;e.chi=549;e.delta=494;e.epsilon=439;e.phi=521;e.gamma=411;e.eta=603;e.iota=329;e.phi1=603;e.kappa=549;e.lambda=549;e.mu=576;e.nu=521;e.omicron=549;e.pi=549;e.theta=521;e.rho=549;e.sigma=603;e.tau=439;e.upsilon=576;e.omega1=713;e.omega=686;e.xi=493;e.psi=686;e.zeta=494;e.braceleft=480;e.bar=200;e.braceright=480;e.similar=549;e.Euro=750;e.Upsilon1=620;e.minute=247;e.lessequal=549;e.fraction=167;e.infinity=713;e.florin=500;e.club=753;e.diamond=753;e.heart=753;e.spade=753;e.arrowboth=1042;e.arrowleft=987;e.arrowup=603;e.arrowright=987;e.arrowdown=603;e.degree=400;e.plusminus=549;e.second=411;e.greaterequal=549;e.multiply=549;e.proportional=713;e.partialdiff=494;e.bullet=460;e.divide=549;e.notequal=549;e.equivalence=549;e.approxequal=549;e.ellipsis=1e3;e.arrowvertex=603;e.arrowhorizex=1e3;e.carriagereturn=658;e.aleph=823;e.Ifraktur=686;e.Rfraktur=795;e.weierstrass=987;e.circlemultiply=768;e.circleplus=768;e.emptyset=823;e.intersection=768;e.union=768;e.propersuperset=713;e.reflexsuperset=713;e.notsubset=713;e.propersubset=713;e.reflexsubset=713;e.element=713;e.notelement=713;e.angle=768;e.gradient=713;e.registerserif=790;e.copyrightserif=790;e.trademarkserif=890;e.product=823;e.radical=549;e.dotmath=250;e.logicalnot=713;e.logicaland=603;e.logicalor=603;e.arrowdblboth=1042;e.arrowdblleft=987;e.arrowdblup=603;e.arrowdblright=987;e.arrowdbldown=603;e.lozenge=494;e.angleleft=329;e.registersans=790;e.copyrightsans=790;e.trademarksans=786;e.summation=713;e.parenlefttp=384;e.parenleftex=384;e.parenleftbt=384;e.bracketlefttp=384;e.bracketleftex=384;e.bracketleftbt=384;e.bracelefttp=494;e.braceleftmid=494;e.braceleftbt=494;e.braceex=494;e.angleright=329;e.integral=274;e.integraltp=686;e.integralex=686;e.integralbt=686;e.parenrighttp=384;e.parenrightex=384;e.parenrightbt=384;e.bracketrighttp=384;e.bracketrightex=384;e.bracketrightbt=384;e.bracerighttp=494;e.bracerightmid=494;e.bracerightbt=494;e.apple=790});e["Times-Roman"]=getLookupTableFactory(function(e){e.space=250;e.exclam=333;e.quotedbl=408;e.numbersign=500;e.dollar=500;e.percent=833;e.ampersand=778;e.quoteright=333;e.parenleft=333;e.parenright=333;e.asterisk=500;e.plus=564;e.comma=250;e.hyphen=333;e.period=250;e.slash=278;e.zero=500;e.one=500;e.two=500;e.three=500;e.four=500;e.five=500;e.six=500;e.seven=500;e.eight=500;e.nine=500;e.colon=278;e.semicolon=278;e.less=564;e.equal=564;e.greater=564;e.question=444;e.at=921;e.A=722;e.B=667;e.C=667;e.D=722;e.E=611;e.F=556;e.G=722;e.H=722;e.I=333;e.J=389;e.K=722;e.L=611;e.M=889;e.N=722;e.O=722;e.P=556;e.Q=722;e.R=667;e.S=556;e.T=611;e.U=722;e.V=722;e.W=944;e.X=722;e.Y=722;e.Z=611;e.bracketleft=333;e.backslash=278;e.bracketright=333;e.asciicircum=469;e.underscore=500;e.quoteleft=333;e.a=444;e.b=500;e.c=444;e.d=500;e.e=444;e.f=333;e.g=500;e.h=500;e.i=278;e.j=278;e.k=500;e.l=278;e.m=778;e.n=500;e.o=500;e.p=500;e.q=500;e.r=333;e.s=389;e.t=278;e.u=500;e.v=500;e.w=722;e.x=500;e.y=500;e.z=444;e.braceleft=480;e.bar=200;e.braceright=480;e.asciitilde=541;e.exclamdown=333;e.cent=500;e.sterling=500;e.fraction=167;e.yen=500;e.florin=500;e.section=500;e.currency=500;e.quotesingle=180;e.quotedblleft=444;e.guillemotleft=500;e.guilsinglleft=333;e.guilsinglright=333;e.fi=556;e.fl=556;e.endash=500;e.dagger=500;e.daggerdbl=500;e.periodcentered=250;e.paragraph=453;e.bullet=350;e.quotesinglbase=333;e.quotedblbase=444;e.quotedblright=444;e.guillemotright=500;e.ellipsis=1e3;e.perthousand=1e3;e.questiondown=444;e.grave=333;e.acute=333;e.circumflex=333;e.tilde=333;e.macron=333;e.breve=333;e.dotaccent=333;e.dieresis=333;e.ring=333;e.cedilla=333;e.hungarumlaut=333;e.ogonek=333;e.caron=333;e.emdash=1e3;e.AE=889;e.ordfeminine=276;e.Lslash=611;e.Oslash=722;e.OE=889;e.ordmasculine=310;e.ae=667;e.dotlessi=278;e.lslash=278;e.oslash=500;e.oe=722;e.germandbls=500;e.Idieresis=333;e.eacute=444;e.abreve=444;e.uhungarumlaut=500;e.ecaron=444;e.Ydieresis=722;e.divide=564;e.Yacute=722;e.Acircumflex=722;e.aacute=444;e.Ucircumflex=722;e.yacute=500;e.scommaaccent=389;e.ecircumflex=444;e.Uring=722;e.Udieresis=722;e.aogonek=444;e.Uacute=722;e.uogonek=500;e.Edieresis=611;e.Dcroat=722;e.commaaccent=250;e.copyright=760;e.Emacron=611;e.ccaron=444;e.aring=444;e.Ncommaaccent=722;e.lacute=278;e.agrave=444;e.Tcommaaccent=611;e.Cacute=667;e.atilde=444;e.Edotaccent=611;e.scaron=389;e.scedilla=389;e.iacute=278;e.lozenge=471;e.Rcaron=667;e.Gcommaaccent=722;e.ucircumflex=500;e.acircumflex=444;e.Amacron=722;e.rcaron=333;e.ccedilla=444;e.Zdotaccent=611;e.Thorn=556;e.Omacron=722;e.Racute=667;e.Sacute=556;e.dcaron=588;e.Umacron=722;e.uring=500;e.threesuperior=300;e.Ograve=722;e.Agrave=722;e.Abreve=722;e.multiply=564;e.uacute=500;e.Tcaron=611;e.partialdiff=476;e.ydieresis=500;e.Nacute=722;e.icircumflex=278;e.Ecircumflex=611;e.adieresis=444;e.edieresis=444;e.cacute=444;e.nacute=500;e.umacron=500;e.Ncaron=722;e.Iacute=333;e.plusminus=564;e.brokenbar=200;e.registered=760;e.Gbreve=722;e.Idotaccent=333;e.summation=600;e.Egrave=611;e.racute=333;e.omacron=500;e.Zacute=611;e.Zcaron=611;e.greaterequal=549;e.Eth=722;e.Ccedilla=667;e.lcommaaccent=278;e.tcaron=326;e.eogonek=444;e.Uogonek=722;e.Aacute=722;e.Adieresis=722;e.egrave=444;e.zacute=444;e.iogonek=278;e.Oacute=722;e.oacute=500;e.amacron=444;e.sacute=389;e.idieresis=278;e.Ocircumflex=722;e.Ugrave=722;e.Delta=612;e.thorn=500;e.twosuperior=300;e.Odieresis=722;e.mu=500;e.igrave=278;e.ohungarumlaut=500;e.Eogonek=611;e.dcroat=500;e.threequarters=750;e.Scedilla=556;e.lcaron=344;e.Kcommaaccent=722;e.Lacute=611;e.trademark=980;e.edotaccent=444;e.Igrave=333;e.Imacron=333;e.Lcaron=611;e.onehalf=750;e.lessequal=549;e.ocircumflex=500;e.ntilde=500;e.Uhungarumlaut=722;e.Eacute=611;e.emacron=444;e.gbreve=500;e.onequarter=750;e.Scaron=556;e.Scommaaccent=556;e.Ohungarumlaut=722;e.degree=400;e.ograve=500;e.Ccaron=667;e.ugrave=500;e.radical=453;e.Dcaron=722;e.rcommaaccent=333;e.Ntilde=722;e.otilde=500;e.Rcommaaccent=667;e.Lcommaaccent=611;e.Atilde=722;e.Aogonek=722;e.Aring=722;e.Otilde=722;e.zdotaccent=444;e.Ecaron=611;e.Iogonek=333;e.kcommaaccent=500;e.minus=564;e.Icircumflex=333;e.ncaron=500;e.tcommaaccent=278;e.logicalnot=564;e.odieresis=500;e.udieresis=500;e.notequal=549;e.gcommaaccent=500;e.eth=500;e.zcaron=444;e.ncommaaccent=500;e.onesuperior=300;e.imacron=278;e.Euro=500});e["Times-Bold"]=getLookupTableFactory(function(e){e.space=250;e.exclam=333;e.quotedbl=555;e.numbersign=500;e.dollar=500;e.percent=1e3;e.ampersand=833;e.quoteright=333;e.parenleft=333;e.parenright=333;e.asterisk=500;e.plus=570;e.comma=250;e.hyphen=333;e.period=250;e.slash=278;e.zero=500;e.one=500;e.two=500;e.three=500;e.four=500;e.five=500;e.six=500;e.seven=500;e.eight=500;e.nine=500;e.colon=333;e.semicolon=333;e.less=570;e.equal=570;e.greater=570;e.question=500;e.at=930;e.A=722;e.B=667;e.C=722;e.D=722;e.E=667;e.F=611;e.G=778;e.H=778;e.I=389;e.J=500;e.K=778;e.L=667;e.M=944;e.N=722;e.O=778;e.P=611;e.Q=778;e.R=722;e.S=556;e.T=667;e.U=722;e.V=722;e.W=1e3;e.X=722;e.Y=722;e.Z=667;e.bracketleft=333;e.backslash=278;e.bracketright=333;e.asciicircum=581;e.underscore=500;e.quoteleft=333;e.a=500;e.b=556;e.c=444;e.d=556;e.e=444;e.f=333;e.g=500;e.h=556;e.i=278;e.j=333;e.k=556;e.l=278;e.m=833;e.n=556;e.o=500;e.p=556;e.q=556;e.r=444;e.s=389;e.t=333;e.u=556;e.v=500;e.w=722;e.x=500;e.y=500;e.z=444;e.braceleft=394;e.bar=220;e.braceright=394;e.asciitilde=520;e.exclamdown=333;e.cent=500;e.sterling=500;e.fraction=167;e.yen=500;e.florin=500;e.section=500;e.currency=500;e.quotesingle=278;e.quotedblleft=500;e.guillemotleft=500;e.guilsinglleft=333;e.guilsinglright=333;e.fi=556;e.fl=556;e.endash=500;e.dagger=500;e.daggerdbl=500;e.periodcentered=250;e.paragraph=540;e.bullet=350;e.quotesinglbase=333;e.quotedblbase=500;e.quotedblright=500;e.guillemotright=500;e.ellipsis=1e3;e.perthousand=1e3;e.questiondown=500;e.grave=333;e.acute=333;e.circumflex=333;e.tilde=333;e.macron=333;e.breve=333;e.dotaccent=333;e.dieresis=333;e.ring=333;e.cedilla=333;e.hungarumlaut=333;e.ogonek=333;e.caron=333;e.emdash=1e3;e.AE=1e3;e.ordfeminine=300;e.Lslash=667;e.Oslash=778;e.OE=1e3;e.ordmasculine=330;e.ae=722;e.dotlessi=278;e.lslash=278;e.oslash=500;e.oe=722;e.germandbls=556;e.Idieresis=389;e.eacute=444;e.abreve=500;e.uhungarumlaut=556;e.ecaron=444;e.Ydieresis=722;e.divide=570;e.Yacute=722;e.Acircumflex=722;e.aacute=500;e.Ucircumflex=722;e.yacute=500;e.scommaaccent=389;e.ecircumflex=444;e.Uring=722;e.Udieresis=722;e.aogonek=500;e.Uacute=722;e.uogonek=556;e.Edieresis=667;e.Dcroat=722;e.commaaccent=250;e.copyright=747;e.Emacron=667;e.ccaron=444;e.aring=500;e.Ncommaaccent=722;e.lacute=278;e.agrave=500;e.Tcommaaccent=667;e.Cacute=722;e.atilde=500;e.Edotaccent=667;e.scaron=389;e.scedilla=389;e.iacute=278;e.lozenge=494;e.Rcaron=722;e.Gcommaaccent=778;e.ucircumflex=556;e.acircumflex=500;e.Amacron=722;e.rcaron=444;e.ccedilla=444;e.Zdotaccent=667;e.Thorn=611;e.Omacron=778;e.Racute=722;e.Sacute=556;e.dcaron=672;e.Umacron=722;e.uring=556;e.threesuperior=300;e.Ograve=778;e.Agrave=722;e.Abreve=722;e.multiply=570;e.uacute=556;e.Tcaron=667;e.partialdiff=494;e.ydieresis=500;e.Nacute=722;e.icircumflex=278;e.Ecircumflex=667;e.adieresis=500;e.edieresis=444;e.cacute=444;e.nacute=556;e.umacron=556;e.Ncaron=722;e.Iacute=389;e.plusminus=570;e.brokenbar=220;e.registered=747;e.Gbreve=778;e.Idotaccent=389;e.summation=600;e.Egrave=667;e.racute=444;e.omacron=500;e.Zacute=667;e.Zcaron=667;e.greaterequal=549;e.Eth=722;e.Ccedilla=722;e.lcommaaccent=278;e.tcaron=416;e.eogonek=444;e.Uogonek=722;e.Aacute=722;e.Adieresis=722;e.egrave=444;e.zacute=444;e.iogonek=278;e.Oacute=778;e.oacute=500;e.amacron=500;e.sacute=389;e.idieresis=278;e.Ocircumflex=778;e.Ugrave=722;e.Delta=612;e.thorn=556;e.twosuperior=300;e.Odieresis=778;e.mu=556;e.igrave=278;e.ohungarumlaut=500;e.Eogonek=667;e.dcroat=556;e.threequarters=750;e.Scedilla=556;e.lcaron=394;e.Kcommaaccent=778;e.Lacute=667;e.trademark=1e3;e.edotaccent=444;e.Igrave=389;e.Imacron=389;e.Lcaron=667;e.onehalf=750;e.lessequal=549;e.ocircumflex=500;e.ntilde=556;e.Uhungarumlaut=722;e.Eacute=667;e.emacron=444;e.gbreve=500;e.onequarter=750;e.Scaron=556;e.Scommaaccent=556;e.Ohungarumlaut=778;e.degree=400;e.ograve=500;e.Ccaron=722;e.ugrave=556;e.radical=549;e.Dcaron=722;e.rcommaaccent=444;e.Ntilde=722;e.otilde=500;e.Rcommaaccent=722;e.Lcommaaccent=667;e.Atilde=722;e.Aogonek=722;e.Aring=722;e.Otilde=778;e.zdotaccent=444;e.Ecaron=667;e.Iogonek=389;e.kcommaaccent=556;e.minus=570;e.Icircumflex=389;e.ncaron=556;e.tcommaaccent=333;e.logicalnot=570;e.odieresis=500;e.udieresis=556;e.notequal=549;e.gcommaaccent=500;e.eth=500;e.zcaron=444;e.ncommaaccent=556;e.onesuperior=300;e.imacron=278;e.Euro=500});e["Times-BoldItalic"]=getLookupTableFactory(function(e){e.space=250;e.exclam=389;e.quotedbl=555;e.numbersign=500;e.dollar=500;e.percent=833;e.ampersand=778;e.quoteright=333;e.parenleft=333;e.parenright=333;e.asterisk=500;e.plus=570;e.comma=250;e.hyphen=333;e.period=250;e.slash=278;e.zero=500;e.one=500;e.two=500;e.three=500;e.four=500;e.five=500;e.six=500;e.seven=500;e.eight=500;e.nine=500;e.colon=333;e.semicolon=333;e.less=570;e.equal=570;e.greater=570;e.question=500;e.at=832;e.A=667;e.B=667;e.C=667;e.D=722;e.E=667;e.F=667;e.G=722;e.H=778;e.I=389;e.J=500;e.K=667;e.L=611;e.M=889;e.N=722;e.O=722;e.P=611;e.Q=722;e.R=667;e.S=556;e.T=611;e.U=722;e.V=667;e.W=889;e.X=667;e.Y=611;e.Z=611;e.bracketleft=333;e.backslash=278;e.bracketright=333;e.asciicircum=570;e.underscore=500;e.quoteleft=333;e.a=500;e.b=500;e.c=444;e.d=500;e.e=444;e.f=333;e.g=500;e.h=556;e.i=278;e.j=278;e.k=500;e.l=278;e.m=778;e.n=556;e.o=500;e.p=500;e.q=500;e.r=389;e.s=389;e.t=278;e.u=556;e.v=444;e.w=667;e.x=500;e.y=444;e.z=389;e.braceleft=348;e.bar=220;e.braceright=348;e.asciitilde=570;e.exclamdown=389;e.cent=500;e.sterling=500;e.fraction=167;e.yen=500;e.florin=500;e.section=500;e.currency=500;e.quotesingle=278;e.quotedblleft=500;e.guillemotleft=500;e.guilsinglleft=333;e.guilsinglright=333;e.fi=556;e.fl=556;e.endash=500;e.dagger=500;e.daggerdbl=500;e.periodcentered=250;e.paragraph=500;e.bullet=350;e.quotesinglbase=333;e.quotedblbase=500;e.quotedblright=500;e.guillemotright=500;e.ellipsis=1e3;e.perthousand=1e3;e.questiondown=500;e.grave=333;e.acute=333;e.circumflex=333;e.tilde=333;e.macron=333;e.breve=333;e.dotaccent=333;e.dieresis=333;e.ring=333;e.cedilla=333;e.hungarumlaut=333;e.ogonek=333;e.caron=333;e.emdash=1e3;e.AE=944;e.ordfeminine=266;e.Lslash=611;e.Oslash=722;e.OE=944;e.ordmasculine=300;e.ae=722;e.dotlessi=278;e.lslash=278;e.oslash=500;e.oe=722;e.germandbls=500;e.Idieresis=389;e.eacute=444;e.abreve=500;e.uhungarumlaut=556;e.ecaron=444;e.Ydieresis=611;e.divide=570;e.Yacute=611;e.Acircumflex=667;e.aacute=500;e.Ucircumflex=722;e.yacute=444;e.scommaaccent=389;e.ecircumflex=444;e.Uring=722;e.Udieresis=722;e.aogonek=500;e.Uacute=722;e.uogonek=556;e.Edieresis=667;e.Dcroat=722;e.commaaccent=250;e.copyright=747;e.Emacron=667;e.ccaron=444;e.aring=500;e.Ncommaaccent=722;e.lacute=278;e.agrave=500;e.Tcommaaccent=611;e.Cacute=667;e.atilde=500;e.Edotaccent=667;e.scaron=389;e.scedilla=389;e.iacute=278;e.lozenge=494;e.Rcaron=667;e.Gcommaaccent=722;e.ucircumflex=556;e.acircumflex=500;e.Amacron=667;e.rcaron=389;e.ccedilla=444;e.Zdotaccent=611;e.Thorn=611;e.Omacron=722;e.Racute=667;e.Sacute=556;e.dcaron=608;e.Umacron=722;e.uring=556;e.threesuperior=300;e.Ograve=722;e.Agrave=667;e.Abreve=667;e.multiply=570;e.uacute=556;e.Tcaron=611;e.partialdiff=494;e.ydieresis=444;e.Nacute=722;e.icircumflex=278;e.Ecircumflex=667;e.adieresis=500;e.edieresis=444;e.cacute=444;e.nacute=556;e.umacron=556;e.Ncaron=722;e.Iacute=389;e.plusminus=570;e.brokenbar=220;e.registered=747;e.Gbreve=722;e.Idotaccent=389;e.summation=600;e.Egrave=667;e.racute=389;e.omacron=500;e.Zacute=611;e.Zcaron=611;e.greaterequal=549;e.Eth=722;e.Ccedilla=667;e.lcommaaccent=278;e.tcaron=366;e.eogonek=444;e.Uogonek=722;e.Aacute=667;e.Adieresis=667;e.egrave=444;e.zacute=389;e.iogonek=278;e.Oacute=722;e.oacute=500;e.amacron=500;e.sacute=389;e.idieresis=278;e.Ocircumflex=722;e.Ugrave=722;e.Delta=612;e.thorn=500;e.twosuperior=300;e.Odieresis=722;e.mu=576;e.igrave=278;e.ohungarumlaut=500;e.Eogonek=667;e.dcroat=500;e.threequarters=750;e.Scedilla=556;e.lcaron=382;e.Kcommaaccent=667;e.Lacute=611;e.trademark=1e3;e.edotaccent=444;e.Igrave=389;e.Imacron=389;e.Lcaron=611;e.onehalf=750;e.lessequal=549;e.ocircumflex=500;e.ntilde=556;e.Uhungarumlaut=722;e.Eacute=667;e.emacron=444;e.gbreve=500;e.onequarter=750;e.Scaron=556;e.Scommaaccent=556;e.Ohungarumlaut=722;e.degree=400;e.ograve=500;e.Ccaron=667;e.ugrave=556;e.radical=549;e.Dcaron=722;e.rcommaaccent=389;e.Ntilde=722;e.otilde=500;e.Rcommaaccent=667;e.Lcommaaccent=611;e.Atilde=667;e.Aogonek=667;e.Aring=667;e.Otilde=722;e.zdotaccent=389;e.Ecaron=667;e.Iogonek=389;e.kcommaaccent=500;e.minus=606;e.Icircumflex=389;e.ncaron=556;e.tcommaaccent=278;e.logicalnot=606;e.odieresis=500;e.udieresis=556;e.notequal=549;e.gcommaaccent=500;e.eth=500;e.zcaron=389;e.ncommaaccent=556;e.onesuperior=300;e.imacron=278;e.Euro=500});e["Times-Italic"]=getLookupTableFactory(function(e){e.space=250;e.exclam=333;e.quotedbl=420;e.numbersign=500;e.dollar=500;e.percent=833;e.ampersand=778;e.quoteright=333;e.parenleft=333;e.parenright=333;e.asterisk=500;e.plus=675;e.comma=250;e.hyphen=333;e.period=250;e.slash=278;e.zero=500;e.one=500;e.two=500;e.three=500;e.four=500;e.five=500;e.six=500;e.seven=500;e.eight=500;e.nine=500;e.colon=333;e.semicolon=333;e.less=675;e.equal=675;e.greater=675;e.question=500;e.at=920;e.A=611;e.B=611;e.C=667;e.D=722;e.E=611;e.F=611;e.G=722;e.H=722;e.I=333;e.J=444;e.K=667;e.L=556;e.M=833;e.N=667;e.O=722;e.P=611;e.Q=722;e.R=611;e.S=500;e.T=556;e.U=722;e.V=611;e.W=833;e.X=611;e.Y=556;e.Z=556;e.bracketleft=389;e.backslash=278;e.bracketright=389;e.asciicircum=422;e.underscore=500;e.quoteleft=333;e.a=500;e.b=500;e.c=444;e.d=500;e.e=444;e.f=278;e.g=500;e.h=500;e.i=278;e.j=278;e.k=444;e.l=278;e.m=722;e.n=500;e.o=500;e.p=500;e.q=500;e.r=389;e.s=389;e.t=278;e.u=500;e.v=444;e.w=667;e.x=444;e.y=444;e.z=389;e.braceleft=400;e.bar=275;e.braceright=400;e.asciitilde=541;e.exclamdown=389;e.cent=500;e.sterling=500;e.fraction=167;e.yen=500;e.florin=500;e.section=500;e.currency=500;e.quotesingle=214;e.quotedblleft=556;e.guillemotleft=500;e.guilsinglleft=333;e.guilsinglright=333;e.fi=500;e.fl=500;e.endash=500;e.dagger=500;e.daggerdbl=500;e.periodcentered=250;e.paragraph=523;e.bullet=350;e.quotesinglbase=333;e.quotedblbase=556;e.quotedblright=556;e.guillemotright=500;e.ellipsis=889;e.perthousand=1e3;e.questiondown=500;e.grave=333;e.acute=333;e.circumflex=333;e.tilde=333;e.macron=333;e.breve=333;e.dotaccent=333;e.dieresis=333;e.ring=333;e.cedilla=333;e.hungarumlaut=333;e.ogonek=333;e.caron=333;e.emdash=889;e.AE=889;e.ordfeminine=276;e.Lslash=556;e.Oslash=722;e.OE=944;e.ordmasculine=310;e.ae=667;e.dotlessi=278;e.lslash=278;e.oslash=500;e.oe=667;e.germandbls=500;e.Idieresis=333;e.eacute=444;e.abreve=500;e.uhungarumlaut=500;e.ecaron=444;e.Ydieresis=556;e.divide=675;e.Yacute=556;e.Acircumflex=611;e.aacute=500;e.Ucircumflex=722;e.yacute=444;e.scommaaccent=389;e.ecircumflex=444;e.Uring=722;e.Udieresis=722;e.aogonek=500;e.Uacute=722;e.uogonek=500;e.Edieresis=611;e.Dcroat=722;e.commaaccent=250;e.copyright=760;e.Emacron=611;e.ccaron=444;e.aring=500;e.Ncommaaccent=667;e.lacute=278;e.agrave=500;e.Tcommaaccent=556;e.Cacute=667;e.atilde=500;e.Edotaccent=611;e.scaron=389;e.scedilla=389;e.iacute=278;e.lozenge=471;e.Rcaron=611;e.Gcommaaccent=722;e.ucircumflex=500;e.acircumflex=500;e.Amacron=611;e.rcaron=389;e.ccedilla=444;e.Zdotaccent=556;e.Thorn=611;e.Omacron=722;e.Racute=611;e.Sacute=500;e.dcaron=544;e.Umacron=722;e.uring=500;e.threesuperior=300;e.Ograve=722;e.Agrave=611;e.Abreve=611;e.multiply=675;e.uacute=500;e.Tcaron=556;e.partialdiff=476;e.ydieresis=444;e.Nacute=667;e.icircumflex=278;e.Ecircumflex=611;e.adieresis=500;e.edieresis=444;e.cacute=444;e.nacute=500;e.umacron=500;e.Ncaron=667;e.Iacute=333;e.plusminus=675;e.brokenbar=275;e.registered=760;e.Gbreve=722;e.Idotaccent=333;e.summation=600;e.Egrave=611;e.racute=389;e.omacron=500;e.Zacute=556;e.Zcaron=556;e.greaterequal=549;e.Eth=722;e.Ccedilla=667;e.lcommaaccent=278;e.tcaron=300;e.eogonek=444;e.Uogonek=722;e.Aacute=611;e.Adieresis=611;e.egrave=444;e.zacute=389;e.iogonek=278;e.Oacute=722;e.oacute=500;e.amacron=500;e.sacute=389;e.idieresis=278;e.Ocircumflex=722;e.Ugrave=722;e.Delta=612;e.thorn=500;e.twosuperior=300;e.Odieresis=722;e.mu=500;e.igrave=278;e.ohungarumlaut=500;e.Eogonek=611;e.dcroat=500;e.threequarters=750;e.Scedilla=500;e.lcaron=300;e.Kcommaaccent=667;e.Lacute=556;e.trademark=980;e.edotaccent=444;e.Igrave=333;e.Imacron=333;e.Lcaron=611;e.onehalf=750;e.lessequal=549;e.ocircumflex=500;e.ntilde=500;e.Uhungarumlaut=722;e.Eacute=611;e.emacron=444;e.gbreve=500;e.onequarter=750;e.Scaron=500;e.Scommaaccent=500;e.Ohungarumlaut=722;e.degree=400;e.ograve=500;e.Ccaron=667;e.ugrave=500;e.radical=453;e.Dcaron=722;e.rcommaaccent=389;e.Ntilde=667;e.otilde=500;e.Rcommaaccent=611;e.Lcommaaccent=556;e.Atilde=611;e.Aogonek=611;e.Aring=611;e.Otilde=722;e.zdotaccent=389;e.Ecaron=611;e.Iogonek=333;e.kcommaaccent=444;e.minus=675;e.Icircumflex=333;e.ncaron=500;e.tcommaaccent=278;e.logicalnot=675;e.odieresis=500;e.udieresis=500;e.notequal=549;e.gcommaaccent=500;e.eth=500;e.zcaron=389;e.ncommaaccent=500;e.onesuperior=300;e.imacron=278;e.Euro=500});e.ZapfDingbats=getLookupTableFactory(function(e){e.space=278;e.a1=974;e.a2=961;e.a202=974;e.a3=980;e.a4=719;e.a5=789;e.a119=790;e.a118=791;e.a117=690;e.a11=960;e.a12=939;e.a13=549;e.a14=855;e.a15=911;e.a16=933;e.a105=911;e.a17=945;e.a18=974;e.a19=755;e.a20=846;e.a21=762;e.a22=761;e.a23=571;e.a24=677;e.a25=763;e.a26=760;e.a27=759;e.a28=754;e.a6=494;e.a7=552;e.a8=537;e.a9=577;e.a10=692;e.a29=786;e.a30=788;e.a31=788;e.a32=790;e.a33=793;e.a34=794;e.a35=816;e.a36=823;e.a37=789;e.a38=841;e.a39=823;e.a40=833;e.a41=816;e.a42=831;e.a43=923;e.a44=744;e.a45=723;e.a46=749;e.a47=790;e.a48=792;e.a49=695;e.a50=776;e.a51=768;e.a52=792;e.a53=759;e.a54=707;e.a55=708;e.a56=682;e.a57=701;e.a58=826;e.a59=815;e.a60=789;e.a61=789;e.a62=707;e.a63=687;e.a64=696;e.a65=689;e.a66=786;e.a67=787;e.a68=713;e.a69=791;e.a70=785;e.a71=791;e.a72=873;e.a73=761;e.a74=762;e.a203=762;e.a75=759;e.a204=759;e.a76=892;e.a77=892;e.a78=788;e.a79=784;e.a81=438;e.a82=138;e.a83=277;e.a84=415;e.a97=392;e.a98=392;e.a99=668;e.a100=668;e.a89=390;e.a90=390;e.a93=317;e.a94=317;e.a91=276;e.a92=276;e.a205=509;e.a85=509;e.a206=410;e.a86=410;e.a87=234;e.a88=234;e.a95=334;e.a96=334;e.a101=732;e.a102=544;e.a103=544;e.a104=910;e.a106=667;e.a107=760;e.a108=760;e.a112=776;e.a111=595;e.a110=694;e.a109=626;e.a120=788;e.a121=788;e.a122=788;e.a123=788;e.a124=788;e.a125=788;e.a126=788;e.a127=788;e.a128=788;e.a129=788;e.a130=788;e.a131=788;e.a132=788;e.a133=788;e.a134=788;e.a135=788;e.a136=788;e.a137=788;e.a138=788;e.a139=788;e.a140=788;e.a141=788;e.a142=788;e.a143=788;e.a144=788;e.a145=788;e.a146=788;e.a147=788;e.a148=788;e.a149=788;e.a150=788;e.a151=788;e.a152=788;e.a153=788;e.a154=788;e.a155=788;e.a156=788;e.a157=788;e.a158=788;e.a159=788;e.a160=894;e.a161=838;e.a163=1016;e.a164=458;e.a196=748;e.a165=924;e.a192=748;e.a166=918;e.a167=927;e.a168=928;e.a169=928;e.a170=834;e.a171=873;e.a172=828;e.a173=924;e.a162=924;e.a174=917;e.a175=930;e.a176=931;e.a177=463;e.a178=883;e.a179=836;e.a193=836;e.a180=867;e.a199=867;e.a181=696;e.a200=696;e.a182=874;e.a201=874;e.a183=760;e.a184=946;e.a197=771;e.a185=865;e.a194=771;e.a198=888;e.a186=967;e.a195=888;e.a187=831;e.a188=873;e.a189=927;e.a190=970;e.a191=918})}),Va=getLookupTableFactory(function(e){e.Courier={ascent:629,descent:-157,capHeight:562,xHeight:-426};e["Courier-Bold"]={ascent:629,descent:-157,capHeight:562,xHeight:439};e["Courier-Oblique"]={ascent:629,descent:-157,capHeight:562,xHeight:426};e["Courier-BoldOblique"]={ascent:629,descent:-157,capHeight:562,xHeight:426};e.Helvetica={ascent:718,descent:-207,capHeight:718,xHeight:523};e["Helvetica-Bold"]={ascent:718,descent:-207,capHeight:718,xHeight:532};e["Helvetica-Oblique"]={ascent:718,descent:-207,capHeight:718,xHeight:523};e["Helvetica-BoldOblique"]={ascent:718,descent:-207,capHeight:718,xHeight:532};e["Times-Roman"]={ascent:683,descent:-217,capHeight:662,xHeight:450};e["Times-Bold"]={ascent:683,descent:-217,capHeight:676,xHeight:461};e["Times-Italic"]={ascent:683,descent:-217,capHeight:653,xHeight:441};e["Times-BoldItalic"]={ascent:683,descent:-217,capHeight:669,xHeight:462};e.Symbol={ascent:Math.NaN,descent:Math.NaN,capHeight:Math.NaN,xHeight:Math.NaN};e.ZapfDingbats={ascent:Math.NaN,descent:Math.NaN,capHeight:Math.NaN,xHeight:Math.NaN}});class GlyfTable{constructor({glyfTable:e,isGlyphLocationsLong:t,locaTable:n,numGlyphs:a}){this.glyphs=[];const s=new DataView(n.buffer,n.byteOffset,n.byteLength),r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=t?4:2;let o=t?s.getUint32(0):2*s.getUint16(0),l=0;for(let e=0;e<a;e++){l+=i;const e=t?s.getUint32(l):2*s.getUint16(l);if(e===o){this.glyphs.push(new Glyph({}));continue}const n=Glyph.parse(o,r);this.glyphs.push(n);o=e}}getSize(){return Math.sumPrecise(this.glyphs.map(e=>e.getSize()+3&-4))}write(){const e=this.getSize(),t=new DataView(new ArrayBuffer(e)),n=e>131070,a=n?4:2,s=new DataView(new ArrayBuffer((this.glyphs.length+1)*a));n?s.setUint32(0,0):s.setUint16(0,0);let r=0,i=0;for(const e of this.glyphs){r+=e.write(r,t);r=r+3&-4;i+=a;n?s.setUint32(i,r):s.setUint16(i,r>>1)}return{isLocationLong:n,loca:new Uint8Array(s.buffer),glyf:new Uint8Array(t.buffer)}}scale(e){for(let t=0,n=this.glyphs.length;t<n;t++)this.glyphs[t].scale(e[t])}}class Glyph{constructor({header:e=null,simple:t=null,composites:n=null}){this.header=e;this.simple=t;this.composites=n}static parse(e,t){const[n,a]=GlyphHeader.parse(e,t);e+=n;if(a.numberOfContours<0){const n=[];for(;;){const[a,s]=CompositeGlyph.parse(e,t);e+=a;n.push(s);if(!(32&s.flags))break}return new Glyph({header:a,composites:n})}const s=SimpleGlyph.parse(e,t,a.numberOfContours);return new Glyph({header:a,simple:s})}getSize(){if(!this.header)return 0;const e=this.simple?this.simple.getSize():Math.sumPrecise(this.composites.map(e=>e.getSize()));return this.header.getSize()+e}write(e,t){if(!this.header)return 0;const n=e;e+=this.header.write(e,t);if(this.simple)e+=this.simple.write(e,t);else for(const n of this.composites)e+=n.write(e,t);return e-n}scale(e){if(!this.header)return;const t=(this.header.xMin+this.header.xMax)/2;this.header.scale(t,e);if(this.simple)this.simple.scale(t,e);else for(const n of this.composites)n.scale(t,e)}}class GlyphHeader{constructor({numberOfContours:e,xMin:t,yMin:n,xMax:a,yMax:s}){this.numberOfContours=e;this.xMin=t;this.yMin=n;this.xMax=a;this.yMax=s}static parse(e,t){return[10,new GlyphHeader({numberOfContours:t.getInt16(e),xMin:t.getInt16(e+2),yMin:t.getInt16(e+4),xMax:t.getInt16(e+6),yMax:t.getInt16(e+8)})]}getSize(){return 10}write(e,t){t.setInt16(e,this.numberOfContours);t.setInt16(e+2,this.xMin);t.setInt16(e+4,this.yMin);t.setInt16(e+6,this.xMax);t.setInt16(e+8,this.yMax);return 10}scale(e,t){this.xMin=Math.round(e+(this.xMin-e)*t);this.xMax=Math.round(e+(this.xMax-e)*t)}}class Contour{constructor({flags:e,xCoordinates:t,yCoordinates:n}){this.xCoordinates=t;this.yCoordinates=n;this.flags=e}}class SimpleGlyph{constructor({contours:e,instructions:t}){this.contours=e;this.instructions=t}static parse(e,t,n){const a=[];for(let s=0;s<n;s++){const n=t.getUint16(e);e+=2;a.push(n)}const s=a[n-1]+1,r=t.getUint16(e);e+=2;const i=new Uint8Array(t).slice(e,e+r);e+=r;const o=[];for(let n=0;n<s;e++,n++){let a=t.getUint8(e);o.push(a);if(8&a){const s=t.getUint8(++e);a^=8;for(let e=0;e<s;e++)o.push(a);n+=s}}const l=[];let f=[],c=[],h=[];const u=[];let m=0,p=0;for(let n=0;n<s;n++){const s=o[n];if(2&s){const n=t.getUint8(e++);p+=16&s?n:-n;f.push(p)}else if(16&s)f.push(p);else{p+=t.getInt16(e);e+=2;f.push(p)}if(a[m]===n){m++;l.push(f);f=[]}}p=0;m=0;for(let n=0;n<s;n++){const s=o[n];if(4&s){const n=t.getUint8(e++);p+=32&s?n:-n;c.push(p)}else if(32&s)c.push(p);else{p+=t.getInt16(e);e+=2;c.push(p)}h.push(1&s|64&s);if(a[m]===n){f=l[m];m++;u.push(new Contour({flags:h,xCoordinates:f,yCoordinates:c}));c=[];h=[]}}return new SimpleGlyph({contours:u,instructions:i})}getSize(){let e=2*this.contours.length+2+this.instructions.length,t=0,n=0;for(const a of this.contours){e+=a.flags.length;for(let s=0,r=a.xCoordinates.length;s<r;s++){const r=a.xCoordinates[s],i=a.yCoordinates[s];let o=Math.abs(r-t);o>255?e+=2:o>0&&(e+=1);t=r;o=Math.abs(i-n);o>255?e+=2:o>0&&(e+=1);n=i}}return e}write(e,t){const n=e,a=[],s=[],r=[];let i=0,o=0;for(const n of this.contours){for(let e=0,t=n.xCoordinates.length;e<t;e++){let t=n.flags[e];const l=n.xCoordinates[e];let f=l-i;if(0===f){t|=16;a.push(0)}else{const e=Math.abs(f);if(e<=255){t|=f>=0?18:2;a.push(e)}else a.push(f)}i=l;const c=n.yCoordinates[e];f=c-o;if(0===f){t|=32;s.push(0)}else{const e=Math.abs(f);if(e<=255){t|=f>=0?36:4;s.push(e)}else s.push(f)}o=c;r.push(t)}t.setUint16(e,a.length-1);e+=2}t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}for(const n of r)t.setUint8(e++,n);for(let n=0,s=a.length;n<s;n++){const s=a[n],i=r[n];if(2&i)t.setUint8(e++,s);else if(!(16&i)){t.setInt16(e,s);e+=2}}for(let n=0,a=s.length;n<a;n++){const a=s[n],i=r[n];if(4&i)t.setUint8(e++,a);else if(!(32&i)){t.setInt16(e,a);e+=2}}return e-n}scale(e,t){for(const n of this.contours)if(0!==n.xCoordinates.length)for(let a=0,s=n.xCoordinates.length;a<s;a++)n.xCoordinates[a]=Math.round(e+(n.xCoordinates[a]-e)*t)}}class CompositeGlyph{constructor({flags:e,glyphIndex:t,argument1:n,argument2:a,transf:s,instructions:r}){this.flags=e;this.glyphIndex=t;this.argument1=n;this.argument2=a;this.transf=s;this.instructions=r}static parse(e,t){const n=e,a=[];let s=t.getUint16(e);const r=t.getUint16(e+2);e+=4;let i,o;if(1&s){if(2&s){i=t.getInt16(e);o=t.getInt16(e+2)}else{i=t.getUint16(e);o=t.getUint16(e+2)}e+=4;s^=1}else{if(2&s){i=t.getInt8(e);o=t.getInt8(e+1)}else{i=t.getUint8(e);o=t.getUint8(e+1)}e+=2}if(8&s){a.push(t.getUint16(e));e+=2}else if(64&s){a.push(t.getUint16(e),t.getUint16(e+2));e+=4}else if(128&s){a.push(t.getUint16(e),t.getUint16(e+2),t.getUint16(e+4),t.getUint16(e+6));e+=8}let l=null;if(256&s){const n=t.getUint16(e);e+=2;l=new Uint8Array(t).slice(e,e+n);e+=n}return[e-n,new CompositeGlyph({flags:s,glyphIndex:r,argument1:i,argument2:o,transf:a,instructions:l})]}getSize(){let e=4+2*this.transf.length;256&this.flags&&(e+=2+this.instructions.length);e+=2;2&this.flags?this.argument1>=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(e+=2):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(e+=2);return e}write(e,t){const n=e;2&this.flags?this.argument1>=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(this.flags|=1):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(this.flags|=1);t.setUint16(e,this.flags);t.setUint16(e+2,this.glyphIndex);e+=4;if(1&this.flags){if(2&this.flags){t.setInt16(e,this.argument1);t.setInt16(e+2,this.argument2)}else{t.setUint16(e,this.argument1);t.setUint16(e+2,this.argument2)}e+=4}else{t.setUint8(e,this.argument1);t.setUint8(e+1,this.argument2);e+=2}if(256&this.flags){t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}}return e-n}scale(e,t){}}function writeInt16(e,t,n){e[t]=n>>8&255;e[t+1]=255&n}function writeInt32(e,t,n){e[t]=n>>24&255;e[t+1]=n>>16&255;e[t+2]=n>>8&255;e[t+3]=255&n}function writeData(e,t,n){if(n instanceof Uint8Array)e.set(n,t);else if("string"==typeof n)for(let a=0,s=n.length;a<s;a++)e[t++]=255&n.charCodeAt(a);else for(const a of n)e[t++]=255&a}class OpenTypeFileBuilder{constructor(e){this.sfnt=e;this.tables=Object.create(null)}static getSearchParams(e,t){let n=1,a=0;for(;(n^e)>n;){n<<=1;a++}const s=n*t;return{range:s,entry:a,rangeShift:t*e-s}}toArray(){let e=this.sfnt;const t=this.tables,n=Object.keys(t);n.sort();const a=n.length;let s,r,i,o,l,f=12+16*a;const c=[f];for(s=0;s<a;s++){o=t[n[s]];f+=(o.length+3&-4)>>>0;c.push(f)}const h=new Uint8Array(f);for(s=0;s<a;s++){o=t[n[s]];writeData(h,c[s],o)}"true"===e&&(e=string32(65536));h[0]=255&e.charCodeAt(0);h[1]=255&e.charCodeAt(1);h[2]=255&e.charCodeAt(2);h[3]=255&e.charCodeAt(3);writeInt16(h,4,a);const u=OpenTypeFileBuilder.getSearchParams(a,16);writeInt16(h,6,u.range);writeInt16(h,8,u.entry);writeInt16(h,10,u.rangeShift);f=12;for(s=0;s<a;s++){l=n[s];h[f]=255&l.charCodeAt(0);h[f+1]=255&l.charCodeAt(1);h[f+2]=255&l.charCodeAt(2);h[f+3]=255&l.charCodeAt(3);let e=0;for(r=c[s],i=c[s+1];r<i;r+=4){e=e+readUint32(h,r)>>>0}writeInt32(h,f+4,e);writeInt32(h,f+8,c[s]);writeInt32(h,f+12,t[l].length);f+=16}return h}addTable(e,t){if(e in this.tables)throw new Error("Table "+e+" already exists");this.tables[e]=t}}const $a=[4],Ya=[5],Ja=[6],Qa=[7],Za=[8],es=[12,35],ts=[14],ns=[21],as=[22],ss=[30],rs=[31];class Type1CharString{width=0;lsb=0;flexing=!1;output=[];stack=[];convert(e,t,n){const a=e.length;let s,r,i,o=!1;for(let l=0;l<a;l++){let a=e[l];if(a<32){12===a&&(a=(a<<8)+e[++l]);switch(a){case 1:case 3:case 9:case 3072:case 3073:case 3074:case 3105:this.stack=[];break;case 4:if(this.flexing){if(this.stack.length<1){o=!0;break}const e=this.stack.pop();this.stack.push(0,e);break}o=this.executeCommand(1,$a);break;case 5:o=this.executeCommand(2,Ya);break;case 6:o=this.executeCommand(1,Ja);break;case 7:o=this.executeCommand(1,Qa);break;case 8:o=this.executeCommand(6,Za);break;case 10:if(this.stack.length<1){o=!0;break}i=this.stack.pop();if(!t[i]){o=!0;break}o=this.convert(t[i],t,n);break;case 11:return o;case 13:if(this.stack.length<2){o=!0;break}s=this.stack.pop();r=this.stack.pop();this.lsb=r;this.width=s;this.stack.push(s,r);o=this.executeCommand(2,as);break;case 14:this.output.push(ts[0]);break;case 21:if(this.flexing)break;o=this.executeCommand(2,ns);break;case 22:if(this.flexing){this.stack.push(0);break}o=this.executeCommand(1,as);break;case 30:o=this.executeCommand(4,ss);break;case 31:o=this.executeCommand(4,rs);break;case 3078:if(n){const e=this.stack.at(-5);this.seac=this.stack.splice(-4,4);this.seac[0]+=this.lsb-e;o=this.executeCommand(0,ts)}else o=this.executeCommand(4,ts);break;case 3079:if(this.stack.length<4){o=!0;break}this.stack.pop();s=this.stack.pop();const e=this.stack.pop();r=this.stack.pop();this.lsb=r;this.width=s;this.stack.push(s,r,e);o=this.executeCommand(3,ns);break;case 3084:if(this.stack.length<2){o=!0;break}const l=this.stack.pop(),f=this.stack.pop();this.stack.push(f/l);break;case 3088:if(this.stack.length<2){o=!0;break}i=this.stack.pop();const c=this.stack.pop();if(0===i&&3===c){const e=this.stack.splice(-17,17);this.stack.push(e[2]+e[0],e[3]+e[1],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14]);o=this.executeCommand(13,es,!0);this.flexing=!1;this.stack.push(e[15],e[16])}else 1===i&&0===c&&(this.flexing=!0);break;case 3089:break;default:warn('Unknown type 1 charstring command of "'+a+'"')}if(o)break}else{a<=246?a-=139:a=a<=250?256*(a-247)+e[++l]+108:a<=254?-256*(a-251)-e[++l]-108:(255&e[++l])<<24|(255&e[++l])<<16|(255&e[++l])<<8|255&e[++l];this.stack.push(a)}}return o}executeCommand(e,t,n){const a=this.stack.length;if(e>a)return!0;const s=a-e;for(let e=s;e<a;e++){let t=this.stack[e];if(Number.isInteger(t))this.output.push(28,t>>8&255,255&t);else{t=65536*t|0;this.output.push(255,t>>24&255,t>>16&255,t>>8&255,255&t)}}this.output.push(...t);n?this.stack.splice(s,e):this.stack.length=0;return!1}}function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function decrypt(e,t,n){if(n>=e.length)return new Uint8Array(0);let a,s,r=0|t;for(a=0;a<n;a++)r=52845*(e[a]+r)+22719&65535;const i=e.length-n,o=new Uint8Array(i);for(a=n,s=0;s<i;a++,s++){const t=e[a];o[s]=t^r>>8;r=52845*(t+r)+22719&65535}return o}function isSpecial(e){return 47===e||91===e||93===e||123===e||125===e||40===e||41===e}class Type1Parser{constructor(e,t,n){if(t){const t=e.getBytes(),n=!((isHexDigit(t[0])||isWhiteSpace(t[0]))&&isHexDigit(t[1])&&isHexDigit(t[2])&&isHexDigit(t[3])&&isHexDigit(t[4])&&isHexDigit(t[5])&&isHexDigit(t[6])&&isHexDigit(t[7]));e=new Stream(n?decrypt(t,55665,4):function decryptAscii(e,t,n){let a=0|t;const s=e.length,r=new Uint8Array(s>>>1);let i,o;for(i=0,o=0;i<s;i++){const t=e[i];if(!isHexDigit(t))continue;i++;let n;for(;i<s&&!isHexDigit(n=e[i]);)i++;if(i<s){const e=parseInt(String.fromCharCode(t,n),16);r[o++]=e^a>>8;a=52845*(e+a)+22719&65535}}return r.slice(n,o)}(t,55665,4))}this.seacAnalysisEnabled=!!n;this.stream=e;this.nextChar()}readNumberArray(){this.getToken();const e=[];for(;;){const t=this.getToken();if(null===t||"]"===t||"}"===t)break;e.push(parseFloat(t||0))}return e}readNumber(){const e=this.getToken();return parseFloat(e||0)}readInt(){const e=this.getToken();return 0|parseInt(e||0,10)}readBoolean(){return"true"===this.getToken()?1:0}nextChar(){return this.currentChar=this.stream.getByte()}prevChar(){this.stream.skip(-2);return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(-1===t)return null;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}if(isSpecial(t)){this.nextChar();return String.fromCharCode(t)}let n="";do{n+=String.fromCharCode(t);t=this.nextChar()}while(t>=0&&!isWhiteSpace(t)&&!isSpecial(t));return n}readCharStrings(e,t){return-1===t?e:decrypt(e,4330,t)}extractFontProgram(e){const t=this.stream,n=[],a=[],s=Object.create(null);s.lenIV=4;const r={subrs:[],charstrings:[],properties:{privateData:s}};let i,o,l,f;for(;null!==(i=this.getToken());)if("/"===i){i=this.getToken();switch(i){case"CharStrings":this.getToken();this.getToken();this.getToken();this.getToken();for(;;){i=this.getToken();if(null===i||"end"===i)break;if("/"!==i)continue;const e=this.getToken();o=this.readInt();this.getToken();l=o>0?t.getBytes(o):new Uint8Array(0);f=r.properties.privateData.lenIV;const n=this.readCharStrings(l,f);this.nextChar();i=this.getToken();"noaccess"===i?this.getToken():"/"===i&&this.prevChar();a.push({glyph:e,encoded:n})}break;case"Subrs":this.readInt();this.getToken();for(;"dup"===this.getToken();){const e=this.readInt();o=this.readInt();this.getToken();l=o>0?t.getBytes(o):new Uint8Array(0);f=r.properties.privateData.lenIV;const a=this.readCharStrings(l,f);this.nextChar();i=this.getToken();"noaccess"===i&&this.getToken();n[e]=a}break;case"BlueValues":case"OtherBlues":case"FamilyBlues":case"FamilyOtherBlues":const e=this.readNumberArray();e.length>0&&e.length,0;break;case"StemSnapH":case"StemSnapV":r.properties.privateData[i]=this.readNumberArray();break;case"StdHW":case"StdVW":r.properties.privateData[i]=this.readNumberArray()[0];break;case"BlueShift":case"lenIV":case"BlueFuzz":case"BlueScale":case"LanguageGroup":r.properties.privateData[i]=this.readNumber();break;case"ExpansionFactor":r.properties.privateData[i]=this.readNumber()||.06;break;case"ForceBold":r.properties.privateData[i]=this.readBoolean()}}for(const{encoded:t,glyph:s}of a){const a=new Type1CharString,i=a.convert(t,n,this.seacAnalysisEnabled);let o=a.output;i&&(o=[14]);const l={glyphName:s,charstring:o,width:a.width,lsb:a.lsb,seac:a.seac};".notdef"===s?r.charstrings.unshift(l):r.charstrings.push(l);if(e.builtInEncoding){const t=e.builtInEncoding.indexOf(s);t>-1&&void 0===e.widths[t]&&t>=e.firstChar&&t<=e.lastChar&&(e.widths[t]=a.width)}}return r}extractFontHeader(e){let t;for(;null!==(t=this.getToken());)if("/"===t){t=this.getToken();switch(t){case"FontMatrix":const n=this.readNumberArray();e.fontMatrix=n;break;case"Encoding":const a=this.getToken();let s;if(/^\d+$/.test(a)){s=[];const e=0|parseInt(a,10);this.getToken();for(let n=0;n<e;n++){t=this.getToken();for(;"dup"!==t&&"def"!==t;){t=this.getToken();if(null===t)return}if("def"===t)break;const e=this.readInt();this.getToken();const n=this.getToken();s[e]=n;this.getToken()}}else s=getEncoding(a);e.builtInEncoding=s;break;case"FontBBox":const r=this.readNumberArray();e.ascent=Math.max(r[3],r[1]);e.descent=Math.min(r[1],r[3]);e.ascentScaled=!0}}}}function findBlock(e,t,n){const a=e.length,s=t.length,r=a-s;let i=n,o=!1;for(;i<r;){let n=0;for(;n<s&&e[i+n]===t[n];)n++;if(n>=s){i+=n;for(;i<a&&isWhiteSpace(e[i]);)i++;o=!0;break}i++}return{found:o,length:i}}class Type1Font{constructor(e,t,n){let a=n.length1,s=n.length2,r=t.peekBytes(6);const i=128===r[0]&&1===r[1];if(i){t.skip(6);a=r[5]<<24|r[4]<<16|r[3]<<8|r[2]}const o=function getHeaderBlock(e,t){const n=[101,101,120,101,99],a=e.pos;let s,r,i,o;try{s=e.getBytes(t);r=s.length}catch{}if(r===t){i=findBlock(s,n,t-2*n.length);if(i.found&&i.length===t)return{stream:new Stream(s),length:t}}warn('Invalid "Length1" property in Type1 font -- trying to recover.');e.pos=a;for(;;){i=findBlock(e.peekBytes(2048),n,0);if(0===i.length)break;e.pos+=i.length;if(i.found){o=e.pos-a;break}}e.pos=a;if(o)return{stream:new Stream(e.getBytes(o)),length:o};warn('Unable to recover "Length1" property in Type1 font -- using as is.');return{stream:new Stream(e.getBytes(t)),length:t}}(t,a);new Type1Parser(o.stream,!1,qa).extractFontHeader(n);if(i){r=t.getBytes(6);s=r[5]<<24|r[4]<<16|r[3]<<8|r[2]}const l=function getEexecBlock(e,t){const n=e.getBytes();if(0===n.length)throw new FormatError("getEexecBlock - no font program found.");return{stream:new Stream(n),length:n.length}}(t),f=new Type1Parser(l.stream,!0,qa).extractFontProgram(n);for(const e in f.properties)n[e]=f.properties[e];const c=f.charstrings,h=this.getType2Charstrings(c),u=this.getType2Subrs(f.subrs);this.charstrings=c;this.data=this.wrap(e,h,this.charstrings,u,n);this.seacs=this.getSeacs(f.charstrings)}get numGlyphs(){return this.charstrings.length+1}getCharset(){const e=[".notdef"];for(const{glyphName:t}of this.charstrings)e.push(t);return e}getGlyphMapping(e){const t=this.charstrings;if(e.composite){const n=Object.create(null);for(let a=0,s=t.length;a<s;a++){n[e.cMap.charCodeOf(a)]=a+1}return n}const n=[".notdef"];let a,s;for(s=0;s<t.length;s++)n.push(t[s].glyphName);const r=e.builtInEncoding;if(r){a=Object.create(null);for(const e in r){s=n.indexOf(r[e]);s>=0&&(a[e]=s)}}return type1FontGlyphMapping(e,a,n)}hasGlyphId(e){if(e<0||e>=this.numGlyphs)return!1;if(0===e)return!0;return this.charstrings[e-1].charstring.length>0}getSeacs(e){const t=[];for(let n=0,a=e.length;n<a;n++){const a=e[n];a.seac&&(t[n+1]=a.seac)}return t}getType2Charstrings(e){const t=[];for(const n of e)t.push(n.charstring);return t}getType2Subrs(e){let t=0;const n=e.length;t=n<1133?107:n<33769?1131:32768;const a=[];let s;for(s=0;s<t;s++)a.push([11]);for(s=0;s<n;s++)a.push(e[s]);return a}wrap(e,t,n,a,s){const r=new CFF;r.header=new CFFHeader(1,0,4,4);r.names=[e];const i=new CFFTopDict;i.setByName("version",391);i.setByName("Notice",392);i.setByName("FullName",393);i.setByName("FamilyName",394);i.setByName("Weight",395);i.setByName("Encoding",null);i.setByName("FontMatrix",s.fontMatrix);i.setByName("FontBBox",s.bbox);i.setByName("charset",null);i.setByName("CharStrings",null);i.setByName("Private",null);r.topDict=i;const o=new CFFStrings;o.add("Version 0.11");o.add("See original notice");o.add(e);o.add(e);o.add("Medium");r.strings=o;r.globalSubrIndex=new CFFIndex;const l=t.length,f=[".notdef"];let c,h;for(c=0;c<l;c++){const e=n[c].glyphName;-1===Oa.indexOf(e)&&o.add(e);f.push(e)}r.charset=new CFFCharset(!1,0,f);const u=new CFFIndex;u.add([139,14]);for(c=0;c<l;c++)u.add(t[c]);r.charStrings=u;const m=new CFFPrivateDict;m.setByName("Subrs",null);const p=["BlueValues","OtherBlues","FamilyBlues","FamilyOtherBlues","StemSnapH","StemSnapV","BlueShift","BlueFuzz","BlueScale","LanguageGroup","ExpansionFactor","ForceBold","StdHW","StdVW"];for(c=0,h=p.length;c<h;c++){const e=p[c];if(!(e in s.privateData))continue;const t=s.privateData[e];if(Array.isArray(t))for(let e=t.length-1;e>0;e--)t[e]-=t[e-1];m.setByName(e,t)}r.topDict.privateDict=m;const d=new CFFIndex;for(c=0,h=a.length;c<h;c++)d.add(a[c]);m.subrsIndex=d;return new CFFCompiler(r).compile()}}const is=[[57344,63743],[1048576,1114109]],os=1e3,ls=["ascent","bbox","black","bold","charProcOperatorList","cssFontInfo","data","defaultVMetrics","defaultWidth","descent","disableFontFace","fallbackName","fontExtraProperties","fontMatrix","isInvalidPDFjsFont","isType3Font","italic","loadedName","mimetype","missingFile","name","remeasure","systemFontInfo","vertical"],fs=["cMap","composite","defaultEncoding","differences","isMonospace","isSerifFont","isSymbolicFont","seacMap","subtype","toFontChar","toUnicode","type","vmetrics","widths"];function adjustWidths(e){if(!e.fontMatrix)return;if(e.fontMatrix[0]===t[0])return;const n=.001/e.fontMatrix[0],a=e.widths;for(const e in a)a[e]*=n;e.defaultWidth*=n}function amendFallbackToUnicode(e){if(!e.fallbackToUnicode)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;const t=[];for(const n in e.fallbackToUnicode)e.toUnicode.has(n)||(t[n]=e.fallbackToUnicode[n]);t.length>0&&e.toUnicode.amend(t)}class fonts_Glyph{constructor(e,t,n,a,s,r,i,o,l){this.originalCharCode=e;this.fontChar=t;this.unicode=n;this.accent=a;this.width=s;this.vmetric=r;this.operatorListId=i;this.isSpace=o;this.isInFont=l}get category(){return shadow(this,"category",function getCharUnicodeCategory(e){const t=ya.get(e);if(t)return t;const n=e.match(ka),a={isWhitespace:!!n?.[1],isZeroWidthDiacritic:!!n?.[2],isInvisibleFormatMark:!!n?.[3]};ya.set(e,a);return a}(this.unicode),!0)}}function int16(e,t){return(e<<8)+t}function writeSignedInt16(e,t,n){e[t+1]=n;e[t]=n>>>8}function signedInt16(e,t){const n=(e<<8)+t;return 32768&n?n-65536:n}function string16(e){return String.fromCharCode(e>>8&255,255&e)}function safeString16(e){e>32767?e=32767:e<-32768&&(e=-32768);return String.fromCharCode(e>>8&255,255&e)}function isTrueTypeCollectionFile(e){return"ttcf"===bytesToString(e.peekBytes(4))}function getFontFileType(e,{type:t,subtype:n,composite:a}){let s,r;if(function isTrueTypeFile(e){const t=e.peekBytes(4);return 65536===readUint32(t,0)||"true"===bytesToString(t)}(e)||isTrueTypeCollectionFile(e))s=a?"CIDFontType2":"TrueType";else if(function isOpenTypeFile(e){return"OTTO"===bytesToString(e.peekBytes(4))}(e))s=a?"CIDFontType2":"OpenType";else if(function isType1File(e){const t=e.peekBytes(2);return 37===t[0]&&33===t[1]||128===t[0]&&1===t[1]}(e))s=a?"CIDFontType0":"MMType1"===t?"MMType1":"Type1";else if(function isCFFFile(e){const t=e.peekBytes(4);return t[0]>=1&&t[3]>=1&&t[3]<=4}(e))if(a){s="CIDFontType0";r="CIDFontType0C"}else{s="MMType1"===t?"MMType1":"Type1";r="Type1C"}else{warn("getFontFileType: Unable to detect correct font file Type/Subtype.");s=t;r=n}return[s,r]}function applyStandardFontGlyphMap(e,t){for(const n in t)e[+n]=t[n]}function buildToFontChar(e,t,n){const a=[];let s;for(let n=0,r=e.length;n<r;n++){s=getUnicodeForGlyph(e[n],t);-1!==s&&(a[n]=s)}for(const e in n){s=getUnicodeForGlyph(n[e],t);-1!==s&&(a[+e]=s)}return a}function isMacNameRecord(e){return 1===e.platform&&0===e.encoding&&0===e.language}function isWinNameRecord(e){return 3===e.platform&&1===e.encoding&&1033===e.language}function convertCidString(e,t,n=!1){switch(t.length){case 1:return t.charCodeAt(0);case 2:return t.charCodeAt(0)<<8|t.charCodeAt(1)}const a=`Unsupported CID string (charCode ${e}): "${t}".`;if(n)throw new FormatError(a);warn(a);return t}function adjustMapping(e,t,n,a){const s=Object.create(null),r=new Map,i=[],o=new Set;let l=0;let f=is[l][0],c=is[l][1];const isInPrivateArea=e=>is[0][0]<=e&&e<=is[0][1]||is[1][0]<=e&&e<=is[1][1];let h=null;for(const u in e){let m=e[u];if(!t(m))continue;if(f>c){l++;if(l>=is.length){warn("Ran out of space in font private use area.");break}f=is[l][0];c=is[l][1]}const p=f++;0===m&&(m=n);let d=a.get(u);if("string"==typeof d)if(1===d.length)d=d.codePointAt(0);else{if(!h){h=new Map;for(let e=64256;e<=64335;e++){const t=String.fromCharCode(e).normalize("NFKD");t.length>1&&h.set(t,e)}}d=h.get(d)||d.codePointAt(0)}if(d&&!isInPrivateArea(d)&&!o.has(m)){r.set(d,m);o.add(m)}s[p]=m;i[u]=p}return{toFontChar:i,charCodeToGlyphId:s,toUnicodeExtraMap:r,nextAvailableFontCharCode:f}}function createCmapTable(e,t,n){const a=function getRanges(e,t,n){const a=[];for(const t in e)e[t]>=n||a.push({fontCharCode:0|t,glyphId:e[t]});if(t)for(const[e,s]of t)s>=n||a.push({fontCharCode:e,glyphId:s});0===a.length&&a.push({fontCharCode:0,glyphId:0});a.sort((e,t)=>e.fontCharCode-t.fontCharCode);const s=[],r=a.length;for(let e=0;e<r;){const t=a[e].fontCharCode,n=[a[e].glyphId];++e;let i=t;for(;e<r&&i+1===a[e].fontCharCode;){n.push(a[e].glyphId);++i;++e;if(65535===i)break}s.push([t,i,n])}return s}(e,t,n),s=a.at(-1)[1]>65535?2:1;let r,i,o,l,f="\0\0"+string16(s)+"\0\0"+string32(4+8*s);for(r=a.length-1;r>=0&&!(a[r][0]<=65535);--r);const c=r+1;a[r][0]<65535&&65535===a[r][1]&&(a[r][1]=65534);const h=a[r][1]<65535?1:0,u=c+h,m=OpenTypeFileBuilder.getSearchParams(u,2);let p,d,g,b,w="",j="",k="",y="",q="",v=0;for(r=0,i=c;r<i;r++){p=a[r];d=p[0];g=p[1];w+=string16(d);j+=string16(g);b=p[2];let e=!0;for(o=1,l=b.length;o<l;++o)if(b[o]!==b[o-1]+1){e=!1;break}if(e){k+=string16(b[0]-d&65535);y+=string16(0)}else{const e=2*(u-r)+2*v;v+=g-d+1;k+=string16(0);y+=string16(e);for(o=0,l=b.length;o<l;++o)q+=string16(b[o])}}if(h>0){j+="ÿÿ";w+="ÿÿ";k+="\0";y+="\0\0"}const S="\0\0"+string16(2*u)+string16(m.range)+string16(m.entry)+string16(m.rangeShift)+j+"\0\0"+w+k+y+q;let x="",C="";if(s>1){f+="\0\0\n"+string32(4+8*s+4+S.length);x="";for(r=0,i=a.length;r<i;r++){p=a[r];d=p[0];b=p[2];let e=b[0];for(o=1,l=b.length;o<l;++o)if(b[o]!==b[o-1]+1){g=p[0]+o-1;x+=string32(d)+string32(g)+string32(e);d=g+1;e=b[o]}x+=string32(d)+string32(p[1])+string32(e)}C="\0\f\0\0"+string32(x.length+16)+"\0\0\0\0"+string32(x.length/12)}return f+"\0"+string16(S.length+4)+S+C+x}function createOS2Table(e,t,n){n||={unitsPerEm:0,yMax:0,yMin:0,ascent:0,descent:0};let a=0,s=0,r=0,i=0,o=null,l=0,f=-1;if(t){for(let e in t){e|=0;(o>e||!o)&&(o=e);l<e&&(l=e);f=getUnicodeRangeFor(e,f);if(f<32)a|=1<<f;else if(f<64)s|=1<<f-32;else if(f<96)r|=1<<f-64;else{if(!(f<123))throw new FormatError("Unicode ranges Bits > 123 are reserved for internal usage");i|=1<<f-96}}l>65535&&(l=65535)}else{o=0;l=255}const c=e.bbox||[0,0,0,0],h=n.unitsPerEm||(e.fontMatrix?1/Math.max(...e.fontMatrix.slice(0,4).map(Math.abs)):1e3),u=e.ascentScaled?1:h/os,m=n.ascent||Math.round(u*(e.ascent||c[3]));let p=n.descent||Math.round(u*(e.descent||c[1]));p>0&&e.descent>0&&c[1]<0&&(p=-p);const d=n.yMax||m,g=-n.yMin||-p;return"\0$ô\0\0\0Š»\0\0\0ŒŠ»\0\0ß\x001\0\0\0\0"+String.fromCharCode(e.fixedPitch?9:0)+"\0\0\0\0\0\0"+string32(a)+string32(s)+string32(r)+string32(i)+"*21*"+string16(e.italicAngle?1:0)+string16(o||e.firstChar)+string16(l||e.lastChar)+string16(m)+string16(p)+"\0d"+string16(d)+string16(g)+"\0\0\0\0\0\0\0\0"+string16(e.xHeight)+string16(e.capHeight)+string16(0)+string16(o||e.firstChar)+"\0"}function createPostTable(e){return"\0\0\0"+string32(Math.floor(65536*e.italicAngle))+"\0\0\0\0"+string32(e.fixedPitch?1:0)+"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}function createPostscriptName(e){return e.replaceAll(/[^\x21-\x7E]|[[\](){}<>/%]/g,"").slice(0,63)}function createNameTable(e,t){t||(t=[[],[]]);const n=[t[0][0]||"Original licence",t[0][1]||e,t[0][2]||"Unknown",t[0][3]||"uniqueID",t[0][4]||e,t[0][5]||"Version 0.11",t[0][6]||createPostscriptName(e),t[0][7]||"Unknown",t[0][8]||"Unknown",t[0][9]||"Unknown"],a=[];let s,r,i,o,l;for(s=0,r=n.length;s<r;s++){l=t[1][s]||n[s];const e=[];for(i=0,o=l.length;i<o;i++)e.push(string16(l.charCodeAt(i)));a.push(e.join(""))}const f=[n,a],c=["\0","\0"],h=["\0\0","\0"],u=["\0\0","\t"],m=n.length*c.length;let p="\0\0"+string16(m)+string16(12*m+6),d=0;for(s=0,r=c.length;s<r;s++){const e=f[s];for(i=0,o=e.length;i<o;i++){l=e[i];p+=c[s]+h[s]+u[s]+string16(i)+string16(l.length)+string16(d);d+=l.length}}p+=n.join("")+a.join("");return p}class Font{constructor(e,t,n,a){this.name=e;this.psName=null;this.mimetype=null;this.disableFontFace=a.disableFontFace;this.fontExtraProperties=a.fontExtraProperties;this.loadedName=n.loadedName;this.isType3Font=n.isType3Font;this.missingFile=!1;this.cssFontInfo=n.cssFontInfo;this._charsCache=Object.create(null);this._glyphCache=Object.create(null);let s=!!(n.flags&Sa);if(!s&&!n.isSimulatedFlags){const t=Na(),n=La(),a=Ua();for(const r of e.split("+")){let e=normalizeFontName(r);e=t[e]||n[e]||e;e=e.split("-",1)[0];if(a[e]){s=!0;break}}}this.isSerifFont=s;this.isSymbolicFont=!!(n.flags&xa);this.isMonospace=!!(n.flags&va);let{type:r,subtype:i}=n;this.type=r;this.subtype=i;this.systemFontInfo=n.systemFontInfo;const o=e.match(/^InvalidPDFjsFont_(.*)_\d+$/);this.isInvalidPDFjsFont=!!o;this.isInvalidPDFjsFont?this.fallbackName=o[1]:this.isMonospace?this.fallbackName="monospace":this.isSerifFont?this.fallbackName="serif":this.fallbackName="sans-serif";if(this.systemFontInfo?.guessFallback){this.systemFontInfo.guessFallback=!1;this.systemFontInfo.css+=`,${this.fallbackName}`}this.differences=n.differences;this.widths=n.widths;this.defaultWidth=n.defaultWidth;this.composite=n.composite;this.cMap=n.cMap;this.capHeight=n.capHeight/os;this.ascent=n.ascent/os;this.descent=n.descent/os;this.lineHeight=this.ascent-this.descent;this.fontMatrix=n.fontMatrix;this.bbox=n.bbox;this.defaultEncoding=n.defaultEncoding;this.toUnicode=n.toUnicode;this.toFontChar=[];if("Type3"===n.type){for(let e=0;e<256;e++)this.toFontChar[e]=this.differences[e]||n.defaultEncoding[e];return}this.cidEncoding=n.cidEncoding||"";this.vertical=!!n.vertical;if(this.vertical){this.vmetrics=n.vmetrics;this.defaultVMetrics=n.defaultVMetrics}if(!t||t.isEmpty){t&&warn('Font file is empty in "'+e+'" ('+this.loadedName+")");this.fallbackToSystemFont(n);return}[r,i]=getFontFileType(t,n);r===this.type&&i===this.subtype||info(`Inconsistent font file Type/SubType, expected: ${this.type}/${this.subtype} but found: ${r}/${i}.`);let l;try{switch(r){case"MMType1":info("MMType1 font ("+e+"), falling back to Type1.");case"Type1":case"CIDFontType0":this.mimetype="font/opentype";const a="Type1C"===i||"CIDFontType0C"===i?new CFFFont(t,n):new Type1Font(e,t,n);adjustWidths(n);l=this.convert(e,a,n);break;case"OpenType":case"TrueType":case"CIDFontType2":this.mimetype="font/opentype";l=this.checkAndRepair(e,t,n);adjustWidths(n);this.isOpenType&&(r="OpenType");break;default:throw new FormatError(`Font ${r} is not supported`)}}catch(e){warn(e);this.fallbackToSystemFont(n);return}amendFallbackToUnicode(n);this.data=l;this.type=r;this.subtype=i;this.fontMatrix=n.fontMatrix;this.widths=n.widths;this.defaultWidth=n.defaultWidth;this.toUnicode=n.toUnicode;this.seacMap=n.seacMap}get renderer(){return shadow(this,"renderer",FontRendererFactory.create(this,qa))}exportData(){const e=Object.create(null);for(const t of ls){const n=this[t];void 0!==n&&(e[t]=n)}if(!this.fontExtraProperties)return{data:e};const t=Object.create(null);for(const e of fs){const n=this[e];void 0!==n&&(t[e]=n)}return{data:e,extra:t}}fallbackToSystemFont(e){this.missingFile=!0;const{name:t,type:n}=this;let a=normalizeFontName(t);const s=Na(),r=La(),i=!!s[a],o=!(!r[a]||!s[r[a]]);a=s[a]||r[a]||a;const l=Va()[a];if(l){isNaN(this.ascent)&&(this.ascent=l.ascent/os);isNaN(this.descent)&&(this.descent=l.descent/os);isNaN(this.capHeight)&&(this.capHeight=l.capHeight/os)}this.bold=/bold/gi.test(a);this.italic=/oblique|italic/gi.test(a);this.black=/Black/g.test(t);const f=/Narrow/g.test(t);this.remeasure=(!i||f)&&Object.keys(this.widths).length>0;if((i||o)&&"CIDFontType2"===n&&this.cidEncoding.startsWith("Identity-")){const n=e.cidToGidMap,a=[];applyStandardFontGlyphMap(a,Xa());/Arial-?Black/i.test(t)?applyStandardFontGlyphMap(a,Wa()):/Calibri/i.test(t)&&applyStandardFontGlyphMap(a,Ka());if(n){for(const e in a){const t=a[e];void 0!==n[t]&&(a[+e]=n[t])}n.length!==this.toUnicode.length&&e.hasIncludedToUnicodeMap&&this.toUnicode instanceof IdentityToUnicodeMap&&this.toUnicode.forEach(function(e,t){const s=a[e];void 0===n[s]&&(a[+e]=t)})}this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach(function(e,t){a[+e]=t});this.toFontChar=a;this.toUnicode=new ToUnicodeMap(a)}else if(/Symbol/i.test(a))this.toFontChar=buildToFontChar(pa,ga(),this.differences);else if(/Dingbats/i.test(a))this.toFontChar=buildToFontChar(da,ba(),this.differences);else if(i||o){const e=buildToFontChar(this.defaultEncoding,ga(),this.differences);"CIDFontType2"!==n||this.cidEncoding.startsWith("Identity-")||this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach(function(t,n){e[+t]=n});this.toFontChar=e}else{const e=ga(),n=[];this.toUnicode.forEach((t,a)=>{if(!this.composite){const n=getUnicodeForGlyph(this.differences[t]||this.defaultEncoding[t],e);-1!==n&&(a=n)}n[+t]=a});this.composite&&this.toUnicode instanceof IdentityToUnicodeMap&&/Tahoma|Verdana/i.test(t)&&applyStandardFontGlyphMap(n,Xa());this.toFontChar=n}amendFallbackToUnicode(e);this.loadedName=a.split("-",1)[0]}checkAndRepair(e,t,n){const a=["OS/2","cmap","head","hhea","hmtx","maxp","name","post","loca","glyf","fpgm","prep","cvt ","CFF "];function readTables(e,t){const n=Object.create(null);n["OS/2"]=null;n.cmap=null;n.head=null;n.hhea=null;n.hmtx=null;n.maxp=null;n.name=null;n.post=null;for(let s=0;s<t;s++){const t=readTableEntry(e);a.includes(t.tag)&&(0!==t.length&&(n[t.tag]=t))}return n}function readTableEntry(e){const t=e.getString(4),n=e.getInt32()>>>0,a=e.getInt32()>>>0,s=e.getInt32()>>>0,r=e.pos;e.pos=e.start||0;e.skip(a);const i=e.getBytes(s);e.pos=r;if("head"===t){i[8]=i[9]=i[10]=i[11]=0;i[17]|=32}return{tag:t,checksum:n,length:s,offset:a,data:i}}function readOpenTypeHeader(e){return{version:e.getString(4),numTables:e.getUint16(),searchRange:e.getUint16(),entrySelector:e.getUint16(),rangeShift:e.getUint16()}}function sanitizeGlyph(e,t,n,a,s,r){const i={length:0,sizeOfInstructions:0};if(t<0||t>=e.length||n>e.length||n-t<=12)return i;const o=e.subarray(t,n),l=signedInt16(o[2],o[3]),f=signedInt16(o[4],o[5]),c=signedInt16(o[6],o[7]),h=signedInt16(o[8],o[9]);if(l>c){writeSignedInt16(o,2,c);writeSignedInt16(o,6,l)}if(f>h){writeSignedInt16(o,4,h);writeSignedInt16(o,8,f)}const u=signedInt16(o[0],o[1]);if(u<0){if(u<-1)return i;a.set(o,s);i.length=o.length;return i}let m,p=10,d=0;for(m=0;m<u;m++){d=(o[p]<<8|o[p+1])+1;p+=2}const g=p,b=o[p]<<8|o[p+1];i.sizeOfInstructions=b;p+=2+b;const w=p;let j=0;for(m=0;m<d;m++){const e=o[p++];192&e&&(o[p-1]=63&e);let t=2;2&e?t=1:16&e&&(t=0);let n=2;4&e?n=1:32&e&&(n=0);const a=t+n;j+=a;if(8&e){const e=o[p++];0===e&&(o[p-1]^=8);m+=e;j+=e*a}}if(0===j)return i;let k=p+j;if(k>o.length)return i;if(!r&&b>0){a.set(o.subarray(0,g),s);a.set([0,0],s+g);a.set(o.subarray(w,k),s+g+2);k-=b;o.length-k>3&&(k=k+3&-4);i.length=k;return i}if(o.length-k>3){k=k+3&-4;a.set(o.subarray(0,k),s);i.length=k;return i}a.set(o,s);i.length=o.length;return i}function readNameTable(e){const n=(t.start||0)+e.offset;t.pos=n;const a=[[],[]],s=[],r=e.length,i=n+r;if(0!==t.getUint16()||r<6)return[a,s];const o=t.getUint16(),l=t.getUint16();let f,c;for(f=0;f<o&&t.pos+12<=i;f++){const e={platform:t.getUint16(),encoding:t.getUint16(),language:t.getUint16(),name:t.getUint16(),length:t.getUint16(),offset:t.getUint16()};(isMacNameRecord(e)||isWinNameRecord(e))&&s.push(e)}for(f=0,c=s.length;f<c;f++){const e=s[f];if(e.length<=0)continue;const r=n+l+e.offset;if(r+e.length>i)continue;t.pos=r;const o=e.name;if(e.encoding){let n="";for(let a=0,s=e.length;a<s;a+=2)n+=String.fromCharCode(t.getUint16());a[1][o]=n}else a[0][o]=t.getString(e.length)}return[a,s]}const s=[0,0,0,0,0,0,0,0,-2,-2,-2,-2,0,0,-2,-5,-1,-1,-1,-1,-1,-1,-1,-1,0,0,-1,0,-1,-1,-1,-1,1,-1,-999,0,1,0,-1,-2,0,-1,-2,-1,-1,0,-1,-1,0,0,-999,-999,-1,-1,-1,-1,-2,-999,-2,-2,-999,0,-2,-2,0,0,-2,0,-2,0,0,0,-2,-1,-1,1,1,0,0,-1,-1,-1,-1,-1,-1,-1,0,0,-1,0,-1,-1,0,-999,-1,-1,-1,-1,-1,-1,0,0,0,0,0,0,0,0,0,0,0,0,-2,-999,-999,-999,-999,-999,-1,-1,-2,-2,0,0,0,0,-1,-1,-999,-2,-2,0,0,-1,-2,-2,0,0,0,-1,-1,-1,-2];function sanitizeTTProgram(e,t){let n,a,r,i,o,l=e.data,f=0,c=0,h=0;const u=[],m=[],p=[];let d=t.tooComplexToFollowFunctions,g=!1,b=0,w=0;for(let e=l.length;f<e;){const e=l[f++];if(64===e){a=l[f++];if(g||w)f+=a;else for(n=0;n<a;n++)u.push(l[f++])}else if(65===e){a=l[f++];if(g||w)f+=2*a;else for(n=0;n<a;n++){r=l[f++];u.push(r<<8|l[f++])}}else if(176==(248&e)){a=e-176+1;if(g||w)f+=a;else for(n=0;n<a;n++)u.push(l[f++])}else if(184==(248&e)){a=e-184+1;if(g||w)f+=2*a;else for(n=0;n<a;n++){r=l[f++];u.push(signedInt16(r,l[f++]))}}else if(43!==e||d)if(44!==e||d){if(45===e)if(g){g=!1;c=f}else{o=m.pop();if(!o){warn("TT: ENDF bad stack");t.hintsValid=!1;return}i=p.pop();l=o.data;f=o.i;t.functionsStackDeltas[i]=u.length-o.stackTop}else if(137===e){if(g||w){warn("TT: nested IDEFs not allowed");d=!0}g=!0;h=f}else if(88===e)++b;else if(27===e)w=b;else if(89===e){w===b&&(w=0);--b}else if(28===e&&!g&&!w){const e=u.at(-1);e>0&&(f+=e-1)}}else{if(g||w){warn("TT: nested FDEFs not allowed");d=!0}g=!0;h=f;i=u.pop();t.functionsDefined[i]={data:l,i:f}}else if(!g&&!w){i=u.at(-1);if(isNaN(i))info("TT: CALL empty stack (or invalid entry).");else{t.functionsUsed[i]=!0;if(i in t.functionsStackDeltas){const e=u.length+t.functionsStackDeltas[i];if(e<0){warn("TT: CALL invalid functions stack delta.");t.hintsValid=!1;return}u.length=e}else if(i in t.functionsDefined&&!p.includes(i)){m.push({data:l,i:f,stackTop:u.length-1});p.push(i);o=t.functionsDefined[i];if(!o){warn("TT: CALL non-existent function");t.hintsValid=!1;return}l=o.data;f=o.i}}}if(!g&&!w){let t=0;e<=142?t=s[e]:e>=192&&e<=223?t=-1:e>=224&&(t=-2);if(e>=113&&e<=117){a=u.pop();isNaN(a)||(t=2*-a)}for(;t<0&&u.length>0;){u.pop();t++}for(;t>0;){u.push(NaN);t--}}}t.tooComplexToFollowFunctions=d;const j=[l];f>l.length&&j.push(new Uint8Array(f-l.length));if(h>c){warn("TT: complementing a missing function tail");j.push(new Uint8Array([34,45]))}!function foldTTTable(e,t){if(t.length>1){let n,a,s=0;for(n=0,a=t.length;n<a;n++)s+=t[n].length;s=s+3&-4;const r=new Uint8Array(s);let i=0;for(n=0,a=t.length;n<a;n++){r.set(t[n],i);i+=t[n].length}e.data=r;e.length=s}}(e,j)}let r,i;if(isTrueTypeCollectionFile(t=new Stream(new Uint8Array(t.getBytes())))){const e=function readTrueTypeCollectionData(e,t){const{numFonts:n,offsetTable:a}=function readTrueTypeCollectionHeader(e){const t=e.getString(4);assert("ttcf"===t,"Must be a TrueType Collection font.");const n=e.getUint16(),a=e.getUint16(),s=e.getInt32()>>>0,r=[];for(let t=0;t<s;t++)r.push(e.getInt32()>>>0);const i={ttcTag:t,majorVersion:n,minorVersion:a,numFonts:s,offsetTable:r};switch(n){case 1:return i;case 2:i.dsigTag=e.getInt32()>>>0;i.dsigLength=e.getInt32()>>>0;i.dsigOffset=e.getInt32()>>>0;return i}throw new FormatError(`Invalid TrueType Collection majorVersion: ${n}.`)}(e),s=t.split("+");let r;for(let i=0;i<n;i++){e.pos=(e.start||0)+a[i];const n=readOpenTypeHeader(e),o=readTables(e,n.numTables);if(!o.name)throw new FormatError('TrueType Collection font must contain a "name" table.');const[l]=readNameTable(o.name);for(let e=0,a=l.length;e<a;e++)for(let a=0,i=l[e].length;a<i;a++){const i=l[e][a]?.replaceAll(/\s/g,"");if(i){if(i===t)return{header:n,tables:o};if(!(s.length<2))for(const e of s)i===e&&(r={name:e,header:n,tables:o})}}}if(r){warn(`TrueType Collection does not contain "${t}" font, falling back to "${r.name}" font instead.`);return{header:r.header,tables:r.tables}}throw new FormatError(`TrueType Collection does not contain "${t}" font.`)}(t,this.name);r=e.header;i=e.tables}else{r=readOpenTypeHeader(t);i=readTables(t,r.numTables)}const o=!i["CFF "];if(o){if(!i.loca)throw new FormatError('Required "loca" table is not found');if(!i.glyf){warn('Required "glyf" table is not found -- trying to recover.');i.glyf={tag:"glyf",data:new Uint8Array(0)}}this.isOpenType=!1}else{if("OTTO"===r.version&&!n.composite||!i.head||!i.hhea||!i.maxp||!i.post)return this.convert(e,new CFFFont(new Stream(i["CFF "].data),n),n);delete i.glyf;delete i.loca;delete i.fpgm;delete i.prep;delete i["cvt "];this.isOpenType=!0}if(!i.maxp)throw new FormatError('Required "maxp" table is not found');let l;if(!o)try{const e=new CFFParser(new Stream(i["CFF "].data),n,qa).parse();e.duplicateFirstGlyph();const t=new CFFCompiler(e);i["CFF "].data=t.compile();l=e.charStringCount}catch{warn("Failed to compile font "+n.loadedName)}t.pos=(t.start||0)+i.maxp.offset;let f=t.getInt32();const c=l??t.getUint16();if(20480===f&&6!==i.maxp.length){i.maxp.data=i.maxp.data.subarray(0,6);i.maxp.length=6}if(65536!==f&&20480!==f){if(6===i.maxp.length)f=20480;else{if(!(i.maxp.length>=32))throw new FormatError('"maxp" table has a wrong version number');f=65536}!function writeUint32(e,t,n){e[t+3]=255&n;e[t+2]=n>>>8;e[t+1]=n>>>16;e[t]=n>>>24}(i.maxp.data,0,f)}let h=int16(i.head.data[50],i.head.data[51]);if(i.loca){const e=h?4*(c+1):2*(c+1);if(i.loca.length!==e){warn("Incorrect 'loca' table length -- attempting to fix it.");const n=Object.values(i).filter(Boolean).sort((e,t)=>e.offset-t.offset),a=n.indexOf(i.loca),s=n[a+1]||null;if(s&&i.loca.offset+e<s.offset){const n=t.pos;t.pos=t.start||0;t.skip(i.loca.offset);i.loca.data=t.getBytes(e);i.loca.length=e;t.pos=n}}}if(n.scaleFactors?.length===c&&o){const{scaleFactors:e}=n,t=new GlyfTable({glyfTable:i.glyf.data,isGlyphLocationsLong:h,locaTable:i.loca.data,numGlyphs:c});t.scale(e);const{glyf:a,loca:s,isLocationLong:r}=t.write();i.glyf.data=a;i.loca.data=s;if(r!==!!h){i.head.data[50]=0;h=i.head.data[51]=r?1:0}const o=i.hmtx.data;for(let t=0;t<c;t++){const n=4*t,a=Math.round(e[t]*int16(o[n],o[n+1]));o[n]=a>>8&255;o[n+1]=255&a;writeSignedInt16(o,n+2,Math.round(e[t]*signedInt16(o[n+2],o[n+3])))}}let u=c+1,m=!0;if(u>65535){m=!1;u=c;warn("Not enough space in glyfs to duplicate first glyph.")}let p=0,d=0;if(f>=65536&&i.maxp.length>=32){t.pos+=8;if(t.getUint16()>2){i.maxp.data[14]=0;i.maxp.data[15]=2}t.pos+=4;p=t.getUint16();t.pos+=4;d=t.getUint16()}i.maxp.data[4]=u>>8;i.maxp.data[5]=255&u;const g=function sanitizeTTPrograms(e,t,n,a){const s={functionsDefined:[],functionsUsed:[],functionsStackDeltas:[],tooComplexToFollowFunctions:!1,hintsValid:!0};e&&sanitizeTTProgram(e,s);t&&sanitizeTTProgram(t,s);e&&function checkInvalidFunctions(e,t){if(!e.tooComplexToFollowFunctions)if(e.functionsDefined.length>t){warn("TT: more functions defined than expected");e.hintsValid=!1}else for(let n=0,a=e.functionsUsed.length;n<a;n++){if(n>t){warn("TT: invalid function id: "+n);e.hintsValid=!1;return}if(e.functionsUsed[n]&&!e.functionsDefined[n]){warn("TT: undefined function: "+n);e.hintsValid=!1;return}}}(s,a);if(n&&1&n.length){const e=new Uint8Array(n.length+1);e.set(n.data);n.data=e}return s.hintsValid}(i.fpgm,i.prep,i["cvt "],p);if(!g){delete i.fpgm;delete i.prep;delete i["cvt "]}!function sanitizeMetrics(e,t,n,a,s,r){if(!t){n&&(n.data=null);return}e.pos=(e.start||0)+t.offset;e.pos+=4;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;const i=e.getUint16();e.pos+=8;e.pos+=2;let o=e.getUint16();if(0!==i){if(!(2&int16(a.data[44],a.data[45]))){t.data[22]=0;t.data[23]=0}}if(o>s){info(`The numOfMetrics (${o}) should not be greater than the numGlyphs (${s}).`);o=s;t.data[34]=(65280&o)>>8;t.data[35]=255&o}const l=s-o-(n.length-4*o>>1);if(l>0){const e=new Uint8Array(n.length+2*l);e.set(n.data);if(r){e[n.length]=n.data[2];e[n.length+1]=n.data[3]}n.data=e}}(t,i.hhea,i.hmtx,i.head,u,m);if(!i.head)throw new FormatError('Required "head" table is not found');!function sanitizeHead(e,t,n){const a=e.data,s=function int32(e,t,n,a){return(e<<24)+(t<<16)+(n<<8)+a}(a[0],a[1],a[2],a[3]);if(s>>16!=1){info("Attempting to fix invalid version in head table: "+s);a[0]=0;a[1]=1;a[2]=0;a[3]=0}const r=int16(a[50],a[51]);if(r<0||r>1){info("Attempting to fix invalid indexToLocFormat in head table: "+r);const e=t+1;if(n===e<<1){a[50]=0;a[51]=0}else{if(n!==e<<2)throw new FormatError("Could not fix indexToLocFormat: "+r);a[50]=0;a[51]=1}}}(i.head,c,o?i.loca.length:0);let b=Object.create(null);if(o){const e=function sanitizeGlyphLocations(e,t,n,a,s,r,i){let o,l,f;if(a){o=4;l=function fontItemDecodeLong(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]};f=function fontItemEncodeLong(e,t,n){e[t]=n>>>24&255;e[t+1]=n>>16&255;e[t+2]=n>>8&255;e[t+3]=255&n}}else{o=2;l=function fontItemDecode(e,t){return e[t]<<9|e[t+1]<<1};f=function fontItemEncode(e,t,n){e[t]=n>>9&255;e[t+1]=n>>1&255}}const c=r?n+1:n,h=o*(1+c),u=new Uint8Array(h);u.set(e.data.subarray(0,h));e.data=u;const m=t.data,p=m.length,d=new Uint8Array(p);let g,b;const w=[];for(g=0,b=0;g<n+1;g++,b+=o){let e=l(u,b);e>p&&(e=p);w.push({index:g,offset:e,endOffset:0})}w.sort((e,t)=>e.offset-t.offset);for(g=0;g<n;g++)w[g].endOffset=w[g+1].offset;w.sort((e,t)=>e.index-t.index);for(g=0;g<n;g++){const{offset:e,endOffset:t}=w[g];if(0!==e||0!==t)break;const n=w[g+1].offset;if(0!==n){w[g].endOffset=n;break}}const j=w.at(-2);0!==j.offset&&0===j.endOffset&&(j.endOffset=p);const k=Object.create(null);let y=0;f(u,0,y);for(g=0,b=o;g<n;g++,b+=o){const e=sanitizeGlyph(m,w[g].offset,w[g].endOffset,d,y,s),t=e.length;0===t&&(k[g]=!0);e.sizeOfInstructions>i&&(i=e.sizeOfInstructions);y+=t;f(u,b,y)}if(0===y){const e=new Uint8Array([0,1,0,0,0,0,0,0,0,0,0,0,0,0,49,0]);for(g=0,b=o;g<c;g++,b+=o)f(u,b,e.length);t.data=e}else if(r){const n=l(u,o);if(d.length>n+y)t.data=d.subarray(0,n+y);else{t.data=new Uint8Array(n+y);t.data.set(d.subarray(0,y))}t.data.set(d.subarray(0,n),y);f(e.data,u.length-o,y+n)}else t.data=d.subarray(0,y);return{missingGlyphs:k,maxSizeOfInstructions:i}}(i.loca,i.glyf,c,h,g,m,d);b=e.missingGlyphs;if(f>=65536&&i.maxp.length>=32){i.maxp.data[26]=e.maxSizeOfInstructions>>8;i.maxp.data[27]=255&e.maxSizeOfInstructions}}if(!i.hhea)throw new FormatError('Required "hhea" table is not found');if(0===i.hhea.data[10]&&0===i.hhea.data[11]){i.hhea.data[10]=255;i.hhea.data[11]=255}const w={unitsPerEm:int16(i.head.data[18],i.head.data[19]),yMax:signedInt16(i.head.data[42],i.head.data[43]),yMin:signedInt16(i.head.data[38],i.head.data[39]),ascent:signedInt16(i.hhea.data[4],i.hhea.data[5]),descent:signedInt16(i.hhea.data[6],i.hhea.data[7]),lineGap:signedInt16(i.hhea.data[8],i.hhea.data[9])};this.ascent=w.ascent/w.unitsPerEm;this.descent=w.descent/w.unitsPerEm;this.lineGap=w.lineGap/w.unitsPerEm;if(this.cssFontInfo?.lineHeight){this.lineHeight=this.cssFontInfo.metrics.lineHeight;this.lineGap=this.cssFontInfo.metrics.lineGap}else this.lineHeight=this.ascent-this.descent+this.lineGap;i.post&&function readPostScriptTable(e,n,a){const s=(t.start||0)+e.offset;t.pos=s;const r=s+e.length,i=t.getInt32();t.skip(28);let o,l,f=!0;switch(i){case 65536:o=Ca;break;case 131072:const e=t.getUint16();if(e!==a){f=!1;break}const s=[];for(l=0;l<e;++l){const e=t.getUint16();if(e>=32768){f=!1;break}s.push(e)}if(!f)break;const c=[],h=[];for(;t.pos<r;){const e=t.getByte();h.length=e;for(l=0;l<e;++l)h[l]=String.fromCharCode(t.getByte());c.push(h.join(""))}o=[];for(l=0;l<e;++l){const e=s[l];e<258?o.push(Ca[e]):o.push(c[e-258])}break;case 196608:break;default:warn("Unknown/unsupported post table version "+i);f=!1;n.defaultEncoding&&(o=n.defaultEncoding)}n.glyphNames=o;return f}(i.post,n,c);i.post={tag:"post",data:createPostTable(n)};const j=Object.create(null);function hasGlyph(e){return!b[e]}if(n.composite){const e=n.cidToGidMap||[],t=0===e.length;n.cMap.forEach(function(n,a){"string"==typeof a&&(a=convertCidString(n,a,!0));if(a>65535)throw new FormatError("Max size of CID is 65,535");let s=-1;t?s=a:void 0!==e[a]&&(s=e[a]);s>=0&&s<c&&hasGlyph(s)&&(j[n]=s)})}else{const e=function readCmapTable(e,t,n,a){if(!e){warn("No cmap table available.");return{platformId:-1,encodingId:-1,mappings:[],hasShortCmap:!1}}let s,r=(t.start||0)+e.offset;t.pos=r;t.skip(2);const i=t.getUint16();let o,l=!1;for(let e=0;e<i;e++){const s=t.getUint16(),r=t.getUint16(),f=t.getInt32()>>>0;let c=!1;if(o?.platformId!==s||o?.encodingId!==r){if(0!==s||0!==r&&1!==r&&3!==r)if(1===s&&0===r)c=!0;else if(3!==s||1!==r||!a&&o){if(n&&3===s&&0===r){c=!0;let n=!0;if(e<i-1){const e=t.peekBytes(2);int16(e[0],e[1])<s&&(n=!1)}n&&(l=!0)}}else{c=!0;n||(l=!0)}else c=!0;c&&(o={platformId:s,encodingId:r,offset:f});if(l)break}}o&&(t.pos=r+o.offset);if(!o||-1===t.peekByte()){warn("Could not find a preferred cmap table.");return{platformId:-1,encodingId:-1,mappings:[],hasShortCmap:!1}}const f=t.getUint16();let c=!1;const h=[];let u,m;if(0===f){t.skip(4);for(u=0;u<256;u++){const e=t.getByte();e&&h.push({charCode:u,glyphId:e})}c=!0}else if(2===f){t.skip(4);const e=[];let n=0;for(let a=0;a<256;a++){const a=t.getUint16()>>3;e.push(a);n=Math.max(a,n)}const a=[];for(let e=0;e<=n;e++)a.push({firstCode:t.getUint16(),entryCount:t.getUint16(),idDelta:signedInt16(t.getByte(),t.getByte()),idRangePos:t.pos+t.getUint16()});for(let n=0;n<256;n++)if(0===e[n]){t.pos=a[0].idRangePos+2*n;m=t.getUint16();h.push({charCode:n,glyphId:m})}else{const s=a[e[n]];for(u=0;u<s.entryCount;u++){const e=(n<<8)+u+s.firstCode;t.pos=s.idRangePos+2*u;m=t.getUint16();0!==m&&(m=(m+s.idDelta)%65536);h.push({charCode:e,glyphId:m})}}}else if(4===f){t.skip(4);const e=t.getUint16()>>1;t.skip(6);const n=[];let a;for(a=0;a<e;a++)n.push({end:t.getUint16()});t.skip(2);for(a=0;a<e;a++)n[a].start=t.getUint16();for(a=0;a<e;a++)n[a].delta=t.getUint16();let i,o=0;for(a=0;a<e;a++){s=n[a];const r=t.getUint16();if(r){i=(r>>1)-(e-a);s.offsetIndex=i;o=Math.max(o,i+s.end-s.start+1)}else s.offsetIndex=-1}const l=[];for(u=0;u<o;u++)l.push(t.getUint16());for(a=0;a<e;a++){s=n[a];r=s.start;const e=s.end,t=s.delta;i=s.offsetIndex;for(u=r;u<=e;u++)if(65535!==u){m=i<0?u:l[i+u-r];m=m+t&65535;h.push({charCode:u,glyphId:m})}}}else if(6===f){t.skip(4);const e=t.getUint16(),n=t.getUint16();for(u=0;u<n;u++){m=t.getUint16();const n=e+u;h.push({charCode:n,glyphId:m})}}else{if(12!==f){warn("cmap table has unsupported format: "+f);return{platformId:-1,encodingId:-1,mappings:[],hasShortCmap:!1}}{t.skip(10);const e=t.getInt32()>>>0;for(u=0;u<e;u++){const e=t.getInt32()>>>0,n=t.getInt32()>>>0;let a=t.getInt32()>>>0;for(let t=e;t<=n;t++)h.push({charCode:t,glyphId:a++})}}}h.sort((e,t)=>e.charCode-t.charCode);const p=[],d=new Set;for(const e of h){const{charCode:t}=e;if(!d.has(t)){d.add(t);p.push(e)}}return{platformId:o.platformId,encodingId:o.encodingId,mappings:p,hasShortCmap:c}}(i.cmap,t,this.isSymbolicFont,n.hasEncoding),a=e.platformId,s=e.encodingId,r=e.mappings;let o=[],l=!1;!n.hasEncoding||"MacRomanEncoding"!==n.baseEncodingName&&"WinAnsiEncoding"!==n.baseEncodingName||(o=getEncoding(n.baseEncodingName));if(n.hasEncoding&&!this.isSymbolicFont&&(3===a&&1===s||1===a&&0===s)){const e=ga();for(let t=0;t<256;t++){let i;i=void 0!==this.differences[t]?this.differences[t]:o.length&&""!==o[t]?o[t]:ua[t];if(!i)continue;const l=recoverGlyphName(i,e);let f;3===a&&1===s?f=e[l]:1===a&&0===s&&(f=ha.indexOf(l));if(void 0===f){if(!n.glyphNames&&n.hasIncludedToUnicodeMap&&!(this.toUnicode instanceof IdentityToUnicodeMap)){const e=this.toUnicode.get(t);e&&(f=e.codePointAt(0))}if(void 0===f)continue}for(const e of r)if(e.charCode===f){j[t]=e.glyphId;break}}}else if(0===a){for(const e of r)j[e.charCode]=e.glyphId;l=!0}else if(3===a&&0===s)for(const e of r){let t=e.charCode;t>=61440&&t<=61695&&(t&=255);j[t]=e.glyphId}else for(const e of r)j[e.charCode]=e.glyphId;if(n.glyphNames&&(o.length||this.differences.length))for(let e=0;e<256;++e){if(!l&&void 0!==j[e])continue;const t=this.differences[e]||o[e];if(!t)continue;const a=n.glyphNames.indexOf(t);a>0&&hasGlyph(a)&&(j[e]=a)}}0===j.length&&(j[0]=0);let k=u-1;m||(k=0);if(!n.cssFontInfo){const e=adjustMapping(j,hasGlyph,k,this.toUnicode);this.toFontChar=e.toFontChar;i.cmap={tag:"cmap",data:createCmapTable(e.charCodeToGlyphId,e.toUnicodeExtraMap,u)};i["OS/2"]&&function validateOS2Table(e,t){t.pos=(t.start||0)+e.offset;const n=t.getUint16();t.skip(60);const a=t.getUint16();if(n<4&&768&a)return!1;if(t.getUint16()>t.getUint16())return!1;t.skip(6);if(0===t.getUint16())return!1;e.data[8]=e.data[9]=0;return!0}(i["OS/2"],t)||(i["OS/2"]={tag:"OS/2",data:createOS2Table(n,e.charCodeToGlyphId,w)})}if(i.name){const[t,a]=readNameTable(i.name);i.name.data=createNameTable(e,t);this.psName=t[0][6]||null;n.composite||function adjustTrueTypeToUnicode(e,t,n){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(e.hasEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;if(!t)return;if(0===n.length)return;if(e.defaultEncoding===ma)return;for(const e of n)if(!isWinNameRecord(e))return;const a=ma,s=[],r=ga();for(const e in a){const t=a[e];if(""===t)continue;const n=r[t];void 0!==n&&(s[e]=String.fromCharCode(n))}s.length>0&&e.toUnicode.amend(s)}(n,this.isSymbolicFont,a)}else i.name={tag:"name",data:createNameTable(this.name)};const y=new OpenTypeFileBuilder(r.version);for(const e in i)y.addTable(e,i[e].data);return y.toArray()}convert(e,n,a){a.fixedPitch=!1;a.builtInEncoding&&function adjustType1ToUnicode(e,t){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(t===e.defaultEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;const n=[],a=ga();for(const s in t){if(e.hasEncoding&&(e.baseEncodingName||void 0!==e.differences[s]))continue;const r=getUnicodeForGlyph(t[s],a);-1!==r&&(n[s]=String.fromCharCode(r))}n.length>0&&e.toUnicode.amend(n)}(a,a.builtInEncoding);let s=1;n instanceof CFFFont&&(s=n.numGlyphs-1);const r=n.getGlyphMapping(a);let i=null,o=r,l=null;if(!a.cssFontInfo){i=adjustMapping(r,n.hasGlyphId.bind(n),s,this.toUnicode);this.toFontChar=i.toFontChar;o=i.charCodeToGlyphId;l=i.toUnicodeExtraMap}const f=n.numGlyphs;function getCharCodes(e,t){let n=null;for(const a in e)t===e[a]&&(n||=[]).push(0|a);return n}function createCharCode(e,t){for(const n in e)if(t===e[n])return 0|n;i.charCodeToGlyphId[i.nextAvailableFontCharCode]=t;return i.nextAvailableFontCharCode++}const c=n.seacs;if(i&&c?.length){const e=a.fontMatrix||t,s=n.getCharset(),o=Object.create(null);for(let t in c){t|=0;const n=c[t],a=ua[n[2]],l=ua[n[3]],f=s.indexOf(a),h=s.indexOf(l);if(f<0||h<0)continue;const u={x:n[0]*e[0]+n[1]*e[2]+e[4],y:n[0]*e[1]+n[1]*e[3]+e[5]},m=getCharCodes(r,t);if(m)for(const e of m){const t=i.charCodeToGlyphId,n=createCharCode(t,f),a=createCharCode(t,h);o[e]={baseFontCharCode:n,accentFontCharCode:a,accentOffset:u}}}a.seacMap=o}const h=a.fontMatrix?1/Math.max(...a.fontMatrix.slice(0,4).map(Math.abs)):1e3,u=new OpenTypeFileBuilder("OTTO");u.addTable("CFF ",n.data);u.addTable("OS/2",createOS2Table(a,o));u.addTable("cmap",createCmapTable(o,l,f));u.addTable("head","\0\0\0\0\0\0\0\0\0\0_<õ\0\0"+safeString16(h)+"\0\0\0\0ž\v~'\0\0\0\0ž\v~'\0\0"+safeString16(a.descent)+"ÿ"+safeString16(a.ascent)+string16(a.italicAngle?2:0)+"\0\0\0\0\0\0\0");u.addTable("hhea","\0\0\0"+safeString16(a.ascent)+safeString16(a.descent)+"\0\0ÿÿ\0\0\0\0\0\0"+safeString16(a.capHeight)+safeString16(Math.tan(a.italicAngle)*a.xHeight)+"\0\0\0\0\0\0\0\0\0\0\0\0"+string16(f));u.addTable("hmtx",function fontFieldsHmtx(){const e=n.charstrings,t=n.cff?n.cff.widths:null;let a="\0\0\0\0";for(let n=1,s=f;n<s;n++){let s=0;if(e){const t=e[n-1];s="width"in t?t.width:0}else t&&(s=Math.ceil(t[n]||0));a+=string16(s)+string16(0)}return a}());u.addTable("maxp","\0\0P\0"+string16(f));u.addTable("name",createNameTable(e));u.addTable("post",createPostTable(a));return u.toArray()}get _spaceWidth(){const e=["space","minus","one","i","I"];let t;for(const n of e){if(n in this.widths){t=this.widths[n];break}const e=ga()[n];let a=0;if(this.composite&&this.cMap.contains(e)){a=this.cMap.lookup(e);"string"==typeof a&&(a=convertCidString(e,a))}!a&&this.toUnicode&&(a=this.toUnicode.charCodeOf(e));a<=0&&(a=e);t=this.widths[a];if(t)break}return shadow(this,"_spaceWidth",t||this.defaultWidth)}_charToGlyph(e,t=!1){let n,a,s,r=this._glyphCache[e];if(r?.isSpace===t)return r;let i=e;if(this.cMap?.contains(e)){i=this.cMap.lookup(e);"string"==typeof i&&(i=convertCidString(e,i))}a=this.widths[i];"number"!=typeof a&&(a=this.defaultWidth);const o=this.vmetrics?.[i];let l=this.toUnicode.get(e)||e;"number"==typeof l&&(l=String.fromCharCode(l));let f=void 0!==this.toFontChar[e];n=this.toFontChar[e]||e;if(this.missingFile){const t=this.differences[e]||this.defaultEncoding[e];if((".notdef"===t||""===t)&&"Type1"===this.type){n=32;if(""===t){a||=this._spaceWidth;l=String.fromCharCode(n)}}n=function mapSpecialUnicodeValues(e){return e>=65520&&e<=65535?0:e>=62976&&e<=63743?wa()[e]||e:173===e?45:e}(n)}this.isType3Font&&(s=n);let c=null;if(this.seacMap?.[e]){f=!0;const t=this.seacMap[e];n=t.baseFontCharCode;c={fontChar:String.fromCodePoint(t.accentFontCharCode),offset:t.accentOffset}}let h="";"number"==typeof n&&(n<=1114111?h=String.fromCodePoint(n):warn(`charToGlyph - invalid fontCharCode: ${n}`));if(this.missingFile&&this.vertical&&1===h.length){const e=Ia()[h.charCodeAt(0)];e&&(h=l=String.fromCharCode(e))}r=new fonts_Glyph(e,h,l,c,a,o,s,t,f);return this._glyphCache[e]=r}charsToGlyphs(e){let t=this._charsCache[e];if(t)return t;t=[];if(this.cMap){const n=Object.create(null),a=e.length;let s=0;for(;s<a;){this.cMap.readCharCode(e,s,n);const{charcode:a,length:r}=n;s+=r;const i=this._charToGlyph(a,1===r&&32===e.charCodeAt(s-1));t.push(i)}}else for(let n=0,a=e.length;n<a;++n){const a=e.charCodeAt(n),s=this._charToGlyph(a,32===a);t.push(s)}return this._charsCache[e]=t}getCharPositions(e){const t=[];if(this.cMap){const n=Object.create(null);let a=0;for(;a<e.length;){this.cMap.readCharCode(e,a,n);const s=n.length;t.push([a,a+s]);a+=s}}else for(let n=0,a=e.length;n<a;++n)t.push([n,n+1]);return t}get glyphCacheValues(){return Object.values(this._glyphCache)}encodeString(e){const t=[],n=[],hasCurrentBufErrors=()=>t.length%2==1,a=this.toUnicode instanceof IdentityToUnicodeMap?e=>this.toUnicode.charCodeOf(e):e=>this.toUnicode.charCodeOf(String.fromCodePoint(e));for(let s=0,r=e.length;s<r;s++){const r=e.codePointAt(s);r>55295&&(r<57344||r>65533)&&s++;if(this.toUnicode){const e=a(r);if(-1!==e){if(hasCurrentBufErrors()){t.push(n.join(""));n.length=0}for(let t=(this.cMap?this.cMap.getCharCodeLength(e):1)-1;t>=0;t--)n.push(String.fromCharCode(e>>8*t&255));continue}}if(!hasCurrentBufErrors()){t.push(n.join(""));n.length=0}n.push(String.fromCodePoint(r))}t.push(n.join(""));return t}}class ErrorFont{constructor(e){this.error=e;this.loadedName="g_font_error";this.missingFile=!0}charsToGlyphs(){return[]}encodeString(e){return[e]}exportData(){return{error:this.error}}}class CssFontInfo{#O;#X;#W;static strings=["fontFamily","fontWeight","italicAngle"];static write(e){const t=new TextEncoder,n={};let a=0;for(const s of CssFontInfo.strings){const r=t.encode(e[s]);n[s]=r;a+=4+r.length}const s=new ArrayBuffer(a),r=new Uint8Array(s),i=new DataView(s);let o=0;for(const e of CssFontInfo.strings){const t=n[e],a=t.length;i.setUint32(o,a);r.set(t,o+4);o+=4+a}assert(o===s.byteLength,"CssFontInfo.write: Buffer overflow");return s}constructor(e){this.#O=e;this.#X=new DataView(this.#O);this.#W=new TextDecoder}#K(e){assert(e<CssFontInfo.strings.length,"Invalid string index");let t=0;for(let n=0;n<e;n++)t+=this.#X.getUint32(t)+4;const n=this.#X.getUint32(t);return this.#W.decode(new Uint8Array(this.#O,t+4,n))}get fontFamily(){return this.#K(0)}get fontWeight(){return this.#K(1)}get italicAngle(){return this.#K(2)}}class SystemFontInfo{#O;#X;#W;static strings=["css","loadedName","baseFontName","src"];static write(e){const t=new TextEncoder,n={};let a=0;for(const s of SystemFontInfo.strings){const r=t.encode(e[s]);n[s]=r;a+=4+r.length}a+=4;let s,r,i=1+a;if(e.style){s=t.encode(e.style.style);r=t.encode(e.style.weight);i+=4+s.length+4+r.length}const o=new ArrayBuffer(i),l=new Uint8Array(o),f=new DataView(o);let c=0;f.setUint8(c++,e.guessFallback?1:0);f.setUint32(c,0);c+=4;a=0;for(const e of SystemFontInfo.strings){const t=n[e],s=t.length;a+=4+s;f.setUint32(c,s);l.set(t,c+4);c+=4+s}f.setUint32(c-a-4,a);if(e.style){f.setUint32(c,s.length);l.set(s,c+4);c+=4+s.length;f.setUint32(c,r.length);l.set(r,c+4);c+=4+r.length}assert(c<=o.byteLength,"SubstitionInfo.write: Buffer overflow");return o.transferToFixedLength(c)}constructor(e){this.#O=e;this.#X=new DataView(this.#O);this.#W=new TextDecoder}get guessFallback(){return 0!==this.#X.getUint8(0)}#K(e){assert(e<SystemFontInfo.strings.length,"Invalid string index");let t=5;for(let n=0;n<e;n++)t+=this.#X.getUint32(t)+4;const n=this.#X.getUint32(t);return this.#W.decode(new Uint8Array(this.#O,t+4,n))}get css(){return this.#K(0)}get loadedName(){return this.#K(1)}get baseFontName(){return this.#K(2)}get src(){return this.#K(3)}get style(){let e=1;e+=4+this.#X.getUint32(e);const t=this.#X.getUint32(e),n=this.#W.decode(new Uint8Array(this.#O,e+4,t));e+=4+t;const a=this.#X.getUint32(e);return{style:n,weight:this.#W.decode(new Uint8Array(this.#O,e+4,a))}}}class FontInfo{static bools=["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"];static numbers=["ascent","defaultWidth","descent"];static strings=["fallbackName","loadedName","mimetype","name"];static#G=Math.ceil(2*this.bools.length/8);static#V=this.#G+8*this.numbers.length;static#$=this.#V+1+8;static#Y=this.#$+1+48;static#J=this.#Y+1+6;#O;#W;#X;constructor({data:e,extra:t}){this.#O=e;this.#W=new TextDecoder;this.#X=new DataView(this.#O);t&&Object.assign(this,t)}#Q(e){assert(e<FontInfo.bools.length,"Invalid boolean index");const t=Math.floor(e/4),n=2*e%8,a=this.#X.getUint8(t)>>n&3;return 0===a?void 0:2===a}get black(){return this.#Q(0)}get bold(){return this.#Q(1)}get disableFontFace(){return this.#Q(2)}get fontExtraProperties(){return this.#Q(3)}get isInvalidPDFjsFont(){return this.#Q(4)}get isType3Font(){return this.#Q(5)}get italic(){return this.#Q(6)}get missingFile(){return this.#Q(7)}get remeasure(){return this.#Q(8)}get vertical(){return this.#Q(9)}#Z(e){assert(e<FontInfo.numbers.length,"Invalid number index");return this.#X.getFloat64(FontInfo.#G+8*e)}get ascent(){return this.#Z(0)}get defaultWidth(){return this.#Z(1)}get descent(){return this.#Z(2)}get bbox(){let e=FontInfo.#V;if(0===this.#X.getUint8(e))return;e+=1;const t=[];for(let n=0;n<4;n++){t.push(this.#X.getInt16(e,!0));e+=2}return t}get fontMatrix(){let e=FontInfo.#$;if(0===this.#X.getUint8(e))return;e+=1;const t=[];for(let n=0;n<6;n++){t.push(this.#X.getFloat64(e,!0));e+=8}return t}get defaultVMetrics(){let e=FontInfo.#Y;if(0===this.#X.getUint8(e))return;e+=1;const t=[];for(let n=0;n<3;n++){t.push(this.#X.getInt16(e,!0));e+=2}return t}#K(e){assert(e<FontInfo.strings.length,"Invalid string index");let t=FontInfo.#J+4;for(let n=0;n<e;n++)t+=this.#X.getUint32(t)+4;const n=this.#X.getUint32(t),a=new Uint8Array(n);a.set(new Uint8Array(this.#O,t+4,n));return this.#W.decode(a)}get fallbackName(){return this.#K(0)}get loadedName(){return this.#K(1)}get mimetype(){return this.#K(2)}get name(){return this.#K(3)}get data(){let e=FontInfo.#J;e+=4+this.#X.getUint32(e);e+=4+this.#X.getUint32(e);e+=4+this.#X.getUint32(e);const t=this.#X.getUint32(e);if(0!==t)return new Uint8Array(this.#O,e+4,t)}clearData(){let e=FontInfo.#J;e+=4+this.#X.getUint32(e);e+=4+this.#X.getUint32(e);e+=4+this.#X.getUint32(e);const t=this.#X.getUint32(e);new Uint8Array(this.#O,e+4,t).fill(0);this.#X.setUint32(e,0)}get cssFontInfo(){let e=FontInfo.#J;e+=4+this.#X.getUint32(e);e+=4+this.#X.getUint32(e);const t=this.#X.getUint32(e);if(0===t)return null;const n=new Uint8Array(t);n.set(new Uint8Array(this.#O,e+4,t));return new CssFontInfo(n.buffer)}get systemFontInfo(){let e=FontInfo.#J;e+=4+this.#X.getUint32(e);const t=this.#X.getUint32(e);if(0===t)return null;const n=new Uint8Array(t);n.set(new Uint8Array(this.#O,e+4,t));return new SystemFontInfo(n.buffer)}static write(e){const t=e.systemFontInfo?SystemFontInfo.write(e.systemFontInfo):null,n=e.cssFontInfo?CssFontInfo.write(e.cssFontInfo):null,a=new TextEncoder,s={};let r=0;for(const t of FontInfo.strings){s[t]=a.encode(e[t]);r+=4+s[t].length}const i=FontInfo.#J+4+r+4+(t?t.byteLength:0)+4+(n?n.byteLength:0)+4+(e.data?e.data.length:0),o=new ArrayBuffer(i),l=new Uint8Array(o),f=new DataView(o);let c=0;const h=FontInfo.bools.length;let u=0,m=0;for(let t=0;t<h;t++){const n=e[FontInfo.bools[t]];u|=(void 0===n?0:n?2:1)<<m;m+=2;if(8===m||t===h-1){f.setUint8(c++,u);u=0;m=0}}assert(c===FontInfo.#G,"FontInfo.write: Boolean properties offset mismatch");for(const t of FontInfo.numbers){f.setFloat64(c,e[t]);c+=8}assert(c===FontInfo.#V,"FontInfo.write: Number properties offset mismatch");if(e.bbox){f.setUint8(c++,4);for(const t of e.bbox){f.setInt16(c,t,!0);c+=2}}else{f.setUint8(c++,0);c+=8}assert(c===FontInfo.#$,"FontInfo.write: BBox properties offset mismatch");if(e.fontMatrix){f.setUint8(c++,6);for(const t of e.fontMatrix){f.setFloat64(c,t,!0);c+=8}}else{f.setUint8(c++,0);c+=48}assert(c===FontInfo.#Y,"FontInfo.write: FontMatrix properties offset mismatch");if(e.defaultVMetrics){f.setUint8(c++,1);for(const t of e.defaultVMetrics){f.setInt16(c,t,!0);c+=2}}else{f.setUint8(c++,0);c+=6}assert(c===FontInfo.#J,"FontInfo.write: DefaultVMetrics properties offset mismatch");f.setUint32(FontInfo.#J,0);c+=4;for(const e of FontInfo.strings){const t=s[e],n=t.length;f.setUint32(c,n);l.set(t,c+4);c+=4+n}f.setUint32(FontInfo.#J,c-FontInfo.#J-4);if(t){const e=t.byteLength;f.setUint32(c,e);assert(c+4+e<=o.byteLength,"FontInfo.write: Buffer overflow at systemFontInfo");l.set(new Uint8Array(t),c+4);c+=4+e}else{f.setUint32(c,0);c+=4}if(n){const e=n.byteLength;f.setUint32(c,e);assert(c+4+e<=o.byteLength,"FontInfo.write: Buffer overflow at cssFontInfo");l.set(new Uint8Array(n),c+4);c+=4+e}else{f.setUint32(c,0);c+=4}if(void 0===e.data){f.setUint32(c,0);c+=4}else{f.setUint32(c,e.data.length);l.set(e.data,c+4);c+=4+e.data.length}assert(c<=o.byteLength,"FontInfo.write: Buffer overflow");return o.transferToFixedLength(c)}}class PatternInfo{static#ee=0;static#te=1;static#ne=2;static#ae=3;static#se=4;static#re=8;static#ie=12;static#oe=16;constructor(e){this.buffer=e;this.view=new DataView(e);this.data=new Uint8Array(e)}static write(e){let t,n=null,a=[],s=[],r=[],i=[],o=null,l=null;switch(e[0]){case"RadialAxial":t="axial"===e[1]?1:2;n=e[2];r=e[3];1===t?a.push(...e[4],...e[5]):a.push(e[4][0],e[4][1],e[6],e[5][0],e[5][1],e[7]);break;case"Mesh":t=3;o=e[1];a=e[2];s=e[3];i=e[4]||[];n=e[6];l=e[7];break;default:throw new Error(`Unsupported pattern type: ${e[0]}`)}const f=Math.floor(a.length/2),c=Math.floor(s.length/3),h=r.length,u=i.length;let m=0;for(const e of i){m+=1;m=4*Math.ceil(m/4);m+=4+4*e.coords.length;m+=4+4*e.colors.length;void 0!==e.verticesPerRow&&(m+=4)}const p=new ArrayBuffer(20+8*f+3*c+8*h+(n?16:0)+(l?3:0)+m),d=new DataView(p),g=new Uint8Array(p);d.setUint8(PatternInfo.#ee,t);d.setUint8(PatternInfo.#te,n?1:0);d.setUint8(PatternInfo.#ne,l?1:0);d.setUint8(PatternInfo.#ae,o);d.setUint32(PatternInfo.#se,f,!0);d.setUint32(PatternInfo.#re,c,!0);d.setUint32(PatternInfo.#ie,h,!0);d.setUint32(PatternInfo.#oe,u,!0);let b=20;new Float32Array(p,b,2*f).set(a);b+=8*f;g.set(s,b);b+=3*c;for(const[e,t]of r){d.setFloat32(b,e,!0);b+=4;d.setUint32(b,parseInt(t.slice(1),16),!0);b+=4}if(n)for(const e of n){d.setFloat32(b,e,!0);b+=4}if(l){g.set(l,b);b+=3}for(let e=0;e<i.length;e++){const t=i[e];d.setUint8(b,t.type);b+=1;b=4*Math.ceil(b/4);d.setUint32(b,t.coords.length,!0);b+=4;new Int32Array(p,b,t.coords.length).set(t.coords);b+=4*t.coords.length;d.setUint32(b,t.colors.length,!0);b+=4;new Int32Array(p,b,t.colors.length).set(t.colors);b+=4*t.colors.length;if(void 0!==t.verticesPerRow){d.setUint32(b,t.verticesPerRow,!0);b+=4}}return p}getIR(){const e=this.view,t=this.data[PatternInfo.#ee],n=!!this.data[PatternInfo.#te],a=!!this.data[PatternInfo.#ne],s=e.getUint32(PatternInfo.#se,!0),r=e.getUint32(PatternInfo.#re,!0),i=e.getUint32(PatternInfo.#ie,!0),o=e.getUint32(PatternInfo.#oe,!0);let l=20;const f=new Float32Array(this.buffer,l,2*s);l+=8*s;const c=new Uint8Array(this.buffer,l,3*r);l+=3*r;const h=[];for(let t=0;t<i;++t){const t=e.getFloat32(l,!0);l+=4;const n=e.getUint32(l,!0);l+=4;h.push([t,`#${n.toString(16).padStart(6,"0")}`])}let u=null;if(n){u=[];for(let t=0;t<4;++t){u.push(e.getFloat32(l,!0));l+=4}}let m=null;if(a){m=new Uint8Array(this.buffer,l,3);l+=3}const p=[];for(let t=0;t<o;++t){const t=e.getUint8(l);l+=1;l=4*Math.ceil(l/4);const n=e.getUint32(l,!0);l+=4;const a=new Int32Array(this.buffer,l,n);l+=4*n;const s=e.getUint32(l,!0);l+=4;const r=new Int32Array(this.buffer,l,s);l+=4*s;const i={type:t,coords:a,colors:r};if(t===y){i.verticesPerRow=e.getUint32(l,!0);l+=4}p.push(i)}if(1===t)return["RadialAxial","axial",u,h,Array.from(f.slice(0,2)),Array.from(f.slice(2,4)),null,null];if(2===t)return["RadialAxial","radial",u,h,[f[0],f[1]],[f[3],f[4]],f[2],f[5]];if(3===t){const e=this.data[PatternInfo.#ae];let t=null;if(f.length>0){let e=f[0],n=f[0],a=f[1],s=f[1];for(let t=0;t<f.length;t+=2){const r=f[t],i=f[t+1];e=e>r?r:e;a=a>i?i:a;n=n<r?r:n;s=s<i?i:s}t=[e,a,n,s]}return["Mesh",e,f,c,p,t,u,m]}throw new Error(`Unsupported pattern kind: ${t}`)}}class FontPathInfo{static write(e){let t,n;if(FeatureTest.isFloat16ArraySupported){n=new ArrayBuffer(2*e.length);t=new Float16Array(n)}else{n=new ArrayBuffer(4*e.length);t=new Float32Array(n)}t.set(e);return n}#O;constructor(e){this.#O=e}get path(){return FeatureTest.isFloat16ArraySupported?new Float16Array(this.#O):new Float32Array(this.#O)}}const cs=2,hs=3,us=4,ms=5,ps=6,ds=7;class Pattern{constructor(){unreachable("Cannot initialize Pattern.")}static parseShading(e,t,n,a,s,r){const i=e instanceof BaseStream?e.dict:e,o=i.get("ShadingType");try{switch(o){case cs:case hs:return new RadialAxialShading(i,t,n,a,s,r);case us:case ms:case ps:case ds:return new MeshShading(e,t,n,a,s,r);default:throw new FormatError("Unsupported ShadingType: "+o)}}catch(e){if(e instanceof MissingDataException)throw e;warn(e);return new DummyShading}}}class BaseShading{static SMALL_NUMBER=1e-6;getIR(){unreachable("Abstract method `getIR` called.")}}class RadialAxialShading extends BaseShading{constructor(e,t,n,a,s,r){super();this.shadingType=e.get("ShadingType");let i=0;this.shadingType===cs?i=4:this.shadingType===hs&&(i=6);this.coordsArr=e.getArray("Coords");if(!isNumberArray(this.coordsArr,i))throw new FormatError("RadialAxialShading: Invalid /Coords array.");const o=ColorSpaceUtils.parse({cs:e.getRaw("CS")||e.getRaw("ColorSpace"),xref:t,resources:n,pdfFunctionFactory:a,globalColorSpaceCache:s,localColorSpaceCache:r});this.bbox=lookupNormalRect(e.getArray("BBox"),null);let l=0,f=1;const c=e.getArray("Domain");isNumberArray(c,2)&&([l,f]=c);let h=!1,u=!1;const m=e.getArray("Extend");(function isBooleanArray(e,t){return Array.isArray(e)&&(null===t||e.length===t)&&e.every(e=>"boolean"==typeof e)})(m,2)&&([h,u]=m);if(!(this.shadingType!==hs||h&&u)){const[e,t,n,a,s,r]=this.coordsArr,i=Math.hypot(e-a,t-s);n<=r+i&&r<=n+i&&warn("Unsupported radial gradient.")}this.extendStart=h;this.extendEnd=u;const p=e.getRaw("Function"),d=a.create(p,!0),g=(f-l)/840,b=this.colorStops=[];if(l>=f||g<=0){info("Bad shading domain.");return}const w=new Float32Array(o.numComps),j=new Float32Array(1);let k=0;j[0]=l;d(j,0,w,0);const y=new Uint8ClampedArray(3);o.getRgb(w,0,y);let[q,v,S]=y;b.push([0,Util.makeHexColor(q,v,S)]);let x=1;j[0]=l+g;d(j,0,w,0);o.getRgb(w,0,y);let[C,F,T]=y,H=C-q+1,O=F-v+1,R=T-S+1,D=C-q-1,M=F-v-1,E=T-S-1;for(let e=2;e<840;e++){j[0]=l+e*g;d(j,0,w,0);o.getRgb(w,0,y);const[t,n,a]=y,s=e-k;H=Math.min(H,(t-q+1)/s);O=Math.min(O,(n-v+1)/s);R=Math.min(R,(a-S+1)/s);D=Math.max(D,(t-q-1)/s);M=Math.max(M,(n-v-1)/s);E=Math.max(E,(a-S-1)/s);if(!(D<=H&&M<=O&&E<=R)){const e=Util.makeHexColor(C,F,T);b.push([x/840,e]);H=t-C+1;O=n-F+1;R=a-T+1;D=t-C-1;M=n-F-1;E=a-T-1;k=x;q=C;v=F;S=T}x=e;C=t;F=n;T=a}b.push([1,Util.makeHexColor(C,F,T)]);let N="transparent";e.has("Background")&&(N=o.getRgbHex(e.get("Background"),0));if(!h){b.unshift([0,N]);b[1][0]+=BaseShading.SMALL_NUMBER}if(!u){b.at(-1)[0]-=BaseShading.SMALL_NUMBER;b.push([1,N])}this.colorStops=b}getIR(){const{coordsArr:e,shadingType:t}=this;let n,a,s,r,i;if(t===cs){a=[e[0],e[1]];s=[e[2],e[3]];r=null;i=null;n="axial"}else if(t===hs){a=[e[0],e[1]];s=[e[3],e[4]];r=e[2];i=e[5];n="radial"}else unreachable(`getPattern type unknown: ${t}`);return["RadialAxial",n,this.bbox,this.colorStops,a,s,r,i]}}class MeshStreamReader{constructor(e,t){this.stream=e;this.context=t;this.buffer=0;this.bufferLength=0;const n=t.numComps;this.tmpCompsBuf=new Float32Array(n);const a=t.colorSpace.numComps;this.tmpCsCompsBuf=t.colorFn?new Float32Array(a):this.tmpCompsBuf}get hasData(){if(this.stream.end)return this.stream.pos<this.stream.end;if(this.bufferLength>0)return!0;const e=this.stream.getByte();if(e<0)return!1;this.buffer=e;this.bufferLength=8;return!0}readBits(e){const{stream:t}=this;let{buffer:n,bufferLength:a}=this;if(32===e){if(0===a)return t.getInt32()>>>0;n=n<<24|t.getByte()<<16|t.getByte()<<8|t.getByte();const e=t.getByte();this.buffer=e&(1<<a)-1;return(n<<8-a|(255&e)>>a)>>>0}if(8===e&&0===a)return t.getByte();for(;a<e;){n=n<<8|t.getByte();a+=8}a-=e;this.bufferLength=a;this.buffer=n&(1<<a)-1;return n>>a}align(){this.buffer=0;this.bufferLength=0}readFlag(){return this.readBits(this.context.bitsPerFlag)}readCoordinate(){const{bitsPerCoordinate:e,decode:t}=this.context,n=this.readBits(e),a=this.readBits(e),s=e<32?1/((1<<e)-1):2.3283064365386963e-10;return[n*s*(t[1]-t[0])+t[0],a*s*(t[3]-t[2])+t[2]]}readComponents(){const{bitsPerComponent:e,colorFn:t,colorSpace:n,decode:a,numComps:s}=this.context,r=e<32?1/((1<<e)-1):2.3283064365386963e-10,i=this.tmpCompsBuf;for(let t=0,n=4;t<s;t++,n+=2){const s=this.readBits(e);i[t]=s*r*(a[n+1]-a[n])+a[n]}const o=this.tmpCsCompsBuf;t?.(i,0,o,0);return n.getRgb(o,0)}}let gs=Object.create(null);function getB(e){return gs[e]||=function buildB(e){const t=[];for(let n=0;n<=e;n++){const a=n/e,s=1-a;t.push(new Float32Array([s**3,3*a*s**2,3*a**2*s,a**3]))}return t}(e)}class MeshShading extends BaseShading{static MIN_SPLIT_PATCH_CHUNKS_AMOUNT=3;static MAX_SPLIT_PATCH_CHUNKS_AMOUNT=20;static TRIANGLE_DENSITY=20;constructor(e,t,n,a,s,r){super();if(!(e instanceof BaseStream))throw new FormatError("Mesh data is not a stream");const i=e.dict;this.shadingType=i.get("ShadingType");this.bbox=lookupNormalRect(i.getArray("BBox"),null);const o=ColorSpaceUtils.parse({cs:i.getRaw("CS")||i.getRaw("ColorSpace"),xref:t,resources:n,pdfFunctionFactory:a,globalColorSpaceCache:s,localColorSpaceCache:r});this.background=i.has("Background")?o.getRgb(i.get("Background"),0):null;const l=i.getRaw("Function"),f=l?a.create(l,!0):null;this.coords=[];this.colors=[];this.figures=[];const c={bitsPerCoordinate:i.get("BitsPerCoordinate"),bitsPerComponent:i.get("BitsPerComponent"),bitsPerFlag:i.get("BitsPerFlag"),decode:i.getArray("Decode"),colorFn:f,colorSpace:o,numComps:f?1:o.numComps},h=new MeshStreamReader(e,c);let u=!1;switch(this.shadingType){case us:this._decodeType4Shading(h);break;case ms:const e=0|i.get("VerticesPerRow");if(e<2)throw new FormatError("Invalid VerticesPerRow");this._decodeType5Shading(h,e);break;case ps:this._decodeType6Shading(h);u=!0;break;case ds:this._decodeType7Shading(h);u=!0;break;default:unreachable("Unsupported mesh type.")}if(u){this._updateBounds();for(let e=0,t=this.figures.length;e<t;e++)this._buildFigureFromPatch(e)}this._updateBounds();this._packData()}_decodeType4Shading(e){const t=this.coords,n=this.colors,a=[],s=[];let r=0;for(;e.hasData;){const i=e.readFlag(),o=e.readCoordinate(),l=e.readComponents();if(0===r){if(!(0<=i&&i<=2))throw new FormatError("Unknown type4 flag");switch(i){case 0:r=3;break;case 1:s.push(s.at(-2),s.at(-1));r=1;break;case 2:s.push(s.at(-3),s.at(-1));r=1}a.push(i)}s.push(t.length);t.push(o);n.push(l);r--;e.align()}this.figures.push({type:k,coords:new Int32Array(s),colors:new Int32Array(s)})}_decodeType5Shading(e,t){const n=this.coords,a=this.colors,s=[];for(;e.hasData;){const t=e.readCoordinate(),r=e.readComponents();s.push(n.length);n.push(t);a.push(r)}this.figures.push({type:y,coords:new Int32Array(s),colors:new Int32Array(s),verticesPerRow:t})}_decodeType6Shading(e){const t=this.coords,n=this.colors,a=new Int32Array(16),s=new Int32Array(4);for(;e.hasData;){const r=e.readFlag();if(!(0<=r&&r<=3))throw new FormatError("Unknown type6 flag");const i=t.length;for(let n=0,a=0!==r?8:12;n<a;n++)t.push(e.readCoordinate());const o=n.length;for(let t=0,a=0!==r?2:4;t<a;t++)n.push(e.readComponents());let l,f,c,h;switch(r){case 0:a[12]=i+3;a[13]=i+4;a[14]=i+5;a[15]=i+6;a[8]=i+2;a[11]=i+7;a[4]=i+1;a[7]=i+8;a[0]=i;a[1]=i+11;a[2]=i+10;a[3]=i+9;s[2]=o+1;s[3]=o+2;s[0]=o;s[1]=o+3;break;case 1:l=a[12];f=a[13];c=a[14];h=a[15];a[12]=h;a[13]=i+0;a[14]=i+1;a[15]=i+2;a[8]=c;a[11]=i+3;a[4]=f;a[7]=i+4;a[0]=l;a[1]=i+7;a[2]=i+6;a[3]=i+5;l=s[2];f=s[3];s[2]=f;s[3]=o;s[0]=l;s[1]=o+1;break;case 2:l=a[15];f=a[11];a[12]=a[3];a[13]=i+0;a[14]=i+1;a[15]=i+2;a[8]=a[7];a[11]=i+3;a[4]=f;a[7]=i+4;a[0]=l;a[1]=i+7;a[2]=i+6;a[3]=i+5;l=s[3];s[2]=s[1];s[3]=o;s[0]=l;s[1]=o+1;break;case 3:a[12]=a[0];a[13]=i+0;a[14]=i+1;a[15]=i+2;a[8]=a[1];a[11]=i+3;a[4]=a[2];a[7]=i+4;a[0]=a[3];a[1]=i+7;a[2]=i+6;a[3]=i+5;s[2]=s[0];s[3]=o;s[0]=s[1];s[1]=o+1}a[5]=t.length;t.push([(-4*t[a[0]][0]-t[a[15]][0]+6*(t[a[4]][0]+t[a[1]][0])-2*(t[a[12]][0]+t[a[3]][0])+3*(t[a[13]][0]+t[a[7]][0]))/9,(-4*t[a[0]][1]-t[a[15]][1]+6*(t[a[4]][1]+t[a[1]][1])-2*(t[a[12]][1]+t[a[3]][1])+3*(t[a[13]][1]+t[a[7]][1]))/9]);a[6]=t.length;t.push([(-4*t[a[3]][0]-t[a[12]][0]+6*(t[a[2]][0]+t[a[7]][0])-2*(t[a[0]][0]+t[a[15]][0])+3*(t[a[4]][0]+t[a[14]][0]))/9,(-4*t[a[3]][1]-t[a[12]][1]+6*(t[a[2]][1]+t[a[7]][1])-2*(t[a[0]][1]+t[a[15]][1])+3*(t[a[4]][1]+t[a[14]][1]))/9]);a[9]=t.length;t.push([(-4*t[a[12]][0]-t[a[3]][0]+6*(t[a[8]][0]+t[a[13]][0])-2*(t[a[0]][0]+t[a[15]][0])+3*(t[a[11]][0]+t[a[1]][0]))/9,(-4*t[a[12]][1]-t[a[3]][1]+6*(t[a[8]][1]+t[a[13]][1])-2*(t[a[0]][1]+t[a[15]][1])+3*(t[a[11]][1]+t[a[1]][1]))/9]);a[10]=t.length;t.push([(-4*t[a[15]][0]-t[a[0]][0]+6*(t[a[11]][0]+t[a[14]][0])-2*(t[a[12]][0]+t[a[3]][0])+3*(t[a[2]][0]+t[a[8]][0]))/9,(-4*t[a[15]][1]-t[a[0]][1]+6*(t[a[11]][1]+t[a[14]][1])-2*(t[a[12]][1]+t[a[3]][1])+3*(t[a[2]][1]+t[a[8]][1]))/9]);this.figures.push({type:q,coords:new Int32Array(a),colors:new Int32Array(s)})}}_decodeType7Shading(e){const t=this.coords,n=this.colors,a=new Int32Array(16),s=new Int32Array(4);for(;e.hasData;){const r=e.readFlag();if(!(0<=r&&r<=3))throw new FormatError("Unknown type7 flag");const i=t.length;for(let n=0,a=0!==r?12:16;n<a;n++)t.push(e.readCoordinate());const o=n.length;for(let t=0,a=0!==r?2:4;t<a;t++)n.push(e.readComponents());let l,f,c,h;switch(r){case 0:a[12]=i+3;a[13]=i+4;a[14]=i+5;a[15]=i+6;a[8]=i+2;a[9]=i+13;a[10]=i+14;a[11]=i+7;a[4]=i+1;a[5]=i+12;a[6]=i+15;a[7]=i+8;a[0]=i;a[1]=i+11;a[2]=i+10;a[3]=i+9;s[2]=o+1;s[3]=o+2;s[0]=o;s[1]=o+3;break;case 1:l=a[12];f=a[13];c=a[14];h=a[15];a[12]=h;a[13]=i+0;a[14]=i+1;a[15]=i+2;a[8]=c;a[9]=i+9;a[10]=i+10;a[11]=i+3;a[4]=f;a[5]=i+8;a[6]=i+11;a[7]=i+4;a[0]=l;a[1]=i+7;a[2]=i+6;a[3]=i+5;l=s[2];f=s[3];s[2]=f;s[3]=o;s[0]=l;s[1]=o+1;break;case 2:l=a[15];f=a[11];a[12]=a[3];a[13]=i+0;a[14]=i+1;a[15]=i+2;a[8]=a[7];a[9]=i+9;a[10]=i+10;a[11]=i+3;a[4]=f;a[5]=i+8;a[6]=i+11;a[7]=i+4;a[0]=l;a[1]=i+7;a[2]=i+6;a[3]=i+5;l=s[3];s[2]=s[1];s[3]=o;s[0]=l;s[1]=o+1;break;case 3:a[12]=a[0];a[13]=i+0;a[14]=i+1;a[15]=i+2;a[8]=a[1];a[9]=i+9;a[10]=i+10;a[11]=i+3;a[4]=a[2];a[5]=i+8;a[6]=i+11;a[7]=i+4;a[0]=a[3];a[1]=i+7;a[2]=i+6;a[3]=i+5;s[2]=s[0];s[3]=o;s[0]=s[1];s[1]=o+1}this.figures.push({type:q,coords:new Int32Array(a),colors:new Int32Array(s)})}}_buildFigureFromPatch(e){const t=this.figures[e];assert(t.type===q,"Unexpected patch mesh figure");const n=this.coords,a=this.colors,s=t.coords,r=t.colors,i=Math.min(n[s[0]][0],n[s[3]][0],n[s[12]][0],n[s[15]][0]),o=Math.min(n[s[0]][1],n[s[3]][1],n[s[12]][1],n[s[15]][1]),l=Math.max(n[s[0]][0],n[s[3]][0],n[s[12]][0],n[s[15]][0]),f=Math.max(n[s[0]][1],n[s[3]][1],n[s[12]][1],n[s[15]][1]);let c=Math.ceil((l-i)*MeshShading.TRIANGLE_DENSITY/(this.bounds[2]-this.bounds[0]));c=MathClamp(c,MeshShading.MIN_SPLIT_PATCH_CHUNKS_AMOUNT,MeshShading.MAX_SPLIT_PATCH_CHUNKS_AMOUNT);let h=Math.ceil((f-o)*MeshShading.TRIANGLE_DENSITY/(this.bounds[3]-this.bounds[1]));h=MathClamp(h,MeshShading.MIN_SPLIT_PATCH_CHUNKS_AMOUNT,MeshShading.MAX_SPLIT_PATCH_CHUNKS_AMOUNT);const u=c+1,m=new Int32Array((h+1)*u),p=new Int32Array((h+1)*u);let d=0;const g=new Uint8Array(3),b=new Uint8Array(3),w=a[r[0]],j=a[r[1]],k=a[r[2]],v=a[r[3]],S=getB(h),x=getB(c);for(let e=0;e<=h;e++){g[0]=(w[0]*(h-e)+k[0]*e)/h|0;g[1]=(w[1]*(h-e)+k[1]*e)/h|0;g[2]=(w[2]*(h-e)+k[2]*e)/h|0;b[0]=(j[0]*(h-e)+v[0]*e)/h|0;b[1]=(j[1]*(h-e)+v[1]*e)/h|0;b[2]=(j[2]*(h-e)+v[2]*e)/h|0;for(let t=0;t<=c;t++,d++){if(!(0!==e&&e!==h||0!==t&&t!==c))continue;let r=0,i=0,o=0;for(let a=0;a<=3;a++)for(let l=0;l<=3;l++,o++){const f=S[e][a]*x[t][l];r+=n[s[o]][0]*f;i+=n[s[o]][1]*f}m[d]=n.length;n.push([r,i]);p[d]=a.length;const l=new Uint8Array(3);l[0]=(g[0]*(c-t)+b[0]*t)/c|0;l[1]=(g[1]*(c-t)+b[1]*t)/c|0;l[2]=(g[2]*(c-t)+b[2]*t)/c|0;a.push(l)}}m[0]=s[0];p[0]=r[0];m[c]=s[3];p[c]=r[1];m[u*h]=s[12];p[u*h]=r[2];m[u*h+c]=s[15];p[u*h+c]=r[3];this.figures[e]={type:y,coords:m,colors:p,verticesPerRow:u}}_updateBounds(){let e=this.coords[0][0],t=this.coords[0][1],n=e,a=t;for(let s=1,r=this.coords.length;s<r;s++){const r=this.coords[s][0],i=this.coords[s][1];e=e>r?r:e;t=t>i?i:t;n=n<r?r:n;a=a<i?i:a}this.bounds=[e,t,n,a]}_packData(){let e,t,n,a;const s=this.coords,r=new Float32Array(2*s.length);for(e=0,n=0,t=s.length;e<t;e++){const t=s[e];r[n++]=t[0];r[n++]=t[1]}this.coords=r;const i=this.colors,o=new Uint8Array(3*i.length);for(e=0,n=0,t=i.length;e<t;e++){const t=i[e];o[n++]=t[0];o[n++]=t[1];o[n++]=t[2]}this.colors=o;const l=this.figures;for(e=0,t=l.length;e<t;e++){const t=l[e],s=t.coords,r=t.colors;for(n=0,a=s.length;n<a;n++){s[n]*=2;r[n]*=3}}}getIR(){const{bounds:e}=this;if(e[2]-e[0]===0||e[3]-e[1]===0)throw new FormatError(`Invalid MeshShading bounds: [${e}].`);return["Mesh",this.shadingType,this.coords,this.colors,this.figures,e,this.bbox,this.background]}}class DummyShading extends BaseShading{getIR(){return["Dummy"]}}function getTilingPatternIR(e,t,n){const a=lookupMatrix(t.getArray("Matrix"),pn),s=lookupNormalRect(t.getArray("BBox"),null);if(!s||s[2]-s[0]===0||s[3]-s[1]===0)throw new FormatError("Invalid getTilingPatternIR /BBox array.");const r=t.get("XStep");if("number"!=typeof r)throw new FormatError("Invalid getTilingPatternIR /XStep value.");const i=t.get("YStep");if("number"!=typeof i)throw new FormatError("Invalid getTilingPatternIR /YStep value.");const o=t.get("PaintType");if(!Number.isInteger(o))throw new FormatError("Invalid getTilingPatternIR /PaintType value.");const l=t.get("TilingType");if(!Number.isInteger(l))throw new FormatError("Invalid getTilingPatternIR /TilingType value.");return["TilingPattern",n,e,a,s,r,i,o,l]}const bs=[1.3877,1,1,1,.97801,.92482,.89552,.91133,.81988,.97566,.98152,.93548,.93548,1.2798,.85284,.92794,1,.96134,1.54657,.91133,.91133,.91133,.91133,.91133,.91133,.91133,.91133,.91133,.91133,.82845,.82845,.85284,.85284,.85284,.75859,.92138,.83908,.7762,.73293,.87289,.73133,.7514,.81921,.87356,.95958,.59526,.75727,.69225,1.04924,.9121,.86943,.79795,.88198,.77958,.70864,.81055,.90399,.88653,.96017,.82577,.77892,.78257,.97507,1.54657,.97507,.85284,.89552,.90176,.88762,.8785,.75241,.8785,.90518,.95015,.77618,.8785,.88401,.91916,.86304,.88401,.91488,.8785,.8801,.8785,.8785,.91343,.7173,1.04106,.8785,.85075,.95794,.82616,.85162,.79492,.88331,1.69808,.88331,.85284,.97801,.89552,.91133,.89552,.91133,1.7801,.89552,1.24487,1.13254,1.12401,.96839,.85284,.68787,.70645,.85592,.90747,1.01466,1.0088,.90323,1,1.07463,1,.91056,.75806,1.19118,.96839,.78864,.82845,.84133,.75859,.83908,.83908,.83908,.83908,.83908,.83908,.77539,.73293,.73133,.73133,.73133,.73133,.95958,.95958,.95958,.95958,.88506,.9121,.86943,.86943,.86943,.86943,.86943,.85284,.87508,.90399,.90399,.90399,.90399,.77892,.79795,.90807,.88762,.88762,.88762,.88762,.88762,.88762,.8715,.75241,.90518,.90518,.90518,.90518,.88401,.88401,.88401,.88401,.8785,.8785,.8801,.8801,.8801,.8801,.8801,.90747,.89049,.8785,.8785,.8785,.8785,.85162,.8785,.85162,.83908,.88762,.83908,.88762,.83908,.88762,.73293,.75241,.73293,.75241,.73293,.75241,.73293,.75241,.87289,.83016,.88506,.93125,.73133,.90518,.73133,.90518,.73133,.90518,.73133,.90518,.73133,.90518,.81921,.77618,.81921,.77618,.81921,.77618,1,1,.87356,.8785,.91075,.89608,.95958,.88401,.95958,.88401,.95958,.88401,.95958,.88401,.95958,.88401,.76229,.90167,.59526,.91916,1,1,.86304,.69225,.88401,1,1,.70424,.79468,.91926,.88175,.70823,.94903,.9121,.8785,1,1,.9121,.8785,.87802,.88656,.8785,.86943,.8801,.86943,.8801,.86943,.8801,.87402,.89291,.77958,.91343,1,1,.77958,.91343,.70864,.7173,.70864,.7173,.70864,.7173,.70864,.7173,1,1,.81055,.75841,.81055,1.06452,.90399,.8785,.90399,.8785,.90399,.8785,.90399,.8785,.90399,.8785,.90399,.8785,.96017,.95794,.77892,.85162,.77892,.78257,.79492,.78257,.79492,.78257,.79492,.9297,.56892,.83908,.88762,.77539,.8715,.87508,.89049,1,1,.81055,1.04106,1.20528,1.20528,1,1.15543,.70674,.98387,.94721,1.33431,1.45894,.95161,1.06303,.83908,.80352,.57184,.6965,.56289,.82001,.56029,.81235,1.02988,.83908,.7762,.68156,.80367,.73133,.78257,.87356,.86943,.95958,.75727,.89019,1.04924,.9121,.7648,.86943,.87356,.79795,.78275,.81055,.77892,.9762,.82577,.99819,.84896,.95958,.77892,.96108,1.01407,.89049,1.02988,.94211,.96108,.8936,.84021,.87842,.96399,.79109,.89049,1.00813,1.02988,.86077,.87445,.92099,.84723,.86513,.8801,.75638,.85714,.78216,.79586,.87965,.94211,.97747,.78287,.97926,.84971,1.02988,.94211,.8801,.94211,.84971,.73133,1,1,1,1,1,1,1,1,1,1,1,1,.90264,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.90518,1,1,1,1,1,1,1,1,1,1,1,1,.90548,1,1,1,1,1,1,.96017,.95794,.96017,.95794,.96017,.95794,.77892,.85162,1,1,.89552,.90527,1,.90363,.92794,.92794,.92794,.92794,.87012,.87012,.87012,.89552,.89552,1.42259,.71143,1.06152,1,1,1.03372,1.03372,.97171,1.4956,2.2807,.93835,.83406,.91133,.84107,.91133,1,1,1,.72021,1,1.23108,.83489,.88525,.88525,.81499,.90527,1.81055,.90527,1.81055,1.31006,1.53711,.94434,1.08696,1,.95018,.77192,.85284,.90747,1.17534,.69825,.9716,1.37077,.90747,.90747,.85356,.90747,.90747,1.44947,.85284,.8941,.8941,.70572,.8,.70572,.70572,.70572,.70572,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.99862,.99862,1,1,1,1,1,1.08004,.91027,1,1,1,.99862,1,1,1,1,1,1,1,1,1,1,1,1,.90727,.90727,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],ws={lineHeight:1.2207,lineGap:.2207},js=[1.3877,1,1,1,.97801,.92482,.89552,.91133,.81988,.97566,.98152,.93548,.93548,1.2798,.85284,.92794,1,.96134,1.56239,.91133,.91133,.91133,.91133,.91133,.91133,.91133,.91133,.91133,.91133,.82845,.82845,.85284,.85284,.85284,.75859,.92138,.83908,.7762,.71805,.87289,.73133,.7514,.81921,.87356,.95958,.59526,.75727,.69225,1.04924,.90872,.85938,.79795,.87068,.77958,.69766,.81055,.90399,.88653,.96068,.82577,.77892,.78257,.97507,1.529,.97507,.85284,.89552,.90176,.94908,.86411,.74012,.86411,.88323,.95015,.86411,.86331,.88401,.91916,.86304,.88401,.9039,.86331,.86331,.86411,.86411,.90464,.70852,1.04106,.86331,.84372,.95794,.82616,.84548,.79492,.88331,1.69808,.88331,.85284,.97801,.89552,.91133,.89552,.91133,1.7801,.89552,1.24487,1.13254,1.19129,.96839,.85284,.68787,.70645,.85592,.90747,1.01466,1.0088,.90323,1,1.07463,1,.91056,.75806,1.19118,.96839,.78864,.82845,.84133,.75859,.83908,.83908,.83908,.83908,.83908,.83908,.77539,.71805,.73133,.73133,.73133,.73133,.95958,.95958,.95958,.95958,.88506,.90872,.85938,.85938,.85938,.85938,.85938,.85284,.87068,.90399,.90399,.90399,.90399,.77892,.79795,.90807,.94908,.94908,.94908,.94908,.94908,.94908,.85887,.74012,.88323,.88323,.88323,.88323,.88401,.88401,.88401,.88401,.8785,.86331,.86331,.86331,.86331,.86331,.86331,.90747,.89049,.86331,.86331,.86331,.86331,.84548,.86411,.84548,.83908,.94908,.83908,.94908,.83908,.94908,.71805,.74012,.71805,.74012,.71805,.74012,.71805,.74012,.87289,.79538,.88506,.92726,.73133,.88323,.73133,.88323,.73133,.88323,.73133,.88323,.73133,.88323,.81921,.86411,.81921,.86411,.81921,.86411,1,1,.87356,.86331,.91075,.8777,.95958,.88401,.95958,.88401,.95958,.88401,.95958,.88401,.95958,.88401,.76467,.90167,.59526,.91916,1,1,.86304,.69225,.88401,1,1,.70424,.77312,.91926,.88175,.70823,.94903,.90872,.86331,1,1,.90872,.86331,.86906,.88116,.86331,.85938,.86331,.85938,.86331,.85938,.86331,.87402,.86549,.77958,.90464,1,1,.77958,.90464,.69766,.70852,.69766,.70852,.69766,.70852,.69766,.70852,1,1,.81055,.75841,.81055,1.06452,.90399,.86331,.90399,.86331,.90399,.86331,.90399,.86331,.90399,.86331,.90399,.86331,.96068,.95794,.77892,.84548,.77892,.78257,.79492,.78257,.79492,.78257,.79492,.9297,.56892,.83908,.94908,.77539,.85887,.87068,.89049,1,1,.81055,1.04106,1.20528,1.20528,1,1.15543,.70088,.98387,.94721,1.33431,1.45894,.95161,1.48387,.83908,.80352,.57118,.6965,.56347,.79179,.55853,.80346,1.02988,.83908,.7762,.67174,.86036,.73133,.78257,.87356,.86441,.95958,.75727,.89019,1.04924,.90872,.74889,.85938,.87891,.79795,.7957,.81055,.77892,.97447,.82577,.97466,.87179,.95958,.77892,.94252,.95612,.8753,1.02988,.92733,.94252,.87411,.84021,.8728,.95612,.74081,.8753,1.02189,1.02988,.84814,.87445,.91822,.84723,.85668,.86331,.81344,.87581,.76422,.82046,.96057,.92733,.99375,.78022,.95452,.86015,1.02988,.92733,.86331,.92733,.86015,.73133,1,1,1,1,1,1,1,1,1,1,1,1,.90631,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.88323,1,1,1,1,1,1,1,1,1,1,1,1,.85174,1,1,1,1,1,1,.96068,.95794,.96068,.95794,.96068,.95794,.77892,.84548,1,1,.89552,.90527,1,.90363,.92794,.92794,.92794,.89807,.87012,.87012,.87012,.89552,.89552,1.42259,.71094,1.06152,1,1,1.03372,1.03372,.97171,1.4956,2.2807,.92972,.83406,.91133,.83326,.91133,1,1,1,.72021,1,1.23108,.83489,.88525,.88525,.81499,.90616,1.81055,.90527,1.81055,1.3107,1.53711,.94434,1.08696,1,.95018,.77192,.85284,.90747,1.17534,.69825,.9716,1.37077,.90747,.90747,.85356,.90747,.90747,1.44947,.85284,.8941,.8941,.70572,.8,.70572,.70572,.70572,.70572,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.99862,.99862,1,1,1,1,1,1.08004,.91027,1,1,1,.99862,1,1,1,1,1,1,1,1,1,1,1,1,.90727,.90727,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],ks={lineHeight:1.2207,lineGap:.2207},ys=[1.3877,1,1,1,1.17223,1.1293,.89552,.91133,.80395,1.02269,1.15601,.91056,.91056,1.2798,.85284,.89807,1,.90861,1.39543,.91133,.91133,.91133,.91133,.91133,.91133,.91133,.91133,.91133,.91133,.96309,.96309,.85284,.85284,.85284,.83319,.88071,.8675,.81552,.72346,.85193,.73206,.7522,.81105,.86275,.90685,.6377,.77892,.75593,1.02638,.89249,.84118,.77452,.85374,.75186,.67789,.79776,.88844,.85066,.94309,.77818,.7306,.76659,1.10369,1.38313,1.10369,1.06139,.89552,.8739,.9245,.9245,.83203,.9245,.85865,1.09842,.9245,.9245,1.03297,1.07692,.90918,1.03297,.94959,.9245,.92274,.9245,.9245,1.02933,.77832,1.20562,.9245,.8916,.98986,.86621,.89453,.79004,.94152,1.77256,.94152,.85284,.97801,.89552,.91133,.89552,.91133,1.91729,.89552,1.17889,1.13254,1.16359,.92098,.85284,.68787,.71353,.84737,.90747,1.0088,1.0044,.87683,1,1.09091,1,.92229,.739,1.15642,.92098,.76288,.80504,.80972,.75859,.8675,.8675,.8675,.8675,.8675,.8675,.76318,.72346,.73206,.73206,.73206,.73206,.90685,.90685,.90685,.90685,.86477,.89249,.84118,.84118,.84118,.84118,.84118,.85284,.84557,.88844,.88844,.88844,.88844,.7306,.77452,.86331,.9245,.9245,.9245,.9245,.9245,.9245,.84843,.83203,.85865,.85865,.85865,.85865,.82601,.82601,.82601,.82601,.94469,.9245,.92274,.92274,.92274,.92274,.92274,.90747,.86651,.9245,.9245,.9245,.9245,.89453,.9245,.89453,.8675,.9245,.8675,.9245,.8675,.9245,.72346,.83203,.72346,.83203,.72346,.83203,.72346,.83203,.85193,.8875,.86477,.99034,.73206,.85865,.73206,.85865,.73206,.85865,.73206,.85865,.73206,.85865,.81105,.9245,.81105,.9245,.81105,.9245,1,1,.86275,.9245,.90872,.93591,.90685,.82601,.90685,.82601,.90685,.82601,.90685,1.03297,.90685,.82601,.77896,1.05611,.6377,1.07692,1,1,.90918,.75593,1.03297,1,1,.76032,.9375,.98156,.93407,.77261,1.11429,.89249,.9245,1,1,.89249,.9245,.92534,.86698,.9245,.84118,.92274,.84118,.92274,.84118,.92274,.8667,.86291,.75186,1.02933,1,1,.75186,1.02933,.67789,.77832,.67789,.77832,.67789,.77832,.67789,.77832,1,1,.79776,.97655,.79776,1.23023,.88844,.9245,.88844,.9245,.88844,.9245,.88844,.9245,.88844,.9245,.88844,.9245,.94309,.98986,.7306,.89453,.7306,.76659,.79004,.76659,.79004,.76659,.79004,1.09231,.54873,.8675,.9245,.76318,.84843,.84557,.86651,1,1,.79776,1.20562,1.18622,1.18622,1,1.1437,.67009,.96334,.93695,1.35191,1.40909,.95161,1.48387,.8675,.90861,.6192,.7363,.64824,.82411,.56321,.85696,1.23516,.8675,.81552,.7286,.84134,.73206,.76659,.86275,.84369,.90685,.77892,.85871,1.02638,.89249,.75828,.84118,.85984,.77452,.76466,.79776,.7306,.90782,.77818,.903,.87291,.90685,.7306,.99058,1.03667,.94635,1.23516,.9849,.99058,.92393,.8916,.942,1.03667,.75026,.94635,1.0297,1.23516,.90918,.94048,.98217,.89746,.84153,.92274,.82507,.88832,.84438,.88178,1.03525,.9849,1.00225,.78086,.97248,.89404,1.23516,.9849,.92274,.9849,.89404,.73206,1,1,1,1,1,1,1,1,1,1,1,1,.89693,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.85865,1,1,1,1,1,1,1,1,1,1,1,1,.90933,1,1,1,1,1,1,.94309,.98986,.94309,.98986,.94309,.98986,.7306,.89453,1,1,.89552,.90527,1,.90186,1.12308,1.12308,1.12308,1.12308,1.2566,1.2566,1.2566,.89552,.89552,1.42259,.68994,1.03809,1,1,1.0176,1.0176,1.11523,1.4956,2.01462,.97858,.82616,.91133,.83437,.91133,1,1,1,.70508,1,1.23108,.79801,.84426,.84426,.774,.90572,1.81055,.90749,1.81055,1.28809,1.55469,.94434,1.07806,1,.97094,.7589,.85284,.90747,1.19658,.69825,.97622,1.33512,.90747,.90747,.85284,.90747,.90747,1.44947,.85284,.8941,.8941,.70572,.8,.70572,.70572,.70572,.70572,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.99862,.99862,1,1,1,1,1,1.0336,.91027,1,1,1,.99862,1,1,1,1,1,1,1,1,1,1,1,1,1.05859,1.05859,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],qs={lineHeight:1.2207,lineGap:.2207},vs=[1.3877,1,1,1,1.17223,1.1293,.89552,.91133,.80395,1.02269,1.15601,.91056,.91056,1.2798,.85284,.89807,1,.90861,1.39016,.91133,.91133,.91133,.91133,.91133,.91133,.91133,.91133,.91133,.91133,.96309,.96309,.85284,.85284,.85284,.83319,.88071,.8675,.81552,.73834,.85193,.73206,.7522,.81105,.86275,.90685,.6377,.77892,.75593,1.02638,.89385,.85122,.77452,.86503,.75186,.68887,.79776,.88844,.85066,.94258,.77818,.7306,.76659,1.10369,1.39016,1.10369,1.06139,.89552,.8739,.86128,.94469,.8457,.94469,.89464,1.09842,.84636,.94469,1.03297,1.07692,.90918,1.03297,.95897,.94469,.9482,.94469,.94469,1.04692,.78223,1.20562,.94469,.90332,.98986,.86621,.90527,.79004,.94152,1.77256,.94152,.85284,.97801,.89552,.91133,.89552,.91133,1.91729,.89552,1.17889,1.13254,1.08707,.92098,.85284,.68787,.71353,.84737,.90747,1.0088,1.0044,.87683,1,1.09091,1,.92229,.739,1.15642,.92098,.76288,.80504,.80972,.75859,.8675,.8675,.8675,.8675,.8675,.8675,.76318,.73834,.73206,.73206,.73206,.73206,.90685,.90685,.90685,.90685,.86477,.89385,.85122,.85122,.85122,.85122,.85122,.85284,.85311,.88844,.88844,.88844,.88844,.7306,.77452,.86331,.86128,.86128,.86128,.86128,.86128,.86128,.8693,.8457,.89464,.89464,.89464,.89464,.82601,.82601,.82601,.82601,.94469,.94469,.9482,.9482,.9482,.9482,.9482,.90747,.86651,.94469,.94469,.94469,.94469,.90527,.94469,.90527,.8675,.86128,.8675,.86128,.8675,.86128,.73834,.8457,.73834,.8457,.73834,.8457,.73834,.8457,.85193,.92454,.86477,.9921,.73206,.89464,.73206,.89464,.73206,.89464,.73206,.89464,.73206,.89464,.81105,.84636,.81105,.84636,.81105,.84636,1,1,.86275,.94469,.90872,.95786,.90685,.82601,.90685,.82601,.90685,.82601,.90685,1.03297,.90685,.82601,.77741,1.05611,.6377,1.07692,1,1,.90918,.75593,1.03297,1,1,.76032,.90452,.98156,1.11842,.77261,1.11429,.89385,.94469,1,1,.89385,.94469,.95877,.86901,.94469,.85122,.9482,.85122,.9482,.85122,.9482,.8667,.90016,.75186,1.04692,1,1,.75186,1.04692,.68887,.78223,.68887,.78223,.68887,.78223,.68887,.78223,1,1,.79776,.92188,.79776,1.23023,.88844,.94469,.88844,.94469,.88844,.94469,.88844,.94469,.88844,.94469,.88844,.94469,.94258,.98986,.7306,.90527,.7306,.76659,.79004,.76659,.79004,.76659,.79004,1.09231,.54873,.8675,.86128,.76318,.8693,.85311,.86651,1,1,.79776,1.20562,1.18622,1.18622,1,1.1437,.67742,.96334,.93695,1.35191,1.40909,.95161,1.48387,.86686,.90861,.62267,.74359,.65649,.85498,.56963,.88254,1.23516,.8675,.81552,.75443,.84503,.73206,.76659,.86275,.85122,.90685,.77892,.85746,1.02638,.89385,.75657,.85122,.86275,.77452,.74171,.79776,.7306,.95165,.77818,.89772,.88831,.90685,.7306,.98142,1.02191,.96576,1.23516,.99018,.98142,.9236,.89258,.94035,1.02191,.78848,.96576,.9561,1.23516,.90918,.92578,.95424,.89746,.83969,.9482,.80113,.89442,.85208,.86155,.98022,.99018,1.00452,.81209,.99247,.89181,1.23516,.99018,.9482,.99018,.89181,.73206,1,1,1,1,1,1,1,1,1,1,1,1,.88844,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.89464,1,1,1,1,1,1,1,1,1,1,1,1,.96766,1,1,1,1,1,1,.94258,.98986,.94258,.98986,.94258,.98986,.7306,.90527,1,1,.89552,.90527,1,.90186,1.12308,1.12308,1.12308,1.12308,1.2566,1.2566,1.2566,.89552,.89552,1.42259,.69043,1.03809,1,1,1.0176,1.0176,1.11523,1.4956,2.01462,.99331,.82616,.91133,.84286,.91133,1,1,1,.70508,1,1.23108,.79801,.84426,.84426,.774,.90527,1.81055,.90527,1.81055,1.28809,1.55469,.94434,1.07806,1,.97094,.7589,.85284,.90747,1.19658,.69825,.97622,1.33512,.90747,.90747,.85356,.90747,.90747,1.44947,.85284,.8941,.8941,.70572,.8,.70572,.70572,.70572,.70572,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.99862,.99862,1,1,1,1,1,1.0336,.91027,1,1,1,.99862,1,1,1,1,1,1,1,1,1,1,1,1,1.05859,1.05859,1,1,1,1.07185,.99413,.96334,1.08065,1,1,1,1,1,1,1,1,1,1,1],Ss={lineHeight:1.2207,lineGap:.2207},xs=[.76116,1,1,1.0006,.99998,.99974,.99973,.99973,.99982,.99977,1.00087,.99998,.99998,.99959,1.00003,1.0006,.99998,1.0006,1.0006,.99973,.99973,.99973,.99973,.99973,.99973,.99973,.99973,.99973,.99973,.99998,1,1.00003,1.00003,1.00003,1.00026,.9999,.99977,.99977,.99977,.99977,1.00001,1.00026,1.00022,.99977,1.0006,.99973,.99977,1.00026,.99999,.99977,1.00022,1.00001,1.00022,.99977,1.00001,1.00026,.99977,1.00001,1.00016,1.00001,1.00001,1.00026,.99998,1.0006,.99998,1.00003,.99973,.99998,.99973,1.00026,.99973,1.00026,.99973,.99998,1.00026,1.00026,1.0006,1.0006,.99973,1.0006,.99982,1.00026,1.00026,1.00026,1.00026,.99959,.99973,.99998,1.00026,.99973,1.00022,.99973,.99973,1,.99959,1.00077,.99959,1.00003,.99998,.99973,.99973,.99973,.99973,1.00077,.99973,.99998,1.00025,.99968,.99973,1.00003,1.00025,.60299,1.00024,1.06409,1,1,.99998,1,.99973,1.0006,.99998,1,.99936,.99973,1.00002,1.00002,1.00002,1.00026,.99977,.99977,.99977,.99977,.99977,.99977,1,.99977,1.00001,1.00001,1.00001,1.00001,1.0006,1.0006,1.0006,1.0006,.99977,.99977,1.00022,1.00022,1.00022,1.00022,1.00022,1.00003,1.00022,.99977,.99977,.99977,.99977,1.00001,1.00001,1.00026,.99973,.99973,.99973,.99973,.99973,.99973,.99982,.99973,.99973,.99973,.99973,.99973,1.0006,1.0006,1.0006,1.0006,1.00026,1.00026,1.00026,1.00026,1.00026,1.00026,1.00026,1.06409,1.00026,1.00026,1.00026,1.00026,1.00026,.99973,1.00026,.99973,.99977,.99973,.99977,.99973,.99977,.99973,.99977,.99973,.99977,.99973,.99977,.99973,.99977,.99973,.99977,1.03374,.99977,1.00026,1.00001,.99973,1.00001,.99973,1.00001,.99973,1.00001,.99973,1.00001,.99973,1.00022,1.00026,1.00022,1.00026,1.00022,1.00026,1.00022,1.00026,.99977,1.00026,.99977,1.00026,1.0006,1.0006,1.0006,1.0006,1.0006,1.0006,1.0006,1.0006,1.0006,1.0006,1.00042,.99973,.99973,1.0006,.99977,.99973,.99973,1.00026,1.0006,1.00026,1.0006,1.00026,1.03828,1.00026,.99999,1.00026,1.0006,.99977,1.00026,.99977,1.00026,.99977,1.00026,.9993,.9998,1.00026,1.00022,1.00026,1.00022,1.00026,1.00022,1.00026,1,1.00016,.99977,.99959,.99977,.99959,.99977,.99959,1.00001,.99973,1.00001,.99973,1.00001,.99973,1.00001,.99973,1.00026,.99998,1.00026,.8121,1.00026,.99998,.99977,1.00026,.99977,1.00026,.99977,1.00026,.99977,1.00026,.99977,1.00026,.99977,1.00026,1.00016,1.00022,1.00001,.99973,1.00001,1.00026,1,1.00026,1,1.00026,1,1.0006,.99973,.99977,.99973,1,.99982,1.00022,1.00026,1.00001,.99973,1.00026,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99998,1.00034,.99977,1,.99997,1.00026,1.00078,1.00036,.99973,1.00013,1.0006,.99977,.99977,.99988,.85148,1.00001,1.00026,.99977,1.00022,1.0006,.99977,1.00001,.99999,.99977,1.00069,1.00022,.99977,1.00001,.99984,1.00026,1.00001,1.00024,1.00001,.9999,1,1.0006,1.00001,1.00041,.99962,1.00026,1.0006,.99995,1.00041,.99942,.99973,.99927,1.00082,.99902,1.00026,1.00087,1.0006,1.00069,.99973,.99867,.99973,.9993,1.00026,1.00049,1.00056,1,.99988,.99935,.99995,.99954,1.00055,.99945,1.00032,1.0006,.99995,1.00026,.99995,1.00032,1.00001,1.00008,.99971,1.00019,.9994,1.00001,1.0006,1.00044,.99973,1.00023,1.00047,1,.99942,.99561,.99989,1.00035,.99977,1.00035,.99977,1.00019,.99944,1.00001,1.00021,.99926,1.00035,1.00035,.99942,1.00048,.99999,.99977,1.00022,1.00035,1.00001,.99977,1.00026,.99989,1.00057,1.00001,.99936,1.00052,1.00012,.99996,1.00043,1,1.00035,.9994,.99976,1.00035,.99973,1.00052,1.00041,1.00119,1.00037,.99973,1.00002,.99986,1.00041,1.00041,.99902,.9996,1.00034,.99999,1.00026,.99999,1.00026,.99973,1.00052,.99973,1,.99973,1.00041,1.00075,.9994,1.0003,.99999,1,1.00041,.99955,1,.99915,.99973,.99973,1.00026,1.00119,.99955,.99973,1.0006,.99911,1.0006,1.00026,.99972,1.00026,.99902,1.00041,.99973,.99999,1,1,1.00038,1.0005,1.00016,1.00022,1.00016,1.00022,1.00016,1.00022,1.00001,.99973,1,1,.99973,1,1,.99955,1.0006,1.0006,1.0006,1.0006,1,1,1,.99973,.99973,.99972,1,1,1.00106,.99999,.99998,.99998,.99999,.99998,1.66475,1,.99973,.99973,1.00023,.99973,.99971,1.00047,1.00023,1,.99991,.99984,1.00002,1.00002,1.00002,1.00002,1,1,1,1,1,1,1,.99972,1,1.20985,1.39713,1.00003,1.00031,1.00015,1,.99561,1.00027,1.00031,1.00031,.99915,1.00031,1.00031,.99999,1.00003,.99999,.99999,1.41144,1.6,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.40579,1.40579,1.36625,.99999,1,.99861,.99861,1,1.00026,1.00026,1.00026,1.00026,.99972,.99999,.99999,.99999,.99999,1.40483,1,.99977,1.00054,1,1,.99953,.99962,1.00042,.9995,1,1,1,1,1,1,1,1,.99998,.99998,.99998,.99998,1,1,1,1,1,1,1,1,1,1,1],As={lineHeight:1.2,lineGap:.2},Cs=[.76116,1,1,1.0006,.99998,.99974,.99973,.99973,.99982,.99977,1.00087,.99998,.99998,.99959,1.00003,1.0006,.99998,1.0006,1.0006,.99973,.99973,.99973,.99973,.99973,.99973,.99973,.99973,.99973,.99973,.99998,1,1.00003,1.00003,1.00003,1.00026,.9999,.99977,.99977,.99977,.99977,1.00001,1.00026,1.00022,.99977,1.0006,.99973,.99977,1.00026,.99999,.99977,1.00022,1.00001,1.00022,.99977,1.00001,1.00026,.99977,1.00001,1.00016,1.00001,1.00001,1.00026,.99998,1.0006,.99998,1.00003,.99973,.99998,.99973,1.00026,.99973,1.00026,.99973,.99998,1.00026,1.00026,1.0006,1.0006,.99973,1.0006,.99982,1.00026,1.00026,1.00026,1.00026,.99959,.99973,.99998,1.00026,.99973,1.00022,.99973,.99973,1,.99959,1.00077,.99959,1.00003,.99998,.99973,.99973,.99973,.99973,1.00077,.99973,.99998,1.00025,.99968,.99973,1.00003,1.00025,.60299,1.00024,1.06409,1,1,.99998,1,.99973,1.0006,.99998,1,.99936,.99973,1.00002,1.00002,1.00002,1.00026,.99977,.99977,.99977,.99977,.99977,.99977,1,.99977,1.00001,1.00001,1.00001,1.00001,1.0006,1.0006,1.0006,1.0006,.99977,.99977,1.00022,1.00022,1.00022,1.00022,1.00022,1.00003,1.00022,.99977,.99977,.99977,.99977,1.00001,1.00001,1.00026,.99973,.99973,.99973,.99973,.99973,.99973,.99982,.99973,.99973,.99973,.99973,.99973,1.0006,1.0006,1.0006,1.0006,1.00026,1.00026,1.00026,1.00026,1.00026,1.00026,1.00026,1.06409,1.00026,1.00026,1.00026,1.00026,1.00026,.99973,1.00026,.99973,.99977,.99973,.99977,.99973,.99977,.99973,.99977,.99973,.99977,.99973,.99977,.99973,.99977,.99973,.99977,1.0044,.99977,1.00026,1.00001,.99973,1.00001,.99973,1.00001,.99973,1.00001,.99973,1.00001,.99973,1.00022,1.00026,1.00022,1.00026,1.00022,1.00026,1.00022,1.00026,.99977,1.00026,.99977,1.00026,1.0006,1.0006,1.0006,1.0006,1.0006,1.0006,1.0006,1.0006,1.0006,1.0006,.99971,.99973,.99973,1.0006,.99977,.99973,.99973,1.00026,1.0006,1.00026,1.0006,1.00026,1.01011,1.00026,.99999,1.00026,1.0006,.99977,1.00026,.99977,1.00026,.99977,1.00026,.9993,.9998,1.00026,1.00022,1.00026,1.00022,1.00026,1.00022,1.00026,1,1.00016,.99977,.99959,.99977,.99959,.99977,.99959,1.00001,.99973,1.00001,.99973,1.00001,.99973,1.00001,.99973,1.00026,.99998,1.00026,.8121,1.00026,.99998,.99977,1.00026,.99977,1.00026,.99977,1.00026,.99977,1.00026,.99977,1.00026,.99977,1.00026,1.00016,1.00022,1.00001,.99973,1.00001,1.00026,1,1.00026,1,1.00026,1,1.0006,.99973,.99977,.99973,1,.99982,1.00022,1.00026,1.00001,.99973,1.00026,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99977,1,1,1.00026,.99969,.99972,.99981,.9998,1.0006,.99977,.99977,1.00022,.91155,1.00001,1.00026,.99977,1.00022,1.0006,.99977,1.00001,.99999,.99977,.99966,1.00022,1.00032,1.00001,.99944,1.00026,1.00001,.99968,1.00001,1.00047,1,1.0006,1.00001,.99981,1.00101,1.00026,1.0006,.99948,.99981,1.00064,.99973,.99942,1.00101,1.00061,1.00026,1.00069,1.0006,1.00014,.99973,1.01322,.99973,1.00065,1.00026,1.00012,.99923,1,1.00064,1.00076,.99948,1.00055,1.00063,1.00007,.99943,1.0006,.99948,1.00026,.99948,.99943,1.00001,1.00001,1.00029,1.00038,1.00035,1.00001,1.0006,1.0006,.99973,.99978,1.00001,1.00057,.99989,.99967,.99964,.99967,.99977,.99999,.99977,1.00038,.99977,1.00001,.99973,1.00066,.99967,.99967,1.00041,.99998,.99999,.99977,1.00022,.99967,1.00001,.99977,1.00026,.99964,1.00031,1.00001,.99999,.99999,1,1.00023,1,1,.99999,1.00035,1.00001,.99999,.99973,.99977,.99999,1.00058,.99973,.99973,.99955,.9995,1.00026,1.00026,1.00032,.99989,1.00034,.99999,1.00026,1.00026,1.00026,.99973,.45998,.99973,1.00026,.99973,1.00001,.99999,.99982,.99994,.99996,1,1.00042,1.00044,1.00029,1.00023,.99973,.99973,1.00026,.99949,1.00002,.99973,1.0006,1.0006,1.0006,.99975,1.00026,1.00026,1.00032,.98685,.99973,1.00026,1,1,.99966,1.00044,1.00016,1.00022,1.00016,1.00022,1.00016,1.00022,1.00001,.99973,1,1,.99973,1,1,.99955,1.0006,1.0006,1.0006,1.0006,1,1,1,.99973,.99973,.99972,1,1,1.00106,.99999,.99998,.99998,.99999,.99998,1.66475,1,.99973,.99973,1,.99973,.99971,.99978,1,1,.99991,.99984,1.00002,1.00002,1.00002,1.00002,1.00098,1,1,1,1.00049,1,1,.99972,1,1.20985,1.39713,1.00003,1.00031,1.00015,1,.99561,1.00027,1.00031,1.00031,.99915,1.00031,1.00031,.99999,1.00003,.99999,.99999,1.41144,1.6,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.40579,1.40579,1.36625,.99999,1,.99861,.99861,1,1.00026,1.00026,1.00026,1.00026,.99972,.99999,.99999,.99999,.99999,1.40483,1,.99977,1.00054,1,1,.99953,.99962,1.00042,.9995,1,1,1,1,1,1,1,1,.99998,.99998,.99998,.99998,1,1,1,1,1,1,1,1,1,1,1],Is={lineHeight:1.35,lineGap:.2},Fs=[.76116,1,1,1.0006,1.0006,1.00006,.99973,.99973,.99982,1.00001,1.00043,.99998,.99998,.99959,1.00003,1.0006,.99998,1.0006,1.0006,.99973,.99973,.99973,.99973,.99973,.99973,.99973,.99973,.99973,.99973,1.0006,1,1.00003,1.00003,1.00003,.99973,.99987,1.00001,1.00001,.99977,.99977,1.00001,1.00026,1.00022,.99977,1.0006,1,1.00001,.99973,.99999,.99977,1.00022,1.00001,1.00022,.99977,1.00001,1.00026,.99977,1.00001,1.00016,1.00001,1.00001,1.00026,1.0006,1.0006,1.0006,.99949,.99973,.99998,.99973,.99973,1,.99973,.99973,1.0006,.99973,.99973,.99924,.99924,1,.99924,.99999,.99973,.99973,.99973,.99973,.99998,1,1.0006,.99973,1,.99977,1,1,1,1.00005,1.0009,1.00005,1.00003,.99998,.99973,.99973,.99973,.99973,1.0009,.99973,.99998,1.00025,.99968,.99973,1.00003,1.00025,.60299,1.00024,1.06409,1,1,.99998,1,.9998,1.0006,.99998,1,.99936,.99973,1.00002,1.00002,1.00002,1.00026,1.00001,1.00001,1.00001,1.00001,1.00001,1.00001,1,.99977,1.00001,1.00001,1.00001,1.00001,1.0006,1.0006,1.0006,1.0006,.99977,.99977,1.00022,1.00022,1.00022,1.00022,1.00022,1.00003,1.00022,.99977,.99977,.99977,.99977,1.00001,1.00001,1.00026,.99973,.99973,.99973,.99973,.99973,.99973,.99982,1,.99973,.99973,.99973,.99973,1.0006,1.0006,1.0006,1.0006,.99973,.99973,.99973,.99973,.99973,.99973,.99973,1.06409,1.00026,.99973,.99973,.99973,.99973,1,.99973,1,1.00001,.99973,1.00001,.99973,1.00001,.99973,.99977,1,.99977,1,.99977,1,.99977,1,.99977,1.0288,.99977,.99973,1.00001,.99973,1.00001,.99973,1.00001,.99973,1.00001,.99973,1.00001,.99973,1.00022,.99973,1.00022,.99973,1.00022,.99973,1.00022,.99973,.99977,.99973,.99977,.99973,1.0006,1.0006,1.0006,1.0006,1.0006,1.0006,1.0006,.99924,1.0006,1.0006,.99946,1.00034,1,.99924,1.00001,1,1,.99973,.99924,.99973,.99924,.99973,1.06311,.99973,1.00024,.99973,.99924,.99977,.99973,.99977,.99973,.99977,.99973,1.00041,.9998,.99973,1.00022,.99973,1.00022,.99973,1.00022,.99973,1,1.00016,.99977,.99998,.99977,.99998,.99977,.99998,1.00001,1,1.00001,1,1.00001,1,1.00001,1,1.00026,1.0006,1.00026,.89547,1.00026,1.0006,.99977,.99973,.99977,.99973,.99977,.99973,.99977,.99973,.99977,.99973,.99977,.99973,1.00016,.99977,1.00001,1,1.00001,1.00026,1,1.00026,1,1.00026,1,.99924,.99973,1.00001,.99973,1,.99982,1.00022,1.00026,1.00001,1,1.00026,1.0006,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99998,1.00001,1,1.00054,.99977,1.00084,1.00007,.99973,1.00013,.99924,1.00001,1.00001,.99945,.91221,1.00001,1.00026,.99977,1.00022,1.0006,1.00001,1.00001,.99999,.99977,.99933,1.00022,1.00054,1.00001,1.00065,1.00026,1.00001,1.0001,1.00001,1.00052,1,1.0006,1.00001,.99945,.99897,.99968,.99924,1.00036,.99945,.99949,1,1.0006,.99897,.99918,.99968,.99911,.99924,1,.99962,1.01487,1,1.0005,.99973,1.00012,1.00043,1,.99995,.99994,1.00036,.99947,1.00019,1.00063,1.00025,.99924,1.00036,.99973,1.00036,1.00025,1.00001,1.00001,1.00027,1.0001,1.00068,1.00001,1.0006,1.0006,1,1.00008,.99957,.99972,.9994,.99954,.99975,1.00051,1.00001,1.00019,1.00001,1.0001,.99986,1.00001,1.00001,1.00038,.99954,.99954,.9994,1.00066,.99999,.99977,1.00022,1.00054,1.00001,.99977,1.00026,.99975,1.0001,1.00001,.99993,.9995,.99955,1.00016,.99978,.99974,1.00019,1.00022,.99955,1.00053,.99973,1.00089,1.00005,.99967,1.00048,.99973,1.00002,1.00034,.99973,.99973,.99964,1.00006,1.00066,.99947,.99973,.98894,.99973,1,.44898,1,.99946,1,1.00039,1.00082,.99991,.99991,.99985,1.00022,1.00023,1.00061,1.00006,.99966,.99973,.99973,.99973,1.00019,1.0008,1,.99924,.99924,.99924,.99983,1.00044,.99973,.99964,.98332,1,.99973,1,1,.99962,.99895,1.00016,.99977,1.00016,.99977,1.00016,.99977,1.00001,1,1,1,.99973,1,1,.99955,.99924,.99924,.99924,.99924,.99998,.99998,.99998,.99973,.99973,.99972,1,1,1.00267,.99999,.99998,.99998,1,.99998,1.66475,1,.99973,.99973,1.00023,.99973,1.00423,.99925,.99999,1,.99991,.99984,1.00002,1.00002,1.00002,1.00002,1.00049,1,1.00245,1,1,1,1,.96329,1,1.20985,1.39713,1.00003,.8254,1.00015,1,1.00035,1.00027,1.00031,1.00031,1.00003,1.00031,1.00031,.99999,1.00003,.99999,.99999,1.41144,1.6,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.40579,1.40579,1.36625,.99999,1,.99861,.99861,1,1.00026,1.00026,1.00026,1.00026,.95317,.99999,.99999,.99999,.99999,1.40483,1,.99977,1.00054,1,1,.99953,.99962,1.00042,.9995,1,1,1,1,1,1,1,1,.99998,.99998,.99998,.99998,1,1,1,1,1,1,1,1,1,1,1],Ts={lineHeight:1.35,lineGap:.2},Hs=[.76116,1,1,1.0006,1.0006,1.00006,.99973,.99973,.99982,1.00001,1.00043,.99998,.99998,.99959,1.00003,1.0006,.99998,1.0006,1.0006,.99973,.99973,.99973,.99973,.99973,.99973,.99973,.99973,.99973,.99973,1.0006,1,1.00003,1.00003,1.00003,.99973,.99987,1.00001,1.00001,.99977,.99977,1.00001,1.00026,1.00022,.99977,1.0006,1,1.00001,.99973,.99999,.99977,1.00022,1.00001,1.00022,.99977,1.00001,1.00026,.99977,1.00001,1.00016,1.00001,1.00001,1.00026,1.0006,1.0006,1.0006,.99949,.99973,.99998,.99973,.99973,1,.99973,.99973,1.0006,.99973,.99973,.99924,.99924,1,.99924,.99999,.99973,.99973,.99973,.99973,.99998,1,1.0006,.99973,1,.99977,1,1,1,1.00005,1.0009,1.00005,1.00003,.99998,.99973,.99973,.99973,.99973,1.0009,.99973,.99998,1.00025,.99968,.99973,1.00003,1.00025,.60299,1.00024,1.06409,1,1,.99998,1,.9998,1.0006,.99998,1,.99936,.99973,1.00002,1.00002,1.00002,1.00026,1.00001,1.00001,1.00001,1.00001,1.00001,1.00001,1,.99977,1.00001,1.00001,1.00001,1.00001,1.0006,1.0006,1.0006,1.0006,.99977,.99977,1.00022,1.00022,1.00022,1.00022,1.00022,1.00003,1.00022,.99977,.99977,.99977,.99977,1.00001,1.00001,1.00026,.99973,.99973,.99973,.99973,.99973,.99973,.99982,1,.99973,.99973,.99973,.99973,1.0006,1.0006,1.0006,1.0006,.99973,.99973,.99973,.99973,.99973,.99973,.99973,1.06409,1.00026,.99973,.99973,.99973,.99973,1,.99973,1,1.00001,.99973,1.00001,.99973,1.00001,.99973,.99977,1,.99977,1,.99977,1,.99977,1,.99977,1.04596,.99977,.99973,1.00001,.99973,1.00001,.99973,1.00001,.99973,1.00001,.99973,1.00001,.99973,1.00022,.99973,1.00022,.99973,1.00022,.99973,1.00022,.99973,.99977,.99973,.99977,.99973,1.0006,1.0006,1.0006,1.0006,1.0006,1.0006,1.0006,.99924,1.0006,1.0006,1.00019,1.00034,1,.99924,1.00001,1,1,.99973,.99924,.99973,.99924,.99973,1.02572,.99973,1.00005,.99973,.99924,.99977,.99973,.99977,.99973,.99977,.99973,.99999,.9998,.99973,1.00022,.99973,1.00022,.99973,1.00022,.99973,1,1.00016,.99977,.99998,.99977,.99998,.99977,.99998,1.00001,1,1.00001,1,1.00001,1,1.00001,1,1.00026,1.0006,1.00026,.84533,1.00026,1.0006,.99977,.99973,.99977,.99973,.99977,.99973,.99977,.99973,.99977,.99973,.99977,.99973,1.00016,.99977,1.00001,1,1.00001,1.00026,1,1.00026,1,1.00026,1,.99924,.99973,1.00001,.99973,1,.99982,1.00022,1.00026,1.00001,1,1.00026,1.0006,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99998,.99928,1,.99977,1.00013,1.00055,.99947,.99945,.99941,.99924,1.00001,1.00001,1.0004,.91621,1.00001,1.00026,.99977,1.00022,1.0006,1.00001,1.00005,.99999,.99977,1.00015,1.00022,.99977,1.00001,.99973,1.00026,1.00001,1.00019,1.00001,.99946,1,1.0006,1.00001,.99978,1.00045,.99973,.99924,1.00023,.99978,.99966,1,1.00065,1.00045,1.00019,.99973,.99973,.99924,1,1,.96499,1,1.00055,.99973,1.00008,1.00027,1,.9997,.99995,1.00023,.99933,1.00019,1.00015,1.00031,.99924,1.00023,.99973,1.00023,1.00031,1.00001,.99928,1.00029,1.00092,1.00035,1.00001,1.0006,1.0006,1,.99988,.99975,1,1.00082,.99561,.9996,1.00035,1.00001,.99962,1.00001,1.00092,.99964,1.00001,.99963,.99999,1.00035,1.00035,1.00082,.99962,.99999,.99977,1.00022,1.00035,1.00001,.99977,1.00026,.9996,.99967,1.00001,1.00034,1.00074,1.00054,1.00053,1.00063,.99971,.99962,1.00035,.99975,.99977,.99973,1.00043,.99953,1.0007,.99915,.99973,1.00008,.99892,1.00073,1.00073,1.00114,.99915,1.00073,.99955,.99973,1.00092,.99973,1,.99998,1,1.0003,1,1.00043,1.00001,.99969,1.0003,1,1.00035,1.00001,.9995,1,1.00092,.99973,.99973,.99973,1.0007,.9995,1,.99924,1.0006,.99924,.99972,1.00062,.99973,1.00114,1.00073,1,.99955,1,1,1.00047,.99968,1.00016,.99977,1.00016,.99977,1.00016,.99977,1.00001,1,1,1,.99973,1,1,.99955,.99924,.99924,.99924,.99924,.99998,.99998,.99998,.99973,.99973,.99972,1,1,1.00267,.99999,.99998,.99998,1,.99998,1.66475,1,.99973,.99973,1.00023,.99973,.99971,.99925,1.00023,1,.99991,.99984,1.00002,1.00002,1.00002,1.00002,1,1,1,1,1,1,1,.96329,1,1.20985,1.39713,1.00003,.8254,1.00015,1,1.00035,1.00027,1.00031,1.00031,.99915,1.00031,1.00031,.99999,1.00003,.99999,.99999,1.41144,1.6,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.41144,1.40579,1.40579,1.36625,.99999,1,.99861,.99861,1,1.00026,1.00026,1.00026,1.00026,.95317,.99999,.99999,.99999,.99999,1.40483,1,.99977,1.00054,1,1,.99953,.99962,1.00042,.9995,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],Os={lineHeight:1.2,lineGap:.2},Bs=[365,0,333,278,333,474,556,556,889,722,238,333,333,389,584,278,333,278,278,556,556,556,556,556,556,556,556,556,556,333,333,584,584,584,611,975,722,722,722,722,667,611,778,722,278,556,722,611,833,722,778,667,778,722,667,611,722,667,944,667,667,611,333,278,333,584,556,333,556,611,556,611,556,333,611,611,278,278,556,278,889,611,611,611,611,389,556,333,611,556,778,556,556,500,389,280,389,584,333,556,556,556,556,280,556,333,737,370,556,584,737,552,400,549,333,333,333,576,556,278,333,333,365,556,834,834,834,611,722,722,722,722,722,722,1e3,722,667,667,667,667,278,278,278,278,722,722,778,778,778,778,778,584,778,722,722,722,722,667,667,611,556,556,556,556,556,556,889,556,556,556,556,556,278,278,278,278,611,611,611,611,611,611,611,549,611,611,611,611,611,556,611,556,722,556,722,556,722,556,722,556,722,556,722,556,722,556,722,719,722,611,667,556,667,556,667,556,667,556,667,556,778,611,778,611,778,611,778,611,722,611,722,611,278,278,278,278,278,278,278,278,278,278,785,556,556,278,722,556,556,611,278,611,278,611,385,611,479,611,278,722,611,722,611,722,611,708,723,611,778,611,778,611,778,611,1e3,944,722,389,722,389,722,389,667,556,667,556,667,556,667,556,611,333,611,479,611,333,722,611,722,611,722,611,722,611,722,611,722,611,944,778,667,556,667,611,500,611,500,611,500,278,556,722,556,1e3,889,778,611,667,556,611,333,333,333,333,333,333,333,333,333,333,333,465,722,333,853,906,474,825,927,838,278,722,722,601,719,667,611,722,778,278,722,667,833,722,644,778,722,667,600,611,667,821,667,809,802,278,667,615,451,611,278,582,615,610,556,606,475,460,611,541,278,558,556,612,556,445,611,766,619,520,684,446,582,715,576,753,845,278,582,611,582,845,667,669,885,567,711,667,278,276,556,1094,1062,875,610,722,622,719,722,719,722,567,712,667,904,626,719,719,610,702,833,722,778,719,667,722,611,622,854,667,730,703,1005,1019,870,979,719,711,1031,719,556,618,615,417,635,556,709,497,615,615,500,635,740,604,611,604,611,556,490,556,875,556,615,581,833,844,729,854,615,552,854,583,556,556,611,417,552,556,278,281,278,969,906,611,500,615,556,604,778,611,487,447,944,778,944,778,944,778,667,556,333,333,556,1e3,1e3,552,278,278,278,278,500,500,500,556,556,350,1e3,1e3,240,479,333,333,604,333,167,396,556,556,1094,556,885,489,1115,1e3,768,600,834,834,834,834,1e3,500,1e3,500,1e3,500,500,494,612,823,713,584,549,713,979,722,274,549,549,583,549,549,604,584,604,604,708,625,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,729,604,604,354,354,1e3,990,990,990,990,494,604,604,604,604,354,1021,1052,917,750,750,531,656,594,510,500,750,750,611,611,333,333,333,333,333,333,333,333,222,222,333,333,333,333,333,333,333,333],Rs=[-1,-1,-1,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,161,162,163,164,165,166,167,168,169,170,171,172,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,402,506,507,508,509,510,511,536,537,538,539,710,711,713,728,729,730,731,732,733,900,901,902,903,904,905,906,908,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,1024,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039,1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,1104,1105,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115,1116,1117,1118,1119,1138,1139,1168,1169,7808,7809,7810,7811,7812,7813,7922,7923,8208,8209,8211,8212,8213,8215,8216,8217,8218,8219,8220,8221,8222,8224,8225,8226,8230,8240,8242,8243,8249,8250,8252,8254,8260,8319,8355,8356,8359,8364,8453,8467,8470,8482,8486,8494,8539,8540,8541,8542,8592,8593,8594,8595,8596,8597,8616,8706,8710,8719,8721,8722,8730,8734,8735,8745,8747,8776,8800,8801,8804,8805,8962,8976,8992,8993,9472,9474,9484,9488,9492,9496,9500,9508,9516,9524,9532,9552,9553,9554,9555,9556,9557,9558,9559,9560,9561,9562,9563,9564,9565,9566,9567,9568,9569,9570,9571,9572,9573,9574,9575,9576,9577,9578,9579,9580,9600,9604,9608,9612,9616,9617,9618,9619,9632,9633,9642,9643,9644,9650,9658,9660,9668,9674,9675,9679,9688,9689,9702,9786,9787,9788,9792,9794,9824,9827,9829,9830,9834,9835,9836,61441,61442,61445,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],Ds=[365,0,333,278,333,474,556,556,889,722,238,333,333,389,584,278,333,278,278,556,556,556,556,556,556,556,556,556,556,333,333,584,584,584,611,975,722,722,722,722,667,611,778,722,278,556,722,611,833,722,778,667,778,722,667,611,722,667,944,667,667,611,333,278,333,584,556,333,556,611,556,611,556,333,611,611,278,278,556,278,889,611,611,611,611,389,556,333,611,556,778,556,556,500,389,280,389,584,333,556,556,556,556,280,556,333,737,370,556,584,737,552,400,549,333,333,333,576,556,278,333,333,365,556,834,834,834,611,722,722,722,722,722,722,1e3,722,667,667,667,667,278,278,278,278,722,722,778,778,778,778,778,584,778,722,722,722,722,667,667,611,556,556,556,556,556,556,889,556,556,556,556,556,278,278,278,278,611,611,611,611,611,611,611,549,611,611,611,611,611,556,611,556,722,556,722,556,722,556,722,556,722,556,722,556,722,556,722,740,722,611,667,556,667,556,667,556,667,556,667,556,778,611,778,611,778,611,778,611,722,611,722,611,278,278,278,278,278,278,278,278,278,278,782,556,556,278,722,556,556,611,278,611,278,611,396,611,479,611,278,722,611,722,611,722,611,708,723,611,778,611,778,611,778,611,1e3,944,722,389,722,389,722,389,667,556,667,556,667,556,667,556,611,333,611,479,611,333,722,611,722,611,722,611,722,611,722,611,722,611,944,778,667,556,667,611,500,611,500,611,500,278,556,722,556,1e3,889,778,611,667,556,611,333,333,333,333,333,333,333,333,333,333,333,333,722,333,854,906,473,844,930,847,278,722,722,610,671,667,611,722,778,278,722,667,833,722,657,778,718,667,590,611,667,822,667,829,781,278,667,620,479,611,278,591,620,621,556,610,479,492,611,558,278,566,556,603,556,450,611,712,605,532,664,409,591,704,578,773,834,278,591,611,591,834,667,667,886,614,719,667,278,278,556,1094,1042,854,622,719,677,719,722,708,722,614,722,667,927,643,719,719,615,687,833,722,778,719,667,722,611,677,781,667,729,708,979,989,854,1e3,708,719,1042,729,556,619,604,534,618,556,736,510,611,611,507,622,740,604,611,611,611,556,889,556,885,556,646,583,889,935,707,854,594,552,865,589,556,556,611,469,563,556,278,278,278,969,906,611,507,619,556,611,778,611,575,467,944,778,944,778,944,778,667,556,333,333,556,1e3,1e3,552,278,278,278,278,500,500,500,556,556,350,1e3,1e3,240,479,333,333,604,333,167,396,556,556,1104,556,885,516,1146,1e3,768,600,834,834,834,834,999,500,1e3,500,1e3,500,500,494,612,823,713,584,549,713,979,722,274,549,549,583,549,549,604,584,604,604,708,625,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,729,604,604,354,354,1e3,990,990,990,990,494,604,604,604,604,354,1021,1052,917,750,750,531,656,594,510,500,750,750,611,611,333,333,333,333,333,333,333,333,222,222,333,333,333,333,333,333,333,333],Ms=[-1,-1,-1,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,161,162,163,164,165,166,167,168,169,170,171,172,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,402,506,507,508,509,510,511,536,537,538,539,710,711,713,728,729,730,731,732,733,900,901,902,903,904,905,906,908,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,1024,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039,1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,1104,1105,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115,1116,1117,1118,1119,1138,1139,1168,1169,7808,7809,7810,7811,7812,7813,7922,7923,8208,8209,8211,8212,8213,8215,8216,8217,8218,8219,8220,8221,8222,8224,8225,8226,8230,8240,8242,8243,8249,8250,8252,8254,8260,8319,8355,8356,8359,8364,8453,8467,8470,8482,8486,8494,8539,8540,8541,8542,8592,8593,8594,8595,8596,8597,8616,8706,8710,8719,8721,8722,8730,8734,8735,8745,8747,8776,8800,8801,8804,8805,8962,8976,8992,8993,9472,9474,9484,9488,9492,9496,9500,9508,9516,9524,9532,9552,9553,9554,9555,9556,9557,9558,9559,9560,9561,9562,9563,9564,9565,9566,9567,9568,9569,9570,9571,9572,9573,9574,9575,9576,9577,9578,9579,9580,9600,9604,9608,9612,9616,9617,9618,9619,9632,9633,9642,9643,9644,9650,9658,9660,9668,9674,9675,9679,9688,9689,9702,9786,9787,9788,9792,9794,9824,9827,9829,9830,9834,9835,9836,61441,61442,61445,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],Es=[365,0,333,278,278,355,556,556,889,667,191,333,333,389,584,278,333,278,278,556,556,556,556,556,556,556,556,556,556,278,278,584,584,584,556,1015,667,667,722,722,667,611,778,722,278,500,667,556,833,722,778,667,778,722,667,611,722,667,944,667,667,611,278,278,278,469,556,333,556,556,500,556,556,278,556,556,222,222,500,222,833,556,556,556,556,333,500,278,556,500,722,500,500,500,334,260,334,584,333,556,556,556,556,260,556,333,737,370,556,584,737,552,400,549,333,333,333,576,537,278,333,333,365,556,834,834,834,611,667,667,667,667,667,667,1e3,722,667,667,667,667,278,278,278,278,722,722,778,778,778,778,778,584,778,722,722,722,722,667,667,611,556,556,556,556,556,556,889,500,556,556,556,556,278,278,278,278,556,556,556,556,556,556,556,549,611,556,556,556,556,500,556,500,667,556,667,556,667,556,722,500,722,500,722,500,722,500,722,625,722,556,667,556,667,556,667,556,667,556,667,556,778,556,778,556,778,556,778,556,722,556,722,556,278,278,278,278,278,278,278,222,278,278,733,444,500,222,667,500,500,556,222,556,222,556,281,556,400,556,222,722,556,722,556,722,556,615,723,556,778,556,778,556,778,556,1e3,944,722,333,722,333,722,333,667,500,667,500,667,500,667,500,611,278,611,354,611,278,722,556,722,556,722,556,722,556,722,556,722,556,944,722,667,500,667,611,500,611,500,611,500,222,556,667,556,1e3,889,778,611,667,500,611,278,333,333,333,333,333,333,333,333,333,333,333,667,278,789,846,389,794,865,775,222,667,667,570,671,667,611,722,778,278,667,667,833,722,648,778,725,667,600,611,667,837,667,831,761,278,667,570,439,555,222,550,570,571,500,556,439,463,555,542,222,500,492,548,500,447,556,670,573,486,603,374,550,652,546,728,779,222,550,556,550,779,667,667,843,544,708,667,278,278,500,1066,982,844,589,715,639,724,667,651,667,544,704,667,917,614,715,715,589,686,833,722,778,725,667,722,611,639,795,667,727,673,920,923,805,886,651,694,1022,682,556,562,522,493,553,556,688,465,556,556,472,564,686,550,556,556,556,500,833,500,835,500,572,518,830,851,621,736,526,492,752,534,556,556,556,378,496,500,222,222,222,910,828,556,472,565,500,556,778,556,492,339,944,722,944,722,944,722,667,500,333,333,556,1e3,1e3,552,222,222,222,222,333,333,333,556,556,350,1e3,1e3,188,354,333,333,500,333,167,365,556,556,1094,556,885,323,1083,1e3,768,600,834,834,834,834,1e3,500,998,500,1e3,500,500,494,612,823,713,584,549,713,979,719,274,549,549,584,549,549,604,584,604,604,708,625,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,729,604,604,354,354,1e3,990,990,990,990,494,604,604,604,604,354,1021,1052,917,750,750,531,656,594,510,500,750,750,500,500,333,333,333,333,333,333,333,333,222,222,294,294,324,324,316,328,398,285],Ns=[-1,-1,-1,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,161,162,163,164,165,166,167,168,169,170,171,172,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,402,506,507,508,509,510,511,536,537,538,539,710,711,713,728,729,730,731,732,733,900,901,902,903,904,905,906,908,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,1024,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039,1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,1104,1105,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115,1116,1117,1118,1119,1138,1139,1168,1169,7808,7809,7810,7811,7812,7813,7922,7923,8208,8209,8211,8212,8213,8215,8216,8217,8218,8219,8220,8221,8222,8224,8225,8226,8230,8240,8242,8243,8249,8250,8252,8254,8260,8319,8355,8356,8359,8364,8453,8467,8470,8482,8486,8494,8539,8540,8541,8542,8592,8593,8594,8595,8596,8597,8616,8706,8710,8719,8721,8722,8730,8734,8735,8745,8747,8776,8800,8801,8804,8805,8962,8976,8992,8993,9472,9474,9484,9488,9492,9496,9500,9508,9516,9524,9532,9552,9553,9554,9555,9556,9557,9558,9559,9560,9561,9562,9563,9564,9565,9566,9567,9568,9569,9570,9571,9572,9573,9574,9575,9576,9577,9578,9579,9580,9600,9604,9608,9612,9616,9617,9618,9619,9632,9633,9642,9643,9644,9650,9658,9660,9668,9674,9675,9679,9688,9689,9702,9786,9787,9788,9792,9794,9824,9827,9829,9830,9834,9835,9836,61441,61442,61445,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],zs=[365,0,333,278,278,355,556,556,889,667,191,333,333,389,584,278,333,278,278,556,556,556,556,556,556,556,556,556,556,278,278,584,584,584,556,1015,667,667,722,722,667,611,778,722,278,500,667,556,833,722,778,667,778,722,667,611,722,667,944,667,667,611,278,278,278,469,556,333,556,556,500,556,556,278,556,556,222,222,500,222,833,556,556,556,556,333,500,278,556,500,722,500,500,500,334,260,334,584,333,556,556,556,556,260,556,333,737,370,556,584,737,552,400,549,333,333,333,576,537,278,333,333,365,556,834,834,834,611,667,667,667,667,667,667,1e3,722,667,667,667,667,278,278,278,278,722,722,778,778,778,778,778,584,778,722,722,722,722,667,667,611,556,556,556,556,556,556,889,500,556,556,556,556,278,278,278,278,556,556,556,556,556,556,556,549,611,556,556,556,556,500,556,500,667,556,667,556,667,556,722,500,722,500,722,500,722,500,722,615,722,556,667,556,667,556,667,556,667,556,667,556,778,556,778,556,778,556,778,556,722,556,722,556,278,278,278,278,278,278,278,222,278,278,735,444,500,222,667,500,500,556,222,556,222,556,292,556,334,556,222,722,556,722,556,722,556,604,723,556,778,556,778,556,778,556,1e3,944,722,333,722,333,722,333,667,500,667,500,667,500,667,500,611,278,611,375,611,278,722,556,722,556,722,556,722,556,722,556,722,556,944,722,667,500,667,611,500,611,500,611,500,222,556,667,556,1e3,889,778,611,667,500,611,278,333,333,333,333,333,333,333,333,333,333,333,667,278,784,838,384,774,855,752,222,667,667,551,668,667,611,722,778,278,667,668,833,722,650,778,722,667,618,611,667,798,667,835,748,278,667,578,446,556,222,547,578,575,500,557,446,441,556,556,222,500,500,576,500,448,556,690,569,482,617,395,547,648,525,713,781,222,547,556,547,781,667,667,865,542,719,667,278,278,500,1057,1010,854,583,722,635,719,667,656,667,542,677,667,923,604,719,719,583,656,833,722,778,719,667,722,611,635,760,667,740,667,917,938,792,885,656,719,1010,722,556,573,531,365,583,556,669,458,559,559,438,583,688,552,556,542,556,500,458,500,823,500,573,521,802,823,625,719,521,510,750,542,556,556,556,365,510,500,222,278,222,906,812,556,438,559,500,552,778,556,489,411,944,722,944,722,944,722,667,500,333,333,556,1e3,1e3,552,222,222,222,222,333,333,333,556,556,350,1e3,1e3,188,354,333,333,500,333,167,365,556,556,1094,556,885,323,1073,1e3,768,600,834,834,834,834,1e3,500,1e3,500,1e3,500,500,494,612,823,713,584,549,713,979,719,274,549,549,583,549,549,604,584,604,604,708,625,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,708,729,604,604,354,354,1e3,990,990,990,990,494,604,604,604,604,354,1021,1052,917,750,750,531,656,594,510,500,750,750,500,500,333,333,333,333,333,333,333,333,222,222,294,294,324,324,316,328,398,285],Ls=[-1,-1,-1,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,161,162,163,164,165,166,167,168,169,170,171,172,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,402,506,507,508,509,510,511,536,537,538,539,710,711,713,728,729,730,731,732,733,900,901,902,903,904,905,906,908,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,1024,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039,1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,1104,1105,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115,1116,1117,1118,1119,1138,1139,1168,1169,7808,7809,7810,7811,7812,7813,7922,7923,8208,8209,8211,8212,8213,8215,8216,8217,8218,8219,8220,8221,8222,8224,8225,8226,8230,8240,8242,8243,8249,8250,8252,8254,8260,8319,8355,8356,8359,8364,8453,8467,8470,8482,8486,8494,8539,8540,8541,8542,8592,8593,8594,8595,8596,8597,8616,8706,8710,8719,8721,8722,8730,8734,8735,8745,8747,8776,8800,8801,8804,8805,8962,8976,8992,8993,9472,9474,9484,9488,9492,9496,9500,9508,9516,9524,9532,9552,9553,9554,9555,9556,9557,9558,9559,9560,9561,9562,9563,9564,9565,9566,9567,9568,9569,9570,9571,9572,9573,9574,9575,9576,9577,9578,9579,9580,9600,9604,9608,9612,9616,9617,9618,9619,9632,9633,9642,9643,9644,9650,9658,9660,9668,9674,9675,9679,9688,9689,9702,9786,9787,9788,9792,9794,9824,9827,9829,9830,9834,9835,9836,61441,61442,61445,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],Us=[1.36898,1,1,.72706,.80479,.83734,.98894,.99793,.9897,.93884,.86209,.94292,.94292,1.16661,1.02058,.93582,.96694,.93582,1.19137,.99793,.99793,.99793,.99793,.99793,.99793,.99793,.99793,.99793,.99793,.78076,.78076,1.02058,1.02058,1.02058,.72851,.78966,.90838,.83637,.82391,.96376,.80061,.86275,.8768,.95407,1.0258,.73901,.85022,.83655,1.0156,.95546,.92179,.87107,.92179,.82114,.8096,.89713,.94438,.95353,.94083,.91905,.90406,.9446,.94292,1.18777,.94292,1.02058,.89903,.90088,.94938,.97898,.81093,.97571,.94938,1.024,.9577,.95933,.98621,1.0474,.97455,.98981,.9672,.95933,.9446,.97898,.97407,.97646,.78036,1.10208,.95442,.95298,.97579,.9332,.94039,.938,.80687,1.01149,.80687,1.02058,.80479,.99793,.99793,.99793,.99793,1.01149,1.00872,.90088,.91882,1.0213,.8361,1.02058,.62295,.54324,.89022,1.08595,1,1,.90088,1,.97455,.93582,.90088,1,1.05686,.8361,.99642,.99642,.99642,.72851,.90838,.90838,.90838,.90838,.90838,.90838,.868,.82391,.80061,.80061,.80061,.80061,1.0258,1.0258,1.0258,1.0258,.97484,.95546,.92179,.92179,.92179,.92179,.92179,1.02058,.92179,.94438,.94438,.94438,.94438,.90406,.86958,.98225,.94938,.94938,.94938,.94938,.94938,.94938,.9031,.81093,.94938,.94938,.94938,.94938,.98621,.98621,.98621,.98621,.93969,.95933,.9446,.9446,.9446,.9446,.9446,1.08595,.9446,.95442,.95442,.95442,.95442,.94039,.97898,.94039,.90838,.94938,.90838,.94938,.90838,.94938,.82391,.81093,.82391,.81093,.82391,.81093,.82391,.81093,.96376,.84313,.97484,.97571,.80061,.94938,.80061,.94938,.80061,.94938,.80061,.94938,.80061,.94938,.8768,.9577,.8768,.9577,.8768,.9577,1,1,.95407,.95933,.97069,.95933,1.0258,.98621,1.0258,.98621,1.0258,.98621,1.0258,.98621,1.0258,.98621,.887,1.01591,.73901,1.0474,1,1,.97455,.83655,.98981,1,1,.83655,.73977,.83655,.73903,.84638,1.033,.95546,.95933,1,1,.95546,.95933,.8271,.95417,.95933,.92179,.9446,.92179,.9446,.92179,.9446,.936,.91964,.82114,.97646,1,1,.82114,.97646,.8096,.78036,.8096,.78036,1,1,.8096,.78036,1,1,.89713,.77452,.89713,1.10208,.94438,.95442,.94438,.95442,.94438,.95442,.94438,.95442,.94438,.95442,.94438,.95442,.94083,.97579,.90406,.94039,.90406,.9446,.938,.9446,.938,.9446,.938,1,.99793,.90838,.94938,.868,.9031,.92179,.9446,1,1,.89713,1.10208,.90088,.90088,.90088,.90088,.90088,.90088,.90088,.90088,.90088,.90989,.9358,.91945,.83181,.75261,.87992,.82976,.96034,.83689,.97268,1.0078,.90838,.83637,.8019,.90157,.80061,.9446,.95407,.92436,1.0258,.85022,.97153,1.0156,.95546,.89192,.92179,.92361,.87107,.96318,.89713,.93704,.95638,.91905,.91709,.92796,1.0258,.93704,.94836,1.0373,.95933,1.0078,.95871,.94836,.96174,.92601,.9498,.98607,.95776,.95933,1.05453,1.0078,.98275,.9314,.95617,.91701,1.05993,.9446,.78367,.9553,1,.86832,1.0128,.95871,.99394,.87548,.96361,.86774,1.0078,.95871,.9446,.95871,.86774,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.94083,.97579,.94083,.97579,.94083,.97579,.90406,.94039,.96694,1,.89903,1,1,1,.93582,.93582,.93582,1,.908,.908,.918,.94219,.94219,.96544,1,1.285,1,1,.81079,.81079,1,1,.74854,1,1,1,1,.99793,1,1,1,.65,1,1.36145,1,1,1,1,1,1,1,1,1,1,1,1.17173,1,.80535,.76169,1.02058,1.0732,1.05486,1,1,1.30692,1.08595,1.08595,1,1.08595,1.08595,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1.16161,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],_s={lineHeight:1.2,lineGap:.2},Xs=[1.36898,1,1,.66227,.80779,.81625,.97276,.97276,.97733,.92222,.83266,.94292,.94292,1.16148,1.02058,.93582,.96694,.93582,1.17337,.97276,.97276,.97276,.97276,.97276,.97276,.97276,.97276,.97276,.97276,.78076,.78076,1.02058,1.02058,1.02058,.71541,.76813,.85576,.80591,.80729,.94299,.77512,.83655,.86523,.92222,.98621,.71743,.81698,.79726,.98558,.92222,.90637,.83809,.90637,.80729,.76463,.86275,.90699,.91605,.9154,.85308,.85458,.90531,.94292,1.21296,.94292,1.02058,.89903,1.18616,.99613,.91677,.78216,.91677,.90083,.98796,.9135,.92168,.95381,.98981,.95298,.95381,.93459,.92168,.91513,.92004,.91677,.95077,.748,1.04502,.91677,.92061,.94236,.89544,.89364,.9,.80687,.8578,.80687,1.02058,.80779,.97276,.97276,.97276,.97276,.8578,.99973,1.18616,.91339,1.08074,.82891,1.02058,.55509,.71526,.89022,1.08595,1,1,1.18616,1,.96736,.93582,1.18616,1,1.04864,.82711,.99043,.99043,.99043,.71541,.85576,.85576,.85576,.85576,.85576,.85576,.845,.80729,.77512,.77512,.77512,.77512,.98621,.98621,.98621,.98621,.95961,.92222,.90637,.90637,.90637,.90637,.90637,1.02058,.90251,.90699,.90699,.90699,.90699,.85458,.83659,.94951,.99613,.99613,.99613,.99613,.99613,.99613,.85811,.78216,.90083,.90083,.90083,.90083,.95381,.95381,.95381,.95381,.9135,.92168,.91513,.91513,.91513,.91513,.91513,1.08595,.91677,.91677,.91677,.91677,.91677,.89364,.92332,.89364,.85576,.99613,.85576,.99613,.85576,.99613,.80729,.78216,.80729,.78216,.80729,.78216,.80729,.78216,.94299,.76783,.95961,.91677,.77512,.90083,.77512,.90083,.77512,.90083,.77512,.90083,.77512,.90083,.86523,.9135,.86523,.9135,.86523,.9135,1,1,.92222,.92168,.92222,.92168,.98621,.95381,.98621,.95381,.98621,.95381,.98621,.95381,.98621,.95381,.86036,.97096,.71743,.98981,1,1,.95298,.79726,.95381,1,1,.79726,.6894,.79726,.74321,.81691,1.0006,.92222,.92168,1,1,.92222,.92168,.79464,.92098,.92168,.90637,.91513,.90637,.91513,.90637,.91513,.909,.87514,.80729,.95077,1,1,.80729,.95077,.76463,.748,.76463,.748,1,1,.76463,.748,1,1,.86275,.72651,.86275,1.04502,.90699,.91677,.90699,.91677,.90699,.91677,.90699,.91677,.90699,.91677,.90699,.91677,.9154,.94236,.85458,.89364,.85458,.90531,.9,.90531,.9,.90531,.9,1,.97276,.85576,.99613,.845,.85811,.90251,.91677,1,1,.86275,1.04502,1.18616,1.18616,1.18616,1.18616,1.18616,1.18616,1.18616,1.18616,1.18616,1.00899,1.30628,.85576,.80178,.66862,.7927,.69323,.88127,.72459,.89711,.95381,.85576,.80591,.7805,.94729,.77512,.90531,.92222,.90637,.98621,.81698,.92655,.98558,.92222,.85359,.90637,.90976,.83809,.94523,.86275,.83509,.93157,.85308,.83392,.92346,.98621,.83509,.92886,.91324,.92168,.95381,.90646,.92886,.90557,.86847,.90276,.91324,.86842,.92168,.99531,.95381,.9224,.85408,.92699,.86847,1.0051,.91513,.80487,.93481,1,.88159,1.05214,.90646,.97355,.81539,.89398,.85923,.95381,.90646,.91513,.90646,.85923,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.9154,.94236,.9154,.94236,.9154,.94236,.85458,.89364,.96694,1,.89903,1,1,1,.91782,.91782,.91782,1,.896,.896,.896,.9332,.9332,.95973,1,1.26,1,1,.80479,.80178,1,1,.85633,1,1,1,1,.97276,1,1,1,.698,1,1.36145,1,1,1,1,1,1,1,1,1,1,1,1.14542,1,.79199,.78694,1.02058,1.03493,1.05486,1,1,1.23026,1.08595,1.08595,1,1.08595,1.08595,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1.20006,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],Ws={lineHeight:1.2,lineGap:.2},Ks=[1.36898,1,1,.65507,.84943,.85639,.88465,.88465,.86936,.88307,.86948,.85283,.85283,1.06383,1.02058,.75945,.9219,.75945,1.17337,.88465,.88465,.88465,.88465,.88465,.88465,.88465,.88465,.88465,.88465,.75945,.75945,1.02058,1.02058,1.02058,.69046,.70926,.85158,.77812,.76852,.89591,.70466,.76125,.80094,.86822,.83864,.728,.77212,.79475,.93637,.87514,.8588,.76013,.8588,.72421,.69866,.77598,.85991,.80811,.87832,.78112,.77512,.8562,1.0222,1.18417,1.0222,1.27014,.89903,1.15012,.93859,.94399,.846,.94399,.81453,1.0186,.94219,.96017,1.03075,1.02175,.912,1.03075,.96998,.96017,.93859,.94399,.94399,.95493,.746,1.12658,.94578,.91,.979,.882,.882,.83,.85034,.83537,.85034,1.02058,.70869,.88465,.88465,.88465,.88465,.83537,.90083,1.15012,.9161,.94565,.73541,1.02058,.53609,.69353,.79519,1.08595,1,1,1.15012,1,.91974,.75945,1.15012,1,.9446,.73361,.9005,.9005,.9005,.62864,.85158,.85158,.85158,.85158,.85158,.85158,.773,.76852,.70466,.70466,.70466,.70466,.83864,.83864,.83864,.83864,.90561,.87514,.8588,.8588,.8588,.8588,.8588,1.02058,.85751,.85991,.85991,.85991,.85991,.77512,.76013,.88075,.93859,.93859,.93859,.93859,.93859,.93859,.8075,.846,.81453,.81453,.81453,.81453,.82424,.82424,.82424,.82424,.9278,.96017,.93859,.93859,.93859,.93859,.93859,1.08595,.8562,.94578,.94578,.94578,.94578,.882,.94578,.882,.85158,.93859,.85158,.93859,.85158,.93859,.76852,.846,.76852,.846,.76852,.846,.76852,.846,.89591,.8544,.90561,.94399,.70466,.81453,.70466,.81453,.70466,.81453,.70466,.81453,.70466,.81453,.80094,.94219,.80094,.94219,.80094,.94219,1,1,.86822,.96017,.86822,.96017,.83864,.82424,.83864,.82424,.83864,.82424,.83864,1.03075,.83864,.82424,.81402,1.02738,.728,1.02175,1,1,.912,.79475,1.03075,1,1,.79475,.83911,.79475,.66266,.80553,1.06676,.87514,.96017,1,1,.87514,.96017,.86865,.87396,.96017,.8588,.93859,.8588,.93859,.8588,.93859,.867,.84759,.72421,.95493,1,1,.72421,.95493,.69866,.746,.69866,.746,1,1,.69866,.746,1,1,.77598,.88417,.77598,1.12658,.85991,.94578,.85991,.94578,.85991,.94578,.85991,.94578,.85991,.94578,.85991,.94578,.87832,.979,.77512,.882,.77512,.8562,.83,.8562,.83,.8562,.83,1,.88465,.85158,.93859,.773,.8075,.85751,.8562,1,1,.77598,1.12658,1.15012,1.15012,1.15012,1.15012,1.15012,1.15313,1.15012,1.15012,1.15012,1.08106,1.03901,.85158,.77025,.62264,.7646,.65351,.86026,.69461,.89947,1.03075,.85158,.77812,.76449,.88836,.70466,.8562,.86822,.8588,.83864,.77212,.85308,.93637,.87514,.82352,.8588,.85701,.76013,.89058,.77598,.8156,.82565,.78112,.77899,.89386,.83864,.8156,.9486,.92388,.96186,1.03075,.91123,.9486,.93298,.878,.93942,.92388,.84596,.96186,.95119,1.03075,.922,.88787,.95829,.88,.93559,.93859,.78815,.93758,1,.89217,1.03737,.91123,.93969,.77487,.85769,.86799,1.03075,.91123,.93859,.91123,.86799,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.87832,.979,.87832,.979,.87832,.979,.77512,.882,.9219,1,.89903,1,1,1,.87321,.87321,.87321,1,1.027,1.027,1.027,.86847,.86847,.79121,1,1.124,1,1,.73572,.73572,1,1,.85034,1,1,1,1,.88465,1,1,1,.669,1,1.36145,1,1,1,1,1,1,1,1,1,1,1,1.04828,1,.74948,.75187,1.02058,.98391,1.02119,1,1,1.06233,1.08595,1.08595,1,1.08595,1.08595,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1.05233,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],Gs={lineHeight:1.2,lineGap:.2},Vs=[1.36898,1,1,.76305,.82784,.94935,.89364,.92241,.89073,.90706,.98472,.85283,.85283,1.0664,1.02058,.74505,.9219,.74505,1.23456,.92241,.92241,.92241,.92241,.92241,.92241,.92241,.92241,.92241,.92241,.74505,.74505,1.02058,1.02058,1.02058,.73002,.72601,.91755,.8126,.80314,.92222,.73764,.79726,.83051,.90284,.86023,.74,.8126,.84869,.96518,.91115,.8858,.79761,.8858,.74498,.73914,.81363,.89591,.83659,.89633,.85608,.8111,.90531,1.0222,1.22736,1.0222,1.27014,.89903,.90088,.86667,1.0231,.896,1.01411,.90083,1.05099,1.00512,.99793,1.05326,1.09377,.938,1.06226,1.00119,.99793,.98714,1.0231,1.01231,.98196,.792,1.19137,.99074,.962,1.01915,.926,.942,.856,.85034,.92006,.85034,1.02058,.69067,.92241,.92241,.92241,.92241,.92006,.9332,.90088,.91882,.93484,.75339,1.02058,.56866,.54324,.79519,1.08595,1,1,.90088,1,.95325,.74505,.90088,1,.97198,.75339,.91009,.91009,.91009,.66466,.91755,.91755,.91755,.91755,.91755,.91755,.788,.80314,.73764,.73764,.73764,.73764,.86023,.86023,.86023,.86023,.92915,.91115,.8858,.8858,.8858,.8858,.8858,1.02058,.8858,.89591,.89591,.89591,.89591,.8111,.79611,.89713,.86667,.86667,.86667,.86667,.86667,.86667,.86936,.896,.90083,.90083,.90083,.90083,.84224,.84224,.84224,.84224,.97276,.99793,.98714,.98714,.98714,.98714,.98714,1.08595,.89876,.99074,.99074,.99074,.99074,.942,1.0231,.942,.91755,.86667,.91755,.86667,.91755,.86667,.80314,.896,.80314,.896,.80314,.896,.80314,.896,.92222,.93372,.92915,1.01411,.73764,.90083,.73764,.90083,.73764,.90083,.73764,.90083,.73764,.90083,.83051,1.00512,.83051,1.00512,.83051,1.00512,1,1,.90284,.99793,.90976,.99793,.86023,.84224,.86023,.84224,.86023,.84224,.86023,1.05326,.86023,.84224,.82873,1.07469,.74,1.09377,1,1,.938,.84869,1.06226,1,1,.84869,.83704,.84869,.81441,.85588,1.08927,.91115,.99793,1,1,.91115,.99793,.91887,.90991,.99793,.8858,.98714,.8858,.98714,.8858,.98714,.894,.91434,.74498,.98196,1,1,.74498,.98196,.73914,.792,.73914,.792,1,1,.73914,.792,1,1,.81363,.904,.81363,1.19137,.89591,.99074,.89591,.99074,.89591,.99074,.89591,.99074,.89591,.99074,.89591,.99074,.89633,1.01915,.8111,.942,.8111,.90531,.856,.90531,.856,.90531,.856,1,.92241,.91755,.86667,.788,.86936,.8858,.89876,1,1,.81363,1.19137,.90088,.90088,.90088,.90088,.90088,.90088,.90088,.90088,.90088,.90388,1.03901,.92138,.78105,.7154,.86169,.80513,.94007,.82528,.98612,1.06226,.91755,.8126,.81884,.92819,.73764,.90531,.90284,.8858,.86023,.8126,.91172,.96518,.91115,.83089,.8858,.87791,.79761,.89297,.81363,.88157,.89992,.85608,.81992,.94307,.86023,.88157,.95308,.98699,.99793,1.06226,.95817,.95308,.97358,.928,.98088,.98699,.92761,.99793,.96017,1.06226,.986,.944,.95978,.938,.96705,.98714,.80442,.98972,1,.89762,1.04552,.95817,.99007,.87064,.91879,.88888,1.06226,.95817,.98714,.95817,.88888,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.89633,1.01915,.89633,1.01915,.89633,1.01915,.8111,.942,.9219,1,.89903,1,1,1,.93173,.93173,.93173,1,1.06304,1.06304,1.06904,.89903,.89903,.80549,1,1.156,1,1,.76575,.76575,1,1,.72458,1,1,1,1,.92241,1,1,1,.619,1,1.36145,1,1,1,1,1,1,1,1,1,1,1,1.07257,1,.74705,.71119,1.02058,1.024,1.02119,1,1,1.1536,1.08595,1.08595,1,1.08595,1.08595,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1.05638,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],$s={lineHeight:1.2,lineGap:.2},Ys=[1.76738,1,1,.99297,.9824,1.04016,1.06497,1.03424,.97529,1.17647,1.23203,1.1085,1.1085,1.16939,1.2107,.9754,1.21408,.9754,1.59578,1.03424,1.03424,1.03424,1.03424,1.03424,1.03424,1.03424,1.03424,1.03424,1.03424,.81378,.81378,1.2107,1.2107,1.2107,.71703,.97847,.97363,.88776,.8641,1.02096,.79795,.85132,.914,1.06085,1.1406,.8007,.89858,.83693,1.14889,1.09398,.97489,.92094,.97489,.90399,.84041,.95923,1.00135,1,1.06467,.98243,.90996,.99361,1.1085,1.56942,1.1085,1.2107,.74627,.94282,.96752,1.01519,.86304,1.01359,.97278,1.15103,1.01359,.98561,1.02285,1.02285,1.00527,1.02285,1.0302,.99041,1.0008,1.01519,1.01359,1.02258,.79104,1.16862,.99041,.97454,1.02511,.99298,.96752,.95801,.94856,1.16579,.94856,1.2107,.9824,1.03424,1.03424,1,1.03424,1.16579,.8727,1.3871,1.18622,1.10818,1.04478,1.2107,1.18622,.75155,.94994,1.28826,1.21408,1.21408,.91056,1,.91572,.9754,.64663,1.18328,1.24866,1.04478,1.14169,1.15749,1.17389,.71703,.97363,.97363,.97363,.97363,.97363,.97363,.93506,.8641,.79795,.79795,.79795,.79795,1.1406,1.1406,1.1406,1.1406,1.02096,1.09398,.97426,.97426,.97426,.97426,.97426,1.2107,.97489,1.00135,1.00135,1.00135,1.00135,.90996,.92094,1.02798,.96752,.96752,.96752,.96752,.96752,.96752,.93136,.86304,.97278,.97278,.97278,.97278,1.02285,1.02285,1.02285,1.02285,.97122,.99041,1,1,1,1,1,1.28826,1.0008,.99041,.99041,.99041,.99041,.96752,1.01519,.96752,.97363,.96752,.97363,.96752,.97363,.96752,.8641,.86304,.8641,.86304,.8641,.86304,.8641,.86304,1.02096,1.03057,1.02096,1.03517,.79795,.97278,.79795,.97278,.79795,.97278,.79795,.97278,.79795,.97278,.914,1.01359,.914,1.01359,.914,1.01359,1,1,1.06085,.98561,1.06085,1.00879,1.1406,1.02285,1.1406,1.02285,1.1406,1.02285,1.1406,1.02285,1.1406,1.02285,.97138,1.08692,.8007,1.02285,1,1,1.00527,.83693,1.02285,1,1,.83693,.9455,.83693,.90418,.83693,1.13005,1.09398,.99041,1,1,1.09398,.99041,.96692,1.09251,.99041,.97489,1.0008,.97489,1.0008,.97489,1.0008,.93994,.97931,.90399,1.02258,1,1,.90399,1.02258,.84041,.79104,.84041,.79104,.84041,.79104,.84041,.79104,1,1,.95923,1.07034,.95923,1.16862,1.00135,.99041,1.00135,.99041,1.00135,.99041,1.00135,.99041,1.00135,.99041,1.00135,.99041,1.06467,1.02511,.90996,.96752,.90996,.99361,.95801,.99361,.95801,.99361,.95801,1.07733,1.03424,.97363,.96752,.93506,.93136,.97489,1.0008,1,1,.95923,1.16862,1.15103,1.15103,1.01173,1.03959,.75953,.81378,.79912,1.15103,1.21994,.95161,.87815,1.01149,.81525,.7676,.98167,1.01134,1.02546,.84097,1.03089,1.18102,.97363,.88776,.85134,.97826,.79795,.99361,1.06085,.97489,1.1406,.89858,1.0388,1.14889,1.09398,.86039,.97489,1.0595,.92094,.94793,.95923,.90996,.99346,.98243,1.02112,.95493,1.1406,.90996,1.03574,1.02597,1.0008,1.18102,1.06628,1.03574,1.0192,1.01932,1.00886,.97531,1.0106,1.0008,1.13189,1.18102,1.02277,.98683,1.0016,.99561,1.07237,1.0008,.90434,.99921,.93803,.8965,1.23085,1.06628,1.04983,.96268,1.0499,.98439,1.18102,1.06628,1.0008,1.06628,.98439,.79795,1,1,1,1,1,1,1,1,1,1,1,1,1.09466,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.97278,1,1,1,1,1,1,1,1,1,1,1,1,1.02065,1,1,1,1,1,1,1.06467,1.02511,1.06467,1.02511,1.06467,1.02511,.90996,.96752,1,1.21408,.89903,1,1,.75155,1.04394,1.04394,1.04394,1.04394,.98633,.98633,.98633,.73047,.73047,1.20642,.91211,1.25635,1.222,1.02956,1.03372,1.03372,.96039,1.24633,1,1.12454,.93503,1.03424,1.19687,1.03424,1,1,1,.771,1,1,1.15749,1.15749,1.15749,1.10948,.86279,.94434,.86279,.94434,.86182,1,1,1.16897,1,.96085,.90137,1.2107,1.18416,1.13973,.69825,.9716,2.10339,1.29004,1.29004,1.21172,1.29004,1.29004,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1.42603,1,.99862,.99862,1,.87025,.87025,.87025,.87025,1.18874,1.42603,1,1.42603,1.42603,.99862,1,1,1,1,1,1.2886,1.04315,1.15296,1.34163,1,1,1,1.09193,1.09193,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],Js={lineHeight:1.33008,lineGap:0},Qs=[1.76738,1,1,.98946,1.03959,1.04016,1.02809,1.036,.97639,1.10953,1.23203,1.11144,1.11144,1.16939,1.21237,.9754,1.21261,.9754,1.59754,1.036,1.036,1.036,1.036,1.036,1.036,1.036,1.036,1.036,1.036,.81378,.81378,1.21237,1.21237,1.21237,.73541,.97847,.97363,.89723,.87897,1.0426,.79429,.85292,.91149,1.05815,1.1406,.79631,.90128,.83853,1.04396,1.10615,.97552,.94436,.97552,.88641,.80527,.96083,1.00135,1,1.06777,.9817,.91142,.99361,1.11144,1.57293,1.11144,1.21237,.74627,1.31818,1.06585,.97042,.83055,.97042,.93503,1.1261,.97042,.97922,1.14236,.94552,1.01054,1.14236,1.02471,.97922,.94165,.97042,.97042,1.0276,.78929,1.1261,.97922,.95874,1.02197,.98507,.96752,.97168,.95107,1.16579,.95107,1.21237,1.03959,1.036,1.036,1,1.036,1.16579,.87357,1.31818,1.18754,1.26781,1.05356,1.21237,1.18622,.79487,.94994,1.29004,1.24047,1.24047,1.31818,1,.91484,.9754,1.31818,1.1349,1.24866,1.05356,1.13934,1.15574,1.17389,.73541,.97363,.97363,.97363,.97363,.97363,.97363,.94385,.87897,.79429,.79429,.79429,.79429,1.1406,1.1406,1.1406,1.1406,1.0426,1.10615,.97552,.97552,.97552,.97552,.97552,1.21237,.97552,1.00135,1.00135,1.00135,1.00135,.91142,.94436,.98721,1.06585,1.06585,1.06585,1.06585,1.06585,1.06585,.96705,.83055,.93503,.93503,.93503,.93503,1.14236,1.14236,1.14236,1.14236,.93125,.97922,.94165,.94165,.94165,.94165,.94165,1.29004,.94165,.97922,.97922,.97922,.97922,.96752,.97042,.96752,.97363,1.06585,.97363,1.06585,.97363,1.06585,.87897,.83055,.87897,.83055,.87897,.83055,.87897,.83055,1.0426,1.0033,1.0426,.97042,.79429,.93503,.79429,.93503,.79429,.93503,.79429,.93503,.79429,.93503,.91149,.97042,.91149,.97042,.91149,.97042,1,1,1.05815,.97922,1.05815,.97922,1.1406,1.14236,1.1406,1.14236,1.1406,1.14236,1.1406,1.14236,1.1406,1.14236,.97441,1.04302,.79631,1.01582,1,1,1.01054,.83853,1.14236,1,1,.83853,1.09125,.83853,.90418,.83853,1.19508,1.10615,.97922,1,1,1.10615,.97922,1.01034,1.10466,.97922,.97552,.94165,.97552,.94165,.97552,.94165,.91602,.91981,.88641,1.0276,1,1,.88641,1.0276,.80527,.78929,.80527,.78929,.80527,.78929,.80527,.78929,1,1,.96083,1.05403,.95923,1.16862,1.00135,.97922,1.00135,.97922,1.00135,.97922,1.00135,.97922,1.00135,.97922,1.00135,.97922,1.06777,1.02197,.91142,.96752,.91142,.99361,.97168,.99361,.97168,.99361,.97168,1.23199,1.036,.97363,1.06585,.94385,.96705,.97552,.94165,1,1,.96083,1.1261,1.31818,1.31818,1.31818,1.31818,1.31818,1.31818,1.31818,1.31818,1.31818,.95161,1.27126,1.00811,.83284,.77702,.99137,.95253,1.0347,.86142,1.07205,1.14236,.97363,.89723,.86869,1.09818,.79429,.99361,1.05815,.97552,1.1406,.90128,1.06662,1.04396,1.10615,.84918,.97552,1.04694,.94436,.98015,.96083,.91142,1.00356,.9817,1.01945,.98999,1.1406,.91142,1.04961,.9898,1.00639,1.14236,1.07514,1.04961,.99607,1.02897,1.008,.9898,.95134,1.00639,1.11121,1.14236,1.00518,.97981,1.02186,1,1.08578,.94165,.99314,.98387,.93028,.93377,1.35125,1.07514,1.10687,.93491,1.04232,1.00351,1.14236,1.07514,.94165,1.07514,1.00351,.79429,1,1,1,1,1,1,1,1,1,1,1,1,1.09097,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.93503,1,1,1,1,1,1,1,1,1,1,1,1,.96609,1,1,1,1,1,1,1.06777,1.02197,1.06777,1.02197,1.06777,1.02197,.91142,.96752,1,1.21261,.89903,1,1,.75155,1.04745,1.04745,1.04745,1.04394,.98633,.98633,.98633,.72959,.72959,1.20502,.91406,1.26514,1.222,1.02956,1.03372,1.03372,.96039,1.24633,1,1.09125,.93327,1.03336,1.16541,1.036,1,1,1,.771,1,1,1.15574,1.15574,1.15574,1.15574,.86364,.94434,.86279,.94434,.86224,1,1,1.16798,1,.96085,.90068,1.21237,1.18416,1.13904,.69825,.9716,2.10339,1.29004,1.29004,1.21339,1.29004,1.29004,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1.42603,1,.99862,.99862,1,.87025,.87025,.87025,.87025,1.18775,1.42603,1,1.42603,1.42603,.99862,1,1,1,1,1,1.2886,1.04315,1.15296,1.34163,1,1,1,1.13269,1.13269,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],Zs={lineHeight:1.33008,lineGap:0},er=[1.76738,1,1,.98946,1.14763,1.05365,1.06234,.96927,.92586,1.15373,1.18414,.91349,.91349,1.07403,1.17308,.78383,1.20088,.78383,1.42531,.96927,.96927,.96927,.96927,.96927,.96927,.96927,.96927,.96927,.96927,.78383,.78383,1.17308,1.17308,1.17308,.77349,.94565,.94729,.85944,.88506,.9858,.74817,.80016,.88449,.98039,.95782,.69238,.89898,.83231,.98183,1.03989,.96924,.86237,.96924,.80595,.74524,.86091,.95402,.94143,.98448,.8858,.83089,.93285,1.0949,1.39016,1.0949,1.45994,.74627,1.04839,.97454,.97454,.87207,.97454,.87533,1.06151,.97454,1.00176,1.16484,1.08132,.98047,1.16484,1.02989,1.01054,.96225,.97454,.97454,1.06598,.79004,1.16344,1.00351,.94629,.9973,.91016,.96777,.9043,.91082,.92481,.91082,1.17308,.95748,.96927,.96927,1,.96927,.92481,.80597,1.04839,1.23393,1.1781,.9245,1.17308,1.20808,.63218,.94261,1.24822,1.09971,1.09971,1.04839,1,.85273,.78032,1.04839,1.09971,1.22326,.9245,1.09836,1.13525,1.15222,.70424,.94729,.94729,.94729,.94729,.94729,.94729,.85498,.88506,.74817,.74817,.74817,.74817,.95782,.95782,.95782,.95782,.9858,1.03989,.96924,.96924,.96924,.96924,.96924,1.17308,.96924,.95402,.95402,.95402,.95402,.83089,.86237,.88409,.97454,.97454,.97454,.97454,.97454,.97454,.92916,.87207,.87533,.87533,.87533,.87533,.93146,.93146,.93146,.93146,.93854,1.01054,.96225,.96225,.96225,.96225,.96225,1.24822,.8761,1.00351,1.00351,1.00351,1.00351,.96777,.97454,.96777,.94729,.97454,.94729,.97454,.94729,.97454,.88506,.87207,.88506,.87207,.88506,.87207,.88506,.87207,.9858,.95391,.9858,.97454,.74817,.87533,.74817,.87533,.74817,.87533,.74817,.87533,.74817,.87533,.88449,.97454,.88449,.97454,.88449,.97454,1,1,.98039,1.00176,.98039,1.00176,.95782,.93146,.95782,.93146,.95782,.93146,.95782,1.16484,.95782,.93146,.84421,1.12761,.69238,1.08132,1,1,.98047,.83231,1.16484,1,1,.84723,1.04861,.84723,.78755,.83231,1.23736,1.03989,1.01054,1,1,1.03989,1.01054,.9857,1.03849,1.01054,.96924,.96225,.96924,.96225,.96924,.96225,.92383,.90171,.80595,1.06598,1,1,.80595,1.06598,.74524,.79004,.74524,.79004,.74524,.79004,.74524,.79004,1,1,.86091,1.02759,.85771,1.16344,.95402,1.00351,.95402,1.00351,.95402,1.00351,.95402,1.00351,.95402,1.00351,.95402,1.00351,.98448,.9973,.83089,.96777,.83089,.93285,.9043,.93285,.9043,.93285,.9043,1.31868,.96927,.94729,.97454,.85498,.92916,.96924,.8761,1,1,.86091,1.16344,1.04839,1.04839,1.04839,1.04839,1.04839,1.04839,1.04839,1.04839,1.04839,.81965,.81965,.94729,.78032,.71022,.90883,.84171,.99877,.77596,1.05734,1.2,.94729,.85944,.82791,.9607,.74817,.93285,.98039,.96924,.95782,.89898,.98316,.98183,1.03989,.78614,.96924,.97642,.86237,.86075,.86091,.83089,.90082,.8858,.97296,1.01284,.95782,.83089,1.0976,1.04,1.03342,1.2,1.0675,1.0976,.98205,1.03809,1.05097,1.04,.95364,1.03342,1.05401,1.2,1.02148,1.0119,1.04724,1.0127,1.02732,.96225,.8965,.97783,.93574,.94818,1.30679,1.0675,1.11826,.99821,1.0557,1.0326,1.2,1.0675,.96225,1.0675,1.0326,.74817,1,1,1,1,1,1,1,1,1,1,1,1,1.03754,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.87533,1,1,1,1,1,1,1,1,1,1,1,1,.98705,1,1,1,1,1,1,.98448,.9973,.98448,.9973,.98448,.9973,.83089,.96777,1,1.20088,.89903,1,1,.75155,.94945,.94945,.94945,.94945,1.12317,1.12317,1.12317,.67603,.67603,1.15621,.73584,1.21191,1.22135,1.06483,.94868,.94868,.95996,1.24633,1,1.07497,.87709,.96927,1.01473,.96927,1,1,1,.77295,1,1,1.09836,1.09836,1.09836,1.01522,.86321,.94434,.8649,.94434,.86182,1,1,1.083,1,.91578,.86438,1.17308,1.18416,1.14589,.69825,.97622,1.96791,1.24822,1.24822,1.17308,1.24822,1.24822,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1.42603,1,.99862,.99862,1,.87025,.87025,.87025,.87025,1.17984,1.42603,1,1.42603,1.42603,.99862,1,1,1,1,1,1.2886,1.04315,1.15296,1.34163,1,1,1,1.10742,1.10742,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],tr={lineHeight:1.33008,lineGap:0},nr=[1.76738,1,1,.98594,1.02285,1.10454,1.06234,.96927,.92037,1.19985,1.2046,.90616,.90616,1.07152,1.1714,.78032,1.20088,.78032,1.40246,.96927,.96927,.96927,.96927,.96927,.96927,.96927,.96927,.96927,.96927,.78032,.78032,1.1714,1.1714,1.1714,.80597,.94084,.96706,.85944,.85734,.97093,.75842,.79936,.88198,.9831,.95782,.71387,.86969,.84636,1.07796,1.03584,.96924,.83968,.96924,.82826,.79649,.85771,.95132,.93119,.98965,.88433,.8287,.93365,1.08612,1.3638,1.08612,1.45786,.74627,.80499,.91484,1.05707,.92383,1.05882,.9403,1.12654,1.05882,1.01756,1.09011,1.09011,.99414,1.09011,1.034,1.01756,1.05356,1.05707,1.05882,1.04399,.84863,1.21968,1.01756,.95801,1.00068,.91797,.96777,.9043,.90351,.92105,.90351,1.1714,.85337,.96927,.96927,.99912,.96927,.92105,.80597,1.2434,1.20808,1.05937,.90957,1.1714,1.20808,.75155,.94261,1.24644,1.09971,1.09971,.84751,1,.85273,.78032,.61584,1.05425,1.17914,.90957,1.08665,1.11593,1.14169,.73381,.96706,.96706,.96706,.96706,.96706,.96706,.86035,.85734,.75842,.75842,.75842,.75842,.95782,.95782,.95782,.95782,.97093,1.03584,.96924,.96924,.96924,.96924,.96924,1.1714,.96924,.95132,.95132,.95132,.95132,.8287,.83968,.89049,.91484,.91484,.91484,.91484,.91484,.91484,.93575,.92383,.9403,.9403,.9403,.9403,.8717,.8717,.8717,.8717,1.00527,1.01756,1.05356,1.05356,1.05356,1.05356,1.05356,1.24644,.95923,1.01756,1.01756,1.01756,1.01756,.96777,1.05707,.96777,.96706,.91484,.96706,.91484,.96706,.91484,.85734,.92383,.85734,.92383,.85734,.92383,.85734,.92383,.97093,1.0969,.97093,1.05882,.75842,.9403,.75842,.9403,.75842,.9403,.75842,.9403,.75842,.9403,.88198,1.05882,.88198,1.05882,.88198,1.05882,1,1,.9831,1.01756,.9831,1.01756,.95782,.8717,.95782,.8717,.95782,.8717,.95782,1.09011,.95782,.8717,.84784,1.11551,.71387,1.09011,1,1,.99414,.84636,1.09011,1,1,.84636,1.0536,.84636,.94298,.84636,1.23297,1.03584,1.01756,1,1,1.03584,1.01756,1.00323,1.03444,1.01756,.96924,1.05356,.96924,1.05356,.96924,1.05356,.93066,.98293,.82826,1.04399,1,1,.82826,1.04399,.79649,.84863,.79649,.84863,.79649,.84863,.79649,.84863,1,1,.85771,1.17318,.85771,1.21968,.95132,1.01756,.95132,1.01756,.95132,1.01756,.95132,1.01756,.95132,1.01756,.95132,1.01756,.98965,1.00068,.8287,.96777,.8287,.93365,.9043,.93365,.9043,.93365,.9043,1.08571,.96927,.96706,.91484,.86035,.93575,.96924,.95923,1,1,.85771,1.21968,1.11437,1.11437,.93109,.91202,.60411,.84164,.55572,1.01173,.97361,.81818,.81818,.96635,.78032,.72727,.92366,.98601,1.03405,.77968,1.09799,1.2,.96706,.85944,.85638,.96491,.75842,.93365,.9831,.96924,.95782,.86969,.94152,1.07796,1.03584,.78437,.96924,.98715,.83968,.83491,.85771,.8287,.94492,.88433,.9287,1.0098,.95782,.8287,1.0625,.98248,1.03424,1.2,1.01071,1.0625,.95246,1.03809,1.04912,.98248,1.00221,1.03424,1.05443,1.2,1.04785,.99609,1.00169,1.05176,.99346,1.05356,.9087,1.03004,.95542,.93117,1.23362,1.01071,1.07831,1.02512,1.05205,1.03502,1.2,1.01071,1.05356,1.01071,1.03502,.75842,1,1,1,1,1,1,1,1,1,1,1,1,1.03719,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.9403,1,1,1,1,1,1,1,1,1,1,1,1,1.04021,1,1,1,1,1,1,.98965,1.00068,.98965,1.00068,.98965,1.00068,.8287,.96777,1,1.20088,.89903,1,1,.75155,1.03077,1.03077,1.03077,1.03077,1.13196,1.13196,1.13196,.67428,.67428,1.16039,.73291,1.20996,1.22135,1.06483,.94868,.94868,.95996,1.24633,1,1.07497,.87796,.96927,1.01518,.96927,1,1,1,.77295,1,1,1.10539,1.10539,1.11358,1.06967,.86279,.94434,.86279,.94434,.86182,1,1,1.083,1,.91578,.86507,1.1714,1.18416,1.14589,.69825,.97622,1.9697,1.24822,1.24822,1.17238,1.24822,1.24822,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1.42603,1,.99862,.99862,1,.87025,.87025,.87025,.87025,1.18083,1.42603,1,1.42603,1.42603,.99862,1,1,1,1,1,1.2886,1.04315,1.15296,1.34163,1,1,1,1.10938,1.10938,1,1,1,1.05425,1.09971,1.09971,1.09971,1,1,1,1,1,1,1,1,1,1,1],ar={lineHeight:1.33008,lineGap:0},sr=getLookupTableFactory(function(e){e["MyriadPro-Regular"]=e["PdfJS-Fallback-Regular"]={name:"LiberationSans-Regular",factors:Vs,baseWidths:zs,baseMapping:Ls,metrics:$s};e["MyriadPro-Bold"]=e["PdfJS-Fallback-Bold"]={name:"LiberationSans-Bold",factors:Us,baseWidths:Bs,baseMapping:Rs,metrics:_s};e["MyriadPro-It"]=e["MyriadPro-Italic"]=e["PdfJS-Fallback-Italic"]={name:"LiberationSans-Italic",factors:Ks,baseWidths:Es,baseMapping:Ns,metrics:Gs};e["MyriadPro-BoldIt"]=e["MyriadPro-BoldItalic"]=e["PdfJS-Fallback-BoldItalic"]={name:"LiberationSans-BoldItalic",factors:Xs,baseWidths:Ds,baseMapping:Ms,metrics:Ws};e.ArialMT=e.Arial=e["Arial-Regular"]={name:"LiberationSans-Regular",baseWidths:zs,baseMapping:Ls};e["Arial-BoldMT"]=e["Arial-Bold"]={name:"LiberationSans-Bold",baseWidths:Bs,baseMapping:Rs};e["Arial-ItalicMT"]=e["Arial-Italic"]={name:"LiberationSans-Italic",baseWidths:Es,baseMapping:Ns};e["Arial-BoldItalicMT"]=e["Arial-BoldItalic"]={name:"LiberationSans-BoldItalic",baseWidths:Ds,baseMapping:Ms};e["Calibri-Regular"]={name:"LiberationSans-Regular",factors:vs,baseWidths:zs,baseMapping:Ls,metrics:Ss};e["Calibri-Bold"]={name:"LiberationSans-Bold",factors:bs,baseWidths:Bs,baseMapping:Rs,metrics:ws};e["Calibri-Italic"]={name:"LiberationSans-Italic",factors:ys,baseWidths:Es,baseMapping:Ns,metrics:qs};e["Calibri-BoldItalic"]={name:"LiberationSans-BoldItalic",factors:js,baseWidths:Ds,baseMapping:Ms,metrics:ks};e["Segoeui-Regular"]={name:"LiberationSans-Regular",factors:nr,baseWidths:zs,baseMapping:Ls,metrics:ar};e["Segoeui-Bold"]={name:"LiberationSans-Bold",factors:Ys,baseWidths:Bs,baseMapping:Rs,metrics:Js};e["Segoeui-Italic"]={name:"LiberationSans-Italic",factors:er,baseWidths:Es,baseMapping:Ns,metrics:tr};e["Segoeui-BoldItalic"]={name:"LiberationSans-BoldItalic",factors:Qs,baseWidths:Ds,baseMapping:Ms,metrics:Zs};e["Helvetica-Regular"]=e.Helvetica={name:"LiberationSans-Regular",factors:Hs,baseWidths:zs,baseMapping:Ls,metrics:Os};e["Helvetica-Bold"]={name:"LiberationSans-Bold",factors:xs,baseWidths:Bs,baseMapping:Rs,metrics:As};e["Helvetica-Italic"]={name:"LiberationSans-Italic",factors:Fs,baseWidths:Es,baseMapping:Ns,metrics:Ts};e["Helvetica-BoldItalic"]={name:"LiberationSans-BoldItalic",factors:Cs,baseWidths:Ds,baseMapping:Ms,metrics:Is}});function getXfaFontName(e){const t=normalizeFontName(e);return sr()[t]}function getXfaFontDict(e){const t=function getXfaFontWidths(e){const t=getXfaFontName(e);if(!t)return null;const{baseWidths:n,baseMapping:a,factors:s}=t,r=s?n.map((e,t)=>e*s[t]):n;let i,o=-2;const l=[];for(const[e,t]of a.map((e,t)=>[e,t]).sort(([e],[t])=>e-t))if(-1!==e)if(e===o+1){i.push(r[t]);o+=1}else{o=e;i=[r[t]];l.push(e,i)}return l}(e),n=new Dict(null);n.set("BaseFont",Name.get(e));n.set("Type",Name.get("Font"));n.set("Subtype",Name.get("CIDFontType2"));n.set("Encoding",Name.get("Identity-H"));n.set("CIDToGIDMap",Name.get("Identity"));n.set("W",t);n.set("FirstChar",t[0]);n.set("LastChar",t.at(-2)+t.at(-1).length-1);const a=new Dict(null);n.set("FontDescriptor",a);const s=new Dict(null);s.set("Ordering","Identity");s.set("Registry","Adobe");s.set("Supplement",0);n.set("CIDSystemInfo",s);return n}class PostScriptParser{constructor(e){this.lexer=e;this.operators=[];this.token=null;this.prev=null}nextToken(){this.prev=this.token;this.token=this.lexer.getToken()}accept(e){if(this.token.type===e){this.nextToken();return!0}return!1}expect(e){if(this.accept(e))return!0;throw new FormatError(`Unexpected symbol: found ${this.token.type} expected ${e}.`)}parse(){this.nextToken();this.expect(rr.LBRACE);this.parseBlock();this.expect(rr.RBRACE);return this.operators}parseBlock(){for(;;)if(this.accept(rr.NUMBER))this.operators.push(this.prev.value);else if(this.accept(rr.OPERATOR))this.operators.push(this.prev.value);else{if(!this.accept(rr.LBRACE))return;this.parseCondition()}}parseCondition(){const e=this.operators.length;this.operators.push(null,null);this.parseBlock();this.expect(rr.RBRACE);if(this.accept(rr.IF)){this.operators[e]=this.operators.length;this.operators[e+1]="jz"}else{if(!this.accept(rr.LBRACE))throw new FormatError("PS Function: error parsing conditional.");{const t=this.operators.length;this.operators.push(null,null);const n=this.operators.length;this.parseBlock();this.expect(rr.RBRACE);this.expect(rr.IFELSE);this.operators[t]=this.operators.length;this.operators[t+1]="j";this.operators[e]=n;this.operators[e+1]="jz"}}}}const rr={LBRACE:0,RBRACE:1,NUMBER:2,OPERATOR:3,IF:4,IFELSE:5};class PostScriptToken{static get opCache(){return shadow(this,"opCache",Object.create(null))}constructor(e,t){this.type=e;this.value=t}static getOperator(e){return PostScriptToken.opCache[e]||=new PostScriptToken(rr.OPERATOR,e)}static get LBRACE(){return shadow(this,"LBRACE",new PostScriptToken(rr.LBRACE,"{"))}static get RBRACE(){return shadow(this,"RBRACE",new PostScriptToken(rr.RBRACE,"}"))}static get IF(){return shadow(this,"IF",new PostScriptToken(rr.IF,"IF"))}static get IFELSE(){return shadow(this,"IFELSE",new PostScriptToken(rr.IFELSE,"IFELSE"))}}class PostScriptLexer{constructor(e){this.stream=e;this.nextChar();this.strBuf=[]}nextChar(){return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(t<0)return on;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return new PostScriptToken(rr.NUMBER,this.getNumber());case 123:this.nextChar();return PostScriptToken.LBRACE;case 125:this.nextChar();return PostScriptToken.RBRACE}const n=this.strBuf;n.length=0;n[0]=String.fromCharCode(t);for(;(t=this.nextChar())>=0&&(t>=65&&t<=90||t>=97&&t<=122);)n.push(String.fromCharCode(t));const a=n.join("");switch(a.toLowerCase()){case"if":return PostScriptToken.IF;case"ifelse":return PostScriptToken.IFELSE;default:return PostScriptToken.getOperator(a)}}getNumber(){let e=this.currentChar;const t=this.strBuf;t.length=0;t[0]=String.fromCharCode(e);for(;(e=this.nextChar())>=0&&(e>=48&&e<=57||45===e||46===e);)t.push(String.fromCharCode(e));const n=parseFloat(t.join(""));if(isNaN(n))throw new FormatError(`Invalid floating point number: ${n}`);return n}}class BaseLocalCache{constructor(e){this._onlyRefs=!0===e?.onlyRefs;if(!this._onlyRefs){this._nameRefMap=new Map;this._imageMap=new Map}this._imageCache=new RefSetCache}getByName(e){this._onlyRefs&&unreachable("Should not call `getByName` method.");const t=this._nameRefMap.get(e);return t?this.getByRef(t):this._imageMap.get(e)||null}getByRef(e){return this._imageCache.get(e)||null}set(e,t,n){unreachable("Abstract method `set` called.")}}class LocalImageCache extends BaseLocalCache{set(e,t=null,n){if("string"!=typeof e)throw new Error('LocalImageCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,n)}else this._imageMap.has(e)||this._imageMap.set(e,n)}}class LocalColorSpaceCache extends BaseLocalCache{set(e=null,t=null,n){if("string"!=typeof e&&!t)throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');if(t){if(this._imageCache.has(t))return;null!==e&&this._nameRefMap.set(e,t);this._imageCache.put(t,n)}else this._imageMap.has(e)||this._imageMap.set(e,n)}}class LocalFunctionCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,n){if(!t)throw new Error('LocalFunctionCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,n)}}class LocalGStateCache extends BaseLocalCache{set(e,t=null,n){if("string"!=typeof e)throw new Error('LocalGStateCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,n)}else this._imageMap.has(e)||this._imageMap.set(e,n)}}class LocalTilingPatternCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,n){if(!t)throw new Error('LocalTilingPatternCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,n)}}class RegionalImageCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,n){if(!t)throw new Error('RegionalImageCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,n)}}class GlobalColorSpaceCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,n){if(!t)throw new Error('GlobalColorSpaceCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,n)}clear(){this._imageCache.clear()}}class GlobalImageCache{static NUM_PAGES_THRESHOLD=2;static MIN_IMAGES_TO_CACHE=10;static MAX_BYTE_SIZE=5e7;#le=new RefSet;constructor(){this._refCache=new RefSetCache;this._imageCache=new RefSetCache}get#fe(){let e=0;for(const t of this._imageCache)e+=t.byteSize;return e}get#ce(){return!(this._imageCache.size<GlobalImageCache.MIN_IMAGES_TO_CACHE)&&!(this.#fe<GlobalImageCache.MAX_BYTE_SIZE)}shouldCache(e,t){let n=this._refCache.get(e);if(!n){n=new Set;this._refCache.put(e,n)}n.add(t);return!(n.size<GlobalImageCache.NUM_PAGES_THRESHOLD)&&!(!this._imageCache.has(e)&&this.#ce)}addDecodeFailed(e){this.#le.put(e)}hasDecodeFailed(e){return this.#le.has(e)}addByteSize(e,t){const n=this._imageCache.get(e);n&&(n.byteSize||(n.byteSize=t))}getData(e,t){const n=this._refCache.get(e);if(!n)return null;if(n.size<GlobalImageCache.NUM_PAGES_THRESHOLD)return null;const a=this._imageCache.get(e);if(!a)return null;n.add(t);return a}setData(e,t){if(!this._refCache.has(e))throw new Error('GlobalImageCache.setData - expected "shouldCache" to have been called.');this._imageCache.has(e)||(this.#ce?warn("GlobalImageCache.setData - cache limit reached."):this._imageCache.put(e,t))}clear(e=!1){if(!e){this.#le.clear();this._refCache.clear()}this._imageCache.clear()}}class PDFFunctionFactory{constructor({xref:e,isEvalSupported:t=!0}){this.xref=e;this.isEvalSupported=!1!==t}create(e,t=!1){let n,a;e instanceof Ref?n=e:e instanceof Dict?n=e.objId:e instanceof BaseStream&&(n=e.dict?.objId);if(n){const e=this._localFunctionCache.getByRef(n);if(e)return e}const s=this.xref.fetchIfRef(e);if(Array.isArray(s)){if(!t)throw new Error('PDFFunctionFactory.create - expected "parseArray" argument.');a=PDFFunction.parseArray(this,s)}else a=PDFFunction.parse(this,s);n&&this._localFunctionCache.set(null,n,a);return a}get _localFunctionCache(){return shadow(this,"_localFunctionCache",new LocalFunctionCache)}}function toNumberArray(e){return Array.isArray(e)?isNumberArray(e,null)?e:e.map(e=>+e):null}class PDFFunction{static getSampleArray(e,t,n,a){let s=t;for(const t of e)s*=t;const r=new Array(s);let i=0,o=0;const l=1/(2**n-1),f=a.getBytes((s*n+7)/8);let c=0;for(let e=0;e<s;e++){for(;i<n;){o<<=8;o|=f[c++];i+=8}i-=n;r[e]=(o>>i)*l;o&=(1<<i)-1}return r}static parse(e,t){const n=t.dict||t;switch(n.get("FunctionType")){case 0:return this.constructSampled(e,t,n);case 1:break;case 2:return this.constructInterpolated(e,n);case 3:return this.constructStiched(e,n);case 4:return this.constructPostScript(e,t,n)}throw new FormatError("Unknown type of function")}static parseArray(e,t){const{xref:n}=e,a=[];for(const s of t)a.push(this.parse(e,n.fetchIfRef(s)));return function(e,t,n,s){for(let r=0,i=a.length;r<i;r++)a[r](e,t,n,s+r)}}static constructSampled(e,t,n){function toMultiArray(e){const t=e.length,n=[];let a=0;for(let s=0;s<t;s+=2)n[a++]=[e[s],e[s+1]];return n}function interpolate(e,t,n,a,s){return a+(s-a)/(n-t)*(e-t)}let a=toNumberArray(n.getArray("Domain")),s=toNumberArray(n.getArray("Range"));if(!a||!s)throw new FormatError("No domain or range");const r=a.length/2,i=s.length/2;a=toMultiArray(a);s=toMultiArray(s);const o=toNumberArray(n.getArray("Size")),l=n.get("BitsPerSample"),f=n.get("Order")||1;1!==f&&info("No support for cubic spline interpolation: "+f);let c=toNumberArray(n.getArray("Encode"));if(c)c=toMultiArray(c);else{c=[];for(let e=0;e<r;++e)c.push([0,o[e]-1])}let h=toNumberArray(n.getArray("Decode"));h=h?toMultiArray(h):s;const u=this.getSampleArray(o,i,l,t);return function constructSampledFn(e,t,n,l){const f=1<<r,m=new Float64Array(f).fill(1),p=new Uint32Array(f);let d,g,b=i,w=1;for(d=0;d<r;++d){const n=a[d][0],s=a[d][1];let r=interpolate(MathClamp(e[t+d],n,s),n,s,c[d][0],c[d][1]);const i=o[d];r=MathClamp(r,0,i-1);const l=r<i-1?Math.floor(r):r-1,h=l+1-r,u=r-l,j=l*b,k=j+b;for(g=0;g<f;g++)if(g&w){m[g]*=u;p[g]+=k}else{m[g]*=h;p[g]+=j}b*=i;w<<=1}for(g=0;g<i;++g){let e=0;for(d=0;d<f;d++)e+=u[p[d]+g]*m[d];e=interpolate(e,0,1,h[g][0],h[g][1]);n[l+g]=MathClamp(e,s[g][0],s[g][1])}}}static constructInterpolated(e,t){const n=toNumberArray(t.getArray("C0"))||[0],a=toNumberArray(t.getArray("C1"))||[1],s=t.get("N"),r=[];for(let e=0,t=n.length;e<t;++e)r.push(a[e]-n[e]);const i=r.length;return function constructInterpolatedFn(e,t,a,o){const l=1===s?e[t]:e[t]**s;for(let e=0;e<i;++e)a[o+e]=n[e]+l*r[e]}}static constructStiched(e,t){const n=toNumberArray(t.getArray("Domain"));if(!n)throw new FormatError("No domain");if(1!==n.length/2)throw new FormatError("Bad domain for stiched function");const{xref:a}=e,s=[];for(const n of t.get("Functions"))s.push(this.parse(e,a.fetchIfRef(n)));const r=toNumberArray(t.getArray("Bounds")),i=toNumberArray(t.getArray("Encode")),o=new Float32Array(1);return function constructStichedFn(e,t,a,l){const f=MathClamp(e[t],n[0],n[1]),c=r.length;let h;for(h=0;h<c&&!(f<r[h]);++h);const u=h>0?r[h-1]:n[0],m=h<c?r[h]:n[1],p=i[2*h],d=i[2*h+1];o[0]=u===m?p:p+(f-u)*(d-p)/(m-u);s[h](o,0,a,l)}}static constructPostScript(e,t,n){const a=toNumberArray(n.getArray("Domain")),s=toNumberArray(n.getArray("Range"));if(!a)throw new FormatError("No domain.");if(!s)throw new FormatError("No range.");const r=new PostScriptLexer(t),i=new PostScriptParser(r).parse();if(e.isEvalSupported&&FeatureTest.isEvalSupported){const e=(new PostScriptCompiler).compile(i,a,s);if(e)return new Function("src","srcOffset","dest","destOffset",e)}info("Unable to compile PS function");const o=s.length>>1,l=a.length>>1,f=new PostScriptEvaluator(i),c=Object.create(null);let h=8192;const u=new Float32Array(l);return function constructPostScriptFn(e,t,n,a){let r,i,m="";const p=u;for(r=0;r<l;r++){i=e[t+r];p[r]=i;m+=i+"_"}const d=c[m];if(void 0!==d){n.set(d,a);return}const g=new Float32Array(o),b=f.execute(p),w=b.length-o;for(r=0;r<o;r++)g[r]=MathClamp(b[w+r],s[2*r],s[2*r+1]);if(h>0){h--;c[m]=g}n.set(g,a)}}}function isPDFFunction(e){let t;if(e instanceof Dict)t=e;else{if(!(e instanceof BaseStream))return!1;t=e.dict}return t.has("FunctionType")}class PostScriptStack{static MAX_STACK_SIZE=100;constructor(e){this.stack=e?Array.from(e):[]}push(e){if(this.stack.length>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");this.stack.push(e)}pop(){if(this.stack.length<=0)throw new Error("PostScript function stack underflow.");return this.stack.pop()}copy(e){if(this.stack.length+e>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");const t=this.stack;for(let n=t.length-e,a=e-1;a>=0;a--,n++)t.push(t[n])}index(e){this.push(this.stack[this.stack.length-e-1])}roll(e,t){const n=this.stack,a=n.length-e,s=n.length-1,r=a+(t-Math.floor(t/e)*e);for(let e=a,t=s;e<t;e++,t--){const a=n[e];n[e]=n[t];n[t]=a}for(let e=a,t=r-1;e<t;e++,t--){const a=n[e];n[e]=n[t];n[t]=a}for(let e=r,t=s;e<t;e++,t--){const a=n[e];n[e]=n[t];n[t]=a}}}class PostScriptEvaluator{constructor(e){this.operators=e}execute(e){const t=new PostScriptStack(e);let n=0;const a=this.operators,s=a.length;let r,i,o;for(;n<s;){r=a[n++];if("number"!=typeof r)switch(r){case"jz":o=t.pop();i=t.pop();i||(n=o);break;case"j":i=t.pop();n=i;break;case"abs":i=t.pop();t.push(Math.abs(i));break;case"add":o=t.pop();i=t.pop();t.push(i+o);break;case"and":o=t.pop();i=t.pop();"boolean"==typeof i&&"boolean"==typeof o?t.push(i&&o):t.push(i&o);break;case"atan":o=t.pop();i=t.pop();i=Math.atan2(i,o)/Math.PI*180;i<0&&(i+=360);t.push(i);break;case"bitshift":o=t.pop();i=t.pop();i>0?t.push(i<<o):t.push(i>>o);break;case"ceiling":i=t.pop();t.push(Math.ceil(i));break;case"copy":i=t.pop();t.copy(i);break;case"cos":i=t.pop();t.push(Math.cos(i%360/180*Math.PI));break;case"cvi":i=0|t.pop();t.push(i);break;case"cvr":break;case"div":o=t.pop();i=t.pop();t.push(i/o);break;case"dup":t.copy(1);break;case"eq":o=t.pop();i=t.pop();t.push(i===o);break;case"exch":t.roll(2,1);break;case"exp":o=t.pop();i=t.pop();t.push(i**o);break;case"false":t.push(!1);break;case"floor":i=t.pop();t.push(Math.floor(i));break;case"ge":o=t.pop();i=t.pop();t.push(i>=o);break;case"gt":o=t.pop();i=t.pop();t.push(i>o);break;case"idiv":o=t.pop();i=t.pop();t.push(i/o|0);break;case"index":i=t.pop();t.index(i);break;case"le":o=t.pop();i=t.pop();t.push(i<=o);break;case"ln":i=t.pop();t.push(Math.log(i));break;case"log":i=t.pop();t.push(Math.log10(i));break;case"lt":o=t.pop();i=t.pop();t.push(i<o);break;case"mod":o=t.pop();i=t.pop();t.push(i%o);break;case"mul":o=t.pop();i=t.pop();t.push(i*o);break;case"ne":o=t.pop();i=t.pop();t.push(i!==o);break;case"neg":i=t.pop();t.push(-i);break;case"not":i=t.pop();"boolean"==typeof i?t.push(!i):t.push(~i);break;case"or":o=t.pop();i=t.pop();"boolean"==typeof i&&"boolean"==typeof o?t.push(i||o):t.push(i|o);break;case"pop":t.pop();break;case"roll":o=t.pop();i=t.pop();t.roll(i,o);break;case"round":i=t.pop();t.push(Math.round(i));break;case"sin":i=t.pop();t.push(Math.sin(i%360/180*Math.PI));break;case"sqrt":i=t.pop();t.push(Math.sqrt(i));break;case"sub":o=t.pop();i=t.pop();t.push(i-o);break;case"true":t.push(!0);break;case"truncate":i=t.pop();i=i<0?Math.ceil(i):Math.floor(i);t.push(i);break;case"xor":o=t.pop();i=t.pop();"boolean"==typeof i&&"boolean"==typeof o?t.push(i!==o):t.push(i^o);break;default:throw new FormatError(`Unknown operator ${r}`)}else t.push(r)}return t.stack}}class AstNode{constructor(e){this.type=e}visit(e){unreachable("abstract method")}}class AstArgument extends AstNode{constructor(e,t,n){super("args");this.index=e;this.min=t;this.max=n}visit(e){e.visitArgument(this)}}class AstLiteral extends AstNode{constructor(e){super("literal");this.number=e;this.min=e;this.max=e}visit(e){e.visitLiteral(this)}}class AstBinaryOperation extends AstNode{constructor(e,t,n,a,s){super("binary");this.op=e;this.arg1=t;this.arg2=n;this.min=a;this.max=s}visit(e){e.visitBinaryOperation(this)}}class AstMin extends AstNode{constructor(e,t){super("max");this.arg=e;this.min=e.min;this.max=t}visit(e){e.visitMin(this)}}class AstVariable extends AstNode{constructor(e,t,n){super("var");this.index=e;this.min=t;this.max=n}visit(e){e.visitVariable(this)}}class AstVariableDefinition extends AstNode{constructor(e,t){super("definition");this.variable=e;this.arg=t}visit(e){e.visitVariableDefinition(this)}}class ExpressionBuilderVisitor{parts=[];visitArgument(e){this.parts.push("Math.max(",e.min,", Math.min(",e.max,", src[srcOffset + ",e.index,"]))")}visitVariable(e){this.parts.push("v",e.index)}visitLiteral(e){this.parts.push(e.number)}visitBinaryOperation(e){this.parts.push("(");e.arg1.visit(this);this.parts.push(" ",e.op," ");e.arg2.visit(this);this.parts.push(")")}visitVariableDefinition(e){this.parts.push("var ");e.variable.visit(this);this.parts.push(" = ");e.arg.visit(this);this.parts.push(";")}visitMin(e){this.parts.push("Math.min(");e.arg.visit(this);this.parts.push(", ",e.max,")")}toString(){return this.parts.join("")}}function buildAddOperation(e,t){return"literal"===t.type&&0===t.number?e:"literal"===e.type&&0===e.number?t:"literal"===t.type&&"literal"===e.type?new AstLiteral(e.number+t.number):new AstBinaryOperation("+",e,t,e.min+t.min,e.max+t.max)}function buildMulOperation(e,t){if("literal"===t.type){if(0===t.number)return new AstLiteral(0);if(1===t.number)return e;if("literal"===e.type)return new AstLiteral(e.number*t.number)}if("literal"===e.type){if(0===e.number)return new AstLiteral(0);if(1===e.number)return t}const n=Math.min(e.min*t.min,e.min*t.max,e.max*t.min,e.max*t.max),a=Math.max(e.min*t.min,e.min*t.max,e.max*t.min,e.max*t.max);return new AstBinaryOperation("*",e,t,n,a)}function buildSubOperation(e,t){if("literal"===t.type){if(0===t.number)return e;if("literal"===e.type)return new AstLiteral(e.number-t.number)}return"binary"===t.type&&"-"===t.op&&"literal"===e.type&&1===e.number&&"literal"===t.arg1.type&&1===t.arg1.number?t.arg2:new AstBinaryOperation("-",e,t,e.min-t.max,e.max-t.min)}function buildMinOperation(e,t){return e.min>=t?new AstLiteral(t):e.max<=t?e:new AstMin(e,t)}class PostScriptCompiler{compile(e,t,n){const a=[],s=[],r=t.length>>1,i=n.length>>1;let o,l,f,c,h,u,m,p,d=0;for(let e=0;e<r;e++)a.push(new AstArgument(e,t[2*e],t[2*e+1]));for(let t=0,n=e.length;t<n;t++){p=e[t];if("number"!=typeof p)switch(p){case"add":if(a.length<2)return null;c=a.pop();f=a.pop();a.push(buildAddOperation(f,c));break;case"cvr":if(a.length<1)return null;break;case"mul":if(a.length<2)return null;c=a.pop();f=a.pop();a.push(buildMulOperation(f,c));break;case"sub":if(a.length<2)return null;c=a.pop();f=a.pop();a.push(buildSubOperation(f,c));break;case"exch":if(a.length<2)return null;h=a.pop();u=a.pop();a.push(h,u);break;case"pop":if(a.length<1)return null;a.pop();break;case"index":if(a.length<1)return null;f=a.pop();if("literal"!==f.type)return null;o=f.number;if(o<0||!Number.isInteger(o)||a.length<o)return null;h=a[a.length-o-1];if("literal"===h.type||"var"===h.type){a.push(h);break}m=new AstVariable(d++,h.min,h.max);a[a.length-o-1]=m;a.push(m);s.push(new AstVariableDefinition(m,h));break;case"dup":if(a.length<1)return null;if("number"==typeof e[t+1]&&"gt"===e[t+2]&&e[t+3]===t+7&&"jz"===e[t+4]&&"pop"===e[t+5]&&e[t+6]===e[t+1]){f=a.pop();a.push(buildMinOperation(f,e[t+1]));t+=6;break}h=a.at(-1);if("literal"===h.type||"var"===h.type){a.push(h);break}m=new AstVariable(d++,h.min,h.max);a[a.length-1]=m;a.push(m);s.push(new AstVariableDefinition(m,h));break;case"roll":if(a.length<2)return null;c=a.pop();f=a.pop();if("literal"!==c.type||"literal"!==f.type)return null;l=c.number;o=f.number;if(o<=0||!Number.isInteger(o)||!Number.isInteger(l)||a.length<o)return null;l=(l%o+o)%o;if(0===l)break;a.push(...a.splice(a.length-o,o-l));break;default:return null}else a.push(new AstLiteral(p))}if(a.length!==i)return null;const g=[];for(const e of s){const t=new ExpressionBuilderVisitor;e.visit(t);g.push(t.toString())}for(let e=0,t=a.length;e<t;e++){const t=a[e],s=new ExpressionBuilderVisitor;t.visit(s);const r=n[2*e],i=n[2*e+1],o=[s.toString()];if(r>t.min){o.unshift("Math.max(",r,", ");o.push(")")}if(i<t.max){o.unshift("Math.min(",i,", ");o.push(")")}o.unshift("dest[destOffset + ",e,"] = ");o.push(";");g.push(o.join(""))}return g.join("\n")}}const ir=["BN","BN","BN","BN","BN","BN","BN","BN","BN","S","B","S","WS","B","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","B","B","B","S","WS","ON","ON","ET","ET","ET","ON","ON","ON","ON","ON","ES","CS","ES","CS","CS","EN","EN","EN","EN","EN","EN","EN","EN","EN","EN","CS","ON","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","ON","ON","ON","BN","BN","BN","BN","BN","BN","B","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","CS","ON","ET","ET","ET","ET","ON","ON","ON","ON","L","ON","ON","BN","ON","ON","ET","ET","EN","EN","ON","L","ON","ON","ON","EN","L","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","L","L","L","L","L","L","L","L"],or=["AN","AN","AN","AN","AN","AN","ON","ON","AL","ET","ET","AL","CS","AL","ON","ON","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","AL","AL","","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","AN","AN","AN","AN","AN","AN","AN","AN","AN","AN","ET","AN","AN","AL","AL","AL","NSM","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","NSM","NSM","NSM","NSM","NSM","NSM","NSM","AN","ON","NSM","NSM","NSM","NSM","NSM","NSM","AL","AL","NSM","NSM","ON","NSM","NSM","NSM","NSM","AL","AL","EN","EN","EN","EN","EN","EN","EN","EN","EN","EN","AL","AL","AL","AL","AL","AL"];function isOdd(e){return!!(1&e)}function isEven(e){return!(1&e)}function findUnequal(e,t,n){let a,s;for(a=t,s=e.length;a<s;++a)if(e[a]!==n)return a;return a}function reverseValues(e,t,n){for(let a=t,s=n-1;a<s;++a,--s){const t=e[a];e[a]=e[s];e[s]=t}}function createBidiText(e,t,n=!1){let a="ltr";n?a="ttb":t||(a="rtl");return{str:e,dir:a}}const lr=[],fr=[];function bidi(e,t=-1,n=!1){let a=!0;const s=e.length;if(0===s||n)return createBidiText(e,a,n);lr.length=s;fr.length=s;let r,i,o=0;for(r=0;r<s;++r){lr[r]=e.charAt(r);const t=e.charCodeAt(r);let n="L";if(t<=255)n=ir[t];else if(1424<=t&&t<=1524)n="R";else if(1536<=t&&t<=1791){n=or[255&t];n||warn("Bidi: invalid Unicode character "+t.toString(16))}else(1792<=t&&t<=2220||64336<=t&&t<=65023||65136<=t&&t<=65279)&&(n="AL");"R"!==n&&"AL"!==n&&"AN"!==n||o++;fr[r]=n}if(0===o){a=!0;return createBidiText(e,a)}if(-1===t)if(o/s<.3&&s>4){a=!0;t=0}else{a=!1;t=1}const l=[];for(r=0;r<s;++r)l[r]=t;const f=isOdd(t)?"R":"L",c=f,h=c;let u,m=c;for(r=0;r<s;++r)"NSM"===fr[r]?fr[r]=m:m=fr[r];m=c;for(r=0;r<s;++r){u=fr[r];"EN"===u?fr[r]="AL"===m?"AN":"EN":"R"!==u&&"L"!==u&&"AL"!==u||(m=u)}for(r=0;r<s;++r){u=fr[r];"AL"===u&&(fr[r]="R")}for(r=1;r<s-1;++r){"ES"===fr[r]&&"EN"===fr[r-1]&&"EN"===fr[r+1]&&(fr[r]="EN");"CS"!==fr[r]||"EN"!==fr[r-1]&&"AN"!==fr[r-1]||fr[r+1]!==fr[r-1]||(fr[r]=fr[r-1])}for(r=0;r<s;++r)if("EN"===fr[r]){for(let e=r-1;e>=0&&"ET"===fr[e];--e)fr[e]="EN";for(let e=r+1;e<s&&"ET"===fr[e];++e)fr[e]="EN"}for(r=0;r<s;++r){u=fr[r];"WS"!==u&&"ES"!==u&&"ET"!==u&&"CS"!==u||(fr[r]="ON")}m=c;for(r=0;r<s;++r){u=fr[r];"EN"===u?fr[r]="L"===m?"L":"EN":"R"!==u&&"L"!==u||(m=u)}for(r=0;r<s;++r)if("ON"===fr[r]){const e=findUnequal(fr,r+1,"ON");let t=c;r>0&&(t=fr[r-1]);let n=h;e+1<s&&(n=fr[e+1]);"L"!==t&&(t="R");"L"!==n&&(n="R");t===n&&fr.fill(t,r,e);r=e-1}for(r=0;r<s;++r)"ON"===fr[r]&&(fr[r]=f);for(r=0;r<s;++r){u=fr[r];isEven(l[r])?"R"===u?l[r]+=1:"AN"!==u&&"EN"!==u||(l[r]+=2):"L"!==u&&"AN"!==u&&"EN"!==u||(l[r]+=1)}let p,d=-1,g=99;for(r=0,i=l.length;r<i;++r){p=l[r];d<p&&(d=p);g>p&&isOdd(p)&&(g=p)}for(p=d;p>=g;--p){let e=-1;for(r=0,i=l.length;r<i;++r)if(l[r]<p){if(e>=0){reverseValues(lr,e,r);e=-1}}else e<0&&(e=r);e>=0&&reverseValues(lr,e,l.length)}for(r=0,i=lr.length;r<i;++r){const e=lr[r];"<"!==e&&">"!==e||(lr[r]="")}return createBidiText(lr.join(""),a)}const cr={style:"normal",weight:"normal"},hr={style:"normal",weight:"bold"},ur={style:"italic",weight:"normal"},mr={style:"italic",weight:"bold"},pr=new Map([["Times-Roman",{local:["Times New Roman","Times-Roman","Times","Liberation Serif","Nimbus Roman","Nimbus Roman L","Tinos","Thorndale","TeX Gyre Termes","FreeSerif","Linux Libertine O","Libertinus Serif","PT Astra Serif","DejaVu Serif","Bitstream Vera Serif","Ubuntu"],style:cr,ultimate:"serif"}],["Times-Bold",{alias:"Times-Roman",style:hr,ultimate:"serif"}],["Times-Italic",{alias:"Times-Roman",style:ur,ultimate:"serif"}],["Times-BoldItalic",{alias:"Times-Roman",style:mr,ultimate:"serif"}],["Helvetica",{local:["Helvetica","Helvetica Neue","Arial","Arial Nova","Liberation Sans","Arimo","Nimbus Sans","Nimbus Sans L","A030","TeX Gyre Heros","FreeSans","DejaVu Sans","Albany","Bitstream Vera Sans","Arial Unicode MS","Microsoft Sans Serif","Apple Symbols","Cantarell"],path:"LiberationSans-Regular.ttf",style:cr,ultimate:"sans-serif"}],["Helvetica-Bold",{alias:"Helvetica",path:"LiberationSans-Bold.ttf",style:hr,ultimate:"sans-serif"}],["Helvetica-Oblique",{alias:"Helvetica",path:"LiberationSans-Italic.ttf",style:ur,ultimate:"sans-serif"}],["Helvetica-BoldOblique",{alias:"Helvetica",path:"LiberationSans-BoldItalic.ttf",style:mr,ultimate:"sans-serif"}],["Courier",{local:["Courier","Courier New","Liberation Mono","Nimbus Mono","Nimbus Mono L","Cousine","Cumberland","TeX Gyre Cursor","FreeMono","Linux Libertine Mono O","Libertinus Mono"],style:cr,ultimate:"monospace"}],["Courier-Bold",{alias:"Courier",style:hr,ultimate:"monospace"}],["Courier-Oblique",{alias:"Courier",style:ur,ultimate:"monospace"}],["Courier-BoldOblique",{alias:"Courier",style:mr,ultimate:"monospace"}],["ArialBlack",{local:["Arial Black"],style:{style:"normal",weight:"900"},fallback:"Helvetica-Bold"}],["ArialBlack-Bold",{alias:"ArialBlack"}],["ArialBlack-Italic",{alias:"ArialBlack",style:{style:"italic",weight:"900"},fallback:"Helvetica-BoldOblique"}],["ArialBlack-BoldItalic",{alias:"ArialBlack-Italic"}],["ArialNarrow",{local:["Arial Narrow","Liberation Sans Narrow","Helvetica Condensed","Nimbus Sans Narrow","TeX Gyre Heros Cn"],style:cr,fallback:"Helvetica"}],["ArialNarrow-Bold",{alias:"ArialNarrow",style:hr,fallback:"Helvetica-Bold"}],["ArialNarrow-Italic",{alias:"ArialNarrow",style:ur,fallback:"Helvetica-Oblique"}],["ArialNarrow-BoldItalic",{alias:"ArialNarrow",style:mr,fallback:"Helvetica-BoldOblique"}],["Calibri",{local:["Calibri","Carlito"],style:cr,fallback:"Helvetica"}],["Calibri-Bold",{alias:"Calibri",style:hr,fallback:"Helvetica-Bold"}],["Calibri-Italic",{alias:"Calibri",style:ur,fallback:"Helvetica-Oblique"}],["Calibri-BoldItalic",{alias:"Calibri",style:mr,fallback:"Helvetica-BoldOblique"}],["Wingdings",{local:["Wingdings","URW Dingbats"],style:cr}],["Wingdings-Regular",{alias:"Wingdings"}],["Wingdings-Bold",{alias:"Wingdings"}],["ËÎÌå",{local:["SimSun","SimSun Regular","NSimSun"],style:cr,ultimate:"serif"}],["ºÚÌå",{local:["SimHei","SimHei Regular"],style:cr,ultimate:"sans-serif"}],["¿¬Ìå",{local:["KaiTi","SimKai","SimKai Regular"],style:cr,ultimate:"sans-serif"}],["·ÂËÎ",{local:["FangSong","SimFang","SimFang Regular"],style:cr,ultimate:"serif"}],["¿¬Ìå_GB2312",{alias:"¿¬Ìå"}],["·ÂËÎ_GB2312",{alias:"·ÂËÎ"}],["Á¥Êé",{local:["SimLi","SimLi Regular"],style:cr,ultimate:"serif"}],["ÐÂËÎ",{alias:"ËÎÌå"}]]),dr=new Map([["Arial-Black","ArialBlack"]]);function getFamilyName(e){const t=new Set(["thin","extralight","ultralight","demilight","semilight","light","book","regular","normal","medium","demibold","semibold","bold","extrabold","ultrabold","black","heavy","extrablack","ultrablack","roman","italic","oblique","ultracondensed","extracondensed","condensed","semicondensed","normal","semiexpanded","expanded","extraexpanded","ultraexpanded","bolditalic"]);return e.split(/[- ,+]+/g).filter(e=>!t.has(e.toLowerCase())).join(" ")}function generateFont({alias:e,local:t,path:n,fallback:a,style:s,ultimate:r},i,o,l=!0,f=!0,c=""){const h={style:null,ultimate:null};if(t){const e=c?` ${c}`:"";for(const n of t)i.push(`local(${n}${e})`)}if(e){const t=pr.get(e),r=c||function getStyleToAppend(e){switch(e){case hr:return"Bold";case ur:return"Italic";case mr:return"Bold Italic";default:if("bold"===e?.weight)return"Bold";if("italic"===e?.style)return"Italic"}return""}(s);Object.assign(h,generateFont(t,i,o,l&&!a,f&&!n,r))}s&&(h.style=s);r&&(h.ultimate=r);if(l&&a){const e=pr.get(a),{ultimate:t}=generateFont(e,i,o,l,f&&!n,c);h.ultimate||=t}f&&n&&o&&i.push(`url(${o}${n})`);return h}function getFontSubstitution(e,t,n,a,s,r){if(a.startsWith("InvalidPDFjsFont_"))return null;"TrueType"!==r&&"Type1"!==r||!/^[A-Z]{6}\+/.test(a)||(a=a.slice(7));const i=a=normalizeFontName(a);let o=e.get(i);if(o)return o;let l=pr.get(a);if(!l)for(const[e,t]of dr)if(a.startsWith(e)){a=`${t}${a.substring(e.length)}`;l=pr.get(a);break}let f=!1;if(!l){l=pr.get(s);f=!0}const c=`${t.getDocId()}_s${t.createFontId()}`;if(!l){if(!validateFontName(a)){warn(`Cannot substitute the font because of its name: ${a}`);e.set(i,null);return null}const t=/bold/gi.test(a),n=/oblique|italic/gi.test(a),s=t&&n&&mr||t&&hr||n&&ur||cr;o={css:`"${getFamilyName(a)}",${c}`,guessFallback:!0,loadedName:c,baseFontName:a,src:`local(${a})`,style:s};e.set(i,o);return o}const h=[];f&&validateFontName(a)&&h.push(`local(${a})`);const{style:u,ultimate:m}=generateFont(l,h,n),p=null===m,d=p?"":`,${m}`;o={css:`"${getFamilyName(a)}",${c}${d}`,guessFallback:p,loadedName:c,baseFontName:a,src:h.join(","),style:u};e.set(i,o);return o}const gr=3285377520,br=4294901760,wr=65535;class MurmurHash3_64{constructor(e){this.h1=e?4294967295&e:gr;this.h2=e?4294967295&e:gr}update(e){let t,n;if("string"==typeof e){t=new Uint8Array(2*e.length);n=0;for(let a=0,s=e.length;a<s;a++){const s=e.charCodeAt(a);if(s<=255)t[n++]=s;else{t[n++]=s>>>8;t[n++]=255&s}}}else{if(!ArrayBuffer.isView(e))throw new Error("Invalid data format, must be a string or TypedArray.");t=e.slice();n=t.byteLength}const a=n>>2,s=n-4*a,r=new Uint32Array(t.buffer,0,a);let i=0,o=0,l=this.h1,f=this.h2;const c=3432918353,h=461845907,u=11601,m=13715;for(let e=0;e<a;e++)if(1&e){i=r[e];i=i*c&br|i*u≀i=i<<15|i>>>17;i=i*h&br|i*m≀l^=i;l=l<<13|l>>>19;l=5*l+3864292196}else{o=r[e];o=o*c&br|o*u≀o=o<<15|o>>>17;o=o*h&br|o*m≀f^=o;f=f<<13|f>>>19;f=5*f+3864292196}i=0;switch(s){case 3:i^=t[4*a+2]<<16;case 2:i^=t[4*a+1]<<8;case 1:i^=t[4*a];i=i*c&br|i*u≀i=i<<15|i>>>17;i=i*h&br|i*m≀1&a?l^=i:f^=i}this.h1=l;this.h2=f}hexdigest(){let e=this.h1,t=this.h2;e^=t>>>1;e=3981806797*e&br|36045*e≀t=4283543511*t&br|(2950163797*(t<<16|e>>>16)&br)>>>16;e^=t>>>1;e=444984403*e&br|60499*e≀t=3301882366*t&br|(3120437893*(t<<16|e>>>16)&br)>>>16;e^=t>>>1;return(e>>>0).toString(16).padStart(8,"0")+(t>>>0).toString(16).padStart(8,"0")}}function resizeImageMask(e,t,n,a,s,r){const i=s*r;let o;o=t<=8?new Uint8Array(i):t<=16?new Uint16Array(i):new Uint32Array(i);const l=n/s,f=a/r;let c,h,u,m,p=0;const d=new Uint16Array(s),g=n;for(c=0;c<s;c++)d[c]=Math.floor(c*l);for(c=0;c<r;c++){u=Math.floor(c*f)*g;for(h=0;h<s;h++){m=u+d[h];o[p++]=e[m]}}return o}class PDFImage{constructor({xref:e,res:t,image:n,isInline:a=!1,smask:s=null,mask:r=null,isMask:i=!1,pdfFunctionFactory:o,globalColorSpaceCache:l,localColorSpaceCache:f}){this.image=n;const c=n.dict,h=c.get("F","Filter");let u;if(h instanceof Name)u=h.name;else if(Array.isArray(h)){const t=e.fetchIfRef(h[0]);t instanceof Name&&(u=t.name)}switch(u){case"JPXDecode":({width:n.width,height:n.height,componentsCount:n.numComps,bitsPerComponent:n.bitsPerComponent}=JpxImage.parseImageProperties(n.stream));n.stream.reset();const e=ImageResizer.getReducePowerForJPX(n.width,n.height,n.numComps);this.jpxDecoderOptions={numComponents:0,isIndexedColormap:!1,smaskInData:c.has("SMaskInData"),reducePower:e};if(e){const t=2**e;n.width=Math.ceil(n.width/t);n.height=Math.ceil(n.height/t)}break;case"JBIG2Decode":n.bitsPerComponent=1;n.numComps=1}let m=c.get("W","Width"),p=c.get("H","Height");if(Number.isInteger(n.width)&&n.width>0&&Number.isInteger(n.height)&&n.height>0&&(n.width!==m||n.height!==p)){warn("PDFImage - using the Width/Height of the image data, rather than the image dictionary.");m=n.width;p=n.height}else{const e="number"==typeof m&&m>0,t="number"==typeof p&&p>0;if(!e||!t){if(!n.fallbackDims)throw new FormatError(`Invalid image width: ${m} or height: ${p}`);warn("PDFImage - using the Width/Height of the parent image, for SMask/Mask data.");e||(m=n.fallbackDims.width);t||(p=n.fallbackDims.height)}}this.width=m;this.height=p;this.interpolate=c.get("I","Interpolate");this.imageMask=c.get("IM","ImageMask")||!1;this.matte=c.get("Matte")||!1;let d=n.bitsPerComponent;if(!d){d=c.get("BPC","BitsPerComponent");if(!d){if(!this.imageMask)throw new FormatError(`Bits per component missing in image: ${this.imageMask}`);d=1}}this.bpc=d;if(!this.imageMask){let s=c.getRaw("CS")||c.getRaw("ColorSpace");const r=!!s;if(r)this.jpxDecoderOptions?.smaskInData&&(s=Name.get("DeviceRGBA"));else if(this.jpxDecoderOptions)s=Name.get("DeviceRGBA");else switch(n.numComps){case 1:s=Name.get("DeviceGray");break;case 3:s=Name.get("DeviceRGB");break;case 4:s=Name.get("DeviceCMYK");break;default:throw new Error(`Images with ${n.numComps} color components not supported.`)}this.colorSpace=ColorSpaceUtils.parse({cs:s,xref:e,resources:a?t:null,pdfFunctionFactory:o,globalColorSpaceCache:l,localColorSpaceCache:f});this.numComps=this.colorSpace.numComps;if(this.jpxDecoderOptions){this.jpxDecoderOptions.numComponents=r?this.numComps:0;this.jpxDecoderOptions.isIndexedColormap="Indexed"===this.colorSpace.name}}this.decode=c.getArray("D","Decode");this.needsDecode=!1;if(this.decode&&(this.colorSpace&&!this.colorSpace.isDefaultDecode(this.decode,d)||i&&!ColorSpace.isDefaultDecode(this.decode,1))){this.needsDecode=!0;const e=(1<<d)-1;this.decodeCoefficients=[];this.decodeAddends=[];const t="Indexed"===this.colorSpace?.name;for(let n=0,a=0;n<this.decode.length;n+=2,++a){const s=this.decode[n],r=this.decode[n+1];this.decodeCoefficients[a]=t?(r-s)/e:r-s;this.decodeAddends[a]=t?s:e*s}}if(s){s.fallbackDims??={width:m,height:p};this.smask=new PDFImage({xref:e,res:t,image:s,isInline:a,pdfFunctionFactory:o,globalColorSpaceCache:l,localColorSpaceCache:f})}else if(r)if(r instanceof BaseStream){if(r.dict.get("IM","ImageMask")){r.fallbackDims??={width:m,height:p};this.mask=new PDFImage({xref:e,res:t,image:r,isInline:a,isMask:!0,pdfFunctionFactory:o,globalColorSpaceCache:l,localColorSpaceCache:f})}else warn("Ignoring /Mask in image without /ImageMask.")}else this.mask=r}static async buildImage({xref:e,res:t,image:n,isInline:a=!1,pdfFunctionFactory:s,globalColorSpaceCache:r,localColorSpaceCache:i}){const o=n;let l=null,f=null;const c=n.dict.get("SMask"),h=n.dict.get("Mask");c?c instanceof BaseStream?l=c:warn("Unsupported /SMask format."):h&&(h instanceof BaseStream||Array.isArray(h)?f=h:warn("Unsupported /Mask format."));return new PDFImage({xref:e,res:t,image:o,isInline:a,smask:l,mask:f,pdfFunctionFactory:s,globalColorSpaceCache:r,localColorSpaceCache:i})}static async createMask({image:e,isOffscreenCanvasSupported:t=!1}){const{dict:n}=e,a=n.get("W","Width"),s=n.get("H","Height"),r=n.get("I","Interpolate"),i=n.getArray("D","Decode"),o=i?.[0]>0,l=(a+7>>3)*s,f=await e.getImageData(l),c=1===a&&1===s&&o===(0===f.length||!!(128&f[0]));if(c)return{isSingleOpaquePixel:c};if(t){if(ImageResizer.needsToBeResized(a,s)){const e=new Uint8ClampedArray(a*s*4);convertBlackAndWhiteToRGBA({src:f,dest:e,width:a,height:s,nonBlackColor:0,inverseDecode:o});return ImageResizer.createImage({kind:F,data:e,width:a,height:s,interpolate:r})}const e=new OffscreenCanvas(a,s),t=e.getContext("2d"),n=t.createImageData(a,s);convertBlackAndWhiteToRGBA({src:f,dest:n.data,width:a,height:s,nonBlackColor:0,inverseDecode:o});t.putImageData(n,0,0);return{data:null,width:a,height:s,interpolate:r,bitmap:e.transferToImageBitmap()}}const h=f.byteLength;let u;if(e instanceof DecodeStream&&(!o||l===h))u=f;else if(o){u=new Uint8Array(l);u.set(f);u.fill(255,h)}else u=new Uint8Array(f);if(o)for(let e=0;e<h;e++)u[e]^=255;return{data:u,width:a,height:s,interpolate:r}}get drawWidth(){return Math.max(this.width,this.smask?.width||0,this.mask?.width||0)}get drawHeight(){return Math.max(this.height,this.smask?.height||0,this.mask?.height||0)}decodeBuffer(e){const t=this.bpc,n=this.numComps,a=this.decodeAddends,s=this.decodeCoefficients,r=(1<<t)-1;let i,o;if(1===t){for(i=0,o=e.length;i<o;i++)e[i]=+!e[i];return}let l=0;for(i=0,o=this.width*this.height;i<o;i++)for(let t=0;t<n;t++){e[l]=MathClamp(a[t]+e[l]*s[t],0,r);l++}}getComponents(e){const t=this.bpc;if(8===t)return e;const n=this.width,a=this.height,s=this.numComps,r=n*a*s;let i,o=0;i=t<=8?new Uint8Array(r):t<=16?new Uint16Array(r):new Uint32Array(r);const l=n*s,f=(1<<t)-1;let c,h,u=0;if(1===t){let t,n,s;for(let r=0;r<a;r++){n=u+(-8&l);s=u+l;for(;u<n;){h=e[o++];i[u]=h>>7&1;i[u+1]=h>>6&1;i[u+2]=h>>5&1;i[u+3]=h>>4&1;i[u+4]=h>>3&1;i[u+5]=h>>2&1;i[u+6]=h>>1&1;i[u+7]=1&h;u+=8}if(u<s){h=e[o++];t=128;for(;u<s;){i[u++]=+!!(h&t);t>>=1}}}}else{let n=0;h=0;for(u=0,c=r;u<c;++u){if(u%l===0){h=0;n=0}for(;n<t;){h=h<<8|e[o++];n+=8}const a=n-t;let s=h>>a;s<0?s=0:s>f&&(s=f);i[u]=s;h&=(1<<a)-1;n=a}}return i}async fillOpacity(e,t,n,a,s){const r=this.smask,i=this.mask;let o,l,f,c,h,u;if(r){l=r.width;f=r.height;o=new Uint8ClampedArray(l*f);await r.fillGrayBuffer(o);l===t&&f===n||(o=resizeImageMask(o,r.bpc,l,f,t,n))}else if(i)if(i instanceof PDFImage){l=i.width;f=i.height;o=new Uint8ClampedArray(l*f);i.numComps=1;await i.fillGrayBuffer(o);for(c=0,h=l*f;c<h;++c)o[c]=255-o[c];l===t&&f===n||(o=resizeImageMask(o,i.bpc,l,f,t,n))}else{if(!Array.isArray(i))throw new FormatError("Unknown mask format.");{o=new Uint8ClampedArray(t*n);const e=this.numComps;for(c=0,h=t*n;c<h;++c){let t=0;const n=c*e;for(u=0;u<e;++u){const e=s[n+u],a=2*u;if(e<i[a]||e>i[a+1]){t=255;break}}o[c]=t}}}if(o)for(c=0,u=3,h=t*a;c<h;++c,u+=4)e[u]=o[c];else for(c=0,u=3,h=t*a;c<h;++c,u+=4)e[u]=255}undoPreblend(e,t,n){const a=this.smask?.matte;if(!a)return;const s=this.colorSpace.getRgb(a,0),r=s[0],i=s[1],o=s[2],l=t*n*4;for(let t=0;t<l;t+=4){const n=e[t+3];if(0===n){e[t]=255;e[t+1]=255;e[t+2]=255;continue}const a=255/n;e[t]=(e[t]-r)*a+r;e[t+1]=(e[t+1]-i)*a+i;e[t+2]=(e[t+2]-o)*a+o}}async createImageData(e=!1,t=!1){const n=this.drawWidth,a=this.drawHeight,s={width:n,height:a,interpolate:this.interpolate,kind:0,data:null},r=this.numComps,i=this.width,o=this.height,l=this.bpc,f=i*r*l+7>>3,c=t&&ImageResizer.needsToBeResized(n,a);if(!this.smask&&!this.mask&&"DeviceRGBA"===this.colorSpace.name){s.kind=F;const e=s.data=await this.getImageBytes(o*i*4,{});return t?c?ImageResizer.createImage(s,!1):this.createBitmap(F,n,a,e):s}if(!e){let e;"DeviceGray"===this.colorSpace.name&&1===l?e=x:"DeviceRGB"!==this.colorSpace.name||8!==l||this.needsDecode||(e=C);if(e&&!this.smask&&!this.mask&&n===i&&a===o){const r=await this.#he(i,o);if(r)return r;const l=await this.getImageBytes(o*f,{});if(t)return c?ImageResizer.createImage({data:l,kind:e,width:n,height:a,interpolate:this.interpolate},this.needsDecode):this.createBitmap(e,i,o,l);s.kind=e;s.data=l;if(this.needsDecode){assert(e===x,"PDFImage.createImageData: The image must be grayscale.");const t=s.data;for(let e=0,n=t.length;e<n;e++)t[e]^=255}return s}if(this.image instanceof JpegStream&&!this.smask&&!this.mask&&!this.needsDecode){let e=o*f;if(t&&!c){let t=!1;switch(this.colorSpace.name){case"DeviceGray":e*=4;t=!0;break;case"DeviceRGB":e=e/3*4;t=!0;break;case"DeviceCMYK":t=!0}if(t){const t=await this.#he(n,a);if(t)return t;const s=await this.getImageBytes(e,{drawWidth:n,drawHeight:a,forceRGBA:!0});return this.createBitmap(F,n,a,s)}}else switch(this.colorSpace.name){case"DeviceGray":e*=3;case"DeviceRGB":case"DeviceCMYK":s.kind=C;s.data=await this.getImageBytes(e,{drawWidth:n,drawHeight:a,forceRGB:!0});return c?ImageResizer.createImage(s):s}}}const h=await this.getImageBytes(o*f,{internal:!0}),u=0|h.length/f*a/o,m=this.getComponents(h);let p,d,g,b,w,j;if(t&&!c){g=new OffscreenCanvas(n,a);b=g.getContext("2d");w=b.createImageData(n,a);j=w.data}s.kind=F;if(e||this.smask||this.mask){t&&!c||(j=new Uint8ClampedArray(n*a*4));p=1;d=!0;await this.fillOpacity(j,n,a,u,m)}else{if(!t||c){s.kind=C;j=new Uint8ClampedArray(n*a*3);p=0}else{new Uint32Array(j.buffer).fill(FeatureTest.isLittleEndian?4278190080:255);p=1}d=!1}this.needsDecode&&this.decodeBuffer(m);this.colorSpace.fillRgb(j,i,o,n,a,u,l,m,p);d&&this.undoPreblend(j,n,u);if(t&&!c){b.putImageData(w,0,0);return{data:null,width:n,height:a,bitmap:g.transferToImageBitmap(),interpolate:this.interpolate}}s.data=j;return c?ImageResizer.createImage(s):s}async fillGrayBuffer(e){const t=this.numComps;if(1!==t)throw new FormatError(`Reading gray scale from a color image: ${t}`);const n=this.width,a=this.height,s=this.bpc,r=n*t*s+7>>3,i=await this.getImageBytes(a*r,{internal:!0}),o=this.getComponents(i);let l,f;if(1===s){f=n*a;if(this.needsDecode)for(l=0;l<f;++l)e[l]=o[l]-1&255;else for(l=0;l<f;++l)e[l]=255&-o[l];return}this.needsDecode&&this.decodeBuffer(o);f=n*a;const c=255/((1<<s)-1);for(l=0;l<f;++l)e[l]=c*o[l]}createBitmap(e,t,n,a){const s=new OffscreenCanvas(t,n),r=s.getContext("2d");let i;if(e===F)i=new ImageData(a,t,n);else{i=r.createImageData(t,n);convertToRGBA({kind:e,src:a,dest:new Uint32Array(i.data.buffer),width:t,height:n,inverseDecode:this.needsDecode})}r.putImageData(i,0,0);return{data:null,width:t,height:n,bitmap:s.transferToImageBitmap(),interpolate:this.interpolate}}async#he(e,t){const n=await this.image.getTransferableImage();return n?{data:null,width:e,height:t,bitmap:n,interpolate:this.interpolate}:null}async getImageBytes(e,{drawWidth:t,drawHeight:n,forceRGBA:a=!1,forceRGB:s=!1,internal:r=!1}){this.image.reset();this.image.drawWidth=t||this.width;this.image.drawHeight=n||this.height;this.image.forceRGBA=!!a;this.image.forceRGB=!!s;const i=await this.image.getImageData(e,this.jpxDecoderOptions);if(r||this.image instanceof DecodeStream)return i;assert(i instanceof Uint8Array,'PDFImage.getImageBytes: Unsupported "imageBytes" type.');return new Uint8Array(i)}}const jr=Object.freeze({maxImageSize:-1,disableFontFace:!1,ignoreErrors:!1,isEvalSupported:!0,isOffscreenCanvasSupported:!1,isImageDecoderSupported:!1,canvasMaxAreaInBytes:-1,fontExtraProperties:!1,useSystemFonts:!0,useWasm:!0,useWorkerFetch:!0,cMapUrl:null,iccUrl:null,standardFontDataUrl:null,wasmUrl:null}),kr=1,yr=2,qr=Promise.resolve();function normalizeBlendMode(e,t=!1){if(Array.isArray(e)){for(const t of e){const e=normalizeBlendMode(t,!0);if(e)return e}warn(`Unsupported blend mode Array: ${e}`);return"source-over"}if(!(e instanceof Name))return t?null:"source-over";switch(e.name){case"Normal":case"Compatible":return"source-over";case"Multiply":return"multiply";case"Screen":return"screen";case"Overlay":return"overlay";case"Darken":return"darken";case"Lighten":return"lighten";case"ColorDodge":return"color-dodge";case"ColorBurn":return"color-burn";case"HardLight":return"hard-light";case"SoftLight":return"soft-light";case"Difference":return"difference";case"Exclusion":return"exclusion";case"Hue":return"hue";case"Saturation":return"saturation";case"Color":return"color";case"Luminosity":return"luminosity"}if(t)return null;warn(`Unsupported blend mode: ${e.name}`);return"source-over"}function addCachedImageOps(e,{objId:t,fn:n,args:a,optionalContent:s,hasMask:r}){t&&e.addDependency(t);e.addImageOps(n,a,s,r);n===Rt&&a[0]?.count>0&&a[0].count++}class TimeSlotManager{static TIME_SLOT_DURATION_MS=20;static CHECK_TIME_EVERY=100;constructor(){this.reset()}check(){if(++this.checked<TimeSlotManager.CHECK_TIME_EVERY)return!1;this.checked=0;return this.endTime<=Date.now()}reset(){this.endTime=Date.now()+TimeSlotManager.TIME_SLOT_DURATION_MS;this.checked=0}}class PartialEvaluator{constructor({xref:e,handler:t,pageIndex:n,idFactory:a,fontCache:s,builtInCMapCache:r,standardFontDataCache:i,globalColorSpaceCache:o,globalImageCache:l,systemFontCache:f,options:c=null}){this.xref=e;this.handler=t;this.pageIndex=n;this.idFactory=a;this.fontCache=s;this.builtInCMapCache=r;this.standardFontDataCache=i;this.globalColorSpaceCache=o;this.globalImageCache=l;this.systemFontCache=f;this.options=c||jr;this.type3FontRefs=null;this._regionalImageCache=new RegionalImageCache;this._fetchBuiltInCMapBound=this.fetchBuiltInCMap.bind(this)}get _pdfFunctionFactory(){return shadow(this,"_pdfFunctionFactory",new PDFFunctionFactory({xref:this.xref,isEvalSupported:this.options.isEvalSupported}))}get parsingType3Font(){return!!this.type3FontRefs}clone(e=null){const t=Object.create(this);t.options=Object.assign(Object.create(null),this.options,e);return t}hasBlendModes(e,t){if(!(e instanceof Dict))return!1;if(e.objId&&t.has(e.objId))return!1;const n=new RefSet(t);e.objId&&n.put(e.objId);const a=[e],s=this.xref;for(;a.length;){const e=a.shift(),t=e.get("ExtGState");if(t instanceof Dict)for(let e of t.getRawValues()){if(e instanceof Ref){if(n.has(e))continue;try{e=s.fetch(e)}catch(t){n.put(e);info(`hasBlendModes - ignoring ExtGState: "${t}".`);continue}}if(!(e instanceof Dict))continue;e.objId&&n.put(e.objId);const t=e.get("BM");if(t instanceof Name){if("Normal"!==t.name)return!0}else if(void 0!==t&&Array.isArray(t))for(const e of t)if(e instanceof Name&&"Normal"!==e.name)return!0}const r=e.get("XObject");if(r instanceof Dict)for(let e of r.getRawValues()){if(e instanceof Ref){if(n.has(e))continue;try{e=s.fetch(e)}catch(t){n.put(e);info(`hasBlendModes - ignoring XObject: "${t}".`);continue}}if(!(e instanceof BaseStream))continue;e.dict.objId&&n.put(e.dict.objId);const t=e.dict.get("Resources");if(t instanceof Dict&&(!t.objId||!n.has(t.objId))){a.push(t);t.objId&&n.put(t.objId)}}}for(const e of n)t.put(e);return!1}async fetchBuiltInCMap(e){const t=this.builtInCMapCache.get(e);if(t)return t;let n;n=this.options.useWorkerFetch?{cMapData:await fetchBinaryData(`${this.options.cMapUrl}${e}.bcmap`),isCompressed:!0}:await this.handler.sendWithPromise("FetchBinaryData",{type:"cMapReaderFactory",name:e});this.builtInCMapCache.set(e,n);return n}async fetchStandardFontData(e){const t=this.standardFontDataCache.get(e);if(t)return new Stream(t);if(this.options.useSystemFonts&&"Symbol"!==e&&"ZapfDingbats"!==e)return null;const n=za()[e];let a;try{a=this.options.useWorkerFetch?await fetchBinaryData(`${this.options.standardFontDataUrl}${n}`):await this.handler.sendWithPromise("FetchBinaryData",{type:"standardFontDataFactory",filename:n})}catch(e){warn(e);return null}this.standardFontDataCache.set(e,a);return new Stream(a)}async buildFormXObject(e,t,n,a,s,r,i,o){const{dict:l}=t,f=lookupMatrix(l.getArray("Matrix"),null),c=lookupNormalRect(l.getArray("BBox"),null);let h,u;l.has("OC")&&(h=await this.parseMarkedContentProps(l.get("OC"),e));void 0!==h&&a.addOp(St,["OC",h]);const m=l.get("Group");if(m){u={matrix:f,bbox:c,smask:n,isolated:!1,knockout:!1};let t=null;if(isName(m.get("S"),"Transparency")){u.isolated=m.get("I")||!1;u.knockout=m.get("K")||!1;if(m.has("CS")){const n=this._getColorSpace(m.getRaw("CS"),e,i);t=n instanceof ColorSpace?n:await this._handleColorSpace(n)}}if(n?.backdrop){t||=ColorSpaceUtils.rgb;n.backdrop=t.getRgbHex(n.backdrop,0)}a.addOp(Tt,[u])}const p=[f&&new Float32Array(f),!m&&c&&new Float32Array(c)||null];a.addOp(It,p);const d=l.get("Resources");await this.getOperatorList({stream:t,task:s,resources:d instanceof Dict?d:e,operatorList:a,initialState:r,prevRefs:o});a.addOp(Ft,[]);m&&a.addOp(Ht,[u]);void 0!==h&&a.addOp(xt,[])}_sendImgData(e,t,n=!1){const a=t?[t.bitmap||t.data.buffer]:null;return this.parsingType3Font||n?this.handler.send("commonobj",[e,"Image",t],a):this.handler.send("obj",[e,this.pageIndex,"Image",t],a)}async buildPaintImageXObject({resources:e,image:t,isInline:n=!1,operatorList:a,cacheKey:s,localImageCache:r,localColorSpaceCache:i}){const{maxImageSize:o,ignoreErrors:l,isOffscreenCanvasSupported:f}=this.options,{dict:c}=t,h=c.objId,u=c.get("W","Width"),m=c.get("H","Height");if(!u||"number"!=typeof u||!m||"number"!=typeof m){warn("Image dimensions are missing, or not numbers.");return}if(-1!==o&&u*m>o){const e="Image exceeded maximum allowed size and was removed.";if(!l)throw new Error(e);warn(e);return}let p;c.has("OC")&&(p=await this.parseMarkedContentProps(c.get("OC"),e));let d,g,b;if(c.get("IM","ImageMask")||!1){d=await PDFImage.createMask({image:t,isOffscreenCanvasSupported:f&&!this.parsingType3Font});if(d.isSingleOpaquePixel){g=Lt;b=[];a.addImageOps(g,b,p);if(s){const e={fn:g,args:b,optionalContent:p};r.set(s,h,e);h&&this._regionalImageCache.set(null,h,e)}return}if(this.parsingType3Font){b=function compileType3Glyph({data:e,width:t,height:n}){if(t>1e3||n>1e3)return null;const a=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),s=t+1,r=new Uint8Array(s*(n+1));let i,o,l;const f=t+7&-8,c=new Uint8Array(f*n);let h=0;for(const t of e){let e=128;for(;e>0;){c[h++]=t&e?0:255;e>>=1}}let u=0;h=0;if(0!==c[h]){r[0]=1;++u}for(o=1;o<t;o++){if(c[h]!==c[h+1]){r[o]=c[h]?2:1;++u}h++}if(0!==c[h]){r[o]=2;++u}for(i=1;i<n;i++){h=i*f;l=i*s;if(c[h-f]!==c[h]){r[l]=c[h]?1:8;++u}let e=(c[h]?4:0)+(c[h-f]?8:0);for(o=1;o<t;o++){e=(e>>2)+(c[h+1]?4:0)+(c[h-f+1]?8:0);if(a[e]){r[l+o]=a[e];++u}h++}if(c[h-f]!==c[h]){r[l+o]=c[h]?2:4;++u}if(u>1e3)return null}h=f*(n-1);l=i*s;if(0!==c[h]){r[l]=8;++u}for(o=1;o<t;o++){if(c[h]!==c[h+1]){r[l+o]=c[h]?4:8;++u}h++}if(0!==c[h]){r[l+o]=4;++u}if(u>1e3)return null;const m=new Int32Array([0,s,-1,0,-s,0,0,0,1]),p=[],{a:d,b:g,c:b,d:w,e:j,f:k}=(new DOMMatrix).scaleSelf(1/t,-1/n).translateSelf(0,-n);for(i=0;u&&i<=n;i++){let e=i*s;const n=e+t;for(;e<n&&!r[e];)e++;if(e===n)continue;let a=e%s,o=i;p.push(Kt,d*a+b*o+j,g*a+w*o+k);const l=e;let f=r[e];do{const t=m[f];do{e+=t}while(!r[e]);const n=r[e];if(5!==n&&10!==n){f=n;r[e]=0}else{f=n&51*f>>4;r[e]&=f>>2|f<<2}a=e%s;o=e/s|0;p.push(Gt,d*a+b*o+j,g*a+w*o+k);r[e]||--u}while(l!==e);--i}return[Wt,[new Float32Array(p)],new Float32Array([0,0,t,n])]}(d);if(b){a.addImageOps(Ut,b,p);return}warn("Cannot compile Type3 glyph.");a.addImageOps(Rt,[d],p);return}const e=`mask_${this.idFactory.createObjId()}`;a.addDependency(e);d.dataLen=d.bitmap?d.width*d.height*4:d.data.length;this._sendImgData(e,d);g=Rt;b=[{data:e,width:d.width,height:d.height,interpolate:d.interpolate,count:1}];a.addImageOps(g,b,p);if(s){const t={objId:e,fn:g,args:b,optionalContent:p};r.set(s,h,t);h&&this._regionalImageCache.set(null,h,t)}return}const w=c.has("SMask")||c.has("Mask");if(n&&u+m<200&&!w){try{const s=new PDFImage({xref:this.xref,res:e,image:t,isInline:n,pdfFunctionFactory:this._pdfFunctionFactory,globalColorSpaceCache:this.globalColorSpaceCache,localColorSpaceCache:i});d=await s.createImageData(!0,!1);a.addImageOps(Pt,[d],p)}catch(e){const t=`Unable to decode inline image: "${e}".`;if(!l)throw new Error(t);warn(t)}return}let j=`img_${this.idFactory.createObjId()}`,k=!1,y=null;if(this.parsingType3Font)j=`${this.idFactory.getDocId()}_type3_${j}`;else if(s&&h){k=this.globalImageCache.shouldCache(h,this.pageIndex);if(k){assert(!n,"Cannot cache an inline image globally.");j=`${this.idFactory.getDocId()}_${j}`}}a.addDependency(j);g=Mt;b=[j,u,m];a.addImageOps(g,b,p,w);if(k){y={objId:j,fn:g,args:b,optionalContent:p,hasMask:w,byteSize:0};if(this.globalImageCache.hasDecodeFailed(h)){this.globalImageCache.setData(h,y);this._sendImgData(j,null,k);return}if(u*m>25e4||w){const e=await this.handler.sendWithPromise("commonobj",[j,"CopyLocalImage",{imageRef:h}]);if(e){this.globalImageCache.setData(h,y);this.globalImageCache.addByteSize(h,e);return}}}PDFImage.buildImage({xref:this.xref,res:e,image:t,isInline:n,pdfFunctionFactory:this._pdfFunctionFactory,globalColorSpaceCache:this.globalColorSpaceCache,localColorSpaceCache:i}).then(async e=>{d=await e.createImageData(!1,f);d.dataLen=d.bitmap?d.width*d.height*4:d.data.length;d.ref=h;k&&this.globalImageCache.addByteSize(h,d.dataLen);return this._sendImgData(j,d,k)}).catch(e=>{warn(`Unable to decode image "${j}": "${e}".`);h&&this.globalImageCache.addDecodeFailed(h);return this._sendImgData(j,null,k)});if(s){const e={objId:j,fn:g,args:b,optionalContent:p,hasMask:w};r.set(s,h,e);if(h){this._regionalImageCache.set(null,h,e);if(k){assert(y,"The global cache-data must be available.");this.globalImageCache.setData(h,y)}}}}handleSMask(e,t,n,a,s,r,i){const o=e.get("G"),l={subtype:e.get("S").name,backdrop:e.get("BC")},f=e.get("TR");if(isPDFFunction(f)){const e=this._pdfFunctionFactory.create(f),t=new Uint8Array(256),n=new Float32Array(1);for(let a=0;a<256;a++){n[0]=a/255;e(n,0,n,0);t[a]=255*n[0]|0}l.transferMap=t}return this.buildFormXObject(t,o,l,n,a,s.state.clone({newPath:!0}),r,i)}handleTransferFunction(e){let t;if(Array.isArray(e)){t=e;e.length>1&&e.every(t=>t===e[0])&&(t=[e[0]])}else{if(!isPDFFunction(e))return null;t=[e]}const n=[];let a=0,s=0;for(const e of t){const t=this.xref.fetchIfRef(e);a++;if(isName(t,"Identity")){n.push(null);continue}if(!isPDFFunction(t))return null;const r=this._pdfFunctionFactory.create(t),i=new Uint8Array(256),o=new Float32Array(1);for(let e=0;e<256;e++){o[0]=e/255;r(o,0,o,0);i[e]=255*o[0]|0}n.push(i);s++}return 1!==a&&4!==a||0===s?null:n}handleTilingType(e,t,n,a,s,r,i,o){const l=new OperatorList,f=Dict.merge({xref:this.xref,dictArray:[s.get("Resources"),n]});return this.getOperatorList({stream:a,task:i,resources:f,operatorList:l}).then(function(){const n=l.getIR(),a=getTilingPatternIR(n,s,t);r.addDependencies(l.dependencies);r.addOp(e,a);s.objId&&o.set(null,s.objId,{operatorListIR:n,dict:s})}).catch(e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`handleTilingType - ignoring pattern: "${e}".`)}})}async handleSetFont(e,t,n,a,s,r,i=null,o=null){const l=t?.[0]instanceof Name?t[0].name:null,f=await this.loadFont(l,n,e,s,i,o);f.font.isType3Font&&a.addDependencies(f.type3Dependencies);r.font=f.font;f.send(this.handler);return f.loadedName}handleText(e,t){const n=t.font,a=n.charsToGlyphs(e);if(n.data){(!!(t.textRenderingMode&S)||"Pattern"===t.fillColorSpace.name||"Pattern"===t.strokeColorSpace.name||n.disableFontFace)&&PartialEvaluator.buildFontPaths(n,a,this.handler,this.options)}return a}ensureStateFont(e){if(e.font)return;const t=new FormatError("Missing setFont (Tf) operator before text rendering operator.");if(!this.options.ignoreErrors)throw t;warn(`ensureStateFont: "${t}".`)}async setGState({resources:e,gState:t,operatorList:n,cacheKey:a,task:s,stateManager:r,localGStateCache:i,localColorSpaceCache:o,seenRefs:l}){const f=t.objId;let c=!0;const h=[];let u=Promise.resolve();for(const[a,i]of t)switch(a){case"Type":break;case"LW":if("number"!=typeof i){warn(`Invalid LW (line width): ${i}`);break}h.push([a,Math.abs(i)]);break;case"LC":case"LJ":case"ML":case"D":case"RI":case"FL":case"CA":case"ca":h.push([a,i]);break;case"Font":c=!1;u=u.then(()=>this.handleSetFont(e,null,i[0],n,s,r.state).then(function(e){n.addDependency(e);h.push([a,[e,i[1]]])}));break;case"BM":h.push([a,normalizeBlendMode(i)]);break;case"SMask":if(isName(i,"None")){h.push([a,!1]);break}if(i instanceof Dict){c=!1;u=u.then(()=>this.handleSMask(i,e,n,s,r,o,l));h.push([a,!0])}else warn("Unsupported SMask type");break;case"TR":const t=this.handleTransferFunction(i);h.push([a,t]);break;case"OP":case"op":case"OPM":case"BG":case"BG2":case"UCR":case"UCR2":case"TR2":case"HT":case"SM":case"SA":case"AIS":case"TK":info("graphic state operator "+a);break;default:info("Unknown graphic state operator "+a)}await u;h.length>0&&n.addOp(be,[h]);c&&i.set(a,f,h)}loadFont(e,t,n,a,s=null,r=null){const errorFont=async()=>new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Font "${e}" is not available.`),dict:t});let i;if(t)t instanceof Ref&&(i=t);else{const t=n.get("Font");t&&(i=t.getRaw(e))}if(i){if(this.type3FontRefs?.has(i))return errorFont();if(this.fontCache.has(i))return this.fontCache.get(i);try{t=this.xref.fetchIfRef(i)}catch(e){warn(`loadFont - lookup failed: "${e}".`)}}if(!(t instanceof Dict)){if(!this.options.ignoreErrors&&!this.parsingType3Font){warn(`Font "${e}" is not available.`);return errorFont()}warn(`Font "${e}" is not available -- attempting to fallback to a default font.`);t=s||PartialEvaluator.fallbackFontDict}if(t.cacheKey&&this.fontCache.has(t.cacheKey))return this.fontCache.get(t.cacheKey);const{promise:o,resolve:l}=Promise.withResolvers();let f;try{f=this.preEvaluateFont(t);f.cssFontInfo=r}catch(e){warn(`loadFont - preEvaluateFont failed: "${e}".`);return errorFont()}const{descriptor:c,hash:h}=f,u=i instanceof Ref;let m;if(h&&c instanceof Dict){const e=c.fontAliases||=Object.create(null);if(e[h]){const t=e[h].aliasRef;if(u&&t&&this.fontCache.has(t)){this.fontCache.putAlias(i,t);return this.fontCache.get(i)}}else e[h]={fontID:this.idFactory.createFontId()};u&&(e[h].aliasRef=i);m=e[h].fontID}else m=this.idFactory.createFontId();assert(m?.startsWith("f"),'The "fontID" must be (correctly) defined.');if(u)this.fontCache.put(i,o);else{t.cacheKey=`cacheKey_${m}`;this.fontCache.put(t.cacheKey,o)}t.loadedName=`${this.idFactory.getDocId()}_${m}`;this.translateFont(f).then(async e=>{const s=new TranslatedFont({loadedName:t.loadedName,font:e,dict:t});if(e.isType3Font)try{await s.loadType3Data(this,n,a)}catch(e){throw new Error(`Type3 font load error: ${e}`)}l(s)}).catch(e=>{warn(`loadFont - translateFont failed: "${e}".`);l(new TranslatedFont({loadedName:t.loadedName,font:new ErrorFont(e?.message),dict:t}))});return o}buildPath(e,t,n){const{pathMinMax:a,pathBuffer:s}=n;switch(0|e){case Ce:{const e=n.currentPointX=t[0],r=n.currentPointY=t[1],i=t[2],o=t[3],l=e+i,f=r+o;0===i||0===o?s.push(Kt,e,r,Gt,l,f,Yt):s.push(Kt,e,r,Gt,l,r,Gt,l,f,Gt,e,f,Yt);Util.rectBoundingBox(e,r,l,f,a);break}case ye:{const e=n.currentPointX=t[0],r=n.currentPointY=t[1];s.push(Kt,e,r);Util.pointBoundingBox(e,r,a);break}case qe:{const e=n.currentPointX=t[0],r=n.currentPointY=t[1];s.push(Gt,e,r);Util.pointBoundingBox(e,r,a);break}case ve:{const e=n.currentPointX,r=n.currentPointY,[i,o,l,f,c,h]=t;n.currentPointX=c;n.currentPointY=h;s.push(Vt,i,o,l,f,c,h);Util.bezierBoundingBox(e,r,i,o,l,f,c,h,a);break}case Se:{const e=n.currentPointX,r=n.currentPointY,[i,o,l,f]=t;n.currentPointX=l;n.currentPointY=f;s.push(Vt,e,r,i,o,l,f);Util.bezierBoundingBox(e,r,e,r,i,o,l,f,a);break}case xe:{const e=n.currentPointX,r=n.currentPointY,[i,o,l,f]=t;n.currentPointX=l;n.currentPointY=f;s.push(Vt,i,o,l,f,l,f);Util.bezierBoundingBox(e,r,i,o,l,f,l,f,a);break}case Ae:s.push(Yt)}}_getColorSpace(e,t,n){return ColorSpaceUtils.parse({cs:e,xref:this.xref,resources:t,pdfFunctionFactory:this._pdfFunctionFactory,globalColorSpaceCache:this.globalColorSpaceCache,localColorSpaceCache:n,asyncIfNotCached:!0})}async _handleColorSpace(e){try{return await e}catch(e){if(e instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`_handleColorSpace - ignoring ColorSpace: "${e}".`);return null}throw e}}parseShading({shading:e,resources:t,localColorSpaceCache:n,localShadingPatternCache:a}){let s,r=a.get(e);if(r)return r;try{s=Pattern.parseShading(e,this.xref,t,this._pdfFunctionFactory,this.globalColorSpaceCache,n).getIR()}catch(t){if(t instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseShading - ignoring shading: "${t}".`);a.set(e,null);return null}throw t}r=`pattern_${this.idFactory.createObjId()}`;this.parsingType3Font&&(r=`${this.idFactory.getDocId()}_type3_${r}`);a.set(e,r);if(this.parsingType3Font){const e=[],t=PatternInfo.write(s);e.push(t);this.handler.send("commonobj",[r,"Pattern",t],e)}else this.handler.send("obj",[r,this.pageIndex,"Pattern",s]);return r}handleColorN(e,t,n,a,s,r,i,o,l,f){const c=n.pop();if(c instanceof Name){const h=s.getRaw(c.name),u=h instanceof Ref&&l.getByRef(h);if(u)try{const s=a.base?a.base.getRgbHex(n,0):null,r=getTilingPatternIR(u.operatorListIR,u.dict,s);e.addOp(t,r);return}catch{}const m=this.xref.fetchIfRef(h);if(m){const s=m instanceof BaseStream?m.dict:m,c=s.get("PatternType");if(c===kr){const o=a.base?a.base.getRgbHex(n,0):null;return this.handleTilingType(t,o,r,m,s,e,i,l)}if(c===yr){const n=s.get("Shading"),a=this.parseShading({shading:n,resources:r,localColorSpaceCache:o,localShadingPatternCache:f});if(a){const n=lookupMatrix(s.getArray("Matrix"),null);e.addOp(t,["Shading",a,n])}return}throw new FormatError(`Unknown PatternType: ${c}`)}}throw new FormatError(`Unknown PatternName: ${c}`)}_parseVisibilityExpression(e,t,n){if(++t>10){warn("Visibility expression is too deeply nested");return}const a=e.length,s=this.xref.fetchIfRef(e[0]);if(!(a<2)&&s instanceof Name){switch(s.name){case"And":case"Or":case"Not":n.push(s.name);break;default:warn(`Invalid operator ${s.name} in visibility expression`);return}for(let s=1;s<a;s++){const a=e[s],r=this.xref.fetchIfRef(a);if(Array.isArray(r)){const e=[];n.push(e);this._parseVisibilityExpression(r,t,e)}else a instanceof Ref&&n.push(a.toString())}}else warn("Invalid visibility expression")}async parseMarkedContentProps(e,t){let n;if(e instanceof Name){n=t.get("Properties").get(e.name)}else{if(!(e instanceof Dict))throw new FormatError("Optional content properties malformed.");n=e}const a=n.get("Type")?.name;if("OCG"===a)return{type:a,id:n.objId};if("OCMD"===a){const e=n.get("VE");if(Array.isArray(e)){const t=[];this._parseVisibilityExpression(e,0,t);if(t.length>0)return{type:"OCMD",expression:t}}const t=n.get("OCGs");if(Array.isArray(t)||t instanceof Dict){const e=[];if(Array.isArray(t))for(const n of t)e.push(n.toString());else e.push(t.objId);return{type:a,ids:e,policy:n.get("P")instanceof Name?n.get("P").name:null,expression:null}}if(t instanceof Ref)return{type:a,id:t.toString()}}return null}async getOperatorList({stream:e,task:t,resources:n,operatorList:a,initialState:s=null,fallbackFontDict:r=null,prevRefs:i=null}){if(e.isAsync){const t=await e.asyncGetBytes();t&&(e=new Stream(t,0,t.length,e.dict))}const o=e.dict?.objId,l=new RefSet(i);if(o){if(i?.has(o))throw new Error(`getOperatorList - ignoring circular reference: ${o}`);l.put(o)}n||=Dict.empty;s||=new EvalState;if(!a)throw new Error('getOperatorList: missing "operatorList" parameter');const f=this,c=this.xref,h=new LocalImageCache,u=new LocalColorSpaceCache,m=new LocalGStateCache,p=new LocalTilingPatternCache,d=new Map,g=n.get("XObject")||Dict.empty,b=n.get("Pattern")||Dict.empty,w=new StateManager(s),j=new EvaluatorPreprocessor(e,c,w),k=new TimeSlotManager;function closePendingRestoreOPS(e){for(let e=0,t=j.savedStatesDepth;e<t;e++)a.addOp(je,[])}return new Promise(function promiseBody(e,s){const next=function(t){Promise.all([t,a.ready]).then(function(){try{promiseBody(e,s)}catch(e){s(e)}},s)};t.ensureNotTerminated();k.reset();const i={};let o,y,q,v,S,x;for(;!(o=k.check());){i.args=null;if(!j.read(i))break;let e=i.args,s=i.fn;switch(0|s){case kt:x=e[0]instanceof Name;S=e[0].name;if(x){const t=h.getByName(S);if(t){addCachedImageOps(a,t);e=null;continue}}next(new Promise(function(e,s){if(!x)throw new FormatError("XObject must be referred to by name.");let r=g.getRaw(S);if(r instanceof Ref){const t=h.getByRef(r)||f._regionalImageCache.getByRef(r)||f.globalImageCache.getData(r,f.pageIndex);if(t){addCachedImageOps(a,t);e();return}r=c.fetch(r)}if(!(r instanceof BaseStream))throw new FormatError("XObject should be a stream");const i=r.dict.get("Subtype");if(!(i instanceof Name))throw new FormatError("XObject should have a Name subtype");if("Form"!==i.name)if("Image"!==i.name){if("PS"!==i.name)throw new FormatError(`Unhandled XObject subtype ${i.name}`);info("Ignored XObject subtype PS");e()}else f.buildPaintImageXObject({resources:n,image:r,operatorList:a,cacheKey:S,localImageCache:h,localColorSpaceCache:u}).then(e,s);else{w.save();f.buildFormXObject(n,r,null,a,t,w.state.clone({newPath:!0}),u,l).then(function(){w.restore();e()},s)}}).catch(function(e){if(!(e instanceof AbortException)){if(!f.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring XObject: "${e}".`)}}));return;case We:const i=e[1];next(f.handleSetFont(n,e,null,a,t,w.state,r).then(function(e){a.addDependency(e);a.addOp(We,[e,i])}));return;case jt:const o=e[0].cacheKey;if(o){const t=h.getByName(o);if(t){addCachedImageOps(a,t);e=null;continue}}next(f.buildPaintImageXObject({resources:n,image:e[0],isInline:!0,operatorList:a,cacheKey:o,localImageCache:h,localColorSpaceCache:u}));return;case Qe:if(!w.state.font){f.ensureStateFont(w.state);continue}e[0]=f.handleText(e[0],w.state);break;case Ze:if(!w.state.font){f.ensureStateFont(w.state);continue}const j=[],k=w.state;for(const t of e[0])"string"==typeof t?j.push(...f.handleText(t,k)):"number"==typeof t&&j.push(t);e[0]=j;s=Qe;break;case et:if(!w.state.font){f.ensureStateFont(w.state);continue}a.addOp(Je);e[0]=f.handleText(e[0],w.state);s=Qe;break;case tt:if(!w.state.font){f.ensureStateFont(w.state);continue}a.addOp(Je);a.addOp(Ue,[e.shift()]);a.addOp(Le,[e.shift()]);e[0]=f.handleText(e[0],w.state);s=Qe;break;case Ke:w.state.textRenderingMode=e[0];break;case rt:{const t=f._getColorSpace(e[0],n,u);if(t instanceof ColorSpace){w.state.fillColorSpace=t;continue}next(f._handleColorSpace(t).then(e=>{w.state.fillColorSpace=e||ColorSpaceUtils.gray}));return}case st:{const t=f._getColorSpace(e[0],n,u);if(t instanceof ColorSpace){w.state.strokeColorSpace=t;continue}next(f._handleColorSpace(t).then(e=>{w.state.strokeColorSpace=e||ColorSpaceUtils.gray}));return}case lt:v=w.state.fillColorSpace;e=[v.getRgbHex(e,0)];s=mt;break;case it:v=w.state.strokeColorSpace;e=[v.getRgbHex(e,0)];s=ut;break;case ht:w.state.fillColorSpace=ColorSpaceUtils.gray;e=[ColorSpaceUtils.gray.getRgbHex(e,0)];s=mt;break;case ct:w.state.strokeColorSpace=ColorSpaceUtils.gray;e=[ColorSpaceUtils.gray.getRgbHex(e,0)];s=ut;break;case dt:w.state.fillColorSpace=ColorSpaceUtils.cmyk;e=[ColorSpaceUtils.cmyk.getRgbHex(e,0)];s=mt;break;case pt:w.state.strokeColorSpace=ColorSpaceUtils.cmyk;e=[ColorSpaceUtils.cmyk.getRgbHex(e,0)];s=ut;break;case mt:w.state.fillColorSpace=ColorSpaceUtils.rgb;e=[ColorSpaceUtils.rgb.getRgbHex(e,0)];break;case ut:w.state.strokeColorSpace=ColorSpaceUtils.rgb;e=[ColorSpaceUtils.rgb.getRgbHex(e,0)];break;case ft:v=w.state.patternFillColorSpace;if(!v){if(isNumberArray(e,null)){e=[ColorSpaceUtils.gray.getRgbHex(e,0)];s=mt;break}e=[];s=Xt;break}if("Pattern"===v.name){next(f.handleColorN(a,ft,e,v,b,n,t,u,p,d));return}e=[v.getRgbHex(e,0)];s=mt;break;case ot:v=w.state.patternStrokeColorSpace;if(!v){if(isNumberArray(e,null)){e=[ColorSpaceUtils.gray.getRgbHex(e,0)];s=ut;break}e=[];s=_t;break}if("Pattern"===v.name){next(f.handleColorN(a,ot,e,v,b,n,t,u,p,d));return}e=[v.getRgbHex(e,0)];s=ut;break;case gt:let C;try{const t=n.get("Shading");if(!t)throw new FormatError("No shading resource found");C=t.get(e[0].name);if(!C)throw new FormatError("No shading object found")}catch(e){if(e instanceof AbortException)continue;if(f.options.ignoreErrors){warn(`getOperatorList - ignoring Shading: "${e}".`);continue}throw e}const F=f.parseShading({shading:C,resources:n,localColorSpaceCache:u,localShadingPatternCache:d});if(!F)continue;e=[F];s=gt;break;case be:x=e[0]instanceof Name;S=e[0].name;if(x){const t=m.getByName(S);if(t){t.length>0&&a.addOp(be,[t]);e=null;continue}}next(new Promise(function(e,s){if(!x)throw new FormatError("GState must be referred to by name.");const r=n.get("ExtGState");if(!(r instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const i=r.get(S);if(!(i instanceof Dict))throw new FormatError("GState should be a dictionary.");f.setGState({resources:n,gState:i,operatorList:a,cacheKey:S,task:t,stateManager:w,localGStateCache:m,localColorSpaceCache:u,seenRefs:l}).then(e,s)}).catch(function(e){if(!(e instanceof AbortException)){if(!f.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring ExtGState: "${e}".`)}}));return;case ce:{const[t]=e;if("number"!=typeof t){warn(`Invalid setLineWidth: ${t}`);continue}e[0]=Math.abs(t);break}case pe:{const t=e[1];if("number"!=typeof t){warn(`Invalid setDash: ${t}`);continue}const n=e[0];if(!Array.isArray(n)){warn(`Invalid setDash: ${n}`);continue}n.some(e=>"number"!=typeof e)&&(e[0]=n.filter(e=>"number"==typeof e));break}case ye:case qe:case ve:case Se:case xe:case Ae:case Ce:f.buildPath(s,e,w.state);continue;case Ie:case Fe:case Te:case He:case Oe:case Be:case Re:case De:case Me:{const{state:{pathBuffer:e,pathMinMax:t}}=w;s!==Fe&&s!==Re&&s!==De||e.push(Yt);if(0===e.length)a.addOp(Ut,[s,[null],null]);else{a.addOp(Ut,[s,[new Float32Array(e)],t.slice()]);e.length=0;t.set([1/0,1/0,-1/0,-1/0],0)}continue}case Ye:a.addOp(s,[new Float32Array(e)]);continue;case yt:case qt:case At:case Ct:continue;case St:if(!(e[0]instanceof Name)){warn(`Expected name for beginMarkedContentProps arg0=${e[0]}`);a.addOp(St,["OC",null]);continue}if("OC"===e[0].name){next(f.parseMarkedContentProps(e[1],n).then(e=>{a.addOp(St,["OC",e])}).catch(e=>{if(!(e instanceof AbortException)){if(!f.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring beginMarkedContentProps: "${e}".`);a.addOp(St,["OC",null])}}));return}e=[e[0].name,e[1]instanceof Dict?e[1].get("MCID"):null];break;default:if(null!==e){for(y=0,q=e.length;y<q&&!(e[y]instanceof Dict);y++);if(y<q){warn("getOperatorList - ignoring operator: "+s);continue}}}a.addOp(s,e)}if(o)next(qr);else{closePendingRestoreOPS();e()}}).catch(e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring errors during "${t.name}" task: "${e}".`);closePendingRestoreOPS()}})}async getTextContent({stream:e,task:n,resources:a,stateManager:s=null,includeMarkedContent:r=!1,sink:i,seenStyles:o=new Set,viewBox:l,lang:f=null,markedContentData:c=null,disableNormalization:h=!1,keepWhiteSpace:u=!1,prevRefs:m=null,intersector:p=null}){if(e.isAsync){const t=await e.asyncGetBytes();t&&(e=new Stream(t,0,t.length,e.dict))}const d=e.dict?.objId,g=new RefSet(m);if(d){if(m?.has(d))throw new Error(`getTextContent - ignoring circular reference: ${d}`);g.put(d)}a||=Dict.empty;s||=new StateManager(new TextState);r&&(c||={level:0});const b={items:[],styles:Object.create(null),lang:f},w={initialized:!1,str:[],totalWidth:0,totalHeight:0,width:0,height:0,vertical:!1,prevTransform:null,textAdvanceScale:0,spaceInFlowMin:0,spaceInFlowMax:0,trackingSpaceMin:1/0,negativeSpaceMax:-1/0,notASpace:-1/0,transform:null,fontName:null,hasEOL:!1},j=[" "," "];let k=0;function saveLastChar(e){const t=(k+1)%2,n=" "!==j[k]&&" "===j[t];j[k]=e;k=t;return!u&&n}function shouldAddWhitepsace(){return!u&&" "!==j[k]&&" "===j[(k+1)%2]}function resetLastChars(){j[0]=j[1]=" ";k=0}const y=this,q=this.xref,v=[];let S=null;const x=new LocalImageCache,C=new LocalGStateCache,F=new EvaluatorPreprocessor(e,q,s);let T,H;function pushWhitespace({width:e=0,height:t=0,transform:n=w.prevTransform,fontName:a=w.fontName}){p?.addExtraChar(" ");b.items.push({str:" ",dir:"ltr",width:e,height:t,transform:n,fontName:a,hasEOL:!1})}function getCurrentTextTransform(){const e=T.font,n=[T.fontSize*T.textHScale,0,0,T.fontSize,0,T.textRise];if(e.isType3Font&&(T.fontSize<=1||e.isCharBBox)&&!isArrayEqual(T.fontMatrix,t)){const t=e.bbox[3]-e.bbox[1];t>0&&(n[3]*=t*T.fontMatrix[3])}return Util.transform(T.ctm,Util.transform(T.textMatrix,n))}function ensureTextContentItem(){if(w.initialized)return w;const{font:e,loadedName:t}=T;if(!o.has(t)){o.add(t);b.styles[t]={fontFamily:e.fallbackName,ascent:e.ascent,descent:e.descent,vertical:e.vertical};if(y.options.fontExtraProperties&&e.systemFontInfo){const n=b.styles[t];n.fontSubstitution=e.systemFontInfo.css;n.fontSubstitutionLoadedName=e.systemFontInfo.loadedName}}w.fontName=t;const n=w.transform=getCurrentTextTransform();if(e.vertical){w.width=w.totalWidth=Math.hypot(n[0],n[1]);w.height=w.totalHeight=0;w.vertical=!0}else{w.width=w.totalWidth=0;w.height=w.totalHeight=Math.hypot(n[2],n[3]);w.vertical=!1}const a=Math.hypot(T.textLineMatrix[0],T.textLineMatrix[1]),s=Math.hypot(T.ctm[0],T.ctm[1]);w.textAdvanceScale=s*a;const{fontSize:r}=T;w.trackingSpaceMin=.102*r;w.notASpace=.03*r;w.negativeSpaceMax=-.2*r;w.spaceInFlowMin=.102*r;w.spaceInFlowMax=.6*r;w.hasEOL=!1;w.initialized=!0;return w}function updateAdvanceScale(){if(!w.initialized)return;const e=Math.hypot(T.textLineMatrix[0],T.textLineMatrix[1]),t=Math.hypot(T.ctm[0],T.ctm[1])*e;if(t!==w.textAdvanceScale){if(w.vertical){w.totalHeight+=w.height*w.textAdvanceScale;w.height=0}else{w.totalWidth+=w.width*w.textAdvanceScale;w.width=0}w.textAdvanceScale=t}}function runBidiTransform(e){let t=e.str.join("");h||(t=function normalizeUnicode(e){if(!an){an=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;sn=new Map([["ſt","ſt"]])}return e.replaceAll(an,(e,t,n)=>t?t.normalize("NFKC"):sn.get(n))}(t));const n=bidi(t,-1,e.vertical);return{str:n.str,dir:n.dir,width:Math.abs(e.totalWidth),height:Math.abs(e.totalHeight),transform:e.transform,fontName:e.fontName,hasEOL:e.hasEOL}}async function handleSetFont(e,s){const r=await y.loadFont(e,s,a,n);T.loadedName=r.loadedName;T.font=r.font;T.fontMatrix=r.font.fontMatrix||t}function applyInverseRotation(e,t,n){const a=Math.hypot(n[0],n[1]);return[(n[0]*e+n[1]*t)/a,(n[2]*e+n[3]*t)/a]}function compareWithLastPosition(e){const t=getCurrentTextTransform();let n=t[4],a=t[5];if(T.font?.vertical){if(n<l[0]||n>l[2]||a+e<l[1]||a>l[3])return!1}else if(n+e<l[0]||n>l[2]||a<l[1]||a>l[3])return!1;if(!T.font||!w.prevTransform)return!0;let s=w.prevTransform[4],r=w.prevTransform[5];if(s===n&&r===a)return!0;let i=-1;t[0]&&0===t[1]&&0===t[2]?i=t[0]>0?0:180:t[1]&&0===t[0]&&0===t[3]&&(i=t[1]>0?90:270);switch(i){case 0:break;case 90:[n,a]=[a,n];[s,r]=[r,s];break;case 180:[n,a,s,r]=[-n,-a,-s,-r];break;case 270:[n,a]=[-a,-n];[s,r]=[-r,-s];break;default:[n,a]=applyInverseRotation(n,a,t);[s,r]=applyInverseRotation(s,r,w.prevTransform)}if(T.font.vertical){const e=(r-a)/w.textAdvanceScale,t=n-s,i=Math.sign(w.height||w.totalHeight);if(e<i*w.negativeSpaceMax){if(Math.abs(t)>.5*w.width){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(t)>w.width){appendEOL();return!0}e<=i*w.notASpace&&resetLastChars();if(e<=i*w.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({height:Math.abs(e)})}else w.height+=e;else if(!addFakeSpaces(e,w.prevTransform,i))if(0===w.str.length){resetLastChars();pushWhitespace({height:Math.abs(e)})}else w.height+=e;Math.abs(t)>.25*w.width&&flushTextContentItem();return!0}const o=(n-s)/w.textAdvanceScale,f=a-r,c=Math.sign(w.width||w.totalWidth);if(o<c*w.negativeSpaceMax){if(Math.abs(f)>.5*w.height){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(f)>w.height){appendEOL();return!0}o<=c*w.notASpace&&resetLastChars();if(o<=c*w.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({width:Math.abs(o)})}else w.width+=o;else if(!addFakeSpaces(o,w.prevTransform,c))if(0===w.str.length){resetLastChars();pushWhitespace({width:Math.abs(o)})}else w.width+=o;Math.abs(f)>.25*w.height&&flushTextContentItem();return!0}function buildTextContentItem({chars:e,extraSpacing:t}){if(H!==T&&(H.fontName!==T.fontName||H.fontSize!==T.fontSize)){flushTextContentItem();H=T.clone()}const n=T.font;if(!e){const e=T.charSpacing+t;e&&(n.vertical?T.translateTextMatrix(0,-e):T.translateTextMatrix(e*T.textHScale,0));u&&compareWithLastPosition(0);return}const a=n.charsToGlyphs(e),s=T.fontMatrix[0]*T.fontSize;for(let e=0,r=a.length;e<r;e++){const i=a[e],{category:o,originalCharCode:l}=i;if(o.isInvisibleFormatMark)continue;let f=T.charSpacing+(e+1===r?t:0),c=i.width;n.vertical&&(c=i.vmetric?i.vmetric[0]:-c);let h=c*s;32===l&&(f+=T.wordSpacing);if(!u&&o.isWhitespace){if(n.vertical){f+=-h;T.translateTextMatrix(0,-f)}else{f+=h;T.translateTextMatrix(f*T.textHScale,0)}saveLastChar(" ");continue}if(!o.isZeroWidthDiacritic&&!compareWithLastPosition(h)){n.vertical?T.translateTextMatrix(0,h):T.translateTextMatrix(h*T.textHScale,0);continue}const m=ensureTextContentItem();o.isZeroWidthDiacritic&&(h=0);if(n.vertical){p?.addGlyph(getCurrentTextTransform(),0,h,i.unicode);T.translateTextMatrix(0,h);h=Math.abs(h);m.height+=h}else{h*=T.textHScale;p?.addGlyph(getCurrentTextTransform(),h,0,i.unicode);T.translateTextMatrix(h,0);m.width+=h}h&&(m.prevTransform=getCurrentTextTransform());const d=i.unicode;if(saveLastChar(d)){m.str.push(" ");p?.addExtraChar(" ")}p||m.str.push(d);f&&(n.vertical?T.translateTextMatrix(0,-f):T.translateTextMatrix(f*T.textHScale,0))}}function appendEOL(){p?.addExtraChar("\n");resetLastChars();if(w.initialized){w.hasEOL=!0;flushTextContentItem()}else b.items.push({str:"",dir:"ltr",width:0,height:0,transform:getCurrentTextTransform(),fontName:T.loadedName,hasEOL:!0})}function addFakeSpaces(e,t,n){if(n*w.spaceInFlowMin<=e&&e<=n*w.spaceInFlowMax){if(w.initialized){resetLastChars();w.str.push(" ");p?.addExtraChar(" ")}return!1}const a=w.fontName;let s=0;if(w.vertical){s=e;e=0}flushTextContentItem();resetLastChars();pushWhitespace({width:Math.abs(e),height:Math.abs(s),transform:t||getCurrentTextTransform(),fontName:a});return!0}function flushTextContentItem(){if(w.initialized&&w.str){w.vertical?w.totalHeight+=w.height*w.textAdvanceScale:w.totalWidth+=w.width*w.textAdvanceScale;b.items.push(runBidiTransform(w));w.initialized=!1;w.str.length=0}}function enqueueChunk(e=!1){const t=b.items.length;if(0!==t&&!(e&&t<10)){i?.enqueue(b,t);b.items=[];b.styles=Object.create(null)}}const O=new TimeSlotManager;return new Promise(function promiseBody(e,t){const next=function(n){enqueueChunk(!0);Promise.all([n,i?.ready]).then(function(){try{promiseBody(e,t)}catch(e){t(e)}},t)};n.ensureNotTerminated();O.reset();const m={};let p,d,w,j=[];for(;!(p=O.check());){j.length=0;m.args=j;if(!F.read(m))break;T=s.state;H||=T.clone();const e=m.fn;j=m.args;switch(0|e){case We:const e=j[0].name,t=j[1];if(T.font&&e===T.fontName&&t===T.fontSize)break;T.fontName=e;T.fontSize=t;next(handleSetFont(e,null));return;case Ge:T.textRise=j[0];break;case _e:T.textHScale=j[0]/100;break;case Xe:T.leading=j[0];break;case Ve:T.translateTextLineMatrix(j[0],j[1]);T.textMatrix=T.textLineMatrix.slice();break;case $e:T.leading=-j[1];T.translateTextLineMatrix(j[0],j[1]);T.textMatrix=T.textLineMatrix.slice();break;case Je:T.carriageReturn();break;case Ye:T.setTextMatrix(j[0],j[1],j[2],j[3],j[4],j[5]);T.setTextLineMatrix(j[0],j[1],j[2],j[3],j[4],j[5]);updateAdvanceScale();break;case Le:T.charSpacing=j[0];break;case Ue:T.wordSpacing=j[0];break;case Ne:T.textMatrix=pn.slice();T.textLineMatrix=pn.slice();break;case Ze:if(!s.state.font){y.ensureStateFont(s.state);continue}const m=(T.font.vertical?1:-1)*T.fontSize/1e3,p=j[0];for(let e=0,t=p.length;e<t;e++){const t=p[e];if("string"==typeof t)v.push(t);else if("number"==typeof t&&0!==t){const e=v.join("");v.length=0;buildTextContentItem({chars:e,extraSpacing:t*m})}}if(v.length>0){const e=v.join("");v.length=0;buildTextContentItem({chars:e,extraSpacing:0})}break;case Qe:if(!s.state.font){y.ensureStateFont(s.state);continue}buildTextContentItem({chars:j[0],extraSpacing:0});break;case et:if(!s.state.font){y.ensureStateFont(s.state);continue}T.carriageReturn();buildTextContentItem({chars:j[0],extraSpacing:0});break;case tt:if(!s.state.font){y.ensureStateFont(s.state);continue}T.wordSpacing=j[0];T.charSpacing=j[1];T.carriageReturn();buildTextContentItem({chars:j[2],extraSpacing:0});break;case kt:flushTextContentItem();S??=a.get("XObject")||Dict.empty;w=j[0]instanceof Name;d=j[0].name;if(w&&x.getByName(d))break;next(new Promise(function(e,t){if(!w)throw new FormatError("XObject must be referred to by name.");let m=S.getRaw(d);if(m instanceof Ref){if(x.getByRef(m)){e();return}if(y.globalImageCache.getData(m,y.pageIndex)){e();return}m=q.fetch(m)}if(!(m instanceof BaseStream))throw new FormatError("XObject should be a stream");const{dict:p}=m,b=p.get("Subtype");if(!(b instanceof Name))throw new FormatError("XObject should have a Name subtype");if("Form"!==b.name){x.set(d,p.objId,!0);e();return}const j=s.state.clone(),k=new StateManager(j),v=lookupMatrix(p.getArray("Matrix"),null);v&&k.transform(v);const C=p.get("Resources");enqueueChunk();const F={enqueueInvoked:!1,enqueue(e,t){this.enqueueInvoked=!0;i.enqueue(e,t)},get desiredSize(){return i.desiredSize??0},get ready(){return i.ready}};y.getTextContent({stream:m,task:n,resources:C instanceof Dict?C:a,stateManager:k,includeMarkedContent:r,sink:i&&F,seenStyles:o,viewBox:l,lang:f,markedContentData:c,disableNormalization:h,keepWhiteSpace:u,prevRefs:g}).then(function(){F.enqueueInvoked||x.set(d,p.objId,!0);e()},t)}).catch(function(e){if(!(e instanceof AbortException)){if(!y.options.ignoreErrors)throw e;warn(`getTextContent - ignoring XObject: "${e}".`)}}));return;case be:w=j[0]instanceof Name;d=j[0].name;if(w&&C.getByName(d))break;next(new Promise(function(e,t){if(!w)throw new FormatError("GState must be referred to by name.");const n=a.get("ExtGState");if(!(n instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const s=n.get(d);if(!(s instanceof Dict))throw new FormatError("GState should be a dictionary.");const r=s.get("Font");if(r){flushTextContentItem();T.fontName=null;T.fontSize=r[1];handleSetFont(null,r[0]).then(e,t)}else{C.set(d,s.objId,!0);e()}}).catch(function(e){if(!(e instanceof AbortException)){if(!y.options.ignoreErrors)throw e;warn(`getTextContent - ignoring ExtGState: "${e}".`)}}));return;case vt:flushTextContentItem();if(r){c.level++;b.items.push({type:"beginMarkedContent",tag:j[0]instanceof Name?j[0].name:null})}break;case St:flushTextContentItem();if(r){c.level++;let e=null;j[1]instanceof Dict&&(e=j[1].get("MCID"));b.items.push({type:"beginMarkedContentProps",id:Number.isInteger(e)?`${y.idFactory.getPageObjId()}_mc${e}`:null,tag:j[0]instanceof Name?j[0].name:null})}break;case xt:flushTextContentItem();if(r){if(0===c.level)break;c.level--;b.items.push({type:"endMarkedContent"})}break;case je:s.restore();break;case we:s.save()}if(b.items.length>=(i?.desiredSize??1)){p=!0;break}}if(p)next(qr);else{flushTextContentItem();enqueueChunk();e()}}).catch(e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getTextContent - ignoring errors during "${n.name}" task: "${e}".`);flushTextContentItem();enqueueChunk()}})}async extractDataStructures(e,t){const n=this.xref;let a;const s=this.readToUnicode(t.toUnicode);if(t.composite){const n=e.get("CIDSystemInfo");n instanceof Dict&&!t.cidSystemInfo&&(t.cidSystemInfo={registry:stringToPDFString(n.get("Registry")),ordering:stringToPDFString(n.get("Ordering")),supplement:n.get("Supplement")});try{const t=e.get("CIDToGIDMap");t instanceof BaseStream&&(a=t.getBytes())}catch(e){if(!this.options.ignoreErrors)throw e;warn(`extractDataStructures - ignoring CIDToGIDMap data: "${e}".`)}}const r=[];let i,o=null;if(e.has("Encoding")){i=e.get("Encoding");if(i instanceof Dict){o=i.get("BaseEncoding");o=o instanceof Name?o.name:null;if(i.has("Differences")){const e=i.get("Differences");let t=0;for(const a of e){const e=n.fetchIfRef(a);if("number"==typeof e)t=e;else{if(!(e instanceof Name))throw new FormatError(`Invalid entry in 'Differences' array: ${e}`);r[t++]=e.name}}}}else if(i instanceof Name)o=i.name;else{const e="Encoding is not a Name nor a Dict";if(!this.options.ignoreErrors)throw new FormatError(e);warn(e)}"MacRomanEncoding"!==o&&"MacExpertEncoding"!==o&&"WinAnsiEncoding"!==o&&(o=null)}const l=!t.file||t.isInternalFont,f=_a()[t.name];o&&l&&f&&(o=null);if("WinAnsiEncoding"===o&&l&&t.name?.charCodeAt(0)>=183){const e=t.name;if(["ËÎÌå","ºÚÌå","¿¬Ìå","·ÂËÎ","¿¬Ìå_GB2312","·ÂËÎ_GB2312","Á¥Êé","ÐÂËÎ"].includes(e)){o=null;t.defaultEncoding="Adobe-GB1-UCS2";t.composite=!0;t.cidEncoding=Name.get("GBK-EUC-H");const e=await CMapFactory.create({encoding:t.cidEncoding,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null});t.cMap=e;t.vertical=t.cMap.vertical;t.cidSystemInfo={registry:"Adobe",ordering:"GB1",supplement:0}}}if(o)t.defaultEncoding=getEncoding(o);else{let e=!!(t.flags&xa);const n=!!(t.flags&Aa);if("TrueType"===t.type&&e&&n&&0!==r.length){t.flags&=~xa;e=!1}i=ua;"TrueType"!==t.type||n||(i=ma);if(e||f){i=ha;l&&(/Symbol/i.test(t.name)?i=pa:/Dingbats/i.test(t.name)?i=da:/Wingdings/i.test(t.name)&&(i=ma))}t.defaultEncoding=i}t.differences=r;t.baseEncodingName=o;t.hasEncoding=!!o||r.length>0;t.dict=e;t.toUnicode=await s;const c=await this.buildToUnicode(t);t.toUnicode=c;a&&(t.cidToGidMap=this.readCidToGidMap(a,c));return t}_simpleFontToUnicode(e,t=!1){assert(!e.composite,"Must be a simple font.");const n=[],a=e.defaultEncoding.slice(),s=e.baseEncodingName,r=e.differences;for(const e in r){const t=r[e];".notdef"!==t&&(a[e]=t)}const i=ga();for(const r in a){let o=a[r];if(""===o)continue;let l=i[o];if(void 0!==l){n[r]=String.fromCharCode(l);continue}let f=0;switch(o[0]){case"G":3===o.length&&(f=parseInt(o.substring(1),16));break;case"g":5===o.length&&(f=parseInt(o.substring(1),16));break;case"C":case"c":if(o.length>=3&&o.length<=4){const n=o.substring(1);if(t){f=parseInt(n,16);break}f=+n;if(Number.isNaN(f)&&Number.isInteger(parseInt(n,16)))return this._simpleFontToUnicode(e,!0)}break;case"u":l=getUnicodeForGlyph(o,i);-1!==l&&(f=l);break;default:switch(o){case"f_h":case"f_t":case"T_h":n[r]=o.replaceAll("_","");continue}}if(f>0&&f<=1114111&&Number.isInteger(f)){if(s&&f===+r){const e=getEncoding(s);if(e&&(o=e[r])){n[r]=String.fromCharCode(i[o]);continue}}n[r]=String.fromCodePoint(f)}}return n}async buildToUnicode(e){e.hasIncludedToUnicodeMap=e.toUnicode?.length>0;if(e.hasIncludedToUnicodeMap){!e.composite&&e.hasEncoding&&(e.fallbackToUnicode=this._simpleFontToUnicode(e));return e.toUnicode}if(!e.composite)return new ToUnicodeMap(this._simpleFontToUnicode(e));if(e.composite&&(e.cMap.builtInCMap&&!(e.cMap instanceof IdentityCMap)||"Adobe"===e.cidSystemInfo?.registry&&("GB1"===e.cidSystemInfo.ordering||"CNS1"===e.cidSystemInfo.ordering||"Japan1"===e.cidSystemInfo.ordering||"Korea1"===e.cidSystemInfo.ordering))){const{registry:t,ordering:n}=e.cidSystemInfo,a=Name.get(`${t}-${n}-UCS2`),s=await CMapFactory.create({encoding:a,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null}),r=[],i=[];e.cMap.forEach(function(e,t){if(t>65535)throw new FormatError("Max size of CID is 65,535");const n=s.lookup(t);if(n){i.length=0;for(let e=0,t=n.length;e<t;e+=2)i.push((n.charCodeAt(e)<<8)+n.charCodeAt(e+1));r[e]=String.fromCharCode(...i)}});return new ToUnicodeMap(r)}return new IdentityToUnicodeMap(e.firstChar,e.lastChar)}async readToUnicode(e){if(!e)return null;if(e instanceof Name){const t=await CMapFactory.create({encoding:e,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null});return t instanceof IdentityCMap?new IdentityToUnicodeMap(0,65535):new ToUnicodeMap(t.getMap())}if(e instanceof BaseStream)try{const t=await CMapFactory.create({encoding:e,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null});if(t instanceof IdentityCMap)return new IdentityToUnicodeMap(0,65535);const n=new Array(t.length);t.forEach(function(e,t){if("number"==typeof t){n[e]=String.fromCodePoint(t);return}t.length%2!=0&&(t="\0"+t);const a=[];for(let e=0;e<t.length;e+=2){const n=t.charCodeAt(e)<<8|t.charCodeAt(e+1);if(55296!=(63488&n)){a.push(n);continue}e+=2;const s=t.charCodeAt(e)<<8|t.charCodeAt(e+1);a.push(((1023&n)<<10)+(1023&s)+65536)}n[e]=String.fromCodePoint(...a)});return new ToUnicodeMap(n)}catch(e){if(e instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`readToUnicode - ignoring ToUnicode data: "${e}".`);return null}throw e}return null}readCidToGidMap(e,t){const n=[];for(let a=0,s=e.length;a<s;a++){const s=e[a++]<<8|e[a],r=a>>1;(0!==s||t.has(r))&&(n[r]=s)}return n}extractWidths(e,t,n){const a=this.xref;let s=[],r=0;const i=[];let o;if(n.composite){const t=e.get("DW");r="number"==typeof t?Math.ceil(t):1e3;const l=e.get("W");if(Array.isArray(l))for(let e=0,t=l.length;e<t;e++){let t=a.fetchIfRef(l[e++]);if(!Number.isInteger(t))break;const n=a.fetchIfRef(l[e]);if(Array.isArray(n))for(const e of n){const n=a.fetchIfRef(e);"number"==typeof n&&(s[t]=n);t++}else{if(!Number.isInteger(n))break;{const r=a.fetchIfRef(l[++e]);if("number"!=typeof r)continue;for(let e=t;e<=n;e++)s[e]=r}}}if(n.vertical){const t=e.getArray("DW2");let n=isNumberArray(t,2)?t:[880,-1e3];o=[n[1],.5*r,n[0]];n=e.get("W2");if(Array.isArray(n))for(let e=0,t=n.length;e<t;e++){let t=a.fetchIfRef(n[e++]);if(!Number.isInteger(t))break;const s=a.fetchIfRef(n[e]);if(Array.isArray(s))for(let e=0,n=s.length;e<n;e++){const n=[a.fetchIfRef(s[e++]),a.fetchIfRef(s[e++]),a.fetchIfRef(s[e])];isNumberArray(n,null)&&(i[t]=n);t++}else{if(!Number.isInteger(s))break;{const r=[a.fetchIfRef(n[++e]),a.fetchIfRef(n[++e]),a.fetchIfRef(n[++e])];if(!isNumberArray(r,null))continue;for(let e=t;e<=s;e++)i[e]=r}}}}}else{const i=e.get("Widths");if(Array.isArray(i)){let e=n.firstChar;for(const t of i){const n=a.fetchIfRef(t);"number"==typeof n&&(s[e]=n);e++}const o=t.get("MissingWidth");r="number"==typeof o?o:0}else{const t=e.get("BaseFont");if(t instanceof Name){const e=this.getBaseFontMetrics(t.name);s=this.buildCharCodeToWidth(e.widths,n);r=e.defaultWidth}}}let l=!0,f=r;for(const e in s){const t=s[e];if(t)if(f){if(f!==t){l=!1;break}}else f=t}l?n.flags|=va:n.flags&=~va;n.defaultWidth=r;n.widths=s;n.defaultVMetrics=o;n.vmetrics=i}isSerifFont(e){const t=e.split("-",1)[0];return t in Ua()||/serif/gi.test(t)}getBaseFontMetrics(e){let t=0,n=Object.create(null),a=!1,s=normalizeFontName(e);s=Na()[s]||s;const r=Ga(),i=r[s]??r[this.isSerifFont(e)?"Times-Roman":"Helvetica"];if("number"==typeof i){t=i;a=!0}else n=i();return{defaultWidth:t,monospace:a,widths:n}}buildCharCodeToWidth(e,t){const n=Object.create(null),a=t.differences,s=t.defaultEncoding;for(let t=0;t<256;t++)t in a&&e[a[t]]?n[t]=e[a[t]]:t in s&&e[s[t]]&&(n[t]=e[s[t]]);return n}preEvaluateFont(e){const t=e;let n=e.get("Subtype");if(!(n instanceof Name))throw new FormatError("invalid font Subtype");let a,s=!1;if("Type0"===n.name){const t=e.get("DescendantFonts");if(!t)throw new FormatError("Descendant fonts are not specified");if(!((e=Array.isArray(t)?this.xref.fetchIfRef(t[0]):t)instanceof Dict))throw new FormatError("Descendant font is not a dictionary.");n=e.get("Subtype");if(!(n instanceof Name))throw new FormatError("invalid font Subtype");s=!0}let r=e.get("FirstChar");Number.isInteger(r)||(r=0);let i=e.get("LastChar");Number.isInteger(i)||(i=s?65535:255);const o=e.get("FontDescriptor"),l=e.get("ToUnicode")||t.get("ToUnicode");if(o){a=new MurmurHash3_64;const n=t.getRaw("Encoding");if(n instanceof Name)a.update(n.name);else if(n instanceof Ref)a.update(n.toString());else if(n instanceof Dict)for(const e of n.getRawValues())if(e instanceof Name)a.update(e.name);else if(e instanceof Ref)a.update(e.toString());else if(Array.isArray(e)){const t=e.length,n=new Array(t);for(let a=0;a<t;a++){const t=e[a];t instanceof Name?n[a]=t.name:("number"==typeof t||t instanceof Ref)&&(n[a]=t.toString())}a.update(n.join())}a.update(`${r}-${i}`);if(l instanceof BaseStream){const e=l.stream||l,t=e.buffer?new Uint8Array(e.buffer.buffer,0,e.bufferLength):new Uint8Array(e.bytes.buffer,e.start,e.end-e.start);a.update(t)}else l instanceof Name&&a.update(l.name);const o=e.get("Widths")||t.get("Widths");if(Array.isArray(o)){const e=[];for(const t of o)("number"==typeof t||t instanceof Ref)&&e.push(t.toString());a.update(e.join())}if(s){a.update("compositeFont");const n=e.get("W")||t.get("W");if(Array.isArray(n)){const e=[];for(const t of n)if("number"==typeof t||t instanceof Ref)e.push(t.toString());else if(Array.isArray(t)){const n=[];for(const e of t)("number"==typeof e||e instanceof Ref)&&n.push(e.toString());e.push(`[${n.join()}]`)}a.update(e.join())}const s=e.getRaw("CIDToGIDMap")||t.getRaw("CIDToGIDMap");s instanceof Name?a.update(s.name):s instanceof Ref?a.update(s.toString()):s instanceof BaseStream&&a.update(s.peekBytes())}}return{descriptor:o,dict:e,baseDict:t,composite:s,type:n.name,firstChar:r,lastChar:i,toUnicode:l,hash:a?a.hexdigest():""}}async translateFont({descriptor:e,dict:n,baseDict:a,composite:s,type:r,firstChar:i,lastChar:o,toUnicode:l,cssFontInfo:f}){const c="Type3"===r;if(!e){if(!c){let e=n.get("BaseFont");if(!(e instanceof Name))throw new FormatError("Base font is not specified");e=normalizeFontName(e.name);const t=this.getBaseFontMetrics(e),s=e.split("-",1)[0],f=(this.isSerifFont(s)?Sa:0)|(t.monospace?va:0)|(_a()[s]?xa:Aa),h={type:r,name:e,loadedName:a.loadedName,systemFontInfo:null,widths:t.widths,defaultWidth:t.defaultWidth,isSimulatedFlags:!0,flags:f,firstChar:i,lastChar:o,toUnicode:l,xHeight:0,capHeight:0,italicAngle:0,isType3Font:c},u=n.get("Widths"),m=getStandardFontName(e);let p=null;if(m){p=await this.fetchStandardFontData(m);h.isInternalFont=!!p}!h.isInternalFont&&this.options.useSystemFonts&&(h.systemFontInfo=getFontSubstitution(this.systemFontCache,this.idFactory,this.options.standardFontDataUrl,e,m,r));const d=await this.extractDataStructures(n,h);if(Array.isArray(u)){const e=[];let t=i;for(const n of u){const a=this.xref.fetchIfRef(n);"number"==typeof a&&(e[t]=a);t++}d.widths=e}else d.widths=this.buildCharCodeToWidth(t.widths,d);return new Font(e,p,d,this.options)}e=Dict.empty}let h=e.get("FontName"),u=n.get("BaseFont");"string"==typeof h&&(h=Name.get(h));"string"==typeof u&&(u=Name.get(u));const m=h?.name,p=u?.name;if(c)m||(h=Name.get(r));else if(m!==p){info(`The FontDescriptor's FontName is "${m}" but should be the same as the Font's BaseFont "${p}".`);m&&p&&(p.startsWith(m)||!isKnownFontName(m)&&isKnownFontName(p))&&(h=null);h||=u}if(!(h instanceof Name))throw new FormatError("invalid font name");let d,g,b,w,j;try{d=e.get("FontFile","FontFile2","FontFile3");if(d){if(!(d instanceof BaseStream))throw new FormatError("FontFile should be a stream");if(d.isAsync){const e=await d.asyncGetBytes();e&&(d=new Stream(e,0,e.length,d.dict))}if(d.isEmpty)throw new FormatError("FontFile is empty")}}catch(e){if(!this.options.ignoreErrors)throw e;warn(`translateFont - fetching "${h.name}" font file: "${e}".`);d=null}let k=!1,y=null,q=null;if(d){if(d.dict){const e=d.dict.get("Subtype");e instanceof Name&&(g=e.name);b=d.dict.get("Length1");w=d.dict.get("Length2");j=d.dict.get("Length3")}}else if(f){const e=getXfaFontName(h.name);if(e){f.fontFamily=`${f.fontFamily}-PdfJS-XFA`;f.metrics=e.metrics||null;y=e.factors||null;d=await this.fetchStandardFontData(e.name);k=!!d;a=n=getXfaFontDict(h.name);s=!0}}else if(!c){const e=getStandardFontName(h.name);if(e){d=await this.fetchStandardFontData(e);k=!!d}!k&&this.options.useSystemFonts&&(q=getFontSubstitution(this.systemFontCache,this.idFactory,this.options.standardFontDataUrl,h.name,e,r))}const v=lookupMatrix(n.getArray("FontMatrix"),t),S=lookupNormalRect(e.getArray("FontBBox")||n.getArray("FontBBox"),c?[0,0,0,0]:void 0);let x=e.get("Ascent");"number"!=typeof x&&(x=void 0);let C=e.get("Descent");"number"!=typeof C&&(C=void 0);let F=e.get("XHeight");"number"!=typeof F&&(F=0);let T=e.get("CapHeight");"number"!=typeof T&&(T=0);let H=e.get("Flags");Number.isInteger(H)||(H=0);let O=e.get("ItalicAngle");"number"!=typeof O&&(O=0);const R={type:r,name:h.name,subtype:g,file:d,length1:b,length2:w,length3:j,isInternalFont:k,loadedName:a.loadedName,composite:s,fixedPitch:!1,fontMatrix:v,firstChar:i,lastChar:o,toUnicode:l,bbox:S,ascent:x,descent:C,xHeight:F,capHeight:T,flags:H,italicAngle:O,isType3Font:c,cssFontInfo:f,scaleFactors:y,systemFontInfo:q};if(s){const e=a.get("Encoding");e instanceof Name&&(R.cidEncoding=e.name);const t=await CMapFactory.create({encoding:e,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null});R.cMap=t;R.vertical=R.cMap.vertical}const D=await this.extractDataStructures(n,R);this.extractWidths(n,e,D);return new Font(h.name,d,D,this.options)}static buildFontPaths(e,t,n,a){function buildPath(t){const s=`${e.loadedName}_path_${t}`;try{if(e.renderer.hasBuiltPath(t))return;const a=FontPathInfo.write(e.renderer.getPathJs(t));n.send("commonobj",[s,"FontPath",a],[a])}catch(e){if(a.ignoreErrors){warn(`buildFontPaths - ignoring ${s} glyph: "${e}".`);return}throw e}}for(const e of t){buildPath(e.fontChar);const t=e.accent;t?.fontChar&&buildPath(t.fontChar)}}static get fallbackFontDict(){const e=new Dict;e.set("BaseFont",Name.get("Helvetica"));e.set("Type",Name.get("FallbackType"));e.set("Subtype",Name.get("FallbackType"));e.set("Encoding",Name.get("WinAnsiEncoding"));return shadow(this,"fallbackFontDict",e)}}class TranslatedFont{#ue=!1;#me=null;constructor({loadedName:e,font:t,dict:n}){this.loadedName=e;this.font=t;this.dict=n;this.type3Dependencies=t.isType3Font?new Set:null}send(e){if(this.#ue)return;this.#ue=!0;const t=this.font.exportData(),n=[];if(t.data){t.data.charProcOperatorList&&(t.charProcOperatorList=t.data.charProcOperatorList);t.data=FontInfo.write(t.data);n.push(t.data)}e.send("commonobj",[this.loadedName,"Font",t],n)}fallback(e,t){if(this.font.data){this.font.disableFontFace=!0;PartialEvaluator.buildFontPaths(this.font,this.font.glyphCacheValues,e,t)}}loadType3Data(e,t,n){if(this.#me)return this.#me;const{font:a,type3Dependencies:s}=this;assert(a.isType3Font,"Must be a Type3 font.");const r=e.clone({ignoreErrors:!1}),i=new RefSet(e.type3FontRefs);this.dict.objId&&!i.has(this.dict.objId)&&i.put(this.dict.objId);r.type3FontRefs=i;let o=Promise.resolve();const l=this.dict.get("CharProcs"),f=this.dict.get("Resources")||t,c=Object.create(null),[h,u,m,p]=a.bbox,d=m-h,g=p-u,b=Math.hypot(d,g);for(const e of l.getKeys())o=o.then(()=>{const t=l.get(e),a=new OperatorList;return r.getOperatorList({stream:t,task:n,resources:f,operatorList:a}).then(()=>{switch(a.fnArray[0]){case at:this.#pe(a,b);break;case nt:b||this.#de(a)}c[e]=a.getIR();for(const e of a.dependencies)s.add(e)}).catch(function(t){warn(`Type3 font resource "${e}" is not available.`);const n=new OperatorList;c[e]=n.getIR()})});this.#me=o.then(()=>{a.charProcOperatorList=c;if(this._bbox){a.isCharBBox=!0;a.bbox=this._bbox}});return this.#me}#pe(e,t=NaN){const n=Util.normalizeRect(e.argsArray[0].slice(2)),a=n[2]-n[0],s=n[3]-n[1],r=Math.hypot(a,s);if(0===a||0===s){e.fnArray.splice(0,1);e.argsArray.splice(0,1)}else if(0===t||Math.round(r/t)>=10){this._bbox??=[1/0,1/0,-1/0,-1/0];Util.rectBoundingBox(...n,this._bbox)}let i=0,o=e.length;for(;i<o;){switch(e.fnArray[i]){case at:break;case st:case rt:case it:case ot:case lt:case ft:case ct:case ht:case ut:case mt:case pt:case dt:case gt:case de:e.fnArray.splice(i,1);e.argsArray.splice(i,1);o--;continue;case be:const[t]=e.argsArray[i];let n=0,a=t.length;for(;n<a;){const[e]=t[n];switch(e){case"TR":case"TR2":case"HT":case"BG":case"BG2":case"UCR":case"UCR2":t.splice(n,1);a--;continue}n++}}i++}}#de(e){let t=1;const n=e.length;for(;t<n;){if(e.fnArray[t]===Ut){const n=e.argsArray[t][2];this._bbox??=[1/0,1/0,-1/0,-1/0];Util.rectBoundingBox(...n,this._bbox)}t++}}}class StateManager{constructor(e=new EvalState){this.state=e;this.stateStack=[]}save(){const e=this.state;this.stateStack.push(this.state);this.state=e.clone()}restore(){const e=this.stateStack.pop();e&&(this.state=e)}transform(e){this.state.ctm=Util.transform(this.state.ctm,e)}}class TextState{ctm=new Float32Array(pn);fontName=null;fontSize=0;loadedName=null;font=null;fontMatrix=t;textMatrix=pn.slice();textLineMatrix=pn.slice();charSpacing=0;wordSpacing=0;leading=0;textHScale=1;textRise=0;setTextMatrix(e,t,n,a,s,r){const i=this.textMatrix;i[0]=e;i[1]=t;i[2]=n;i[3]=a;i[4]=s;i[5]=r}setTextLineMatrix(e,t,n,a,s,r){const i=this.textLineMatrix;i[0]=e;i[1]=t;i[2]=n;i[3]=a;i[4]=s;i[5]=r}translateTextMatrix(e,t){const n=this.textMatrix;n[4]=n[0]*e+n[2]*t+n[4];n[5]=n[1]*e+n[3]*t+n[5]}translateTextLineMatrix(e,t){const n=this.textLineMatrix;n[4]=n[0]*e+n[2]*t+n[4];n[5]=n[1]*e+n[3]*t+n[5]}carriageReturn(){this.translateTextLineMatrix(0,-this.leading);this.textMatrix=this.textLineMatrix.slice()}clone(){const e=Object.assign(Object.create(this),this);e.textMatrix=this.textMatrix.slice();e.textLineMatrix=this.textLineMatrix.slice();e.fontMatrix=this.fontMatrix.slice();return e}}class EvalState{ctm=new Float32Array(pn);font=null;textRenderingMode=v;_fillColorSpace=ColorSpaceUtils.gray;_strokeColorSpace=ColorSpaceUtils.gray;patternFillColorSpace=null;patternStrokeColorSpace=null;currentPointX=0;currentPointY=0;pathMinMax=new Float32Array([1/0,1/0,-1/0,-1/0]);pathBuffer=[];get fillColorSpace(){return this._fillColorSpace}set fillColorSpace(e){this._fillColorSpace=this.patternFillColorSpace=e}get strokeColorSpace(){return this._strokeColorSpace}set strokeColorSpace(e){this._strokeColorSpace=this.patternStrokeColorSpace=e}clone({newPath:e=!1}={}){const t=Object.create(this);if(e){t.pathBuffer=[];t.pathMinMax=new Float32Array([1/0,1/0,-1/0,-1/0])}return t}}class EvaluatorPreprocessor{static get opMap(){return shadow(this,"opMap",Object.assign(Object.create(null),{w:{id:ce,numArgs:1,variableArgs:!1},J:{id:he,numArgs:1,variableArgs:!1},j:{id:ue,numArgs:1,variableArgs:!1},M:{id:me,numArgs:1,variableArgs:!1},d:{id:pe,numArgs:2,variableArgs:!1},ri:{id:de,numArgs:1,variableArgs:!1},i:{id:ge,numArgs:1,variableArgs:!1},gs:{id:be,numArgs:1,variableArgs:!1},q:{id:we,numArgs:0,variableArgs:!1},Q:{id:je,numArgs:0,variableArgs:!1},cm:{id:ke,numArgs:6,variableArgs:!1},m:{id:ye,numArgs:2,variableArgs:!1},l:{id:qe,numArgs:2,variableArgs:!1},c:{id:ve,numArgs:6,variableArgs:!1},v:{id:Se,numArgs:4,variableArgs:!1},y:{id:xe,numArgs:4,variableArgs:!1},h:{id:Ae,numArgs:0,variableArgs:!1},re:{id:Ce,numArgs:4,variableArgs:!1},S:{id:Ie,numArgs:0,variableArgs:!1},s:{id:Fe,numArgs:0,variableArgs:!1},f:{id:Te,numArgs:0,variableArgs:!1},F:{id:Te,numArgs:0,variableArgs:!1},"f*":{id:He,numArgs:0,variableArgs:!1},B:{id:Oe,numArgs:0,variableArgs:!1},"B*":{id:Be,numArgs:0,variableArgs:!1},b:{id:Re,numArgs:0,variableArgs:!1},"b*":{id:De,numArgs:0,variableArgs:!1},n:{id:Me,numArgs:0,variableArgs:!1},W:{id:Pe,numArgs:0,variableArgs:!1},"W*":{id:Ee,numArgs:0,variableArgs:!1},BT:{id:Ne,numArgs:0,variableArgs:!1},ET:{id:ze,numArgs:0,variableArgs:!1},Tc:{id:Le,numArgs:1,variableArgs:!1},Tw:{id:Ue,numArgs:1,variableArgs:!1},Tz:{id:_e,numArgs:1,variableArgs:!1},TL:{id:Xe,numArgs:1,variableArgs:!1},Tf:{id:We,numArgs:2,variableArgs:!1},Tr:{id:Ke,numArgs:1,variableArgs:!1},Ts:{id:Ge,numArgs:1,variableArgs:!1},Td:{id:Ve,numArgs:2,variableArgs:!1},TD:{id:$e,numArgs:2,variableArgs:!1},Tm:{id:Ye,numArgs:6,variableArgs:!1},"T*":{id:Je,numArgs:0,variableArgs:!1},Tj:{id:Qe,numArgs:1,variableArgs:!1},TJ:{id:Ze,numArgs:1,variableArgs:!1},"'":{id:et,numArgs:1,variableArgs:!1},'"':{id:tt,numArgs:3,variableArgs:!1},d0:{id:nt,numArgs:2,variableArgs:!1},d1:{id:at,numArgs:6,variableArgs:!1},CS:{id:st,numArgs:1,variableArgs:!1},cs:{id:rt,numArgs:1,variableArgs:!1},SC:{id:it,numArgs:4,variableArgs:!0},SCN:{id:ot,numArgs:33,variableArgs:!0},sc:{id:lt,numArgs:4,variableArgs:!0},scn:{id:ft,numArgs:33,variableArgs:!0},G:{id:ct,numArgs:1,variableArgs:!1},g:{id:ht,numArgs:1,variableArgs:!1},RG:{id:ut,numArgs:3,variableArgs:!1},rg:{id:mt,numArgs:3,variableArgs:!1},K:{id:pt,numArgs:4,variableArgs:!1},k:{id:dt,numArgs:4,variableArgs:!1},sh:{id:gt,numArgs:1,variableArgs:!1},BI:{id:bt,numArgs:0,variableArgs:!1},ID:{id:wt,numArgs:0,variableArgs:!1},EI:{id:jt,numArgs:1,variableArgs:!1},Do:{id:kt,numArgs:1,variableArgs:!1},MP:{id:yt,numArgs:1,variableArgs:!1},DP:{id:qt,numArgs:2,variableArgs:!1},BMC:{id:vt,numArgs:1,variableArgs:!1},BDC:{id:St,numArgs:2,variableArgs:!1},EMC:{id:xt,numArgs:0,variableArgs:!1},BX:{id:At,numArgs:0,variableArgs:!1},EX:{id:Ct,numArgs:0,variableArgs:!1},BM:null,BD:null,true:null,fa:null,fal:null,fals:null,false:null,nu:null,nul:null,null:null}))}static MAX_INVALID_PATH_OPS=10;constructor(e,t,n=new StateManager){this.parser=new Parser({lexer:new Lexer(e,EvaluatorPreprocessor.opMap),xref:t});this.stateManager=n;this.nonProcessedArgs=[];this._isPathOp=!1;this._numInvalidPathOPS=0}get savedStatesDepth(){return this.stateManager.stateStack.length}read(e){let t=e.args;for(;;){const n=this.parser.getObj();if(n instanceof Cmd){const a=n.cmd,s=EvaluatorPreprocessor.opMap[a];if(!s){warn(`Unknown command "${a}".`);continue}const r=s.id,i=s.numArgs;let o=null!==t?t.length:0;this._isPathOp||(this._numInvalidPathOPS=0);this._isPathOp=r>=ye&&r<=Me;if(s.variableArgs)o>i&&info(`Command ${a}: expected [0, ${i}] args, but received ${o} args.`);else{if(o!==i){const e=this.nonProcessedArgs;for(;o>i;){e.push(t.shift());o--}for(;o<i&&0!==e.length;){null===t&&(t=[]);t.unshift(e.pop());o++}}if(o<i){const e=`command ${a}: expected ${i} args, but received ${o} args.`;if(this._isPathOp&&++this._numInvalidPathOPS>EvaluatorPreprocessor.MAX_INVALID_PATH_OPS)throw new FormatError(`Invalid ${e}`);warn(`Skipping ${e}`);null!==t&&(t.length=0);continue}}this.preprocessCommand(r,t);e.fn=r;e.args=t;return!0}if(n===on)return!1;if(null!==n){null===t&&(t=[]);t.push(n);if(t.length>33)throw new FormatError("Too many arguments")}}}preprocessCommand(e,t){switch(0|e){case we:this.stateManager.save();break;case je:this.stateManager.restore();break;case ke:this.stateManager.transform(t)}}}class DefaultAppearanceEvaluator extends EvaluatorPreprocessor{constructor(e){super(new StringStream(e))}parse(){const e={fn:0,args:[]},t={fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3)};try{for(;;){e.args.length=0;if(!this.read(e))break;if(0!==this.savedStatesDepth)continue;const{fn:n,args:a}=e;switch(0|n){case We:const[e,n]=a;e instanceof Name&&(t.fontName=e.name);"number"==typeof n&&n>0&&(t.fontSize=n);break;case mt:ColorSpaceUtils.rgb.getRgbItem(a,0,t.fontColor,0);break;case ht:ColorSpaceUtils.gray.getRgbItem(a,0,t.fontColor,0);break;case dt:ColorSpaceUtils.cmyk.getRgbItem(a,0,t.fontColor,0)}}}catch(e){warn(`parseDefaultAppearance - ignoring errors: "${e}".`)}return t}}function parseDefaultAppearance(e){return new DefaultAppearanceEvaluator(e).parse()}class AppearanceStreamEvaluator extends EvaluatorPreprocessor{constructor(e,t,n,a){super(e);this.stream=e;this.evaluatorOptions=t;this.xref=n;this.globalColorSpaceCache=a;this.resources=e.dict?.get("Resources")}parse(){const e={fn:0,args:[]};let t={scaleFactor:1,fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3),fillColorSpace:ColorSpaceUtils.gray},n=!1;const a=[];try{for(;;){e.args.length=0;if(n||!this.read(e))break;const{fn:s,args:r}=e;switch(0|s){case we:a.push({scaleFactor:t.scaleFactor,fontSize:t.fontSize,fontName:t.fontName,fontColor:t.fontColor.slice(),fillColorSpace:t.fillColorSpace});break;case je:t=a.pop()||t;break;case Ye:t.scaleFactor*=Math.hypot(r[0],r[1]);break;case We:const[e,s]=r;e instanceof Name&&(t.fontName=e.name);"number"==typeof s&&s>0&&(t.fontSize=s*t.scaleFactor);break;case rt:t.fillColorSpace=ColorSpaceUtils.parse({cs:r[0],xref:this.xref,resources:this.resources,pdfFunctionFactory:this._pdfFunctionFactory,globalColorSpaceCache:this.globalColorSpaceCache,localColorSpaceCache:this._localColorSpaceCache});break;case lt:t.fillColorSpace.getRgbItem(r,0,t.fontColor,0);break;case mt:ColorSpaceUtils.rgb.getRgbItem(r,0,t.fontColor,0);break;case ht:ColorSpaceUtils.gray.getRgbItem(r,0,t.fontColor,0);break;case dt:ColorSpaceUtils.cmyk.getRgbItem(r,0,t.fontColor,0);break;case Qe:case Ze:case et:case tt:n=!0}}}catch(e){warn(`parseAppearanceStream - ignoring errors: "${e}".`)}this.stream.reset();delete t.scaleFactor;delete t.fillColorSpace;return t}get _localColorSpaceCache(){return shadow(this,"_localColorSpaceCache",new LocalColorSpaceCache)}get _pdfFunctionFactory(){return shadow(this,"_pdfFunctionFactory",new PDFFunctionFactory({xref:this.xref,isEvalSupported:this.evaluatorOptions.isEvalSupported}))}}function getPdfColor(e,t){if(e[0]===e[1]&&e[1]===e[2]){return`${numberToString(e[0]/255)} ${t?"g":"G"}`}return Array.from(e,e=>numberToString(e/255)).join(" ")+" "+(t?"rg":"RG")}class FakeUnicodeFont{constructor(e,t){this.xref=e;this.widths=null;this.firstChar=1/0;this.lastChar=-1/0;this.fontFamily=t;const n=new OffscreenCanvas(1,1);this.ctxMeasure=n.getContext("2d",{willReadFrequently:!0});FakeUnicodeFont._fontNameId||(FakeUnicodeFont._fontNameId=1);this.fontName=Name.get(`InvalidPDFjsFont_${t}_${FakeUnicodeFont._fontNameId++}`)}get fontDescriptorRef(){if(!FakeUnicodeFont._fontDescriptorRef){const e=new Dict(this.xref);e.setIfName("Type","FontDescriptor");e.set("FontName",this.fontName);e.set("FontFamily","MyriadPro Regular");e.set("FontBBox",[0,0,0,0]);e.setIfName("FontStretch","Normal");e.set("FontWeight",400);e.set("ItalicAngle",0);FakeUnicodeFont._fontDescriptorRef=this.xref.getNewPersistentRef(e)}return FakeUnicodeFont._fontDescriptorRef}get descendantFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.setIfName("Type","Font");e.setIfName("Subtype","CIDFontType0");e.setIfName("CIDToGIDMap","Identity");e.set("FirstChar",this.firstChar);e.set("LastChar",this.lastChar);e.set("FontDescriptor",this.fontDescriptorRef);e.set("DW",1e3);const t=[],n=[...this.widths].sort();let a=null,s=null;for(const[e,r]of n)if(a)if(e===a+s.length)s.push(r);else{t.push(a,s);a=e;s=[r]}else{a=e;s=[r]}a&&t.push(a,s);e.set("W",t);const r=new Dict(this.xref);r.set("Ordering","Identity");r.set("Registry","Adobe");r.set("Supplement",0);e.set("CIDSystemInfo",r);return this.xref.getNewPersistentRef(e)}get baseFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.setIfName("Type","Font");e.setIfName("Subtype","Type0");e.setIfName("Encoding","Identity-H");e.set("DescendantFonts",[this.descendantFontRef]);e.setIfName("ToUnicode","Identity-H");return this.xref.getNewPersistentRef(e)}get resources(){const e=new Dict(this.xref),t=new Dict(this.xref);t.set(this.fontName.name,this.baseFontRef);e.set("Font",t);return e}_createContext(){this.widths=new Map;this.ctxMeasure.font=`1000px ${this.fontFamily}`;return this.ctxMeasure}createFontResources(e){const t=this._createContext();for(const n of e.split(/\r\n?|\n/))for(const e of n.split("")){const n=e.charCodeAt(0);if(this.widths.has(n))continue;const a=t.measureText(e),s=Math.ceil(a.width);this.widths.set(n,s);this.firstChar=Math.min(n,this.firstChar);this.lastChar=Math.max(n,this.lastChar)}return this.resources}static getFirstPositionInfo(e,t,s){const[r,i,o,l]=e;let f=o-r,c=l-i;t%180!=0&&([f,c]=[c,f]);const h=n*s;return{coords:[0,c+a*s-h],bbox:[0,0,f,c],matrix:0!==t?getRotationMatrix(t,c,h):void 0}}createAppearance(e,t,s,r,i,o){const l=this._createContext(),f=[];let c=-1/0;for(const t of e.split(/\r\n?|\n/)){f.push(t);const e=l.measureText(t).width;c=Math.max(c,e);for(const e of codePointIter(t)){const t=String.fromCodePoint(e);let n=this.widths.get(e);if(void 0===n){const a=l.measureText(t);n=Math.ceil(a.width);this.widths.set(e,n);this.firstChar=Math.min(e,this.firstChar);this.lastChar=Math.max(e,this.lastChar)}}}c*=r/1e3;const[h,u,m,p]=t;let d=m-h,g=p-u;s%180!=0&&([d,g]=[g,d]);let b=1;c>d&&(b=d/c);let w=1;const j=n*r,k=a*r,y=j*f.length;y>g&&(w=g/y);const q=r*Math.min(b,w),v=["q",`0 0 ${numberToString(d)} ${numberToString(g)} re W n`,"BT",`1 0 0 1 0 ${numberToString(g+k)} Tm 0 Tc ${getPdfColor(i,!0)}`,`/${this.fontName.name} ${numberToString(q)} Tf`],{resources:S}=this;if(1!==(o="number"==typeof o&&o>=0&&o<=1?o:1)){v.push("/R0 gs");const e=new Dict(this.xref),t=new Dict(this.xref);t.set("ca",o);t.set("CA",o);t.setIfName("Type","ExtGState");e.set("R0",t);S.set("ExtGState",e)}const x=numberToString(j);for(const e of f)v.push(`0 -${x} Td <${stringToUTF16HexString(e)}> Tj`);v.push("ET","Q");const C=v.join("\n"),F=new Dict(this.xref);F.setIfName("Subtype","Form");F.setIfName("Type","XObject");F.set("BBox",[0,0,d,g]);F.set("Length",C.length);F.set("Resources",S);if(s){const e=getRotationMatrix(s,d,g);F.set("Matrix",e)}const T=new StringStream(C);T.dict=F;return T}}const vr=["m/d","m/d/yy","mm/dd/yy","mm/yy","d-mmm","d-mmm-yy","dd-mmm-yy","yy-mm-dd","mmm-yy","mmmm-yy","mmm d, yyyy","mmmm d, yyyy","m/d/yy h:MM tt","m/d/yy HH:MM"],Sr=["HH:MM","h:MM tt","HH:MM:ss","h:MM:ss tt"];class NameOrNumberTree{constructor(e,t,n){this.root=e;this.xref=t;this._type=n}getAll(e=!1){const t=new Map;if(!this.root)return t;const n=this.xref,a=new RefSet;a.put(this.root);const s=[this.root];for(;s.length>0;){const r=n.fetchIfRef(s.shift());if(!(r instanceof Dict))continue;if(r.has("Kids")){const e=r.get("Kids");if(!Array.isArray(e))continue;for(const t of e){if(a.has(t))throw new FormatError(`Duplicate entry in "${this._type}" tree.`);s.push(t);a.put(t)}continue}const i=r.get(this._type);if(Array.isArray(i))for(let a=0,s=i.length;a<s;a+=2)t.set(n.fetchIfRef(i[a]),e?i[a+1]:n.fetchIfRef(i[a+1]))}return t}getRaw(e){if(!this.root)return null;const t=this.xref;let n=t.fetchIfRef(this.root),a=0;for(;n.has("Kids");){if(++a>10){warn(`Search depth limit reached for "${this._type}" tree.`);return null}const s=n.get("Kids");if(!Array.isArray(s))return null;let r=0,i=s.length-1;for(;r<=i;){const a=r+i>>1,o=t.fetchIfRef(s[a]),l=o.get("Limits");if(e<t.fetchIfRef(l[0]))i=a-1;else{if(!(e>t.fetchIfRef(l[1]))){n=o;break}r=a+1}}if(r>i)return null}const s=n.get(this._type);if(Array.isArray(s)){let n=0,a=s.length-2;for(;n<=a;){const r=n+a>>1,i=r+(1&r),o=t.fetchIfRef(s[i]);if(e<o)a=i-2;else{if(!(e>o))return s[i+1];n=i+2}}}return null}get(e){return this.xref.fetchIfRef(this.getRaw(e))}}class NameTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Names")}}class NumberTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Nums")}}function clearGlobalCaches(){!function clearPatternCaches(){gs=Object.create(null)}();!function clearPrimitiveCaches(){ln=Object.create(null);fn=Object.create(null);cn=Object.create(null)}();!function clearUnicodeCaches(){ya.clear()}();JpxImage.cleanup()}function pickPlatformItem(e){if(e instanceof Dict)for(const t of["UF","F","Unix","Mac","DOS"])if(e.has(t))return e.get(t);return null}class FileSpec{#ge=!1;constructor(e,t=!1){if(e instanceof Dict){this.root=e;e.has("FS")&&(this.fs=e.get("FS"));e.has("RF")&&warn("Related file specifications are not supported");t||(e.has("EF")?this.#ge=!0:warn("Non-embedded file specifications are not supported"))}}get filename(){const e=pickPlatformItem(this.root);return e&&"string"==typeof e?stringToPDFString(e,!0).replaceAll("\\\\","\\").replaceAll("\\/","/").replaceAll("\\","/"):""}get content(){if(!this.#ge)return null;const e=pickPlatformItem(this.root?.get("EF"));if(e instanceof BaseStream)return e.getBytes();warn("Embedded file specification points to non-existing/invalid content");return null}get description(){const e=this.root?.get("Desc");return e&&"string"==typeof e?stringToPDFString(e):""}get serializable(){const{filename:e,content:t,description:n}=this;return{rawFilename:e,filename:(a=e,a.substring(a.lastIndexOf("/")+1))||"unnamed",content:t,description:n};var a}}const xr=0,Ar=-2,Cr=-3,Ir=-4,Fr=-5,Tr=-6,Hr=-9;function isWhitespace(e,t){const n=e[t];return" "===n||"\n"===n||"\r"===n||"\t"===n}class XMLParserBase{_resolveEntities(e){return e.replaceAll(/&([^;]+);/g,(e,t)=>{if("#x"===t.substring(0,2))return String.fromCodePoint(parseInt(t.substring(2),16));if("#"===t.substring(0,1))return String.fromCodePoint(parseInt(t.substring(1),10));switch(t){case"lt":return"<";case"gt":return">";case"amp":return"&";case"quot":return'"';case"apos":return"'"}return this.onResolveEntity(t)})}_parseContent(e,t){const n=[];let a=t;function skipWs(){for(;a<e.length&&isWhitespace(e,a);)++a}for(;a<e.length&&!isWhitespace(e,a)&&">"!==e[a]&&"/"!==e[a];)++a;const s=e.substring(t,a);skipWs();for(;a<e.length&&">"!==e[a]&&"/"!==e[a]&&"?"!==e[a];){skipWs();let t="",s="";for(;a<e.length&&!isWhitespace(e,a)&&"="!==e[a];){t+=e[a];++a}skipWs();if("="!==e[a])return null;++a;skipWs();const r=e[a];if('"'!==r&&"'"!==r)return null;const i=e.indexOf(r,++a);if(i<0)return null;s=e.substring(a,i);n.push({name:t,value:this._resolveEntities(s)});a=i+1;skipWs()}return{name:s,attributes:n,parsed:a-t}}_parseProcessingInstruction(e,t){let n=t;for(;n<e.length&&!isWhitespace(e,n)&&">"!==e[n]&&"?"!==e[n]&&"/"!==e[n];)++n;const a=e.substring(t,n);!function skipWs(){for(;n<e.length&&isWhitespace(e,n);)++n}();const s=n;for(;n<e.length&&("?"!==e[n]||">"!==e[n+1]);)++n;return{name:a,value:e.substring(s,n),parsed:n-t}}parseXml(e){let t=0;for(;t<e.length;){let n=t;if("<"===e[t]){++n;let t;switch(e[n]){case"/":++n;t=e.indexOf(">",n);if(t<0){this.onError(Hr);return}this.onEndElement(e.substring(n,t));n=t+1;break;case"?":++n;const a=this._parseProcessingInstruction(e,n);if("?>"!==e.substring(n+a.parsed,n+a.parsed+2)){this.onError(Cr);return}this.onPi(a.name,a.value);n+=a.parsed+2;break;case"!":if("--"===e.substring(n+1,n+3)){t=e.indexOf("--\x3e",n+3);if(t<0){this.onError(Fr);return}this.onComment(e.substring(n+3,t));n=t+3}else if("[CDATA["===e.substring(n+1,n+8)){t=e.indexOf("]]>",n+8);if(t<0){this.onError(Ar);return}this.onCdata(e.substring(n+8,t));n=t+3}else{if("DOCTYPE"!==e.substring(n+1,n+8)){this.onError(Tr);return}{const a=e.indexOf("[",n+8);let s=!1;t=e.indexOf(">",n+8);if(t<0){this.onError(Ir);return}if(a>0&&t>a){t=e.indexOf("]>",n+8);if(t<0){this.onError(Ir);return}s=!0}const r=e.substring(n+8,t+(s?1:0));this.onDoctype(r);n=t+(s?2:1)}}break;default:const s=this._parseContent(e,n);if(null===s){this.onError(Tr);return}let r=!1;if("/>"===e.substring(n+s.parsed,n+s.parsed+2))r=!0;else if(">"!==e.substring(n+s.parsed,n+s.parsed+1)){this.onError(Hr);return}this.onBeginElement(s.name,s.attributes,r);n+=s.parsed+(r?2:1)}}else{for(;n<e.length&&"<"!==e[n];)n++;const a=e.substring(t,n);this.onText(this._resolveEntities(a))}t=n}}onResolveEntity(e){return`&${e};`}onPi(e,t){}onComment(e){}onCdata(e){}onDoctype(e){}onText(e){}onBeginElement(e,t,n){}onEndElement(e){}onError(e){}}class SimpleDOMNode{constructor(e,t){this.nodeName=e;this.nodeValue=t;Object.defineProperty(this,"parentNode",{value:null,writable:!0})}get firstChild(){return this.childNodes?.[0]}get nextSibling(){const e=this.parentNode.childNodes;if(!e)return;const t=e.indexOf(this);return-1!==t?e[t+1]:void 0}get textContent(){return this.childNodes?this.childNodes.map(e=>e.textContent).join(""):this.nodeValue||""}get children(){return this.childNodes||[]}hasChildNodes(){return this.childNodes?.length>0}searchNode(e,t){if(t>=e.length)return this;const n=e[t];if(n.name.startsWith("#")&&t<e.length-1)return this.searchNode(e,t+1);const a=[];let s=this;for(;;){if(n.name===s.nodeName){if(0!==n.pos){if(0===a.length)return null;{const[r]=a.pop();let i=0;for(const a of r.childNodes)if(n.name===a.nodeName){if(i===n.pos)return a.searchNode(e,t+1);i++}return s.searchNode(e,t+1)}}{const n=s.searchNode(e,t+1);if(null!==n)return n}}if(s.childNodes?.length>0){a.push([s,0]);s=s.childNodes[0]}else{if(0===a.length)return null;for(;0!==a.length;){const[e,t]=a.pop(),n=t+1;if(n<e.childNodes.length){a.push([e,n]);s=e.childNodes[n];break}}if(0===a.length)return null}}}dump(e){if("#text"!==this.nodeName){e.push(`<${this.nodeName}`);if(this.attributes)for(const t of this.attributes)e.push(` ${t.name}="${encodeToXmlString(t.value)}"`);if(this.hasChildNodes()){e.push(">");for(const t of this.childNodes)t.dump(e);e.push(`</${this.nodeName}>`)}else this.nodeValue?e.push(`>${encodeToXmlString(this.nodeValue)}</${this.nodeName}>`):e.push("/>")}else e.push(encodeToXmlString(this.nodeValue))}}class SimpleXMLParser extends XMLParserBase{constructor({hasAttributes:e=!1,lowerCaseName:t=!1}){super();this._currentFragment=null;this._stack=null;this._errorCode=xr;this._hasAttributes=e;this._lowerCaseName=t}parseFromString(e){this._currentFragment=[];this._stack=[];this._errorCode=xr;this.parseXml(e);if(this._errorCode!==xr)return;const[t]=this._currentFragment;return t?{documentElement:t}:void 0}onText(e){if(function isWhitespaceString(e){for(let t=0,n=e.length;t<n;t++)if(!isWhitespace(e,t))return!1;return!0}(e))return;const t=new SimpleDOMNode("#text",e);this._currentFragment.push(t)}onCdata(e){const t=new SimpleDOMNode("#text",e);this._currentFragment.push(t)}onBeginElement(e,t,n){this._lowerCaseName&&(e=e.toLowerCase());const a=new SimpleDOMNode(e);a.childNodes=[];this._hasAttributes&&(a.attributes=t);this._currentFragment.push(a);if(!n){this._stack.push(this._currentFragment);this._currentFragment=a.childNodes}}onEndElement(e){this._currentFragment=this._stack.pop()||[];const t=this._currentFragment.at(-1);if(!t)return null;for(const e of t.childNodes)e.parentNode=t;return t}onError(e){this._errorCode=e}}class MetadataParser{constructor(e){e=this._repair(e);const t=new SimpleXMLParser({lowerCaseName:!0}).parseFromString(e);this._metadataMap=new Map;this._data=e;t&&this._parse(t)}_repair(e){return e.replace(/^[^<]+/,"").replaceAll(/>\\376\\377([^<]+)/g,function(e,t){const n=t.replaceAll(/\\([0-3])([0-7])([0-7])/g,function(e,t,n,a){return String.fromCharCode(64*t+8*n+1*a)}).replaceAll(/&(amp|apos|gt|lt|quot);/g,function(e,t){switch(t){case"amp":return"&";case"apos":return"'";case"gt":return">";case"lt":return"<";case"quot":return'"'}throw new Error(`_repair: ${t} isn't defined.`)}),a=[">"];for(let e=0,t=n.length;e<t;e+=2){const t=256*n.charCodeAt(e)+n.charCodeAt(e+1);t>=32&&t<127&&60!==t&&62!==t&&38!==t?a.push(String.fromCharCode(t)):a.push("&#x"+(65536+t).toString(16).substring(1)+";")}return a.join("")})}_getSequence(e){const t=e.nodeName;return"rdf:bag"!==t&&"rdf:seq"!==t&&"rdf:alt"!==t?null:e.childNodes.filter(e=>"rdf:li"===e.nodeName)}_parseArray(e){if(!e.hasChildNodes())return;const[t]=e.childNodes,n=this._getSequence(t)||[];this._metadataMap.set(e.nodeName,n.map(e=>e.textContent.trim()))}_parse(e){let t=e.documentElement;if("rdf:rdf"!==t.nodeName){t=t.firstChild;for(;t&&"rdf:rdf"!==t.nodeName;)t=t.nextSibling}if(t&&"rdf:rdf"===t.nodeName&&t.hasChildNodes())for(const e of t.childNodes)if("rdf:description"===e.nodeName)for(const t of e.childNodes){const e=t.nodeName;switch(e){case"#text":continue;case"dc:creator":case"dc:subject":this._parseArray(t);continue}this._metadataMap.set(e,t.textContent.trim())}}get serializable(){return{parsedData:this._metadataMap,rawData:this._data}}}const Or=1,Rr=2,Dr=3,Mr=4,Pr=5;class StructTreeRoot{constructor(e,t,n){this.xref=e;this.dict=t;this.ref=n instanceof Ref?n:null;this.roleMap=new Map;this.structParentIds=null;this.kidRefToPosition=void 0;this.parentTree=null}getKidPosition(e){if(void 0===this.kidRefToPosition){const e=this.dict.get("K");if(Array.isArray(e)){const t=this.kidRefToPosition=new Map;for(let n=0,a=e.length;n<a;n++){const a=e[n];a&&t.set(a.toString(),n)}}else this.kidRefToPosition=e instanceof Dict?new Map([[e.objId,0]]):e?null:new Map}return this.kidRefToPosition?this.kidRefToPosition.get(e)??NaN:-1}init(){this.readRoleMap();const e=this.dict.get("ParentTree");e&&(this.parentTree=new NumberTree(e,this.xref))}#be(e,t,n){if(!(e instanceof Ref)||t<0)return;this.structParentIds||=new RefSetCache;let a=this.structParentIds.get(e);if(!a){a=[];this.structParentIds.put(e,a)}a.push([t,n])}addAnnotationIdToPage(e,t){this.#be(e,t,Mr)}readRoleMap(){const e=this.dict.get("RoleMap");if(e instanceof Dict)for(const[t,n]of e)n instanceof Name&&this.roleMap.set(t,n.name)}static async canCreateStructureTree({catalogRef:e,pdfManager:t,newAnnotationsByPage:n}){if(!(e instanceof Ref)){warn("Cannot save the struct tree: no catalog reference.");return!1}let a=0,s=!0;for(const[e,r]of n){const{ref:n}=await t.getPage(e);if(!(n instanceof Ref)){warn(`Cannot save the struct tree: page ${e} has no ref.`);s=!0;break}for(const e of r)if(e.accessibilityData?.type){e.parentTreeId=a++;s=!1}}if(s){for(const e of n.values())for(const t of e)delete t.parentTreeId;return!1}return!0}static async createStructureTree({newAnnotationsByPage:e,xref:t,catalogRef:n,pdfManager:a,changes:s}){const r=await a.ensureCatalog("cloneDict"),i=new RefSetCache;i.put(n,r);const o=t.getNewTemporaryRef();r.set("StructTreeRoot",o);const l=new Dict(t);l.set("Type",Name.get("StructTreeRoot"));const f=t.getNewTemporaryRef();l.set("ParentTree",f);const c=[];l.set("K",c);i.put(o,l);const h=new Dict(t),u=[];h.set("Nums",u);const m=await this.#we({newAnnotationsByPage:e,structTreeRootRef:o,structTreeRoot:null,kids:c,nums:u,xref:t,pdfManager:a,changes:s,cache:i});l.set("ParentTreeNextKey",m);i.put(f,h);for(const[e,t]of i.items())s.put(e,{data:t})}async canUpdateStructTree({pdfManager:e,newAnnotationsByPage:t}){if(!this.ref){warn("Cannot update the struct tree: no root reference.");return!1}let n=this.dict.get("ParentTreeNextKey");if(!Number.isInteger(n)||n<0){warn("Cannot update the struct tree: invalid next key.");return!1}const a=this.dict.get("ParentTree");if(!(a instanceof Dict)){warn("Cannot update the struct tree: ParentTree isn't a dict.");return!1}const s=a.get("Nums");if(!Array.isArray(s)){warn("Cannot update the struct tree: nums isn't an array.");return!1}const r=new NumberTree(a,this.xref);for(const n of t.keys()){const{pageDict:t}=await e.getPage(n);if(!t.has("StructParents"))continue;const a=t.get("StructParents");if(!Number.isInteger(a)||!Array.isArray(r.get(a))){warn(`Cannot save the struct tree: page ${n} has a wrong id.`);return!1}}let i=!0;for(const[a,s]of t){const{pageDict:t}=await e.getPage(a);StructTreeRoot.#je({elements:s,xref:this.xref,pageDict:t,numberTree:r});for(const e of s)if(e.accessibilityData?.type){e.accessibilityData.structParent>=0||(e.parentTreeId=n++);i=!1}}if(i){for(const e of t.values())for(const t of e){delete t.parentTreeId;delete t.structTreeParent}return!1}return!0}async updateStructureTree({newAnnotationsByPage:e,pdfManager:t,changes:n}){const{ref:a,xref:s}=this,r=this.dict.clone(),i=new RefSetCache;i.put(a,r);let o,l=r.getRaw("ParentTree");if(l instanceof Ref)o=s.fetch(l);else{o=l;l=s.getNewTemporaryRef();r.set("ParentTree",l)}o=o.clone();i.put(l,o);let f=o.getRaw("Nums"),c=null;if(f instanceof Ref){c=f;f=s.fetch(c)}f=f.slice();c||o.set("Nums",f);const h=await StructTreeRoot.#we({newAnnotationsByPage:e,structTreeRootRef:a,structTreeRoot:this,kids:null,nums:f,xref:s,pdfManager:t,changes:n,cache:i});if(-1!==h){r.set("ParentTreeNextKey",h);c&&i.put(c,f);for(const[e,t]of i.items())n.put(e,{data:t})}}static async#we({newAnnotationsByPage:e,structTreeRootRef:t,structTreeRoot:n,kids:a,nums:s,xref:r,pdfManager:i,changes:o,cache:l}){const f=Name.get("OBJR");let c,h=-1;for(const[u,m]of e){const e=await i.getPage(u),{ref:p}=e,d=p instanceof Ref;for(const{accessibilityData:i,ref:g,parentTreeId:b,structTreeParent:w}of m){if(!i?.type)continue;const{structParent:m}=i;if(n&&Number.isInteger(m)&&m>=0){let t=(c||=new Map).get(u);if(void 0===t){t=new StructTreePage(n,e.pageDict).collectObjects(p);c.set(u,t)}const a=t?.get(m);if(a){const e=r.fetch(a).clone();StructTreeRoot.#ke(e,i);o.put(a,{data:e});continue}}h=Math.max(h,b);const j=r.getNewTemporaryRef(),k=new Dict(r);StructTreeRoot.#ke(k,i);await this.#ye({structTreeParent:w,tagDict:k,newTagRef:j,structTreeRootRef:t,fallbackKids:a,xref:r,cache:l});const y=new Dict(r);k.set("K",y);y.set("Type",f);d&&y.set("Pg",p);y.set("Obj",g);l.put(j,k);s.push(b,j)}}return h+1}static#ke(e,{type:t,title:n,lang:a,alt:s,expanded:r,actualText:i}){e.set("S",Name.get(t));n&&e.set("T",stringToAsciiOrUTF16BE(n));a&&e.set("Lang",stringToAsciiOrUTF16BE(a));s&&e.set("Alt",stringToAsciiOrUTF16BE(s));r&&e.set("E",stringToAsciiOrUTF16BE(r));i&&e.set("ActualText",stringToAsciiOrUTF16BE(i))}static#je({elements:e,xref:t,pageDict:n,numberTree:a}){const s=new Map;for(const t of e)if(t.structTreeParentId){const e=parseInt(t.structTreeParentId.split("_mc")[1],10);s.getOrInsertComputed(e,makeArr).push(t)}const r=n.get("StructParents");if(!Number.isInteger(r))return;const i=a.get(r),updateElement=(e,n,a)=>{const r=s.get(e);if(r){const e=n.getRaw("P"),s=t.fetchIfRef(e);if(e instanceof Ref&&s instanceof Dict){const e={ref:a,dict:n};for(const t of r)t.structTreeParent=e}return!0}return!1};for(const e of i){if(!(e instanceof Ref))continue;const n=t.fetch(e),a=n.get("K");if(Number.isInteger(a))updateElement(a,n,e);else if(Array.isArray(a))for(let s of a){s=t.fetchIfRef(s);if(Number.isInteger(s)&&updateElement(s,n,e))break;if(!(s instanceof Dict))continue;if(!isName(s.get("Type"),"MCR"))break;const a=s.get("MCID");if(Number.isInteger(a)&&updateElement(a,n,e))break}}}static async#ye({structTreeParent:e,tagDict:t,newTagRef:n,structTreeRootRef:a,fallbackKids:s,xref:r,cache:i}){let o,l=null;if(e){({ref:l}=e);o=e.dict.getRaw("P")||a}else o=a;t.set("P",o);const f=r.fetchIfRef(o);if(!f){s.push(n);return}let c=i.get(o);if(!c){c=f.clone();i.put(o,c)}const h=c.getRaw("K");let u=h instanceof Ref?i.get(h):null;if(!u){u=r.fetchIfRef(h);u=Array.isArray(u)?u.slice():[h];const e=r.getNewTemporaryRef();c.set("K",e);i.put(e,u)}const m=u.indexOf(l);u.splice(m>=0?m+1:u.length,0,n)}}class StructElementNode{constructor(e,t){this.tree=e;this.xref=e.xref;this.dict=t;this.kids=[];this.parseKids()}get role(){const e=this.dict.get("S"),t=e instanceof Name?e.name:"",{root:n}=this.tree;return n.roleMap.get(t)??t}get mathML(){let e=this.dict.get("AF")||[];Array.isArray(e)||(e=[e]);for(let t of e){t=this.xref.fetchIfRef(t);if(!(t instanceof Dict))continue;if(!isName(t.get("Type"),"Filespec"))continue;if(!isName(t.get("AFRelationship"),"Supplement"))continue;const e=t.get("EF");if(!(e instanceof Dict))continue;const n=e.get("UF")||e.get("F");if(n instanceof BaseStream&&(isName(n.dict.get("Type"),"EmbeddedFile")&&isName(n.dict.get("Subtype"),"application/mathml+xml")))return stringToUTF8String(n.getString())}const t=this.dict.get("A");if(t instanceof Dict){if(isName(t.get("O"),"MSFT_Office")){const e=t.get("MSFT_MathML");return e?stringToPDFString(e):null}}return null}parseKids(){let e=null;const t=this.dict.getRaw("Pg");t instanceof Ref&&(e=t.toString());const n=this.dict.get("K");if(Array.isArray(n))for(const t of n){const n=this.parseKid(e,this.xref.fetchIfRef(t));n&&this.kids.push(n)}else{const t=this.parseKid(e,n);t&&this.kids.push(t)}}parseKid(e,t){if(Number.isInteger(t))return this.tree.pageDict.objId!==e?null:new StructElement({type:Or,mcid:t,pageObjId:e});if(!(t instanceof Dict))return null;const n=t.getRaw("Pg");n instanceof Ref&&(e=n.toString());const a=t.get("Type")instanceof Name?t.get("Type").name:null;if("MCR"===a){if(this.tree.pageDict.objId!==e)return null;const n=t.getRaw("Stm");return new StructElement({type:Rr,refObjId:n instanceof Ref?n.toString():null,pageObjId:e,mcid:t.get("MCID")})}if("OBJR"===a){if(this.tree.pageDict.objId!==e)return null;const n=t.getRaw("Obj");return new StructElement({type:Dr,refObjId:n instanceof Ref?n.toString():null,pageObjId:e})}return new StructElement({type:Pr,dict:t})}}class StructElement{constructor({type:e,dict:t=null,mcid:n=null,pageObjId:a=null,refObjId:s=null}){this.type=e;this.dict=t;this.mcid=n;this.pageObjId=a;this.refObjId=s;this.parentNode=null}}class StructTreePage{constructor(e,t){this.root=e;this.xref=e?.xref??null;this.rootDict=e?.dict??null;this.pageDict=t;this.nodes=[]}collectObjects(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return null;const t=this.rootDict.get("ParentTree");if(!t)return null;const n=this.root.structParentIds?.get(e);if(!n)return null;const a=new Map,s=new NumberTree(t,this.xref);for(const[e]of n){const t=s.getRaw(e);t instanceof Ref&&a.set(e,t)}return a}parse(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return;const{parentTree:t}=this.root;if(!t)return;const n=this.pageDict.get("StructParents"),a=this.root.structParentIds?.get(e);if(!Number.isInteger(n)&&!a)return;const s=new Map;if(Number.isInteger(n)){const e=t.get(n);if(Array.isArray(e))for(const t of e)t instanceof Ref&&this.addNode(this.xref.fetch(t),s)}if(a)for(const[e,n]of a){const a=t.get(e);if(a){const e=this.addNode(this.xref.fetchIfRef(a),s);1===e?.kids?.length&&e.kids[0].type===Dr&&(e.kids[0].type=n)}}}addNode(e,t,n=0){if(n>40){warn("StructTree MAX_DEPTH reached.");return null}if(!(e instanceof Dict))return null;if(t.has(e))return t.get(e);const a=new StructElementNode(this,e);t.set(e,a);switch(a.role){case"L":case"LBody":case"LI":case"Table":case"THead":case"TBody":case"TFoot":case"TR":for(const e of a.kids)e.type===Pr&&this.addNode(e.dict,t,n-1)}const s=e.get("P");if(!(s instanceof Dict)||isName(s.get("Type"),"StructTreeRoot")){this.addTopLevelNode(e,a)||t.delete(e);return a}const r=this.addNode(s,t,n+1);if(!r)return a;let i=!1;for(const t of r.kids)if(t.type===Pr&&t.dict===e){t.parentNode=a;i=!0}i||t.delete(e);return a}addTopLevelNode(e,t){const n=this.root.getKidPosition(e.objId);if(isNaN(n))return!1;-1!==n&&(this.nodes[n]=t);return!0}get serializable(){function nodeToSerializable(e,t,n=0){if(n>40){warn("StructTree too deep to be fully serialized.");return}const a=Object.create(null);a.role=e.role;a.children=[];t.children.push(a);let s=e.dict.get("Alt");"string"!=typeof s&&(s=e.dict.get("ActualText"));"string"==typeof s&&(a.alt=stringToPDFString(s));if("Formula"===a.role){const{mathML:t}=e;t&&(a.mathML=t)}const r=e.dict.get("A");if(r instanceof Dict){const e=lookupNormalRect(r.getArray("BBox"),null);if(e)a.bbox=e;else{const e=r.get("Width"),t=r.get("Height");"number"==typeof e&&e>0&&"number"==typeof t&&t>0&&(a.bbox=[0,0,e,t])}}const i=e.dict.get("Lang");"string"==typeof i&&(a.lang=stringToPDFString(i));for(const t of e.kids){const e=t.type===Pr?t.parentNode:null;e?nodeToSerializable(e,a,n+1):t.type===Or||t.type===Rr?a.children.push({type:"content",id:`p${t.pageObjId}_mc${t.mcid}`}):t.type===Dr?a.children.push({type:"object",id:t.refObjId}):t.type===Mr&&a.children.push({type:"annotation",id:`pdfjs_internal_id_${t.refObjId}`})}}const e=Object.create(null);e.children=[];e.role="Root";for(const t of this.nodes)t&&nodeToSerializable(t,e);return e}}const Er=function _isValidExplicitDest(e,t,n){if(!Array.isArray(n)||n.length<2)return!1;const[a,s,...r]=n;if(!e(a)&&!Number.isInteger(a))return!1;if(!t(s))return!1;const i=r.length;let o=!0;switch(s.name){case"XYZ":if(i<2||i>3)return!1;break;case"Fit":case"FitB":return 0===i;case"FitH":case"FitBH":case"FitV":case"FitBV":if(i>1)return!1;break;case"FitR":if(4!==i)return!1;o=!1;break;default:return!1}for(const e of r)if(!("number"==typeof e||o&&null===e))return!1;return!0}.bind(null,e=>e instanceof Ref,isName);function fetchDest(e){e instanceof Dict&&(e=e.get("D"));return Er(e)?e:null}function fetchRemoteDest(e){let t=e.get("D");if(t){t instanceof Name&&(t=t.name);if("string"==typeof t)return stringToPDFString(t,!0);if(Er(t))return JSON.stringify(t)}return null}class Catalog{#qe=null;#ve=null;builtInCMapCache=new Map;fontCache=new RefSetCache;globalColorSpaceCache=new GlobalColorSpaceCache;globalImageCache=new GlobalImageCache;nonBlendModesSet=new RefSet;pageDictCache=new RefSetCache;pageIndexCache=new RefSetCache;pageKidsCountCache=new RefSetCache;standardFontDataCache=new Map;systemFontCache=new Map;constructor(e,t){this.pdfManager=e;this.xref=t;this.#ve=t.getCatalogObj();if(!(this.#ve instanceof Dict))throw new FormatError("Catalog object is not a dictionary.");this.toplevelPagesDict}cloneDict(){return this.#ve.clone()}get version(){const e=this.#ve.get("Version");if(e instanceof Name){if(un.test(e.name))return shadow(this,"version",e.name);warn(`Invalid PDF catalog version: ${e.name}`)}return shadow(this,"version",null)}get lang(){const e=this.#ve.get("Lang");return shadow(this,"lang",e&&"string"==typeof e?stringToPDFString(e):null)}get needsRendering(){const e=this.#ve.get("NeedsRendering");return shadow(this,"needsRendering","boolean"==typeof e&&e)}get collection(){let e=null;try{const t=this.#ve.get("Collection");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch Collection entry; assuming no collection is present.")}return shadow(this,"collection",e)}get acroForm(){let e=null;try{const t=this.#ve.get("AcroForm");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch AcroForm entry; assuming no forms are present.")}return shadow(this,"acroForm",e)}get acroFormRef(){const e=this.#ve.getRaw("AcroForm");return shadow(this,"acroFormRef",e instanceof Ref?e:null)}get metadata(){const e=this.#ve.getRaw("Metadata");if(!(e instanceof Ref))return shadow(this,"metadata",null);let t=null;try{const n=this.xref.fetch(e,!this.xref.encrypt?.encryptMetadata);if(n instanceof BaseStream&&n.dict instanceof Dict){const e=n.dict.get("Type"),a=n.dict.get("Subtype");if(isName(e,"Metadata")&&isName(a,"XML")){const e=stringToUTF8String(n.getString());e&&(t=new MetadataParser(e).serializable)}}}catch(e){if(e instanceof MissingDataException)throw e;info(`Skipping invalid Metadata: "${e}".`)}return shadow(this,"metadata",t)}get markInfo(){let e=null;try{e=this.#Se()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read mark info.")}return shadow(this,"markInfo",e)}#Se(){const e=this.#ve.get("MarkInfo");if(!(e instanceof Dict))return null;const t={Marked:!1,UserProperties:!1,Suspects:!1};for(const n in t){const a=e.get(n);"boolean"==typeof a&&(t[n]=a)}return t}get hasStructTree(){return this.#ve.has("StructTreeRoot")}get structTreeRoot(){let e=null;try{e=this.#xe()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable read to structTreeRoot info.")}return shadow(this,"structTreeRoot",e)}#xe(){const e=this.#ve.getRaw("StructTreeRoot"),t=this.xref.fetchIfRef(e);if(!(t instanceof Dict))return null;const n=new StructTreeRoot(this.xref,t,e);n.init();return n}get toplevelPagesDict(){const e=this.#ve.get("Pages");if(!(e instanceof Dict))throw new FormatError("Invalid top-level pages dictionary.");return shadow(this,"toplevelPagesDict",e)}get documentOutline(){let e=null;try{e=this.#Ae()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read document outline.")}return shadow(this,"documentOutline",e)}#Ae(){let e=this.#ve.get("Outlines");if(!(e instanceof Dict))return null;e=e.getRaw("First");if(!(e instanceof Ref))return null;const t={items:[]},n=[{obj:e,parent:t}],a=new RefSet;a.put(e);const s=this.xref,r=new Uint8ClampedArray(3);for(;n.length>0;){const t=n.shift(),i=s.fetchIfRef(t.obj);if(null===i)continue;i.has("Title")||warn("Invalid outline item encountered.");const o={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:i,resultObj:o,docBaseUrl:this.baseUrl,docAttachments:this.attachments});const l=i.get("Title"),f=i.get("F")||0,c=i.getArray("C"),h=i.get("Count");let u=r;!isNumberArray(c,3)||0===c[0]&&0===c[1]&&0===c[2]||(u=ColorSpaceUtils.rgb.getRgb(c,0));const m={action:o.action,attachment:o.attachment,dest:o.dest,url:o.url,unsafeUrl:o.unsafeUrl,newWindow:o.newWindow,setOCGState:o.setOCGState,title:"string"==typeof l?stringToPDFString(l):"",color:u,count:Number.isInteger(h)?h:void 0,bold:!!(2&f),italic:!!(1&f),items:[]};t.parent.items.push(m);e=i.getRaw("First");if(e instanceof Ref&&!a.has(e)){n.push({obj:e,parent:m});a.put(e)}e=i.getRaw("Next");if(e instanceof Ref&&!a.has(e)){n.push({obj:e,parent:t.parent});a.put(e)}}return t.items.length>0?t.items:null}get permissions(){let e=null;try{e=this.#Ce()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read permissions.")}return shadow(this,"permissions",e)}#Ce(){const e=this.xref.trailer.get("Encrypt");if(!(e instanceof Dict))return null;let t=e.get("P");if("number"!=typeof t)return null;t+=2**32;const n=[];for(const e in j){const a=j[e];t&a&&n.push(a)}return n}get optionalContentConfig(){let e=null;try{const t=this.#ve.get("OCProperties");if(!t)return shadow(this,"optionalContentConfig",null);const n=t.get("D");if(!n)return shadow(this,"optionalContentConfig",null);const a=t.get("OCGs");if(!Array.isArray(a))return shadow(this,"optionalContentConfig",null);const s=new RefSetCache;for(const e of a)e instanceof Ref&&!s.has(e)&&s.put(e,this.#Ie(e));e=this.#Fe(n,s)}catch(e){if(e instanceof MissingDataException)throw e;warn(`Unable to read optional content config: ${e}`)}return shadow(this,"optionalContentConfig",e)}#Ie(e){const t=this.xref.fetch(e),n={id:e.toString(),name:null,intent:null,usage:{print:null,view:null},rbGroups:[]},a=t.get("Name");"string"==typeof a&&(n.name=stringToPDFString(a));let s=t.getArray("Intent");Array.isArray(s)||(s=[s]);s.every(e=>e instanceof Name)&&(n.intent=s.map(e=>e.name));const r=t.get("Usage");if(!(r instanceof Dict))return n;const i=n.usage,o=r.get("Print");if(o instanceof Dict){const e=o.get("PrintState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":i.print={printState:e.name}}}const l=r.get("View");if(l instanceof Dict){const e=l.get("ViewState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":i.view={viewState:e.name}}}return n}#Fe(e,t){function parseOnOff(e){const n=[];if(Array.isArray(e))for(const a of e)a instanceof Ref&&t.has(a)&&n.push(a.toString());return n}function parseOrder(e,n=0){if(!Array.isArray(e))return null;const s=[];for(const r of e){if(r instanceof Ref&&t.has(r)){a.put(r);s.push(r.toString());continue}const e=parseNestedOrder(r,n);e&&s.push(e)}if(n>0)return s;const r=[];for(const[e]of t.items())a.has(e)||r.push(e.toString());r.length&&s.push({name:null,order:r});return s}function parseNestedOrder(e,t){if(++t>s){warn("parseNestedOrder - reached MAX_NESTED_LEVELS.");return null}const a=n.fetchIfRef(e);if(!Array.isArray(a))return null;const r=n.fetchIfRef(a[0]);if("string"!=typeof r)return null;const i=parseOrder(a.slice(1),t);return i?.length?{name:stringToPDFString(r),order:i}:null}const n=this.xref,a=new RefSet,s=10;!function parseRBGroups(e){if(Array.isArray(e))for(const a of e){const e=n.fetchIfRef(a);if(!Array.isArray(e)||!e.length)continue;const s=new Set;for(const n of e)if(n instanceof Ref&&t.has(n)&&!s.has(n.toString())){s.add(n.toString());t.get(n).rbGroups.push(s)}}}(e.get("RBGroups"));return{name:"string"==typeof e.get("Name")?stringToPDFString(e.get("Name")):null,creator:"string"==typeof e.get("Creator")?stringToPDFString(e.get("Creator")):null,baseState:e.get("BaseState")instanceof Name?e.get("BaseState").name:null,on:parseOnOff(e.get("ON")),off:parseOnOff(e.get("OFF")),order:parseOrder(e.get("Order")),groups:[...t]}}setActualNumPages(e=null){this.#qe=e}get hasActualNumPages(){return null!==this.#qe}get _pagesCount(){const e=this.toplevelPagesDict.get("Count");if(!Number.isInteger(e))throw new FormatError("Page count in top-level pages dictionary is not an integer.");return shadow(this,"_pagesCount",e)}get numPages(){return this.#qe??this._pagesCount}get destinations(){const e=this.#Te(),t=Object.create(null);for(const n of e)if(n instanceof NameTree)for(const[e,a]of n.getAll()){const n=fetchDest(a);n&&(t[stringToPDFString(e,!0)]=n)}else if(n instanceof Dict)for(const[e,a]of n){const n=fetchDest(a);n&&(t[stringToPDFString(e,!0)]||=n)}return shadow(this,"destinations",t)}getDestination(e){if(this.hasOwnProperty("destinations"))return this.destinations[e]??null;const t=this.#Te();for(const n of t)if(n instanceof NameTree||n instanceof Dict){const t=fetchDest(n.get(e));if(t)return t}if(t.length){const t=this.destinations[e];if(t)return t}return null}#Te(){const e=this.#ve.get("Names"),t=[];e?.has("Dests")&&t.push(new NameTree(e.getRaw("Dests"),this.xref));this.#ve.has("Dests")&&t.push(this.#ve.get("Dests"));return t}get rawPageLabels(){const e=this.#ve.getRaw("PageLabels");if(!e)return null;return new NumberTree(e,this.xref).getAll()}get pageLabels(){let e=null;try{e=this.#He()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read page labels.")}return shadow(this,"pageLabels",e)}#He(){const e=this.rawPageLabels;if(!e)return null;const t=new Array(this.numPages);let n=null,a="",s="",r=1;for(let i=0,o=this.numPages;i<o;i++){const o=e.get(i);if(void 0!==o){if(!(o instanceof Dict))throw new FormatError("PageLabel is not a dictionary.");if(o.has("Type")&&!isName(o.get("Type"),"PageLabel"))throw new FormatError("Invalid type in PageLabel dictionary.");if(o.has("S")){const e=o.get("S");if(!(e instanceof Name))throw new FormatError("Invalid style in PageLabel dictionary.");n=e.name}else n=null;if(o.has("P")){const e=o.get("P");if("string"!=typeof e)throw new FormatError("Invalid prefix in PageLabel dictionary.");a=stringToPDFString(e)}else a="";if(o.has("St")){const e=o.get("St");if(!(Number.isInteger(e)&&e>=1))throw new FormatError("Invalid start in PageLabel dictionary.");r=e}else r=1}switch(n){case"D":s=r;break;case"R":case"r":s=toRomanNumerals(r,"r"===n);break;case"A":case"a":const e=26,t="a"===n?97:65,a=r-1;s=String.fromCharCode(t+a%e).repeat(Math.floor(a/e)+1);break;default:if(n)throw new FormatError(`Invalid style "${n}" in PageLabel dictionary.`);s=""}t[i]=a+s;r++}return t}get pageLayout(){const e=this.#ve.get("PageLayout");let t="";if(e instanceof Name)switch(e.name){case"SinglePage":case"OneColumn":case"TwoColumnLeft":case"TwoColumnRight":case"TwoPageLeft":case"TwoPageRight":t=e.name}return shadow(this,"pageLayout",t)}get pageMode(){const e=this.#ve.get("PageMode");let t="UseNone";if(e instanceof Name)switch(e.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"FullScreen":case"UseOC":case"UseAttachments":t=e.name}return shadow(this,"pageMode",t)}get viewerPreferences(){const e=this.#ve.get("ViewerPreferences");if(!(e instanceof Dict))return shadow(this,"viewerPreferences",null);let t=null;for(const[n,a]of e){let e;switch(n){case"HideToolbar":case"HideMenubar":case"HideWindowUI":case"FitWindow":case"CenterWindow":case"DisplayDocTitle":case"PickTrayByPDFSize":"boolean"==typeof a&&(e=a);break;case"NonFullScreenPageMode":if(a instanceof Name)switch(a.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"UseOC":e=a.name;break;default:e="UseNone"}break;case"Direction":if(a instanceof Name)switch(a.name){case"L2R":case"R2L":e=a.name;break;default:e="L2R"}break;case"ViewArea":case"ViewClip":case"PrintArea":case"PrintClip":if(a instanceof Name)switch(a.name){case"MediaBox":case"CropBox":case"BleedBox":case"TrimBox":case"ArtBox":e=a.name;break;default:e="CropBox"}break;case"PrintScaling":if(a instanceof Name)switch(a.name){case"None":case"AppDefault":e=a.name;break;default:e="AppDefault"}break;case"Duplex":if(a instanceof Name)switch(a.name){case"Simplex":case"DuplexFlipShortEdge":case"DuplexFlipLongEdge":e=a.name;break;default:e="None"}break;case"PrintPageRange":if(Array.isArray(a)&&a.length%2==0){a.every((e,t,n)=>Number.isInteger(e)&&e>0&&(0===t||e>=n[t-1])&&e<=this.numPages)&&(e=a)}break;case"NumCopies":Number.isInteger(a)&&a>0&&(e=a);break;default:warn(`Ignoring non-standard key in ViewerPreferences: ${n}.`);continue}if(void 0!==e){t??=Object.create(null);t[n]=e}else warn(`Bad value, for key "${n}", in ViewerPreferences: ${a}.`)}return shadow(this,"viewerPreferences",t)}get openAction(){const e=this.#ve.get("OpenAction"),t=Object.create(null);if(e instanceof Dict){const n=new Dict(this.xref);n.set("A",e);const a={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:n,resultObj:a});Array.isArray(a.dest)?t.dest=a.dest:a.action&&(t.action=a.action)}else Er(e)&&(t.dest=e);return shadow(this,"openAction",objectSize(t)>0?t:null)}get attachments(){const e=this.#ve.get("Names");let t=null;if(e instanceof Dict&&e.has("EmbeddedFiles")){const n=new NameTree(e.getRaw("EmbeddedFiles"),this.xref);for(const[e,a]of n.getAll()){const n=new FileSpec(a);t??=Object.create(null);t[stringToPDFString(e,!0)]=n.serializable}}return shadow(this,"attachments",t)}get xfaImages(){const e=this.#ve.get("Names");let t=null;if(e instanceof Dict&&e.has("XFAImages")){const n=new NameTree(e.getRaw("XFAImages"),this.xref);for(const[e,a]of n.getAll())if(a instanceof BaseStream){t??=new Map;t.set(stringToPDFString(e,!0),a.getBytes())}}return shadow(this,"xfaImages",t)}#Oe(){const e=this.#ve.get("Names");let t=null;function appendIfJavaScriptDict(e,n){if(!(n instanceof Dict))return;if(!isName(n.get("S"),"JavaScript"))return;let a=n.get("JS");if(a instanceof BaseStream)a=a.getString();else if("string"!=typeof a)return;a=stringToPDFString(a,!0).replaceAll("\0","");a&&(t||=new Map).set(e,a)}if(e instanceof Dict&&e.has("JavaScript")){const t=new NameTree(e.getRaw("JavaScript"),this.xref);for(const[e,n]of t.getAll())appendIfJavaScriptDict(stringToPDFString(e,!0),n)}const n=this.#ve.get("OpenAction");n&&appendIfJavaScriptDict("OpenAction",n);return t}get jsActions(){const e=this.#Oe();let t=collectActions(this.xref,this.#ve,re);if(e){t||=Object.create(null);for(const[n,a]of e)n in t?t[n].push(a):t[n]=[a]}return shadow(this,"jsActions",t)}async cleanup(e=!1){clearGlobalCaches();this.globalColorSpaceCache.clear();this.globalImageCache.clear(e);this.pageKidsCountCache.clear();this.pageIndexCache.clear();this.pageDictCache.clear();this.nonBlendModesSet.clear();for(const{dict:e}of await Promise.all(this.fontCache))delete e.cacheKey;this.fontCache.clear();this.builtInCMapCache.clear();this.standardFontDataCache.clear();this.systemFontCache.clear()}async getPageDict(e){const t=[this.toplevelPagesDict],n=new RefSet,a=this.#ve.getRaw("Pages");a instanceof Ref&&n.put(a);const s=this.xref,r=this.pageKidsCountCache,i=this.pageIndexCache,o=this.pageDictCache;let l=0;for(;t.length;){const a=t.pop();if(a instanceof Ref){const f=r.get(a);if(f>=0&&l+f<=e){l+=f;continue}if(n.has(a))throw new FormatError("Pages tree contains circular reference.");n.put(a);const c=await(o.get(a)||s.fetchAsync(a));if(c instanceof Dict){let t=c.getRaw("Type");t instanceof Ref&&(t=await s.fetchAsync(t));if(isName(t,"Page")||!c.has("Kids")){r.has(a)||r.put(a,1);i.has(a)||i.put(a,l);if(l===e)return[c,a];l++;continue}}t.push(c);continue}if(!(a instanceof Dict))throw new FormatError("Page dictionary kid reference points to wrong type of object.");const{objId:f}=a;let c=a.getRaw("Count");c instanceof Ref&&(c=await s.fetchAsync(c));if(Number.isInteger(c)&&c>=0){f&&!r.has(f)&&r.put(f,c);if(l+c<=e){l+=c;continue}}let h=a.getRaw("Kids");h instanceof Ref&&(h=await s.fetchAsync(h));if(!Array.isArray(h)){let t=a.getRaw("Type");t instanceof Ref&&(t=await s.fetchAsync(t));if(isName(t,"Page")||!a.has("Kids")){if(l===e)return[a,null];l++;continue}throw new FormatError("Page dictionary kids object is not an array.")}for(let e=h.length-1;e>=0;e--){const n=h[e];t.push(n);a===this.toplevelPagesDict&&n instanceof Ref&&!o.has(n)&&o.put(n,s.fetchAsync(n))}}throw new Error(`Page index ${e} not found.`)}async getAllPageDicts(e=!1){const{ignoreErrors:t}=this.pdfManager.evaluatorOptions,n=[{currentNode:this.toplevelPagesDict,posInKids:0}],a=new RefSet,s=this.#ve.getRaw("Pages");s instanceof Ref&&a.put(s);const r=new Map,i=this.xref,o=this.pageIndexCache;let l=0;function addPageDict(e,t){t&&!o.has(t)&&o.put(t,l);r.set(l++,[e,t])}function addPageError(n){if(n instanceof XRefEntryException&&!e)throw n;if(e&&t&&0===l){warn(`getAllPageDicts - Skipping invalid first page: "${n}".`);n=Dict.empty}r.set(l++,[n,null])}for(;n.length>0;){const e=n.at(-1),{currentNode:t,posInKids:s}=e;let r=t.getRaw("Kids");if(r instanceof Ref)try{r=await i.fetchAsync(r)}catch(e){addPageError(e);break}if(!Array.isArray(r)){addPageError(new FormatError("Page dictionary kids object is not an array."));break}if(s>=r.length){n.pop();continue}const o=r[s];let l;if(o instanceof Ref){if(a.has(o)){addPageError(new FormatError("Pages tree contains circular reference."));break}a.put(o);try{l=await i.fetchAsync(o)}catch(e){addPageError(e);break}}else l=o;if(!(l instanceof Dict)){addPageError(new FormatError("Page dictionary kid reference points to wrong type of object."));break}let f=l.getRaw("Type");if(f instanceof Ref)try{f=await i.fetchAsync(f)}catch(e){addPageError(e);break}isName(f,"Page")||!l.has("Kids")?addPageDict(l,o instanceof Ref?o:null):n.push({currentNode:l,posInKids:0});e.posInKids++}return r}getPageIndex(e){const t=this.pageIndexCache.get(e);if(void 0!==t)return Promise.resolve(t);const n=this.xref;let a=0;const next=t=>function pagesBeforeRef(t){let a,s=0;return n.fetchAsync(t).then(function(n){if(isRefsEqual(t,e)&&!isDict(n,"Page")&&!(n instanceof Dict&&!n.has("Type")&&n.has("Contents")))throw new FormatError("The reference does not point to a /Page dictionary.");if(!n)return null;if(!(n instanceof Dict))throw new FormatError("Node must be a dictionary.");a=n.getRaw("Parent");return n.getAsync("Parent")}).then(function(e){if(!e)return null;if(!(e instanceof Dict))throw new FormatError("Parent must be a dictionary.");return e.getAsync("Kids")}).then(function(e){if(!e)return null;const r=[];let i=!1;for(const a of e){if(!(a instanceof Ref))throw new FormatError("Kid must be a reference.");if(isRefsEqual(a,t)){i=!0;break}r.push(n.fetchAsync(a).then(function(e){if(!(e instanceof Dict))throw new FormatError("Kid node must be a dictionary.");e.has("Count")?s+=e.get("Count"):s++}))}if(!i)throw new FormatError("Kid reference not found in parent's kids.");return Promise.all(r).then(()=>[s,a])})}(t).then(t=>{if(!t){this.pageIndexCache.put(e,a);return a}const[n,s]=t;a+=n;return next(s)});return next(e)}get baseUrl(){const e=this.#ve.get("URI");if(e instanceof Dict){const t=e.get("Base");if("string"==typeof t){const e=createValidAbsoluteUrl(t,null,{tryConvertEncoding:!0});if(e)return shadow(this,"baseUrl",e.href)}}return shadow(this,"baseUrl",this.pdfManager.docBaseUrl)}static parseDestDictionary({destDict:e,resultObj:t,docBaseUrl:n=null,docAttachments:a=null}){if(!(e instanceof Dict)){warn("parseDestDictionary: `destDict` must be a dictionary.");return}let s,r,i=e.get("A");if(!(i instanceof Dict))if(e.has("Dest"))i=e.get("Dest");else{i=e.get("AA");i instanceof Dict&&(i.has("D")?i=i.get("D"):i.has("U")&&(i=i.get("U")))}if(i instanceof Dict){const e=i.get("S");if(!(e instanceof Name)){warn("parseDestDictionary: Invalid type in Action dictionary.");return}const n=e.name;switch(n){case"ResetForm":const e=i.get("Flags"),o=!(1&("number"==typeof e?e:0)),l=[],f=[];for(const e of i.get("Fields")||[])e instanceof Ref?f.push(e.toString()):"string"==typeof e&&l.push(stringToPDFString(e));t.resetForm={fields:l,refs:f,include:o};break;case"URI":s=i.get("URI");s instanceof Name&&(s="/"+s.name);break;case"GoTo":r=i.get("D");break;case"Launch":case"GoToR":const c=i.get("F");if(c instanceof Dict){const e=new FileSpec(c,!0);({rawFilename:s}=e.serializable)}else{if("string"!=typeof c)break;s=c}const h=fetchRemoteDest(i);h&&(s=s.split("#",1)[0]+"#"+h);const u=i.get("NewWindow");"boolean"==typeof u&&(t.newWindow=u);break;case"GoToE":const m=i.get("T");let p;if(a&&m instanceof Dict){const e=m.get("R"),t=m.get("N");isName(e,"C")&&"string"==typeof t&&(p=a[stringToPDFString(t,!0)])}if(p){t.attachment=p;const e=fetchRemoteDest(i);e&&(t.attachmentDest=e)}else warn('parseDestDictionary - unimplemented "GoToE" action.');break;case"Named":const d=i.get("N");d instanceof Name&&(t.action=d.name);break;case"SetOCGState":const g=i.get("State"),b=i.get("PreserveRB");if(!Array.isArray(g)||0===g.length)break;const w=[];for(const e of g)if(e instanceof Name)switch(e.name){case"ON":case"OFF":case"Toggle":w.push(e.name)}else e instanceof Ref&&w.push(e.toString());if(w.length!==g.length)break;t.setOCGState={state:w,preserveRB:"boolean"!=typeof b||b};break;case"JavaScript":const j=i.get("JS");let k;j instanceof BaseStream?k=j.getString():"string"==typeof j&&(k=j);const y=k&&recoverJsURL(stringToPDFString(k,!0));if(y){s=y.url;t.newWindow=y.newWindow;break}default:if("JavaScript"===n||"SubmitForm"===n)break;warn(`parseDestDictionary - unsupported action: "${n}".`)}}else e.has("Dest")&&(r=e.get("Dest"));if("string"==typeof s){const e=createValidAbsoluteUrl(s,n,{addDefaultProtocol:!0,tryConvertEncoding:!0});e&&(t.url=e.href);t.unsafeUrl=s}if(r){r instanceof Name&&(r=r.name);"string"==typeof r?t.dest=stringToPDFString(r,!0):Er(r)&&(t.dest=r)}}}function mayHaveChildren(e){return e instanceof Ref||e instanceof Dict||e instanceof BaseStream||Array.isArray(e)}function addChildren(e,t){if(e instanceof Dict)e=e.getRawValues();else if(e instanceof BaseStream)e=e.dict.getRawValues();else if(!Array.isArray(e))return;for(const n of e)mayHaveChildren(n)&&t.push(n)}class ObjectLoader{refSet=new RefSet;constructor(e,t,n){this.dict=e;this.keys=t;this.xref=n}async load(){const{keys:e,dict:t}=this,n=[];for(const a of e){const e=t.getRaw(a);void 0!==e&&n.push(e)}await this.#Be(n);this.refSet=null}async#Be(e){const t=[],n=[];for(;e.length;){let a=e.pop();if(a instanceof Ref){if(this.refSet.has(a))continue;try{this.refSet.put(a);a=this.xref.fetch(a)}catch(e){if(!(e instanceof MissingDataException)){warn(`ObjectLoader.#walk - requesting all data: "${e}".`);await this.xref.stream.manager.requestAllChunks();return}t.push(a);n.push({begin:e.begin,end:e.end})}}if(a instanceof BaseStream){const e=a.getBaseStreams();if(e){let s=!1;for(const t of e)if(!t.isDataLoaded){s=!0;n.push({begin:t.start,end:t.end})}s&&t.push(a)}}addChildren(a,e)}if(n.length){await this.xref.stream.manager.requestRanges(n);for(const e of t)e instanceof Ref&&this.refSet.remove(e);await this.#Be(t)}}static async load(e,t,n){if(n.stream.isDataLoaded)return;const a=new ObjectLoader(e,t,n);await a.load()}}const Nr=Symbol(),zr=Symbol(),Lr=Symbol(),Ur=Symbol(),_r=Symbol(),Xr=Symbol(),Wr=Symbol(),Kr=Symbol(),Gr=Symbol(),Vr=Symbol("content"),$r=Symbol("data"),Yr=Symbol(),Jr=Symbol("extra"),Qr=Symbol(),Zr=Symbol(),ei=Symbol(),ti=Symbol(),ni=Symbol(),ai=Symbol(),si=Symbol(),ri=Symbol(),ii=Symbol(),oi=Symbol(),li=Symbol(),fi=Symbol(),ci=Symbol(),hi=Symbol(),ui=Symbol(),mi=Symbol(),pi=Symbol(),di=Symbol(),gi=Symbol(),bi=Symbol(),wi=Symbol(),ji=Symbol(),ki=Symbol(),yi=Symbol(),qi=Symbol(),vi=Symbol(),Si=Symbol(),xi=Symbol(),Ai=Symbol(),Ci=Symbol(),Ii=Symbol(),Fi=Symbol(),Ti=Symbol("namespaceId"),Hi=Symbol("nodeName"),Oi=Symbol(),Bi=Symbol(),Ri=Symbol(),Di=Symbol(),Mi=Symbol(),Pi=Symbol(),Ei=Symbol(),Ni=Symbol(),zi=Symbol("root"),_i=Symbol(),Xi=Symbol(),Wi=Symbol(),Ki=Symbol(),Gi=Symbol(),Vi=Symbol(),$i=Symbol(),Yi=Symbol(),Ji=Symbol(),Qi=Symbol(),Zi=Symbol(),eo=Symbol("uid"),to=Symbol(),no={config:{id:0,check:e=>e.startsWith("http://www.xfa.org/schema/xci/")},connectionSet:{id:1,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-connection-set/")},datasets:{id:2,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-data/")},form:{id:3,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-form/")},localeSet:{id:4,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-locale-set/")},pdf:{id:5,check:e=>"http://ns.adobe.com/xdp/pdf/"===e},signature:{id:6,check:e=>"http://www.w3.org/2000/09/xmldsig#"===e},sourceSet:{id:7,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-source-set/")},stylesheet:{id:8,check:e=>"http://www.w3.org/1999/XSL/Transform"===e},template:{id:9,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-template/")},xdc:{id:10,check:e=>e.startsWith("http://www.xfa.org/schema/xdc/")},xdp:{id:11,check:e=>"http://ns.adobe.com/xdp/"===e},xfdf:{id:12,check:e=>"http://ns.adobe.com/xfdf/"===e},xhtml:{id:13,check:e=>"http://www.w3.org/1999/xhtml"===e},xmpmeta:{id:14,check:e=>"http://ns.adobe.com/xmpmeta/"===e}},ao={pt:e=>e,cm:e=>e/2.54*72,mm:e=>e/25.4*72,in:e=>72*e,px:e=>e},so=/([+-]?\d+\.?\d*)(.*)/;function stripQuotes(e){return e.startsWith("'")||e.startsWith('"')?e.slice(1,-1):e}function getInteger({data:e,defaultValue:t,validate:n}){if(!e)return t;e=e.trim();const a=parseInt(e,10);return!isNaN(a)&&n(a)?a:t}function getFloat({data:e,defaultValue:t,validate:n}){if(!e)return t;e=e.trim();const a=parseFloat(e);return!isNaN(a)&&n(a)?a:t}function getKeyword({data:e,defaultValue:t,validate:n}){return e&&n(e=e.trim())?e:t}function getStringOption(e,t){return getKeyword({data:e,defaultValue:t[0],validate:e=>t.includes(e)})}function getMeasurement(e,t="0"){t||="0";if(!e)return getMeasurement(t);const n=e.trim().match(so);if(!n)return getMeasurement(t);const[,a,s]=n,r=parseFloat(a);if(isNaN(r))return getMeasurement(t);if(0===r)return 0;const i=ao[s];return i?i(r):r}function getRatio(e){if(!e)return{num:1,den:1};const t=e.split(":",2).map(e=>parseFloat(e.trim())).filter(e=>!isNaN(e));1===t.length&&t.push(1);if(0===t.length)return{num:1,den:1};const[n,a]=t;return{num:n,den:a}}function getRelevant(e){return e?e.trim().split(/\s+/).map(e=>({excluded:"-"===e[0],viewname:e.substring(1)})):[]}class HTMLResult{static get FAILURE(){return shadow(this,"FAILURE",new HTMLResult(!1,null,null,null))}static get EMPTY(){return shadow(this,"EMPTY",new HTMLResult(!0,null,null,null))}constructor(e,t,n,a){this.success=e;this.html=t;this.bbox=n;this.breakNode=a}isBreak(){return!!this.breakNode}static breakNode(e){return new HTMLResult(!1,null,null,e)}static success(e,t=null){return new HTMLResult(!0,e,t,null)}}class FontFinder{constructor(e){this.fonts=new Map;this.cache=new Map;this.warned=new Set;this.defaultFont=null;this.add(e)}add(e,t=null){for(const t of e)this.addPdfFont(t);for(const e of this.fonts.values())e.regular||(e.regular=e.italic||e.bold||e.bolditalic);if(!t||0===t.size)return;const n=this.fonts.get("PdfJS-Fallback-PdfJS-XFA");for(const e of t)this.fonts.set(e,n)}addPdfFont(e){const t=e.cssFontInfo,n=t.fontFamily,a=this.fonts.getOrInsertComputed(n,makeObj);this.defaultFont??=a;let s="";const r=parseFloat(t.fontWeight);0!==parseFloat(t.italicAngle)?s=r>=700?"bolditalic":"italic":r>=700&&(s="bold");if(!s){(e.name.includes("Bold")||e.psName?.includes("Bold"))&&(s="bold");(e.name.includes("Italic")||e.name.endsWith("It")||e.psName?.includes("Italic")||e.psName?.endsWith("It"))&&(s+="italic")}s||(s="regular");a[s]=e}getDefault(){return this.defaultFont}find(e,t=!0){let n=this.fonts.get(e)||this.cache.get(e);if(n)return n;const a=/,|-|_| |bolditalic|bold|italic|regular|it/gi;let s=e.replaceAll(a,"");n=this.fonts.get(s);if(n){this.cache.set(e,n);return n}s=s.toLowerCase();const r=[];for(const[e,t]of this.fonts)e.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(t);if(0===r.length)for(const e of this.fonts.values())e.regular.name?.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(e);if(0===r.length){s=s.replaceAll(/psmt|mt/gi,"");for(const[e,t]of this.fonts)e.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(t)}if(0===r.length)for(const e of this.fonts.values())e.regular.name?.replaceAll(a,"").toLowerCase().startsWith(s)&&r.push(e);if(r.length>=1){1!==r.length&&t&&warn(`XFA - Too many choices to guess the correct font: ${e}`);this.cache.set(e,r[0]);return r[0]}if(t&&!this.warned.has(e)){this.warned.add(e);warn(`XFA - Cannot find the font: ${e}`)}return null}}function selectFont(e,t){return"italic"===e.posture?"bold"===e.weight?t.bolditalic:t.italic:"bold"===e.weight?t.bold:t.regular}class text_FontInfo{constructor(e,t,n,a){this.lineHeight=n;this.paraMargin=t||{top:0,bottom:0,left:0,right:0};if(!e){[this.pdfFont,this.xfaFont]=this.defaultFont(a);return}this.xfaFont={typeface:e.typeface,posture:e.posture,weight:e.weight,size:e.size,letterSpacing:e.letterSpacing};const s=a.find(e.typeface);if(s){this.pdfFont=selectFont(e,s);this.pdfFont||([this.pdfFont,this.xfaFont]=this.defaultFont(a))}else[this.pdfFont,this.xfaFont]=this.defaultFont(a)}defaultFont(e){const t=e.find("Helvetica",!1)||e.find("Myriad Pro",!1)||e.find("Arial",!1)||e.getDefault();if(t?.regular){const e=t.regular;return[e,{typeface:e.cssFontInfo.fontFamily,posture:"normal",weight:"normal",size:10,letterSpacing:0}]}return[null,{typeface:"Courier",posture:"normal",weight:"normal",size:10,letterSpacing:0}]}}class FontSelector{constructor(e,t,n,a){this.fontFinder=a;this.stack=[new text_FontInfo(e,t,n,a)]}pushData(e,t,n){const a=this.stack.at(-1);for(const t of["typeface","posture","weight","size","letterSpacing"])e[t]||(e[t]=a.xfaFont[t]);for(const e of["top","bottom","left","right"])isNaN(t[e])&&(t[e]=a.paraMargin[e]);const s=new text_FontInfo(e,t,n||a.lineHeight,this.fontFinder);s.pdfFont||(s.pdfFont=a.pdfFont);this.stack.push(s)}popFont(){this.stack.pop()}topFont(){return this.stack.at(-1)}}class TextMeasure{constructor(e,t,n,a){this.glyphs=[];this.fontSelector=new FontSelector(e,t,n,a);this.extraHeight=0}pushData(e,t,n){this.fontSelector.pushData(e,t,n)}popFont(e){return this.fontSelector.popFont()}addPara(){const e=this.fontSelector.topFont();this.extraHeight+=e.paraMargin.top+e.paraMargin.bottom}addString(e){if(!e)return;const t=this.fontSelector.topFont(),n=t.xfaFont.size;if(t.pdfFont){const a=t.xfaFont.letterSpacing,s=t.pdfFont,r=s.lineHeight||1.2,i=t.lineHeight||Math.max(1.2,r)*n,o=r-(void 0===s.lineGap?.2:s.lineGap),l=Math.max(1,o)*n,f=n/1e3,c=s.defaultWidth||s.charsToGlyphs(" ")[0].width;for(const t of e.split(/[\u2029\n]/)){const e=s.encodeString(t).join(""),n=s.charsToGlyphs(e);for(const e of n){const t=e.width||c;this.glyphs.push([t*f+a,i,l,e.unicode,!1])}this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop();return}for(const t of e.split(/[\u2029\n]/)){for(const e of t.split(""))this.glyphs.push([n,1.2*n,n,e,!1]);this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}compute(e){let t=-1,n=0,a=0,s=0,r=0,i=0,o=!1,l=!0;for(let f=0,c=this.glyphs.length;f<c;f++){const[c,h,u,m,p]=this.glyphs[f],d=" "===m,g=l?u:h;if(p){a=Math.max(a,r);r=0;s+=i;i=g;t=-1;n=0;l=!1}else if(d)if(r+c>e){a=Math.max(a,r);r=0;s+=i;i=g;t=-1;n=0;o=!0;l=!1}else{i=Math.max(g,i);n=r;r+=c;t=f}else if(r+c>e){s+=i;i=g;if(-1!==t){f=t;a=Math.max(a,n);r=0;t=-1;n=0}else{a=Math.max(a,r);r=c}o=!0;l=!1}else{r+=c;i=Math.max(g,i)}}a=Math.max(a,r);s+=i+this.extraHeight;return{width:1.02*a,height:s,isBroken:o}}}const ro=/^[^.[]+/,io=/^[^\]]+/,oo=0,lo=1,fo=2,co=3,ho=4,uo=new Map([["$data",(e,t)=>e.datasets?e.datasets.data:e],["$record",(e,t)=>(e.datasets?e.datasets.data:e)[fi]()[0]],["$template",(e,t)=>e.template],["$connectionSet",(e,t)=>e.connectionSet],["$form",(e,t)=>e.form],["$layout",(e,t)=>e.layout],["$host",(e,t)=>e.host],["$dataWindow",(e,t)=>e.dataWindow],["$event",(e,t)=>e.event],["!",(e,t)=>e.datasets],["$xfa",(e,t)=>e],["xfa",(e,t)=>e],["$",(e,t)=>t]]),mo=new WeakMap;function parseIndex(e){return"*"===(e=e.trim())?1/0:parseInt(e,10)||0}function parseExpression(e,t,n=!0){let a=e.match(ro);if(!a)return null;let[s]=a;const r=[{name:s,cacheName:"."+s,index:0,js:null,formCalc:null,operator:oo}];let i=s.length;for(;i<e.length;){const o=i;if("["===e.charAt(i++)){a=e.slice(i).match(io);if(!a){warn("XFA - Invalid index in SOM expression");return null}r.at(-1).index=parseIndex(a[0]);i+=a[0].length+1;continue}let l;switch(e.charAt(i)){case".":if(!t)return null;i++;l=lo;break;case"#":i++;l=fo;break;case"[":if(n){warn("XFA - SOM expression contains a FormCalc subexpression which is not supported for now.");return null}l=co;break;case"(":if(n){warn("XFA - SOM expression contains a JavaScript subexpression which is not supported for now.");return null}l=ho;break;default:l=oo}a=e.slice(i).match(ro);if(!a)break;[s]=a;i+=s.length;r.push({name:s,cacheName:e.slice(o,i),operator:l,index:0,js:null,formCalc:null})}return r}function searchNode(e,t,n,a=!0,s=!0){const r=parseExpression(n,a);if(!r)return null;const i=uo.get(r[0].name);let o,l=0;if(i){o=!0;e=[i(e,t)];l=1}else{o=null===t;e=[t||e]}for(let n=r.length;l<n;l++){const{name:n,cacheName:a,operator:i,index:f}=r[l],c=[];for(const t of e){if(!t.isXFAObject)continue;let e,r;if(s){r=mo.getOrInsertComputed(t,makeMap);e=r.get(a)}if(!e){switch(i){case oo:e=t[si](n,!1);break;case lo:e=t[si](n,!0);break;case fo:e=t[ai](n);e=e.isXFAObjectArray?e.children:[e]}s&&r.set(a,e)}e.length>0&&c.push(e)}if(0===c.length&&!o&&0===l){const n=t[mi]();if(!(t=n))return null;l=-1;e=[t];continue}e=isFinite(f)?c.filter(e=>f<e.length).map(e=>e[f]):c.flat()}return 0===e.length?null:e}function createDataNode(e,t,n){const a=parseExpression(n);if(!a)return null;if(a.some(e=>e.operator===lo))return null;const s=uo.get(a[0].name);let r=0;if(s){e=s(e,t);r=1}else e=t||e;for(let t=a.length;r<t;r++){const{name:t,operator:n,index:s}=a[r];if(!isFinite(s)){a[r].index=0;return e.createNodes(a.slice(r))}let i;switch(n){case oo:i=e[si](t,!1);break;case lo:i=e[si](t,!0);break;case fo:i=e[ai](t);i=i.isXFAObjectArray?i.children:[i]}if(0===i.length)return e.createNodes(a.slice(r));if(!(s<i.length)){a[r].index=s-i.length;return e.createNodes(a.slice(r))}{const t=i[s];if(!t.isXFAObject){warn("XFA - Cannot create a node.");return null}e=t}}return null}const po=Symbol(),go=Symbol(),bo=Symbol(),wo=Symbol("_children"),jo=Symbol(),ko=Symbol(),yo=Symbol(),qo=Symbol(),vo=Symbol(),So=Symbol(),xo=Symbol(),Ao=Symbol(),Co=Symbol(),Io=Symbol("parent"),Fo=Symbol(),Ho=Symbol(),Oo=Symbol();let Bo=0;const Ro=no.datasets.id;class XFAObject{constructor(e,t,n=!1){this[Ti]=e;this[Hi]=t;this[xo]=n;this[Io]=null;this[wo]=[];this[eo]=`${t}${Bo++}`;this[di]=null}get isXFAObject(){return!0}get isXFAObjectArray(){return!1}createNodes(e){let t=this,n=null;for(const{name:a,index:s}of e){for(let e=0,r=isFinite(s)?s:0;e<=r;e++){const e=t[Ti]===Ro?-1:t[Ti];n=new XmlObject(e,a);t[Lr](n)}t=n}return n}[Bi](e){if(!this[xo]||!this[Ri](e))return!1;const t=e[Hi],n=this[t];if(!(n instanceof XFAObjectArray)){null!==n&&this[Ni](n);this[t]=e;this[Lr](e);return!0}if(n.push(e)){this[Lr](e);return!0}let a="";this.id?a=` (id: ${this.id})`:this.name&&(a=` (name: ${this.name} ${this.h.value})`);warn(`XFA - node "${this[Hi]}"${a} has already enough "${t}"!`);return!1}[Ri](e){return this.hasOwnProperty(e[Hi])&&e[Ti]===this[Ti]}[Si](){return!1}[Nr](){return!1}[ki](){return!1}[yi](){return!1}[Pi](){this.para&&this[pi]()[Jr].paraStack.pop()}[Ei](){this[pi]()[Jr].paraStack.push(this.para)}[Wi](e){this.id&&this[Ti]===no.template.id&&e.set(this.id,this)}[pi](){return this[di].template}[xi](){return!1}[Ai](){return!1}[Lr](e){e[Io]=this;this[wo].push(e);!e[di]&&this[di]&&(e[di]=this[di])}[Ni](e){const t=this[wo].indexOf(e);this[wo].splice(t,1)}[gi](){return this.hasOwnProperty("value")}[Gi](e){}[Di](e){}[Qr](){}[_r](e){delete this[xo];if(this[Wr]){e.clean(this[Wr]);delete this[Wr]}}[wi](e){return this[wo].indexOf(e)}[ji](e,t){t[Io]=this;this[wo].splice(e,0,t);!t[di]&&this[di]&&(t[di]=this[di])}[Ci](){return!this.name}[Fi](){return""}[$i](){return 0===this[wo].length?this[Vr]:this[wo].map(e=>e[$i]()).join("")}get[bo](){const e=Object.getPrototypeOf(this);if(!e._attributes){const t=e._attributes=new Set;for(const e of Object.getOwnPropertyNames(this)){if(null===this[e]||this[e]instanceof XFAObject||this[e]instanceof XFAObjectArray)break;t.add(e)}}return shadow(this,bo,e._attributes)}[vi](e){let t=this;for(;t;){if(t===e)return!0;t=t[mi]()}return!1}[mi](){return this[Io]}[ui](){return this[mi]()}[fi](e=null){return e?this[e]:this[wo]}[Yr](){const e=Object.create(null);this[Vr]&&(e.$content=this[Vr]);for(const t of Object.getOwnPropertyNames(this)){const n=this[t];null!==n&&(n instanceof XFAObject?e[t]=n[Yr]():n instanceof XFAObjectArray?n.isEmpty()||(e[t]=n.dump()):e[t]=n)}return e}[Zi](){return null}[Ji](){return HTMLResult.EMPTY}*[ci](){for(const e of this[fi]())yield e}*[qo](e,t){for(const n of this[ci]())if(!e||t===e.has(n[Hi])){const e=this[ni](),t=n[Ji](e);t.success||(this[Jr].failingNode=n);yield t}}[Zr](){return null}[zr](e,t){this[Jr].children.push(e)}[ni](){}[Ur]({filter:e=null,include:t=!0}){if(this[Jr].generator){const e=this[ni](),t=this[Jr].failingNode[Ji](e);if(!t.success)return t;t.html&&this[zr](t.html,t.bbox);delete this[Jr].failingNode}else this[Jr].generator=this[qo](e,t);for(;;){const e=this[Jr].generator.next();if(e.done)break;const t=e.value;if(!t.success)return t;t.html&&this[zr](t.html,t.bbox)}this[Jr].generator=null;return HTMLResult.EMPTY}[Ki](e){this[Ho]=new Set(Object.keys(e))}[So](e){const t=this[bo],n=this[Ho];return[...e].filter(e=>t.has(e)&&!n.has(e))}[_i](e,t=new Set){for(const n of this[wo])n[Fo](e,t)}[Fo](e,t){const n=this[vo](e,t);n?this[po](n,e,t):this[_i](e,t)}[vo](e,t){const{use:n,usehref:a}=this;if(!n&&!a)return null;let s=null,r=null,i=null,o=n;if(a){o=a;a.startsWith("#som(")&&a.endsWith(")")?r=a.slice(5,-1):a.startsWith(".#som(")&&a.endsWith(")")?r=a.slice(6,-1):a.startsWith("#")?i=a.slice(1):a.startsWith(".#")&&(i=a.slice(2))}else n.startsWith("#")?i=n.slice(1):r=n;this.use=this.usehref="";if(i)s=e.get(i);else{s=searchNode(e.get(zi),this,r,!0,!1);s&&(s=s[0])}if(!s){warn(`XFA - Invalid prototype reference: ${o}.`);return null}if(s[Hi]!==this[Hi]){warn(`XFA - Incompatible prototype: ${s[Hi]} !== ${this[Hi]}.`);return null}if(t.has(s)){warn("XFA - Cycle detected in prototypes use.");return null}t.add(s);const l=s[vo](e,t);l&&s[po](l,e,t);s[_i](e,t);t.delete(s);return s}[po](e,t,n){if(n.has(e)){warn("XFA - Cycle detected in prototypes use.");return}!this[Vr]&&e[Vr]&&(this[Vr]=e[Vr]);new Set(n).add(e);for(const t of this[So](e[Ho])){this[t]=e[t];this[Ho]&&this[Ho].add(t)}for(const a of Object.getOwnPropertyNames(this)){if(this[bo].has(a))continue;const s=this[a],r=e[a];if(s instanceof XFAObjectArray){for(const e of s[wo])e[Fo](t,n);for(let a=s[wo].length,i=r[wo].length;a<i;a++){const r=e[wo][a][Kr]();if(!s.push(r))break;r[Io]=this;this[wo].push(r);r[Fo](t,n)}}else if(null===s){if(null!==r){const e=r[Kr]();e[Io]=this;this[a]=e;this[wo].push(e);e[Fo](t,n)}}else{s[_i](t,n);r&&s[po](r,t,n)}}}static[jo](e){return Array.isArray(e)?e.map(e=>XFAObject[jo](e)):"object"==typeof e&&null!==e?Object.assign({},e):e}[Kr](){const e=Object.create(Object.getPrototypeOf(this));for(const t of Object.getOwnPropertySymbols(this))try{e[t]=this[t]}catch{shadow(e,t,this[t])}e[eo]=`${e[Hi]}${Bo++}`;e[wo]=[];for(const t of Object.getOwnPropertyNames(this)){if(this[bo].has(t)){e[t]=XFAObject[jo](this[t]);continue}const n=this[t];e[t]=n instanceof XFAObjectArray?new XFAObjectArray(n[Ao]):null}for(const t of this[wo]){const n=t[Hi],a=t[Kr]();e[wo].push(a);a[Io]=e;null===e[n]?e[n]=a:e[n][wo].push(a)}return e}[fi](e=null){return e?this[wo].filter(t=>t[Hi]===e):this[wo]}[ai](e){return this[e]}[si](e,t,n=!0){return Array.from(this[ri](e,t,n))}*[ri](e,t,n=!0){if("parent"!==e){for(const n of this[wo]){n[Hi]===e&&(yield n);n.name===e&&(yield n);(t||n[Ci]())&&(yield*n[ri](e,t,!1))}n&&this[bo].has(e)&&(yield new XFAAttribute(this,e,this[e]))}else yield this[Io]}}class XFAObjectArray{constructor(e=1/0){this[Ao]=e;this[wo]=[]}get isXFAObject(){return!1}get isXFAObjectArray(){return!0}push(e){if(this[wo].length<=this[Ao]){this[wo].push(e);return!0}warn(`XFA - node "${e[Hi]}" accepts no more than ${this[Ao]} children`);return!1}isEmpty(){return 0===this[wo].length}dump(){return 1===this[wo].length?this[wo][0][Yr]():this[wo].map(e=>e[Yr]())}[Kr](){const e=new XFAObjectArray(this[Ao]);e[wo]=this[wo].map(e=>e[Kr]());return e}get children(){return this[wo]}clear(){this[wo].length=0}}class XFAAttribute{constructor(e,t,n){this[Io]=e;this[Hi]=t;this[Vr]=n;this[Gr]=!1;this[eo]="attribute"+Bo++}[mi](){return this[Io]}[qi](){return!0}[ii](){return this[Vr].trim()}[Gi](e){e=e.value||"";this[Vr]=e.toString()}[$i](){return this[Vr]}[vi](e){return this[Io]===e||this[Io][vi](e)}}class XmlObject extends XFAObject{constructor(e,t,n={}){super(e,t);this[Vr]="";this[ko]=null;if("#text"!==t){const e=new Map;this[go]=e;for(const[t,a]of Object.entries(n))e.set(t,new XFAAttribute(this,t,a));if(n.hasOwnProperty(Oi)){const e=n[Oi].xfa.dataNode;void 0!==e&&("dataGroup"===e?this[ko]=!1:"dataValue"===e&&(this[ko]=!0))}}this[Gr]=!1}[Qi](e){const t=this[Hi];if("#text"===t){e.push(encodeToXmlString(this[Vr]));return}const n=utf8StringToString(t),a=this[Ti]===Ro?"xfa:":"";e.push(`<${a}${n}`);for(const[t,n]of this[go]){const a=utf8StringToString(t);e.push(` ${a}="${encodeToXmlString(n[Vr])}"`)}null!==this[ko]&&(this[ko]?e.push(' xfa:dataNode="dataValue"'):e.push(' xfa:dataNode="dataGroup"'));if(this[Vr]||0!==this[wo].length){e.push(">");if(this[Vr])"string"==typeof this[Vr]?e.push(encodeToXmlString(this[Vr])):this[Vr][Qi](e);else for(const t of this[wo])t[Qi](e);e.push(`</${a}${n}>`)}else e.push("/>")}[Bi](e){if(this[Vr]){const e=new XmlObject(this[Ti],"#text");this[Lr](e);e[Vr]=this[Vr];this[Vr]=""}this[Lr](e);return!0}[Di](e){this[Vr]+=e}[Qr](){if(this[Vr]&&this[wo].length>0){const e=new XmlObject(this[Ti],"#text");this[Lr](e);e[Vr]=this[Vr];delete this[Vr]}}[Ji](){return"#text"===this[Hi]?HTMLResult.success({name:"#text",value:this[Vr]}):HTMLResult.EMPTY}[fi](e=null){return e?this[wo].filter(t=>t[Hi]===e):this[wo]}[ti](){return this[go]}[ai](e){const t=this[go].get(e);return void 0!==t?t:this[fi](e)}*[ri](e,t){const n=this[go].get(e);n&&(yield n);for(const n of this[wo]){n[Hi]===e&&(yield n);t&&(yield*n[ri](e,t))}}*[ei](e,t){const n=this[go].get(e);!n||t&&n[Gr]||(yield n);for(const n of this[wo])yield*n[ei](e,t)}*[li](e,t,n){for(const a of this[wo]){a[Hi]!==e||n&&a[Gr]||(yield a);t&&(yield*a[li](e,t,n))}}[qi](){return null===this[ko]?0===this[wo].length||this[wo][0][Ti]===no.xhtml.id:this[ko]}[ii](){return null===this[ko]?0===this[wo].length?this[Vr].trim():this[wo][0][Ti]===no.xhtml.id?this[wo][0][$i]().trim():null:this[Vr].trim()}[Gi](e){e=e.value||"";this[Vr]=e.toString()}[Yr](e=!1){const t=Object.create(null);e&&(t.$ns=this[Ti]);this[Vr]&&(t.$content=this[Vr]);t.$name=this[Hi];t.children=[];for(const n of this[wo])t.children.push(n[Yr](e));t.attributes=Object.create(null);for(const[e,n]of this[go])t.attributes[e]=n[Vr];return t}}class ContentObject extends XFAObject{constructor(e,t){super(e,t);this[Vr]=""}[Di](e){this[Vr]+=e}[Qr](){}}class OptionObject extends ContentObject{constructor(e,t,n){super(e,t);this[Co]=n}[Qr](){this[Vr]=getKeyword({data:this[Vr],defaultValue:this[Co][0],validate:e=>this[Co].includes(e)})}[_r](e){super[_r](e);delete this[Co]}}class StringObject extends ContentObject{[Qr](){this[Vr]=this[Vr].trim()}}class IntegerObject extends ContentObject{constructor(e,t,n,a){super(e,t);this[yo]=n;this[Oo]=a}[Qr](){this[Vr]=getInteger({data:this[Vr],defaultValue:this[yo],validate:this[Oo]})}[_r](e){super[_r](e);delete this[yo];delete this[Oo]}}class Option01 extends IntegerObject{constructor(e,t){super(e,t,0,e=>1===e)}}class Option10 extends IntegerObject{constructor(e,t){super(e,t,1,e=>0===e)}}function measureToString(e){return"string"==typeof e?"0px":Number.isInteger(e)?`${e}px`:`${e.toFixed(2)}px`}const Do={anchorType(e,t){const n=e[ui]();if(n&&(!n.layout||"position"===n.layout)){"transform"in t||(t.transform="");switch(e.anchorType){case"bottomCenter":t.transform+="translate(-50%, -100%)";break;case"bottomLeft":t.transform+="translate(0,-100%)";break;case"bottomRight":t.transform+="translate(-100%,-100%)";break;case"middleCenter":t.transform+="translate(-50%,-50%)";break;case"middleLeft":t.transform+="translate(0,-50%)";break;case"middleRight":t.transform+="translate(-100%,-50%)";break;case"topCenter":t.transform+="translate(-50%,0)";break;case"topRight":t.transform+="translate(-100%,0)"}}},dimensions(e,t){const n=e[ui]();let a=e.w;const s=e.h;if(n.layout?.includes("row")){const t=n[Jr],s=e.colSpan;let r;if(-1===s){r=Math.sumPrecise(t.columnWidths.slice(t.currentColumn));t.currentColumn=0}else{r=Math.sumPrecise(t.columnWidths.slice(t.currentColumn,t.currentColumn+s));t.currentColumn=(t.currentColumn+e.colSpan)%t.columnWidths.length}isNaN(r)||(a=e.w=r)}t.width=""!==a?measureToString(a):"auto";t.height=""!==s?measureToString(s):"auto"},position(e,t){const n=e[ui]();if(!n?.layout||"position"===n.layout){t.position="absolute";t.left=measureToString(e.x);t.top=measureToString(e.y)}},rotate(e,t){if(e.rotate){"transform"in t||(t.transform="");t.transform+=`rotate(-${e.rotate}deg)`;t.transformOrigin="top left"}},presence(e,t){switch(e.presence){case"invisible":t.visibility="hidden";break;case"hidden":case"inactive":t.display="none"}},hAlign(e,t){if("para"===e[Hi])switch(e.hAlign){case"justifyAll":t.textAlign="justify-all";break;case"radix":t.textAlign="left";break;default:t.textAlign=e.hAlign}else switch(e.hAlign){case"left":t.alignSelf="start";break;case"center":t.alignSelf="center";break;case"right":t.alignSelf="end"}},margin(e,t){e.margin&&(t.margin=e.margin[Zi]().margin)}};function setMinMaxDimensions(e,t){if("position"===e[ui]().layout){e.minW>0&&(t.minWidth=measureToString(e.minW));e.maxW>0&&(t.maxWidth=measureToString(e.maxW));e.minH>0&&(t.minHeight=measureToString(e.minH));e.maxH>0&&(t.maxHeight=measureToString(e.maxH))}}function layoutText(e,t,n,a,s,r){const i=new TextMeasure(t,n,a,s);"string"==typeof e?i.addString(e):e[Mi](i);return i.compute(r)}function layoutNode(e,t){let n=null,a=null,s=!1;if((!e.w||!e.h)&&e.value){let r=0,i=0;if(e.margin){r=e.margin.leftInset+e.margin.rightInset;i=e.margin.topInset+e.margin.bottomInset}let o=null,l=null;if(e.para){l=Object.create(null);o=""===e.para.lineHeight?null:e.para.lineHeight;l.top=""===e.para.spaceAbove?0:e.para.spaceAbove;l.bottom=""===e.para.spaceBelow?0:e.para.spaceBelow;l.left=""===e.para.marginLeft?0:e.para.marginLeft;l.right=""===e.para.marginRight?0:e.para.marginRight}let f=e.font;if(!f){const t=e[pi]();let n=e[mi]();for(;n&&n!==t;){if(n.font){f=n.font;break}n=n[mi]()}}const c=(e.w||t.width)-r,h=e[di].fontFinder;if(e.value.exData&&e.value.exData[Vr]&&"text/html"===e.value.exData.contentType){const t=layoutText(e.value.exData[Vr],f,l,o,h,c);a=t.width;n=t.height;s=t.isBroken}else{const t=e.value[$i]();if(t){const e=layoutText(t,f,l,o,h,c);a=e.width;n=e.height;s=e.isBroken}}null===a||e.w||(a+=r);null===n||e.h||(n+=i)}return{w:a,h:n,isBroken:s}}function computeBbox(e,t,n){let a;if(""!==e.w&&""!==e.h)a=[e.x,e.y,e.w,e.h];else{if(!n)return null;let s=e.w;if(""===s){if(0===e.maxW){const t=e[ui]();s="position"===t.layout&&""!==t.w?0:e.minW}else s=Math.min(e.maxW,n.width);t.attributes.style.width=measureToString(s)}let r=e.h;if(""===r){if(0===e.maxH){const t=e[ui]();r="position"===t.layout&&""!==t.h?0:e.minH}else r=Math.min(e.maxH,n.height);t.attributes.style.height=measureToString(r)}a=[e.x,e.y,s,r]}return a}function fixDimensions(e){const t=e[ui]();if(t.layout?.includes("row")){const n=t[Jr],a=e.colSpan;let s;s=-1===a?Math.sumPrecise(n.columnWidths.slice(n.currentColumn)):Math.sumPrecise(n.columnWidths.slice(n.currentColumn,n.currentColumn+a));isNaN(s)||(e.w=s)}t.layout&&"position"!==t.layout&&(e.x=e.y=0);"table"===e.layout&&""===e.w&&Array.isArray(e.columnWidths)&&(e.w=Math.sumPrecise(e.columnWidths))}function layoutClass(e){switch(e.layout){case"position":default:return"xfaPosition";case"lr-tb":return"xfaLrTb";case"rl-row":return"xfaRlRow";case"rl-tb":return"xfaRlTb";case"row":return"xfaRow";case"table":return"xfaTable";case"tb":return"xfaTb"}}function toStyle(e,...t){const n=Object.create(null);for(const a of t){const t=e[a];if(null!==t)if(Do.hasOwnProperty(a))Do[a](e,n);else if(t instanceof XFAObject){const e=t[Zi]();e?Object.assign(n,e):warn(`(DEBUG) - XFA - style for ${a} not implemented yet`)}}return n}function createWrapper(e,t){const{attributes:n}=t,{style:a}=n,s={name:"div",attributes:{class:["xfaWrapper"],style:Object.create(null)},children:[]};n.class.push("xfaWrapped");if(e.border){const{widths:n,insets:r}=e.border[Jr];let i,o,l=r[0],f=r[3];const c=r[0]+r[2],h=r[1]+r[3];switch(e.border.hand){case"even":l-=n[0]/2;f-=n[3]/2;i=`calc(100% + ${(n[1]+n[3])/2-h}px)`;o=`calc(100% + ${(n[0]+n[2])/2-c}px)`;break;case"left":l-=n[0];f-=n[3];i=`calc(100% + ${n[1]+n[3]-h}px)`;o=`calc(100% + ${n[0]+n[2]-c}px)`;break;case"right":i=h?`calc(100% - ${h}px)`:"100%";o=c?`calc(100% - ${c}px)`:"100%"}const u=["xfaBorder"];isPrintOnly(e.border)&&u.push("xfaPrintOnly");const m={name:"div",attributes:{class:u,style:{top:`${l}px`,left:`${f}px`,width:i,height:o}},children:[]};for(const e of["border","borderWidth","borderColor","borderRadius","borderStyle"])if(void 0!==a[e]){m.attributes.style[e]=a[e];delete a[e]}s.children.push(m,t)}else s.children.push(t);for(const e of["background","backgroundClip","top","left","width","height","minWidth","minHeight","maxWidth","maxHeight","transform","transformOrigin","visibility"])if(void 0!==a[e]){s.attributes.style[e]=a[e];delete a[e]}s.attributes.style.position="absolute"===a.position?"absolute":"relative";delete a.position;if(a.alignSelf){s.attributes.style.alignSelf=a.alignSelf;delete a.alignSelf}return s}function fixTextIndent(e){const t=getMeasurement(e.textIndent,"0px");if(t>=0)return;const n="padding"+("left"===("right"===e.textAlign?"right":"left")?"Left":"Right"),a=getMeasurement(e[n],"0px");e[n]=a-t+"px"}function setAccess(e,t){switch(e.access){case"nonInteractive":t.push("xfaNonInteractive");break;case"readOnly":t.push("xfaReadOnly");break;case"protected":t.push("xfaDisabled")}}function isPrintOnly(e){return e.relevant.length>0&&!e.relevant[0].excluded&&"print"===e.relevant[0].viewname}function getCurrentPara(e){const t=e[pi]()[Jr].paraStack;return t.length?t.at(-1):null}function setPara(e,t,n){if(n.attributes.class?.includes("xfaRich")){if(t){""===e.h&&(t.height="auto");""===e.w&&(t.width="auto")}const a=getCurrentPara(e);if(a){const e=n.attributes.style;e.display="flex";e.flexDirection="column";switch(a.vAlign){case"top":e.justifyContent="start";break;case"bottom":e.justifyContent="end";break;case"middle":e.justifyContent="center"}const t=a[Zi]();for(const[n,a]of Object.entries(t))n in e||(e[n]=a)}}}function setFontFamily(e,t,n,a){if(!n){delete a.fontFamily;return}const s=stripQuotes(e.typeface);a.fontFamily=`"${s}"`;const r=n.find(s);if(r){const{fontFamily:n}=r.regular.cssFontInfo;n!==s&&(a.fontFamily=`"${n}"`);const i=getCurrentPara(t);if(i&&""!==i.lineHeight)return;if(a.lineHeight)return;const o=selectFont(e,r);o&&(a.lineHeight=Math.max(1.2,o.lineHeight))}}function fixURL(e){const t=createValidAbsoluteUrl(e,null,{addDefaultProtocol:!0,tryConvertEncoding:!0});return t?t.href:null}function createLine(e,t){return{name:"div",attributes:{class:["lr-tb"===e.layout?"xfaLr":"xfaRl"]},children:t}}function flushHTML(e){if(!e[Jr])return null;const t={name:"div",attributes:e[Jr].attributes,children:e[Jr].children};if(e[Jr].failingNode){const n=e[Jr].failingNode[Zr]();n&&(e.layout.endsWith("-tb")?t.children.push(createLine(e,[n])):t.children.push(n))}return 0===t.children.length?null:t}function addHTML(e,t,n){const a=e[Jr],s=a.availableSpace,[r,i,o,l]=n;switch(e.layout){case"position":a.width=Math.max(a.width,r+o);a.height=Math.max(a.height,i+l);a.children.push(t);break;case"lr-tb":case"rl-tb":if(!a.line||1===a.attempt){a.line=createLine(e,[]);a.children.push(a.line);a.numberInLine=0}a.numberInLine+=1;a.line.children.push(t);if(0===a.attempt){a.currentWidth+=o;a.height=Math.max(a.height,a.prevHeight+l)}else{a.currentWidth=o;a.prevHeight=a.height;a.height+=l;a.attempt=0}a.width=Math.max(a.width,a.currentWidth);break;case"rl-row":case"row":{a.children.push(t);a.width+=o;a.height=Math.max(a.height,l);const e=measureToString(a.height);for(const t of a.children)t.attributes.style.height=e;break}case"table":case"tb":a.width=MathClamp(o,a.width,s.width);a.height+=l;a.children.push(t)}}function getAvailableSpace(e){const t=e[Jr].availableSpace,n=e.margin?e.margin.topInset+e.margin.bottomInset:0,a=e.margin?e.margin.leftInset+e.margin.rightInset:0;switch(e.layout){case"lr-tb":case"rl-tb":return 0===e[Jr].attempt?{width:t.width-a-e[Jr].currentWidth,height:t.height-n-e[Jr].prevHeight}:{width:t.width-a,height:t.height-n-e[Jr].height};case"rl-row":case"row":return{width:Math.sumPrecise(e[Jr].columnWidths.slice(e[Jr].currentColumn)),height:t.height-a};case"table":case"tb":return{width:t.width-a,height:t.height-n-e[Jr].height};default:return t}}function checkDimensions(e,t){if(null===e[pi]()[Jr].firstUnsplittable)return!0;if(0===e.w||0===e.h)return!0;const n=e[ui](),a=n[Jr]?.attempt||0,[,s,r,i]=function getTransformedBBox(e){let t,n,a=""===e.w?NaN:e.w,s=""===e.h?NaN:e.h,[r,i]=[0,0];switch(e.anchorType||""){case"bottomCenter":[r,i]=[a/2,s];break;case"bottomLeft":[r,i]=[0,s];break;case"bottomRight":[r,i]=[a,s];break;case"middleCenter":[r,i]=[a/2,s/2];break;case"middleLeft":[r,i]=[0,s/2];break;case"middleRight":[r,i]=[a,s/2];break;case"topCenter":[r,i]=[a/2,0];break;case"topRight":[r,i]=[a,0]}switch(e.rotate||0){case 0:[t,n]=[-r,-i];break;case 90:[t,n]=[-i,r];[a,s]=[s,-a];break;case 180:[t,n]=[r,i];[a,s]=[-a,-s];break;case 270:[t,n]=[i,-r];[a,s]=[-s,a]}return[e.x+t+Math.min(0,a),e.y+n+Math.min(0,s),Math.abs(a),Math.abs(s)]}(e);switch(n.layout){case"lr-tb":case"rl-tb":return 0===a?e[pi]()[Jr].noLayoutFailure?""!==e.w?Math.round(r-t.width)<=2:t.width>2:!(""!==e.h&&Math.round(i-t.height)>2)&&(""!==e.w?Math.round(r-t.width)<=2||0===n[Jr].numberInLine&&t.height>2:t.width>2):!!e[pi]()[Jr].noLayoutFailure||!(""!==e.h&&Math.round(i-t.height)>2)&&((""===e.w||Math.round(r-t.width)<=2||!n[Ai]())&&t.height>2);case"table":case"tb":return!!e[pi]()[Jr].noLayoutFailure||(""===e.h||e[xi]()?(""===e.w||Math.round(r-t.width)<=2||!n[Ai]())&&t.height>2:Math.round(i-t.height)<=2);case"position":if(e[pi]()[Jr].noLayoutFailure)return!0;if(""===e.h||Math.round(i+s-t.height)<=2)return!0;return i+s>e[pi]()[Jr].currentContentArea.h;case"rl-row":case"row":return!!e[pi]()[Jr].noLayoutFailure||(""===e.h||Math.round(i-t.height)<=2);default:return!0}}const Mo=no.template.id,Po="http://www.w3.org/2000/svg",Eo=/^H(\d+)$/,No=new Set(["image/gif","image/jpeg","image/jpg","image/pjpeg","image/png","image/apng","image/x-png","image/bmp","image/x-ms-bmp","image/tiff","image/tif","application/octet-stream"]),zo=[[[66,77],"image/bmp"],[[255,216,255],"image/jpeg"],[[73,73,42,0],"image/tiff"],[[77,77,0,42],"image/tiff"],[[71,73,70,56,57,97],"image/gif"],[[137,80,78,71,13,10,26,10],"image/png"]];function getBorderDims(e){if(!e||!e.border)return{w:0,h:0};const t=e.border[oi]();return t?{w:t.widths[0]+t.widths[2]+t.insets[0]+t.insets[2],h:t.widths[1]+t.widths[3]+t.insets[1]+t.insets[3]}:{w:0,h:0}}function hasMargin(e){return e.margin&&(e.margin.topInset||e.margin.rightInset||e.margin.bottomInset||e.margin.leftInset)}function _setValue(e,t){if(!e.value){const t=new Value({});e[Lr](t);e.value=t}e.value[Gi](t)}function*getContainedChildren(e){for(const t of e[fi]())t instanceof SubformSet?yield*t[ci]():yield t}function isRequired(e){return"error"===e.validate?.nullTest}function setTabIndex(e){for(;e;){if(!e.traversal){e[Vi]=e[mi]()[Vi];return}if(e[Vi])return;let t=null;for(const n of e.traversal[fi]())if("next"===n.operation){t=n;break}if(!t||!t.ref){e[Vi]=e[mi]()[Vi];return}const n=e[pi]();e[Vi]=++n[Vi];const a=n[Xi](t.ref,e);if(!a)return;e=a[0]}}function applyAssist(e,t){const n=e.assist;if(n){const e=n[Ji]();e&&(t.title=e);const a=n.role.match(Eo);if(a){const e="heading",n=a[1];t.role=e;t["aria-level"]=n}}if("table"===e.layout)t.role="table";else if("row"===e.layout)t.role="row";else{const n=e[mi]();"row"===n.layout&&(t.role="TH"===n.assist?.role?"columnheader":"cell")}}function ariaLabel(e){if(!e.assist)return null;const t=e.assist;return t.speak&&""!==t.speak[Vr]?t.speak[Vr]:t.toolTip?t.toolTip[Vr]:null}function valueToHtml(e){return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:Object.create(null)},children:[{name:"span",attributes:{style:Object.create(null)},value:e}]})}function setFirstUnsplittable(e){const t=e[pi]();if(null===t[Jr].firstUnsplittable){t[Jr].firstUnsplittable=e;t[Jr].noLayoutFailure=!0}}function unsetFirstUnsplittable(e){const t=e[pi]();t[Jr].firstUnsplittable===e&&(t[Jr].noLayoutFailure=!1)}function handleBreak(e){if(e[Jr])return!1;e[Jr]=Object.create(null);if("auto"===e.targetType)return!1;const t=e[pi]();let n=null;if(e.target){n=t[Xi](e.target,e[mi]());if(!n)return!1;n=n[0]}const{currentPageArea:a,currentContentArea:s}=t[Jr];if("pageArea"===e.targetType){n instanceof PageArea||(n=null);if(e.startNew){e[Jr].target=n||a;return!0}if(n&&n!==a){e[Jr].target=n;return!0}return!1}n instanceof ContentArea||(n=null);const r=n&&n[mi]();let i,o=r;if(e.startNew)if(n){const e=r.contentArea.children,t=e.indexOf(s),a=e.indexOf(n);-1!==t&&t<a&&(o=null);i=a-1}else i=a.contentArea.children.indexOf(s);else{if(!n||n===s)return!1;i=r.contentArea.children.indexOf(n)-1;o=r===a?null:r}e[Jr].target=o;e[Jr].index=i;return!0}function handleOverflow(e,t,n){const a=e[pi](),s=a[Jr].noLayoutFailure,r=t[ui];t[ui]=()=>e;a[Jr].noLayoutFailure=!0;const i=t[Ji](n);e[zr](i.html,i.bbox);a[Jr].noLayoutFailure=s;t[ui]=r}class AppearanceFilter extends StringObject{constructor(e){super(Mo,"appearanceFilter");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Arc extends XFAObject{constructor(e){super(Mo,"arc",!0);this.circular=getInteger({data:e.circular,defaultValue:0,validate:e=>1===e});this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.startAngle=getFloat({data:e.startAngle,defaultValue:0,validate:e=>!0});this.sweepAngle=getFloat({data:e.sweepAngle,defaultValue:360,validate:e=>!0});this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null;this.fill=null}[Ji](){const e=this.edge||new Edge({}),t=e[Zi](),n=Object.create(null);"visible"===this.fill?.presence?Object.assign(n,this.fill[Zi]()):n.fill="transparent";n.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);n.stroke=t.color;let a;const s={xmlns:Po,style:{width:"100%",height:"100%",overflow:"visible"}};if(360===this.sweepAngle)a={name:"ellipse",attributes:{xmlns:Po,cx:"50%",cy:"50%",rx:"50%",ry:"50%",style:n}};else{const e=this.startAngle*Math.PI/180,t=this.sweepAngle*Math.PI/180,r=this.sweepAngle>180?1:0,[i,o,l,f]=[50*(1+Math.cos(e)),50*(1-Math.sin(e)),50*(1+Math.cos(e+t)),50*(1-Math.sin(e+t))];a={name:"path",attributes:{xmlns:Po,d:`M ${i} ${o} A 50 50 0 ${r} 0 ${l} ${f}`,vectorEffect:"non-scaling-stroke",style:n}};Object.assign(s,{viewBox:"0 0 100 100",preserveAspectRatio:"none"})}const r={name:"svg",children:[a],attributes:s};if(hasMargin(this[mi]()[mi]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[r]});r.attributes.style.position="absolute";return HTMLResult.success(r)}}class Area extends XFAObject{constructor(e){super(Mo,"area",!0);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null;this.area=new XFAObjectArray;this.draw=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[ci](){yield*getContainedChildren(this)}[Ci](){return!0}[yi](){return!0}[zr](e,t){const[n,a,s,r]=t;this[Jr].width=Math.max(this[Jr].width,n+s);this[Jr].height=Math.max(this[Jr].height,a+r);this[Jr].children.push(e)}[ni](){return this[Jr].availableSpace}[Ji](e){const t=toStyle(this,"position"),n={style:t,id:this[eo],class:["xfaArea"]};isPrintOnly(this)&&n.class.push("xfaPrintOnly");this.name&&(n.xfaName=this.name);const a=[];this[Jr]={children:a,width:0,height:0,availableSpace:e};const s=this[Ur]({filter:new Set(["area","draw","field","exclGroup","subform","subformSet"]),include:!0});if(!s.success){if(s.isBreak())return s;delete this[Jr];return HTMLResult.FAILURE}t.width=measureToString(this[Jr].width);t.height=measureToString(this[Jr].height);const r={name:"div",attributes:n,children:a},i=[this.x,this.y,this[Jr].width,this[Jr].height];delete this[Jr];return HTMLResult.success(r,i)}}class Assist extends XFAObject{constructor(e){super(Mo,"assist",!0);this.id=e.id||"";this.role=e.role||"";this.use=e.use||"";this.usehref=e.usehref||"";this.speak=null;this.toolTip=null}[Ji](){return this.toolTip?.[Vr]||null}}class Barcode extends XFAObject{constructor(e){super(Mo,"barcode",!0);this.charEncoding=getKeyword({data:e.charEncoding?e.charEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.checksum=getStringOption(e.checksum,["none","1mod10","1mod10_1mod11","2mod10","auto"]);this.dataColumnCount=getInteger({data:e.dataColumnCount,defaultValue:-1,validate:e=>e>=0});this.dataLength=getInteger({data:e.dataLength,defaultValue:-1,validate:e=>e>=0});this.dataPrep=getStringOption(e.dataPrep,["none","flateCompress"]);this.dataRowCount=getInteger({data:e.dataRowCount,defaultValue:-1,validate:e=>e>=0});this.endChar=e.endChar||"";this.errorCorrectionLevel=getInteger({data:e.errorCorrectionLevel,defaultValue:-1,validate:e=>e>=0&&e<=8});this.id=e.id||"";this.moduleHeight=getMeasurement(e.moduleHeight,"5mm");this.moduleWidth=getMeasurement(e.moduleWidth,"0.25mm");this.printCheckDigit=getInteger({data:e.printCheckDigit,defaultValue:0,validate:e=>1===e});this.rowColumnRatio=getRatio(e.rowColumnRatio);this.startChar=e.startChar||"";this.textLocation=getStringOption(e.textLocation,["below","above","aboveEmbedded","belowEmbedded","none"]);this.truncate=getInteger({data:e.truncate,defaultValue:0,validate:e=>1===e});this.type=getStringOption(e.type?e.type.toLowerCase():"",["aztec","codabar","code2of5industrial","code2of5interleaved","code2of5matrix","code2of5standard","code3of9","code3of9extended","code11","code49","code93","code128","code128a","code128b","code128c","code128sscc","datamatrix","ean8","ean8add2","ean8add5","ean13","ean13add2","ean13add5","ean13pwcd","fim","logmars","maxicode","msi","pdf417","pdf417macro","plessey","postauscust2","postauscust3","postausreplypaid","postausstandard","postukrm4scc","postusdpbc","postusimb","postusstandard","postus5zip","qrcode","rfid","rss14","rss14expanded","rss14limited","rss14stacked","rss14stackedomni","rss14truncated","telepen","ucc128","ucc128random","ucc128sscc","upca","upcaadd2","upcaadd5","upcapwcd","upce","upceadd2","upceadd5","upcean2","upcean5","upsmaxicode"]);this.upsMode=getStringOption(e.upsMode,["usCarrier","internationalCarrier","secureSymbol","standardSymbol"]);this.use=e.use||"";this.usehref=e.usehref||"";this.wideNarrowRatio=getRatio(e.wideNarrowRatio);this.encrypt=null;this.extras=null}}class Bind extends XFAObject{constructor(e){super(Mo,"bind",!0);this.match=getStringOption(e.match,["once","dataRef","global","none"]);this.ref=e.ref||"";this.picture=null}}class BindItems extends XFAObject{constructor(e){super(Mo,"bindItems");this.connection=e.connection||"";this.labelRef=e.labelRef||"";this.ref=e.ref||"";this.valueRef=e.valueRef||""}}class Bookend extends XFAObject{constructor(e){super(Mo,"bookend");this.id=e.id||"";this.leader=e.leader||"";this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||""}}class BooleanElement extends Option01{constructor(e){super(Mo,"boolean");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Ji](e){return valueToHtml(1===this[Vr]?"1":"0")}}class Border extends XFAObject{constructor(e){super(Mo,"border",!0);this.break=getStringOption(e.break,["close","open"]);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.extras=null;this.fill=null;this.margin=null}[oi](){if(!this[Jr]){const e=this.edge.children.slice();if(e.length<4){const t=e.at(-1)||new Edge({});for(let n=e.length;n<4;n++)e.push(t)}const t=e.map(e=>e.thickness),n=[0,0,0,0];if(this.margin){n[0]=this.margin.topInset;n[1]=this.margin.rightInset;n[2]=this.margin.bottomInset;n[3]=this.margin.leftInset}this[Jr]={widths:t,insets:n,edges:e}}return this[Jr]}[Zi](){const{edges:e}=this[oi](),t=e.map(e=>{const t=e[Zi]();t.color||="#000000";return t}),n=Object.create(null);this.margin&&Object.assign(n,this.margin[Zi]());"visible"===this.fill?.presence&&Object.assign(n,this.fill[Zi]());if(this.corner.children.some(e=>0!==e.radius)){const e=this.corner.children.map(e=>e[Zi]());if(2===e.length||3===e.length){const t=e.at(-1);for(let n=e.length;n<4;n++)e.push(t)}n.borderRadius=e.map(e=>e.radius).join(" ")}switch(this.presence){case"invisible":case"hidden":n.borderStyle="";break;case"inactive":n.borderStyle="none";break;default:n.borderStyle=t.map(e=>e.style).join(" ")}n.borderWidth=t.map(e=>e.width).join(" ");n.borderColor=t.map(e=>e.color).join(" ");return n}}class Break extends XFAObject{constructor(e){super(Mo,"break",!0);this.after=getStringOption(e.after,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.afterTarget=e.afterTarget||"";this.before=getStringOption(e.before,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.beforeTarget=e.beforeTarget||"";this.bookendLeader=e.bookendLeader||"";this.bookendTrailer=e.bookendTrailer||"";this.id=e.id||"";this.overflowLeader=e.overflowLeader||"";this.overflowTarget=e.overflowTarget||"";this.overflowTrailer=e.overflowTrailer||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class BreakAfter extends XFAObject{constructor(e){super(Mo,"breakAfter",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}}class BreakBefore extends XFAObject{constructor(e){super(Mo,"breakBefore",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}[Ji](e){this[Jr]={};return HTMLResult.FAILURE}}class Button extends XFAObject{constructor(e){super(Mo,"button",!0);this.highlight=getStringOption(e.highlight,["inverted","none","outline","push"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Ji](e){const t=this[mi]()[mi](),n={name:"button",attributes:{id:this[eo],class:["xfaButton"],style:{}},children:[]};for(const e of t.event.children){if("click"!==e.activity||!e.script)continue;const t=recoverJsURL(e.script[Vr]);if(!t)continue;const a=fixURL(t.url);a&&n.children.push({name:"a",attributes:{id:"link"+this[eo],href:a,newWindow:t.newWindow,class:["xfaLink"],style:{}},children:[]})}return HTMLResult.success(n)}}class Calculate extends XFAObject{constructor(e){super(Mo,"calculate",!0);this.id=e.id||"";this.override=getStringOption(e.override,["disabled","error","ignore","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.script=null}}class Caption extends XFAObject{constructor(e){super(Mo,"caption",!0);this.id=e.id||"";this.placement=getStringOption(e.placement,["left","bottom","inline","right","top"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.reserve=Math.ceil(getMeasurement(e.reserve));this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.font=null;this.margin=null;this.para=null;this.value=null}[Gi](e){_setValue(this,e)}[oi](e){if(!this[Jr]){let{width:t,height:n}=e;switch(this.placement){case"left":case"right":case"inline":t=this.reserve<=0?t:this.reserve;break;case"top":case"bottom":n=this.reserve<=0?n:this.reserve}this[Jr]=layoutNode(this,{width:t,height:n})}return this[Jr]}[Ji](e){if(!this.value)return HTMLResult.EMPTY;this[Ei]();const t=this.value[Ji](e).html;if(!t){this[Pi]();return HTMLResult.EMPTY}const n=this.reserve;if(this.reserve<=0){const{w:t,h:n}=this[oi](e);switch(this.placement){case"left":case"right":case"inline":this.reserve=t;break;case"top":case"bottom":this.reserve=n}}const a=[];"string"==typeof t?a.push({name:"#text",value:t}):a.push(t);const s=toStyle(this,"font","margin","visibility");switch(this.placement){case"left":case"right":this.reserve>0&&(s.width=measureToString(this.reserve));break;case"top":case"bottom":this.reserve>0&&(s.height=measureToString(this.reserve))}setPara(this,null,t);this[Pi]();this.reserve=n;return HTMLResult.success({name:"div",attributes:{style:s,class:["xfaCaption"]},children:a})}}class Certificate extends StringObject{constructor(e){super(Mo,"certificate");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Certificates extends XFAObject{constructor(e){super(Mo,"certificates",!0);this.credentialServerPolicy=getStringOption(e.credentialServerPolicy,["optional","required"]);this.id=e.id||"";this.url=e.url||"";this.urlPolicy=e.urlPolicy||"";this.use=e.use||"";this.usehref=e.usehref||"";this.encryption=null;this.issuers=null;this.keyUsage=null;this.oids=null;this.signing=null;this.subjectDNs=null}}class CheckButton extends XFAObject{constructor(e){super(Mo,"checkButton",!0);this.id=e.id||"";this.mark=getStringOption(e.mark,["default","check","circle","cross","diamond","square","star"]);this.shape=getStringOption(e.shape,["square","round"]);this.size=getMeasurement(e.size,"10pt");this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[Ji](e){const t=toStyle(this,"margin"),n=measureToString(this.size);t.width=t.height=n;let a,s,r;const i=this[mi]()[mi](),o=i.items.children.length&&i.items.children[0][Ji]().html||[],l={on:(void 0!==o[0]?o[0]:"on").toString(),off:(void 0!==o[1]?o[1]:"off").toString()},f=(i.value?.[$i]()||"off")===l.on||void 0,c=i[ui](),h=i[eo];let u;if(c instanceof ExclGroup){r=c[eo];a="radio";s="xfaRadio";u=c[$r]?.[eo]||c[eo]}else{a="checkbox";s="xfaCheckbox";u=i[$r]?.[eo]||i[eo]}const m={name:"input",attributes:{class:[s],style:t,fieldId:h,dataId:u,type:a,checked:f,xfaOn:l.on,xfaOff:l.off,"aria-label":ariaLabel(i),"aria-required":!1}};r&&(m.attributes.name=r);if(isRequired(i)){m.attributes["aria-required"]=!0;m.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[m]})}}class ChoiceList extends XFAObject{constructor(e){super(Mo,"choiceList",!0);this.commitOn=getStringOption(e.commitOn,["select","exit"]);this.id=e.id||"";this.open=getStringOption(e.open,["userControl","always","multiSelect","onEntry"]);this.textEntry=getInteger({data:e.textEntry,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[Ji](e){const t=toStyle(this,"border","margin"),n=this[mi]()[mi](),a={fontSize:`calc(${n.font?.size||10}px * var(--total-scale-factor))`},s=[];if(n.items.children.length>0){const e=n.items;let t=0,r=0;if(2===e.children.length){t=e.children[0].save;r=1-t}const i=e.children[t][Ji]().html,o=e.children[r][Ji]().html;let l=!1;const f=n.value?.[$i]()||"";for(let e=0,t=i.length;e<t;e++){const t={name:"option",attributes:{value:o[e]||i[e],style:a},value:i[e]};o[e]===f&&(t.attributes.selected=l=!0);s.push(t)}l||s.splice(0,0,{name:"option",attributes:{hidden:!0,selected:!0},value:" "})}const r={class:["xfaSelect"],fieldId:n[eo],dataId:n[$r]?.[eo]||n[eo],style:t,"aria-label":ariaLabel(n),"aria-required":!1};if(isRequired(n)){r["aria-required"]=!0;r.required=!0}"multiSelect"===this.open&&(r.multiple=!0);return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[{name:"select",children:s,attributes:r}]})}}class Color extends XFAObject{constructor(e){super(Mo,"color",!0);this.cSpace=getStringOption(e.cSpace,["SRGB"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.value=e.value?function getColor(e,t=[0,0,0]){let[n,a,s]=t;if(!e)return{r:n,g:a,b:s};const r=e.split(",",3).map(e=>MathClamp(parseInt(e.trim(),10),0,255)).map(e=>isNaN(e)?0:e);if(r.length<3)return{r:n,g:a,b:s};[n,a,s]=r;return{r:n,g:a,b:s}}(e.value):"";this.extras=null}[gi](){return!1}[Zi](){return this.value?Util.makeHexColor(this.value.r,this.value.g,this.value.b):null}}class Comb extends XFAObject{constructor(e){super(Mo,"comb");this.id=e.id||"";this.numberOfCells=getInteger({data:e.numberOfCells,defaultValue:0,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||""}}class Connect extends XFAObject{constructor(e){super(Mo,"connect",!0);this.connection=e.connection||"";this.id=e.id||"";this.ref=e.ref||"";this.usage=getStringOption(e.usage,["exportAndImport","exportOnly","importOnly"]);this.use=e.use||"";this.usehref=e.usehref||"";this.picture=null}}class ContentArea extends XFAObject{constructor(e){super(Mo,"contentArea",!0);this.h=getMeasurement(e.h);this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=getMeasurement(e.w);this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null}[Ji](e){const t={left:measureToString(this.x),top:measureToString(this.y),width:measureToString(this.w),height:measureToString(this.h)},n=["xfaContentarea"];isPrintOnly(this)&&n.push("xfaPrintOnly");return HTMLResult.success({name:"div",children:[],attributes:{style:t,class:n,id:this[eo]}})}}class Corner extends XFAObject{constructor(e){super(Mo,"corner",!0);this.id=e.id||"";this.inverted=getInteger({data:e.inverted,defaultValue:0,validate:e=>1===e});this.join=getStringOption(e.join,["square","round"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.radius=getMeasurement(e.radius);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zi](){const e=toStyle(this,"visibility");e.radius=measureToString("square"===this.join?0:this.radius);return e}}class DateElement extends ContentObject{constructor(e){super(Mo,"date");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Qr](){const e=this[Vr].trim();this[Vr]=e?new Date(e):null}[Ji](e){return valueToHtml(this[Vr]?this[Vr].toString():"")}}class DateTime extends ContentObject{constructor(e){super(Mo,"dateTime");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Qr](){const e=this[Vr].trim();this[Vr]=e?new Date(e):null}[Ji](e){return valueToHtml(this[Vr]?this[Vr].toString():"")}}class DateTimeEdit extends XFAObject{constructor(e){super(Mo,"dateTimeEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.picker=getStringOption(e.picker,["host","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[Ji](e){const t=toStyle(this,"border","font","margin"),n=this[mi]()[mi](),a={name:"input",attributes:{type:"text",fieldId:n[eo],dataId:n[$r]?.[eo]||n[eo],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(n),"aria-required":!1}};if(isRequired(n)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Decimal extends ContentObject{constructor(e){super(Mo,"decimal");this.fracDigits=getInteger({data:e.fracDigits,defaultValue:2,validate:e=>!0});this.id=e.id||"";this.leadDigits=getInteger({data:e.leadDigits,defaultValue:-1,validate:e=>!0});this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Qr](){const e=parseFloat(this[Vr].trim());this[Vr]=isNaN(e)?null:e}[Ji](e){return valueToHtml(null!==this[Vr]?this[Vr].toString():"")}}class DefaultUi extends XFAObject{constructor(e){super(Mo,"defaultUi",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class Desc extends XFAObject{constructor(e){super(Mo,"desc",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class DigestMethod extends OptionObject{constructor(e){super(Mo,"digestMethod",["","SHA1","SHA256","SHA512","RIPEMD160"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class DigestMethods extends XFAObject{constructor(e){super(Mo,"digestMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.digestMethod=new XFAObjectArray}}class Draw extends XFAObject{constructor(e){super(Mo,"draw",!0);this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.border=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.value=null;this.setProperty=new XFAObjectArray}[Gi](e){_setValue(this,e)}[Ji](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;fixDimensions(this);this[Ei]();const t=this.w,n=this.h,{w:a,h:s,isBroken:r}=layoutNode(this,e);if(a&&""===this.w){if(r&&this[ui]()[Ai]()){this[Pi]();return HTMLResult.FAILURE}this.w=a}s&&""===this.h&&(this.h=s);setFirstUnsplittable(this);if(!checkDimensions(this,e)){this.w=t;this.h=n;this[Pi]();return HTMLResult.FAILURE}unsetFirstUnsplittable(this);const i=toStyle(this,"font","hAlign","dimensions","position","presence","rotate","anchorType","border","margin");setMinMaxDimensions(this,i);if(i.margin){i.padding=i.margin;delete i.margin}const o=["xfaDraw"];this.font&&o.push("xfaFont");isPrintOnly(this)&&o.push("xfaPrintOnly");const l={style:i,id:this[eo],class:o};this.name&&(l.xfaName=this.name);const f={name:"div",attributes:l,children:[]};applyAssist(this,l);const c=computeBbox(this,f,e),h=this.value?this.value[Ji](e).html:null;if(null===h){this.w=t;this.h=n;this[Pi]();return HTMLResult.success(createWrapper(this,f),c)}f.children.push(h);setPara(this,i,h);this.w=t;this.h=n;this[Pi]();return HTMLResult.success(createWrapper(this,f),c)}}class Edge extends XFAObject{constructor(e){super(Mo,"edge",!0);this.cap=getStringOption(e.cap,["square","butt","round"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zi](){const e=toStyle(this,"visibility");Object.assign(e,{linecap:this.cap,width:measureToString(this.thickness),color:this.color?this.color[Zi]():"#000000",style:""});if("visible"!==this.presence)e.style="none";else switch(this.stroke){case"solid":e.style="solid";break;case"dashDot":case"dashDotDot":case"dashed":e.style="dashed";break;case"dotted":e.style="dotted";break;case"embossed":e.style="ridge";break;case"etched":e.style="groove";break;case"lowered":e.style="inset";break;case"raised":e.style="outset"}return e}}class Encoding extends OptionObject{constructor(e){super(Mo,"encoding",["adbe.x509.rsa_sha1","adbe.pkcs7.detached","adbe.pkcs7.sha1"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Encodings extends XFAObject{constructor(e){super(Mo,"encodings",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encoding=new XFAObjectArray}}class Encrypt extends XFAObject{constructor(e){super(Mo,"encrypt",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=null}}class EncryptData extends XFAObject{constructor(e){super(Mo,"encryptData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["encrypt","decrypt"]);this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Encryption extends XFAObject{constructor(e){super(Mo,"encryption",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class EncryptionMethod extends OptionObject{constructor(e){super(Mo,"encryptionMethod",["","AES256-CBC","TRIPLEDES-CBC","AES128-CBC","AES192-CBC"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EncryptionMethods extends XFAObject{constructor(e){super(Mo,"encryptionMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encryptionMethod=new XFAObjectArray}}class Event extends XFAObject{constructor(e){super(Mo,"event",!0);this.activity=getStringOption(e.activity,["click","change","docClose","docReady","enter","exit","full","indexChange","initialize","mouseDown","mouseEnter","mouseExit","mouseUp","postExecute","postOpen","postPrint","postSave","postSign","postSubmit","preExecute","preOpen","prePrint","preSave","preSign","preSubmit","ready","validationState"]);this.id=e.id||"";this.listen=getStringOption(e.listen,["refOnly","refAndDescendents"]);this.name=e.name||"";this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.encryptData=null;this.execute=null;this.script=null;this.signData=null;this.submit=null}}class ExData extends ContentObject{constructor(e){super(Mo,"exData");this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.maxLength=getInteger({data:e.maxLength,defaultValue:-1,validate:e=>e>=-1});this.name=e.name||"";this.rid=e.rid||"";this.transferEncoding=getStringOption(e.transferEncoding,["none","base64","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[ki](){return"text/html"===this.contentType}[Bi](e){if("text/html"===this.contentType&&e[Ti]===no.xhtml.id){this[Vr]=e;return!0}if("text/xml"===this.contentType){this[Vr]=e;return!0}return!1}[Ji](e){return"text/html"===this.contentType&&this[Vr]?this[Vr][Ji](e):HTMLResult.EMPTY}}class ExObject extends XFAObject{constructor(e){super(Mo,"exObject",!0);this.archive=e.archive||"";this.classId=e.classId||"";this.codeBase=e.codeBase||"";this.codeType=e.codeType||"";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class ExclGroup extends XFAObject{constructor(e){super(Mo,"exclGroup",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.accessKey=e.accessKey||"";this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.margin=null;this.para=null;this.traversal=null;this.validate=null;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.field=new XFAObjectArray;this.setProperty=new XFAObjectArray}[yi](){return!0}[gi](){return!0}[Gi](e){for(const t of this.field.children){if(!t.value){const e=new Value({});t[Lr](e);t.value=e}t.value[Gi](e)}}[Ai](){return this.layout.endsWith("-tb")&&0===this[Jr].attempt&&this[Jr].numberInLine>0||this[mi]()[Ai]()}[xi](){const e=this[ui]();if(!e[xi]())return!1;if(void 0!==this[Jr]._isSplittable)return this[Jr]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Jr]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Jr].numberInLine)return!1;this[Jr]._isSplittable=!0;return!0}[Zr](){return flushHTML(this)}[zr](e,t){addHTML(this,e,t)}[ni](){return getAvailableSpace(this)}[Ji](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;fixDimensions(this);const t=[],n={id:this[eo],class:[]};setAccess(this,n.class);this[Jr]||=Object.create(null);Object.assign(this[Jr],{children:t,attributes:n,attempt:0,line:null,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const a=this[xi]();a||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const s=new Set(["field"]);if(this.layout.includes("row")){const e=this[ui]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Jr].columnWidths=e;this[Jr].currentColumn=0}}const r=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),i=["xfaExclgroup"],o=layoutClass(this);o&&i.push(o);isPrintOnly(this)&&i.push("xfaPrintOnly");n.style=r;n.class=i;this.name&&(n.xfaName=this.name);this[Ei]();const l="lr-tb"===this.layout||"rl-tb"===this.layout,f=l?2:1;for(;this[Jr].attempt<f;this[Jr].attempt++){l&&1===this[Jr].attempt&&(this[Jr].numberInLine=0);const e=this[Ur]({filter:s,include:!0});if(e.success)break;if(e.isBreak()){this[Pi]();return e}if(l&&0===this[Jr].attempt&&0===this[Jr].numberInLine&&!this[pi]()[Jr].noLayoutFailure){this[Jr].attempt=f;break}}this[Pi]();a||unsetFirstUnsplittable(this);if(this[Jr].attempt===f){a||delete this[Jr];return HTMLResult.FAILURE}let c=0,h=0;if(this.margin){c=this.margin.leftInset+this.margin.rightInset;h=this.margin.topInset+this.margin.bottomInset}const u=Math.max(this[Jr].width+c,this.w||0),m=Math.max(this[Jr].height+h,this.h||0),p=[this.x,this.y,u,m];""===this.w&&(r.width=measureToString(u));""===this.h&&(r.height=measureToString(m));const d={name:"div",attributes:n,children:t};applyAssist(this,n);delete this[Jr];return HTMLResult.success(createWrapper(this,d),p)}}class Execute extends XFAObject{constructor(e){super(Mo,"execute");this.connection=e.connection||"";this.executeType=getStringOption(e.executeType,["import","remerge"]);this.id=e.id||"";this.runAt=getStringOption(e.runAt,["client","both","server"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Extras extends XFAObject{constructor(e){super(Mo,"extras",!0);this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.extras=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class Field extends XFAObject{constructor(e){super(Mo,"field",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.accessKey=e.accessKey||"";this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.format=null;this.items=new XFAObjectArray(2);this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.validate=null;this.value=null;this.bindItems=new XFAObjectArray;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.setProperty=new XFAObjectArray}[yi](){return!0}[Gi](e){_setValue(this,e)}[Ji](e){setTabIndex(this);if(!this.ui){this.ui=new Ui({});this.ui[di]=this[di];this[Lr](this.ui);let e;switch(this.items.children.length){case 0:e=new TextEdit({});this.ui.textEdit=e;break;case 1:e=new CheckButton({});this.ui.checkButton=e;break;case 2:e=new ChoiceList({});this.ui.choiceList=e}this.ui[Lr](e)}if(!this.ui||"hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;this.caption&&delete this.caption[Jr];this[Ei]();const t=this.caption?this.caption[Ji](e).html:null,n=this.w,a=this.h;let s=0,r=0;if(this.margin){s=this.margin.leftInset+this.margin.rightInset;r=this.margin.topInset+this.margin.bottomInset}let i=null;if(""===this.w||""===this.h){let t=null,n=null,a=0,o=0;if(this.ui.checkButton)a=o=this.ui.checkButton.size;else{const{w:t,h:n}=layoutNode(this,e);if(null!==t){a=t;o=n}else o=function fonts_getMetrics(e,t=!1){let n=null;if(e){const t=stripQuotes(e.typeface),a=e[di].fontFinder.find(t);n=selectFont(e,a)}if(!n)return{lineHeight:12,lineGap:2,lineNoGap:10};const a=e.size||10,s=n.lineHeight?Math.max(t?0:1.2,n.lineHeight):1.2,r=void 0===n.lineGap?.2:n.lineGap;return{lineHeight:s*a,lineGap:r*a,lineNoGap:Math.max(1,s-r)*a}}(this.font,!0).lineNoGap}i=getBorderDims(this.ui[oi]());a+=i.w;o+=i.h;if(this.caption){const{w:s,h:r,isBroken:i}=this.caption[oi](e);if(i&&this[ui]()[Ai]()){this[Pi]();return HTMLResult.FAILURE}t=s;n=r;switch(this.caption.placement){case"left":case"right":case"inline":t+=a;break;case"top":case"bottom":n+=o}}else{t=a;n=o}if(t&&""===this.w){t+=s;this.w=Math.min(this.maxW<=0?1/0:this.maxW,this.minW+1<t?t:this.minW)}if(n&&""===this.h){n+=r;this.h=Math.min(this.maxH<=0?1/0:this.maxH,this.minH+1<n?n:this.minH)}}this[Pi]();fixDimensions(this);setFirstUnsplittable(this);if(!checkDimensions(this,e)){this.w=n;this.h=a;this[Pi]();return HTMLResult.FAILURE}unsetFirstUnsplittable(this);const o=toStyle(this,"font","dimensions","position","rotate","anchorType","presence","margin","hAlign");setMinMaxDimensions(this,o);const l=["xfaField"];this.font&&l.push("xfaFont");isPrintOnly(this)&&l.push("xfaPrintOnly");const f={style:o,id:this[eo],class:l};if(o.margin){o.padding=o.margin;delete o.margin}setAccess(this,l);this.name&&(f.xfaName=this.name);const c=[],h={name:"div",attributes:f,children:c};applyAssist(this,f);const u=this.border?this.border[Zi]():null,m=computeBbox(this,h,e),p=this.ui[Ji]().html;if(!p){Object.assign(o,u);return HTMLResult.success(createWrapper(this,h),m)}this[Vi]&&(p.children?.[0]?p.children[0].attributes.tabindex=this[Vi]:p.attributes.tabindex=this[Vi]);p.attributes.style||=Object.create(null);let d=null;if(this.ui.button){1===p.children.length&&([d]=p.children.splice(0,1));Object.assign(p.attributes.style,u)}else Object.assign(o,u);c.push(p);if(this.value)if(this.ui.imageEdit)p.children.push(this.value[Ji]().html);else if(!this.ui.button){let e="";if(this.value.exData)e=this.value.exData[$i]();else if(this.value.text)e=this.value.text[oi]();else{const t=this.value[Ji]().html;null!==t&&(e=t.children[0].value)}this.ui.textEdit&&this.value.text?.maxChars&&(p.children[0].attributes.maxLength=this.value.text.maxChars);if(e){if(this.ui.numericEdit){e=parseFloat(e);e=isNaN(e)?"":e.toString()}"textarea"===p.children[0].name?p.children[0].attributes.textContent=e:p.children[0].attributes.value=e}}if(!this.ui.imageEdit&&p.children?.[0]&&this.h){i=i||getBorderDims(this.ui[oi]());let t=0;if(this.caption&&["top","bottom"].includes(this.caption.placement)){t=this.caption.reserve;t<=0&&(t=this.caption[oi](e).h);const n=this.h-t-r-i.h;p.children[0].attributes.style.height=measureToString(n)}else p.children[0].attributes.style.height="100%"}d&&p.children.push(d);if(!t){p.attributes.class&&p.attributes.class.push("xfaLeft");this.w=n;this.h=a;return HTMLResult.success(createWrapper(this,h),m)}if(this.ui.button){o.padding&&delete o.padding;"div"===t.name&&(t.name="span");p.children.push(t);return HTMLResult.success(h,m)}this.ui.checkButton&&(t.attributes.class[0]="xfaCaptionForCheckButton");p.attributes.class||=[];p.children.splice(0,0,t);switch(this.caption.placement){case"left":case"inline":p.attributes.class.push("xfaLeft");break;case"right":p.attributes.class.push("xfaRight");break;case"top":p.attributes.class.push("xfaTop");break;case"bottom":p.attributes.class.push("xfaBottom")}this.w=n;this.h=a;return HTMLResult.success(createWrapper(this,h),m)}}class Fill extends XFAObject{constructor(e){super(Mo,"fill",!0);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null;this.linear=null;this.pattern=null;this.radial=null;this.solid=null;this.stipple=null}[Zi](){const e=this[mi](),t=e[mi]()[mi](),n=Object.create(null);let a="color",s=a;if(e instanceof Border){a="background-color";s="background";t instanceof Ui&&(n.backgroundColor="white")}if(e instanceof Rectangle||e instanceof Arc){a=s="fill";n.fill="white"}for(const e of Object.getOwnPropertyNames(this)){if("extras"===e||"color"===e)continue;const t=this[e];if(!(t instanceof XFAObject))continue;const r=t[Zi](this.color);r&&(n[r.startsWith("#")?a:s]=r);return n}if(this.color?.value){const e=this.color[Zi]();n[e.startsWith("#")?a:s]=e}return n}}class Filter extends XFAObject{constructor(e){super(Mo,"filter",!0);this.addRevocationInfo=getStringOption(e.addRevocationInfo,["","required","optional","none"]);this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.version=getInteger({data:this.version,defaultValue:5,validate:e=>e>=1&&e<=5});this.appearanceFilter=null;this.certificates=null;this.digestMethods=null;this.encodings=null;this.encryptionMethods=null;this.handler=null;this.lockDocument=null;this.mdp=null;this.reasons=null;this.timeStamp=null}}class Float extends ContentObject{constructor(e){super(Mo,"float");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Qr](){const e=parseFloat(this[Vr].trim());this[Vr]=isNaN(e)?null:e}[Ji](e){return valueToHtml(null!==this[Vr]?this[Vr].toString():"")}}class template_Font extends XFAObject{constructor(e){super(Mo,"font",!0);this.baselineShift=getMeasurement(e.baselineShift);this.fontHorizontalScale=getFloat({data:e.fontHorizontalScale,defaultValue:100,validate:e=>e>=0});this.fontVerticalScale=getFloat({data:e.fontVerticalScale,defaultValue:100,validate:e=>e>=0});this.id=e.id||"";this.kerningMode=getStringOption(e.kerningMode,["none","pair"]);this.letterSpacing=getMeasurement(e.letterSpacing,"0");this.lineThrough=getInteger({data:e.lineThrough,defaultValue:0,validate:e=>1===e||2===e});this.lineThroughPeriod=getStringOption(e.lineThroughPeriod,["all","word"]);this.overline=getInteger({data:e.overline,defaultValue:0,validate:e=>1===e||2===e});this.overlinePeriod=getStringOption(e.overlinePeriod,["all","word"]);this.posture=getStringOption(e.posture,["normal","italic"]);this.size=getMeasurement(e.size,"10pt");this.typeface=e.typeface||"Courier";this.underline=getInteger({data:e.underline,defaultValue:0,validate:e=>1===e||2===e});this.underlinePeriod=getStringOption(e.underlinePeriod,["all","word"]);this.use=e.use||"";this.usehref=e.usehref||"";this.weight=getStringOption(e.weight,["normal","bold"]);this.extras=null;this.fill=null}[_r](e){super[_r](e);this[di].usedTypefaces.add(this.typeface)}[Zi](){const e=toStyle(this,"fill"),t=e.color;if(t)if("#000000"===t)delete e.color;else if(!t.startsWith("#")){e.background=t;e.backgroundClip="text";e.color="transparent"}this.baselineShift&&(e.verticalAlign=measureToString(this.baselineShift));e.fontKerning="none"===this.kerningMode?"none":"normal";e.letterSpacing=measureToString(this.letterSpacing);if(0!==this.lineThrough){e.textDecoration="line-through";2===this.lineThrough&&(e.textDecorationStyle="double")}if(0!==this.overline){e.textDecoration="overline";2===this.overline&&(e.textDecorationStyle="double")}e.fontStyle=this.posture;e.fontSize=measureToString(.99*this.size);setFontFamily(this,this,this[di].fontFinder,e);if(0!==this.underline){e.textDecoration="underline";2===this.underline&&(e.textDecorationStyle="double")}e.fontWeight=this.weight;return e}}class Format extends XFAObject{constructor(e){super(Mo,"format",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null}}class Handler extends StringObject{constructor(e){super(Mo,"handler");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Hyphenation extends XFAObject{constructor(e){super(Mo,"hyphenation");this.excludeAllCaps=getInteger({data:e.excludeAllCaps,defaultValue:0,validate:e=>1===e});this.excludeInitialCap=getInteger({data:e.excludeInitialCap,defaultValue:0,validate:e=>1===e});this.hyphenate=getInteger({data:e.hyphenate,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.pushCharacterCount=getInteger({data:e.pushCharacterCount,defaultValue:3,validate:e=>e>=0});this.remainCharacterCount=getInteger({data:e.remainCharacterCount,defaultValue:3,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||"";this.wordCharacterCount=getInteger({data:e.wordCharacterCount,defaultValue:7,validate:e=>e>=0})}}class Image extends StringObject{constructor(e){super(Mo,"image");this.aspect=getStringOption(e.aspect,["fit","actual","height","none","width"]);this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.name=e.name||"";this.transferEncoding=getStringOption(e.transferEncoding,["base64","none","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[Ji](){if(this.contentType&&!No.has(this.contentType.toLowerCase()))return HTMLResult.EMPTY;let e=this[di].images?.get(this.href);if(!e&&(this.href||!this[Vr]))return HTMLResult.EMPTY;e||"base64"!==this.transferEncoding||(e=Uint8Array.fromBase64(this[Vr]));if(!e)return HTMLResult.EMPTY;if(!this.contentType){for(const[t,n]of zo)if(e.length>t.length&&t.every((t,n)=>t===e[n])){this.contentType=n;break}if(!this.contentType)return HTMLResult.EMPTY}const t=new Blob([e],{type:this.contentType});let n;switch(this.aspect){case"fit":case"actual":break;case"height":n={height:"100%",objectFit:"fill"};break;case"none":n={width:"100%",height:"100%",objectFit:"fill"};break;case"width":n={width:"100%",objectFit:"fill"}}const a=this[mi]();return HTMLResult.success({name:"img",attributes:{class:["xfaImage"],style:n,src:URL.createObjectURL(t),alt:a?ariaLabel(a[mi]()):null}})}}class ImageEdit extends XFAObject{constructor(e){super(Mo,"imageEdit",!0);this.data=getStringOption(e.data,["link","embed"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[Ji](e){return"embed"===this.data?HTMLResult.success({name:"div",children:[],attributes:{}}):HTMLResult.EMPTY}}class Integer extends ContentObject{constructor(e){super(Mo,"integer");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Qr](){const e=parseInt(this[Vr].trim(),10);this[Vr]=isNaN(e)?null:e}[Ji](e){return valueToHtml(null!==this[Vr]?this[Vr].toString():"")}}class Issuers extends XFAObject{constructor(e){super(Mo,"issuers",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Items extends XFAObject{constructor(e){super(Mo,"items",!0);this.id=e.id||"";this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.ref=e.ref||"";this.save=getInteger({data:e.save,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[Ji](){const e=[];for(const t of this[fi]())e.push(t[$i]());return HTMLResult.success(e)}}class Keep extends XFAObject{constructor(e){super(Mo,"keep",!0);this.id=e.id||"";const t=["none","contentArea","pageArea"];this.intact=getStringOption(e.intact,t);this.next=getStringOption(e.next,t);this.previous=getStringOption(e.previous,t);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class KeyUsage extends XFAObject{constructor(e){super(Mo,"keyUsage");const t=["","yes","no"];this.crlSign=getStringOption(e.crlSign,t);this.dataEncipherment=getStringOption(e.dataEncipherment,t);this.decipherOnly=getStringOption(e.decipherOnly,t);this.digitalSignature=getStringOption(e.digitalSignature,t);this.encipherOnly=getStringOption(e.encipherOnly,t);this.id=e.id||"";this.keyAgreement=getStringOption(e.keyAgreement,t);this.keyCertSign=getStringOption(e.keyCertSign,t);this.keyEncipherment=getStringOption(e.keyEncipherment,t);this.nonRepudiation=getStringOption(e.nonRepudiation,t);this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Line extends XFAObject{constructor(e){super(Mo,"line",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.slope=getStringOption(e.slope,["\\","/"]);this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null}[Ji](){const e=this[mi]()[mi](),t=this.edge||new Edge({}),n=t[Zi](),a=Object.create(null),s="visible"===t.presence?t.thickness:0;a.strokeWidth=measureToString(s);a.stroke=n.color;let r,i,o,l,f="100%",c="100%";if(e.w<=s){[r,i,o,l]=["50%",0,"50%","100%"];f=a.strokeWidth}else if(e.h<=s){[r,i,o,l]=[0,"50%","100%","50%"];c=a.strokeWidth}else"\\"===this.slope?[r,i,o,l]=[0,0,"100%","100%"]:[r,i,o,l]=[0,"100%","100%",0];const h={name:"svg",children:[{name:"line",attributes:{xmlns:Po,x1:r,y1:i,x2:o,y2:l,style:a}}],attributes:{xmlns:Po,width:f,height:c,style:{overflow:"visible"}}};if(hasMargin(e))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[h]});h.attributes.style.position="absolute";return HTMLResult.success(h)}}class Linear extends XFAObject{constructor(e){super(Mo,"linear",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toRight","toBottom","toLeft","toTop"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zi](e){e=e?e[Zi]():"#FFFFFF";return`linear-gradient(${this.type.replace(/([RBLT])/," $1").toLowerCase()}, ${e}, ${this.color?this.color[Zi]():"#000000"})`}}class LockDocument extends ContentObject{constructor(e){super(Mo,"lockDocument");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}[Qr](){this[Vr]=getStringOption(this[Vr],["auto","0","1"])}}class Manifest extends XFAObject{constructor(e){super(Mo,"manifest",!0);this.action=getStringOption(e.action,["include","all","exclude"]);this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.ref=new XFAObjectArray}}class Margin extends XFAObject{constructor(e){super(Mo,"margin",!0);this.bottomInset=getMeasurement(e.bottomInset,"0");this.id=e.id||"";this.leftInset=getMeasurement(e.leftInset,"0");this.rightInset=getMeasurement(e.rightInset,"0");this.topInset=getMeasurement(e.topInset,"0");this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Zi](){return{margin:measureToString(this.topInset)+" "+measureToString(this.rightInset)+" "+measureToString(this.bottomInset)+" "+measureToString(this.leftInset)}}}class Mdp extends XFAObject{constructor(e){super(Mo,"mdp");this.id=e.id||"";this.permissions=getInteger({data:e.permissions,defaultValue:2,validate:e=>1===e||3===e});this.signatureType=getStringOption(e.signatureType,["filler","author"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Medium extends XFAObject{constructor(e){super(Mo,"medium");this.id=e.id||"";this.imagingBBox=function getBBox(e){const t=-1;if(!e)return{x:t,y:t,width:t,height:t};const n=e.split(",",4).map(e=>getMeasurement(e.trim(),"-1"));if(n.length<4||n[2]<0||n[3]<0)return{x:t,y:t,width:t,height:t};const[a,s,r,i]=n;return{x:a,y:s,width:r,height:i}}(e.imagingBBox);this.long=getMeasurement(e.long);this.orientation=getStringOption(e.orientation,["portrait","landscape"]);this.short=getMeasurement(e.short);this.stock=e.stock||"";this.trayIn=getStringOption(e.trayIn,["auto","delegate","pageFront"]);this.trayOut=getStringOption(e.trayOut,["auto","delegate"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Message extends XFAObject{constructor(e){super(Mo,"message",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.text=new XFAObjectArray}}class NumericEdit extends XFAObject{constructor(e){super(Mo,"numericEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[Ji](e){const t=toStyle(this,"border","font","margin"),n=this[mi]()[mi](),a={name:"input",attributes:{type:"text",fieldId:n[eo],dataId:n[$r]?.[eo]||n[eo],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(n),"aria-required":!1}};if(isRequired(n)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Occur extends XFAObject{constructor(e){super(Mo,"occur",!0);this.id=e.id||"";this.initial=""!==e.initial?getInteger({data:e.initial,defaultValue:"",validate:e=>!0}):"";this.max=""!==e.max?getInteger({data:e.max,defaultValue:-1,validate:e=>!0}):"";this.min=""!==e.min?getInteger({data:e.min,defaultValue:1,validate:e=>!0}):"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[_r](){const e=this[mi](),t=this.min;""===this.min&&(this.min=e instanceof PageArea||e instanceof PageSet?0:1);""===this.max&&(this.max=""===t?e instanceof PageArea||e instanceof PageSet?-1:1:this.min);-1!==this.max&&this.max<this.min&&(this.max=this.min);""===this.initial&&(this.initial=e instanceof Template?1:this.min)}}class Oid extends StringObject{constructor(e){super(Mo,"oid");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Oids extends XFAObject{constructor(e){super(Mo,"oids",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.oid=new XFAObjectArray}}class Overflow extends XFAObject{constructor(e){super(Mo,"overflow");this.id=e.id||"";this.leader=e.leader||"";this.target=e.target||"";this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||""}[oi](){if(!this[Jr]){const e=this[mi](),t=this[pi](),n=t[Xi](this.target,e),a=t[Xi](this.leader,e),s=t[Xi](this.trailer,e);this[Jr]={target:n?.[0]||null,leader:a?.[0]||null,trailer:s?.[0]||null,addLeader:!1,addTrailer:!1}}return this[Jr]}}class PageArea extends XFAObject{constructor(e){super(Mo,"pageArea",!0);this.blankOrNotBlank=getStringOption(e.blankOrNotBlank,["any","blank","notBlank"]);this.id=e.id||"";this.initialNumber=getInteger({data:e.initialNumber,defaultValue:1,validate:e=>!0});this.name=e.name||"";this.numbered=getInteger({data:e.numbered,defaultValue:1,validate:e=>!0});this.oddOrEven=getStringOption(e.oddOrEven,["any","even","odd"]);this.pagePosition=getStringOption(e.pagePosition,["any","first","last","only","rest"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.desc=null;this.extras=null;this.medium=null;this.occur=null;this.area=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.draw=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray}[Ii](){if(!this[Jr]){this[Jr]={numberOfUse:0};return!0}return!this.occur||-1===this.occur.max||this[Jr].numberOfUse<this.occur.max}[Xr](){delete this[Jr]}[hi](){this[Jr]||={numberOfUse:0};const e=this[mi]();if("orderedOccurrence"===e.relation&&this[Ii]()){this[Jr].numberOfUse+=1;return this}return e[hi]()}[ni](){return this[Jr].space||{width:0,height:0}}[Ji](){this[Jr]||={numberOfUse:1};const e=[];this[Jr].children=e;const t=Object.create(null);if(this.medium&&this.medium.short&&this.medium.long){t.width=measureToString(this.medium.short);t.height=measureToString(this.medium.long);this[Jr].space={width:this.medium.short,height:this.medium.long};if("landscape"===this.medium.orientation){const e=t.width;t.width=t.height;t.height=e;this[Jr].space={width:this.medium.long,height:this.medium.short}}}else warn("XFA - No medium specified in pageArea: please file a bug.");this[Ur]({filter:new Set(["area","draw","field","subform"]),include:!0});this[Ur]({filter:new Set(["contentArea"]),include:!0});return HTMLResult.success({name:"div",children:e,attributes:{class:["xfaPage"],id:this[eo],style:t,xfaName:this.name}})}}class PageSet extends XFAObject{constructor(e){super(Mo,"pageSet",!0);this.duplexImposition=getStringOption(e.duplexImposition,["longEdge","shortEdge"]);this.id=e.id||"";this.name=e.name||"";this.relation=getStringOption(e.relation,["orderedOccurrence","duplexPaginated","simplexPaginated"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.occur=null;this.pageArea=new XFAObjectArray;this.pageSet=new XFAObjectArray}[Xr](){for(const e of this.pageArea.children)e[Xr]();for(const e of this.pageSet.children)e[Xr]()}[Ii](){return!this.occur||-1===this.occur.max||this[Jr].numberOfUse<this.occur.max}[hi](){this[Jr]||={numberOfUse:1,pageIndex:-1,pageSetIndex:-1};if("orderedOccurrence"===this.relation){if(this[Jr].pageIndex+1<this.pageArea.children.length){this[Jr].pageIndex+=1;return this.pageArea.children[this[Jr].pageIndex][hi]()}if(this[Jr].pageSetIndex+1<this.pageSet.children.length){this[Jr].pageSetIndex+=1;return this.pageSet.children[this[Jr].pageSetIndex][hi]()}if(this[Ii]()){this[Jr].numberOfUse+=1;this[Jr].pageIndex=-1;this[Jr].pageSetIndex=-1;return this[hi]()}const e=this[mi]();if(e instanceof PageSet)return e[hi]();this[Xr]();return this[hi]()}const e=this[pi]()[Jr].pageNumber,t=e%2==0?"even":"odd",n=0===e?"first":"rest";let a=this.pageArea.children.find(e=>e.oddOrEven===t&&e.pagePosition===n);if(a)return a;a=this.pageArea.children.find(e=>"any"===e.oddOrEven&&e.pagePosition===n);if(a)return a;a=this.pageArea.children.find(e=>"any"===e.oddOrEven&&"any"===e.pagePosition);return a||this.pageArea.children[0]}}class Para extends XFAObject{constructor(e){super(Mo,"para",!0);this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.lineHeight=e.lineHeight?getMeasurement(e.lineHeight,"0pt"):"";this.marginLeft=e.marginLeft?getMeasurement(e.marginLeft,"0pt"):"";this.marginRight=e.marginRight?getMeasurement(e.marginRight,"0pt"):"";this.orphans=getInteger({data:e.orphans,defaultValue:0,validate:e=>e>=0});this.preserve=e.preserve||"";this.radixOffset=e.radixOffset?getMeasurement(e.radixOffset,"0pt"):"";this.spaceAbove=e.spaceAbove?getMeasurement(e.spaceAbove,"0pt"):"";this.spaceBelow=e.spaceBelow?getMeasurement(e.spaceBelow,"0pt"):"";this.tabDefault=e.tabDefault?getMeasurement(this.tabDefault):"";this.tabStops=(e.tabStops||"").trim().split(/\s+/).map((e,t)=>t%2==1?getMeasurement(e):e);this.textIndent=e.textIndent?getMeasurement(e.textIndent,"0pt"):"";this.use=e.use||"";this.usehref=e.usehref||"";this.vAlign=getStringOption(e.vAlign,["top","bottom","middle"]);this.widows=getInteger({data:e.widows,defaultValue:0,validate:e=>e>=0});this.hyphenation=null}[Zi](){const e=toStyle(this,"hAlign");""!==this.marginLeft&&(e.paddingLeft=measureToString(this.marginLeft));""!==this.marginRight&&(e.paddingRight=measureToString(this.marginRight));""!==this.spaceAbove&&(e.paddingTop=measureToString(this.spaceAbove));""!==this.spaceBelow&&(e.paddingBottom=measureToString(this.spaceBelow));if(""!==this.textIndent){e.textIndent=measureToString(this.textIndent);fixTextIndent(e)}this.lineHeight>0&&(e.lineHeight=measureToString(this.lineHeight));""!==this.tabDefault&&(e.tabSize=measureToString(this.tabDefault));this.tabStops.length;this.hyphenatation&&Object.assign(e,this.hyphenatation[Zi]());return e}}class PasswordEdit extends XFAObject{constructor(e){super(Mo,"passwordEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.passwordChar=e.passwordChar||"*";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}}class template_Pattern extends XFAObject{constructor(e){super(Mo,"pattern",!0);this.id=e.id||"";this.type=getStringOption(e.type,["crossHatch","crossDiagonal","diagonalLeft","diagonalRight","horizontal","vertical"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zi](e){e=e?e[Zi]():"#FFFFFF";const t=this.color?this.color[Zi]():"#000000",n="repeating-linear-gradient",a=`${e},${e} 5px,${t} 5px,${t} 10px`;switch(this.type){case"crossHatch":return`${n}(to top,${a}) ${n}(to right,${a})`;case"crossDiagonal":return`${n}(45deg,${a}) ${n}(-45deg,${a})`;case"diagonalLeft":return`${n}(45deg,${a})`;case"diagonalRight":return`${n}(-45deg,${a})`;case"horizontal":return`${n}(to top,${a})`;case"vertical":return`${n}(to right,${a})`}return""}}class Picture extends StringObject{constructor(e){super(Mo,"picture");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Proto extends XFAObject{constructor(e){super(Mo,"proto",!0);this.appearanceFilter=new XFAObjectArray;this.arc=new XFAObjectArray;this.area=new XFAObjectArray;this.assist=new XFAObjectArray;this.barcode=new XFAObjectArray;this.bindItems=new XFAObjectArray;this.bookend=new XFAObjectArray;this.boolean=new XFAObjectArray;this.border=new XFAObjectArray;this.break=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.button=new XFAObjectArray;this.calculate=new XFAObjectArray;this.caption=new XFAObjectArray;this.certificate=new XFAObjectArray;this.certificates=new XFAObjectArray;this.checkButton=new XFAObjectArray;this.choiceList=new XFAObjectArray;this.color=new XFAObjectArray;this.comb=new XFAObjectArray;this.connect=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.corner=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.dateTimeEdit=new XFAObjectArray;this.decimal=new XFAObjectArray;this.defaultUi=new XFAObjectArray;this.desc=new XFAObjectArray;this.digestMethod=new XFAObjectArray;this.digestMethods=new XFAObjectArray;this.draw=new XFAObjectArray;this.edge=new XFAObjectArray;this.encoding=new XFAObjectArray;this.encodings=new XFAObjectArray;this.encrypt=new XFAObjectArray;this.encryptData=new XFAObjectArray;this.encryption=new XFAObjectArray;this.encryptionMethod=new XFAObjectArray;this.encryptionMethods=new XFAObjectArray;this.event=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.execute=new XFAObjectArray;this.extras=new XFAObjectArray;this.field=new XFAObjectArray;this.fill=new XFAObjectArray;this.filter=new XFAObjectArray;this.float=new XFAObjectArray;this.font=new XFAObjectArray;this.format=new XFAObjectArray;this.handler=new XFAObjectArray;this.hyphenation=new XFAObjectArray;this.image=new XFAObjectArray;this.imageEdit=new XFAObjectArray;this.integer=new XFAObjectArray;this.issuers=new XFAObjectArray;this.items=new XFAObjectArray;this.keep=new XFAObjectArray;this.keyUsage=new XFAObjectArray;this.line=new XFAObjectArray;this.linear=new XFAObjectArray;this.lockDocument=new XFAObjectArray;this.manifest=new XFAObjectArray;this.margin=new XFAObjectArray;this.mdp=new XFAObjectArray;this.medium=new XFAObjectArray;this.message=new XFAObjectArray;this.numericEdit=new XFAObjectArray;this.occur=new XFAObjectArray;this.oid=new XFAObjectArray;this.oids=new XFAObjectArray;this.overflow=new XFAObjectArray;this.pageArea=new XFAObjectArray;this.pageSet=new XFAObjectArray;this.para=new XFAObjectArray;this.passwordEdit=new XFAObjectArray;this.pattern=new XFAObjectArray;this.picture=new XFAObjectArray;this.radial=new XFAObjectArray;this.reason=new XFAObjectArray;this.reasons=new XFAObjectArray;this.rectangle=new XFAObjectArray;this.ref=new XFAObjectArray;this.script=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.signData=new XFAObjectArray;this.signature=new XFAObjectArray;this.signing=new XFAObjectArray;this.solid=new XFAObjectArray;this.speak=new XFAObjectArray;this.stipple=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray;this.subjectDN=new XFAObjectArray;this.subjectDNs=new XFAObjectArray;this.submit=new XFAObjectArray;this.text=new XFAObjectArray;this.textEdit=new XFAObjectArray;this.time=new XFAObjectArray;this.timeStamp=new XFAObjectArray;this.toolTip=new XFAObjectArray;this.traversal=new XFAObjectArray;this.traverse=new XFAObjectArray;this.ui=new XFAObjectArray;this.validate=new XFAObjectArray;this.value=new XFAObjectArray;this.variables=new XFAObjectArray}}class Radial extends XFAObject{constructor(e){super(Mo,"radial",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toEdge","toCenter"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zi](e){e=e?e[Zi]():"#FFFFFF";const t=this.color?this.color[Zi]():"#000000";return`radial-gradient(circle at center, ${"toEdge"===this.type?`${e},${t}`:`${t},${e}`})`}}class Reason extends StringObject{constructor(e){super(Mo,"reason");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Reasons extends XFAObject{constructor(e){super(Mo,"reasons",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.reason=new XFAObjectArray}}class Rectangle extends XFAObject{constructor(e){super(Mo,"rectangle",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.fill=null}[Ji](){const e=this.edge.children.length?this.edge.children[0]:new Edge({}),t=e[Zi](),n=Object.create(null);"visible"===this.fill?.presence?Object.assign(n,this.fill[Zi]()):n.fill="transparent";n.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);n.stroke=t.color;const a=(this.corner.children.length?this.corner.children[0]:new Corner({}))[Zi](),s={name:"svg",children:[{name:"rect",attributes:{xmlns:Po,width:"100%",height:"100%",x:0,y:0,rx:a.radius,ry:a.radius,style:n}}],attributes:{xmlns:Po,style:{overflow:"visible"},width:"100%",height:"100%"}};if(hasMargin(this[mi]()[mi]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[s]});s.attributes.style.position="absolute";return HTMLResult.success(s)}}class RefElement extends StringObject{constructor(e){super(Mo,"ref");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Script extends StringObject{constructor(e){super(Mo,"script");this.binding=e.binding||"";this.contentType=e.contentType||"";this.id=e.id||"";this.name=e.name||"";this.runAt=getStringOption(e.runAt,["client","both","server"]);this.use=e.use||"";this.usehref=e.usehref||""}}class SetProperty extends XFAObject{constructor(e){super(Mo,"setProperty");this.connection=e.connection||"";this.ref=e.ref||"";this.target=e.target||""}}class SignData extends XFAObject{constructor(e){super(Mo,"signData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["sign","clear","verify"]);this.ref=e.ref||"";this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Signature extends XFAObject{constructor(e){super(Mo,"signature",!0);this.id=e.id||"";this.type=getStringOption(e.type,["PDF1.3","PDF1.6"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.filter=null;this.manifest=null;this.margin=null}}class Signing extends XFAObject{constructor(e){super(Mo,"signing",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Solid extends XFAObject{constructor(e){super(Mo,"solid",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Zi](e){return e?e[Zi]():"#FFFFFF"}}class Speak extends StringObject{constructor(e){super(Mo,"speak");this.disable=getInteger({data:e.disable,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.priority=getStringOption(e.priority,["custom","caption","name","toolTip"]);this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Stipple extends XFAObject{constructor(e){super(Mo,"stipple",!0);this.id=e.id||"";this.rate=getInteger({data:e.rate,defaultValue:50,validate:e=>e>=0&&e<=100});this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Zi](e){const t=this.rate/100;return Util.makeHexColor(Math.round(e.value.r*(1-t)+this.value.r*t),Math.round(e.value.g*(1-t)+this.value.g*t),Math.round(e.value.b*(1-t)+this.value.b*t))}}class Subform extends XFAObject{constructor(e){super(Mo,"subform",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.allowMacro=getInteger({data:e.allowMacro,defaultValue:0,validate:e=>1===e});this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.columnWidths=(e.columnWidths||"").trim().split(/\s+/).map(e=>"-1"===e?-1:getMeasurement(e));this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.mergeMode=getStringOption(e.mergeMode,["consumeData","matchTemplate"]);this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.restoreState=getStringOption(e.restoreState,["manual","auto"]);this.scope=getStringOption(e.scope,["name","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.bookend=null;this.border=null;this.break=null;this.calculate=null;this.desc=null;this.extras=null;this.keep=null;this.margin=null;this.occur=null;this.overflow=null;this.pageSet=null;this.para=null;this.traversal=null;this.validate=null;this.variables=null;this.area=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.connect=new XFAObjectArray;this.draw=new XFAObjectArray;this.event=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.proto=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}[ui](){const e=this[mi]();return e instanceof SubformSet?e[ui]():e}[yi](){return!0}[Ai](){return this.layout.endsWith("-tb")&&0===this[Jr].attempt&&this[Jr].numberInLine>0||this[mi]()[Ai]()}*[ci](){yield*getContainedChildren(this)}[Zr](){return flushHTML(this)}[zr](e,t){addHTML(this,e,t)}[ni](){return getAvailableSpace(this)}[xi](){const e=this[ui]();if(!e[xi]())return!1;if(void 0!==this[Jr]._isSplittable)return this[Jr]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Jr]._isSplittable=!1;return!1}if(this.keep&&"none"!==this.keep.intact){this[Jr]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Jr].numberInLine)return!1;this[Jr]._isSplittable=!0;return!0}[Ji](e){setTabIndex(this);if(this.break){if("auto"!==this.break.after||""!==this.break.afterTarget){const e=new BreakAfter({targetType:this.break.after,target:this.break.afterTarget,startNew:this.break.startNew.toString()});e[di]=this[di];this[Lr](e);this.breakAfter.push(e)}if("auto"!==this.break.before||""!==this.break.beforeTarget){const e=new BreakBefore({targetType:this.break.before,target:this.break.beforeTarget,startNew:this.break.startNew.toString()});e[di]=this[di];this[Lr](e);this.breakBefore.push(e)}if(""!==this.break.overflowTarget){const e=new Overflow({target:this.break.overflowTarget,leader:this.break.overflowLeader,trailer:this.break.overflowTrailer});e[di]=this[di];this[Lr](e);this.overflow.push(e)}this[Ni](this.break);this.break=null}if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;(this.breakBefore.children.length>1||this.breakAfter.children.length>1)&&warn("XFA - Several breakBefore or breakAfter in subforms: please file a bug.");if(this.breakBefore.children.length>=1){const e=this.breakBefore.children[0];if(handleBreak(e))return HTMLResult.breakNode(e)}if(this[Jr]?.afterBreakAfter)return HTMLResult.EMPTY;fixDimensions(this);const t=[],n={id:this[eo],class:[]};setAccess(this,n.class);this[Jr]||=Object.create(null);Object.assign(this[Jr],{children:t,line:null,attributes:n,attempt:0,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const a=this[pi](),s=a[Jr].noLayoutFailure,r=this[xi]();r||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const i=new Set(["area","draw","exclGroup","field","subform","subformSet"]);if(this.layout.includes("row")){const e=this[ui]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Jr].columnWidths=e;this[Jr].currentColumn=0}}const o=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),l=["xfaSubform"],f=layoutClass(this);f&&l.push(f);n.style=o;n.class=l;this.name&&(n.xfaName=this.name);if(this.overflow){const t=this.overflow[oi]();if(t.addLeader){t.addLeader=!1;handleOverflow(this,t.leader,e)}}this[Ei]();const c="lr-tb"===this.layout||"rl-tb"===this.layout,h=c?2:1;for(;this[Jr].attempt<h;this[Jr].attempt++){c&&1===this[Jr].attempt&&(this[Jr].numberInLine=0);const e=this[Ur]({filter:i,include:!0});if(e.success)break;if(e.isBreak()){this[Pi]();return e}if(c&&0===this[Jr].attempt&&0===this[Jr].numberInLine&&!a[Jr].noLayoutFailure){this[Jr].attempt=h;break}}this[Pi]();r||unsetFirstUnsplittable(this);a[Jr].noLayoutFailure=s;if(this[Jr].attempt===h){this.overflow&&(this[pi]()[Jr].overflowNode=this.overflow);r||delete this[Jr];return HTMLResult.FAILURE}if(this.overflow){const t=this.overflow[oi]();if(t.addTrailer){t.addTrailer=!1;handleOverflow(this,t.trailer,e)}}let u=0,m=0;if(this.margin){u=this.margin.leftInset+this.margin.rightInset;m=this.margin.topInset+this.margin.bottomInset}const p=Math.max(this[Jr].width+u,this.w||0),d=Math.max(this[Jr].height+m,this.h||0),g=[this.x,this.y,p,d];""===this.w&&(o.width=measureToString(p));""===this.h&&(o.height=measureToString(d));if(("0px"===o.width||"0px"===o.height)&&0===t.length)return HTMLResult.EMPTY;const b={name:"div",attributes:n,children:t};applyAssist(this,n);const w=HTMLResult.success(createWrapper(this,b),g);if(this.breakAfter.children.length>=1){const e=this.breakAfter.children[0];if(handleBreak(e)){this[Jr].afterBreakAfter=w;return HTMLResult.breakNode(e)}}delete this[Jr];return w}}class SubformSet extends XFAObject{constructor(e){super(Mo,"subformSet",!0);this.id=e.id||"";this.name=e.name||"";this.relation=getStringOption(e.relation,["ordered","choice","unordered"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.bookend=null;this.break=null;this.desc=null;this.extras=null;this.occur=null;this.overflow=null;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[ci](){yield*getContainedChildren(this)}[ui](){let e=this[mi]();for(;!(e instanceof Subform);)e=e[mi]();return e}[yi](){return!0}}class SubjectDN extends ContentObject{constructor(e){super(Mo,"subjectDN");this.delimiter=e.delimiter||",";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Qr](){this[Vr]=new Map(this[Vr].split(this.delimiter).map(e=>{(e=e.split("=",2))[0]=e[0].trim();return e}))}}class SubjectDNs extends XFAObject{constructor(e){super(Mo,"subjectDNs",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.subjectDN=new XFAObjectArray}}class Submit extends XFAObject{constructor(e){super(Mo,"submit",!0);this.embedPDF=getInteger({data:e.embedPDF,defaultValue:0,validate:e=>1===e});this.format=getStringOption(e.format,["xdp","formdata","pdf","urlencoded","xfd","xml"]);this.id=e.id||"";this.target=e.target||"";this.textEncoding=getKeyword({data:e.textEncoding?e.textEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.use=e.use||"";this.usehref=e.usehref||"";this.xdpContent=e.xdpContent||"";this.encrypt=null;this.encryptData=new XFAObjectArray;this.signData=new XFAObjectArray}}class Template extends XFAObject{constructor(e){super(Mo,"template",!0);this.baseProfile=getStringOption(e.baseProfile,["full","interactiveForms"]);this.extras=null;this.subform=new XFAObjectArray}[Qr](){0===this.subform.children.length&&warn("XFA - No subforms in template node.");this.subform.children.length>=2&&warn("XFA - Several subforms in template node: please file a bug.");this[Vi]=5e3}[xi](){return!0}[Xi](e,t){return e.startsWith("#")?[this[bi].get(e.slice(1))]:searchNode(this,t,e,!0,!0)}*[Yi](){if(!this.subform.children.length)return HTMLResult.success({name:"div",children:[]});this[Jr]={overflowNode:null,firstUnsplittable:null,currentContentArea:null,currentPageArea:null,noLayoutFailure:!1,pageNumber:1,pagePosition:"first",oddOrEven:"odd",blankOrNotBlank:"nonBlank",paraStack:[]};const e=this.subform.children[0];e.pageSet[Xr]();const t=e.pageSet.pageArea.children,n={name:"div",children:[]};let a=null,s=null,r=null;if(e.breakBefore.children.length>=1){s=e.breakBefore.children[0];r=s.target}else if(e.subform.children.length>=1&&e.subform.children[0].breakBefore.children.length>=1){s=e.subform.children[0].breakBefore.children[0];r=s.target}else if(e.break?.beforeTarget){s=e.break;r=s.beforeTarget}else if(e.subform.children.length>=1&&e.subform.children[0].break?.beforeTarget){s=e.subform.children[0].break;r=s.beforeTarget}if(s){const e=this[Xi](r,s[mi]());if(e instanceof PageArea){a=e;s[Jr]={}}}a||=t[0];a[Jr]={numberOfUse:1};const i=a[mi]();i[Jr]={numberOfUse:1,pageIndex:i.pageArea.children.indexOf(a),pageSetIndex:0};let o,l=null,f=null,c=!0,h=0,u=0;for(;;){if(c)h=0;else{n.children.pop();if(3===++h){warn("XFA - Something goes wrong: please file a bug.");return n}}o=null;this[Jr].currentPageArea=a;const t=a[Ji]().html;n.children.push(t);if(l){this[Jr].noLayoutFailure=!0;t.children.push(l[Ji](a[Jr].space).html);l=null}if(f){this[Jr].noLayoutFailure=!0;t.children.push(f[Ji](a[Jr].space).html);f=null}const s=a.contentArea.children,r=t.children.filter(e=>e.attributes.class.includes("xfaContentarea"));c=!1;this[Jr].firstUnsplittable=null;this[Jr].noLayoutFailure=!1;const flush=t=>{const n=e[Zr]();if(n){c||=n.children?.length>0;r[t].children.push(n)}};for(let t=u,a=s.length;t<a;t++){const a=this[Jr].currentContentArea=s[t],i={width:a.w,height:a.h};u=0;if(l){r[t].children.push(l[Ji](i).html);l=null}if(f){r[t].children.push(f[Ji](i).html);f=null}const h=e[Ji](i);if(h.success){if(h.html){c||=h.html.children?.length>0;r[t].children.push(h.html)}else!c&&n.children.length>1&&n.children.pop();return n}if(h.isBreak()){const e=h.breakNode;flush(t);if("auto"===e.targetType)continue;if(e.leader){l=this[Xi](e.leader,e[mi]());l=l?l[0]:null}if(e.trailer){f=this[Xi](e.trailer,e[mi]());f=f?f[0]:null}if("pageArea"===e.targetType){o=e[Jr].target;t=1/0}else if(e[Jr].target){o=e[Jr].target;u=e[Jr].index+1;t=1/0}else t=e[Jr].index;continue}if(this[Jr].overflowNode){const e=this[Jr].overflowNode;this[Jr].overflowNode=null;const n=e[oi](),a=n.target;n.addLeader=null!==n.leader;n.addTrailer=null!==n.trailer;flush(t);const r=t;t=1/0;if(a instanceof PageArea)o=a;else if(a instanceof ContentArea){const e=s.indexOf(a);if(-1!==e)e>r?t=e-1:u=e;else{o=a[mi]();u=o.contentArea.children.indexOf(a)}}continue}flush(t)}this[Jr].pageNumber+=1;o&&(o[Ii]()?o[Jr].numberOfUse+=1:o=null);a=o||a[hi]();yield null}}}class Text extends ContentObject{constructor(e){super(Mo,"text");this.id=e.id||"";this.maxChars=getInteger({data:e.maxChars,defaultValue:0,validate:e=>e>=0});this.name=e.name||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}[Nr](){return!0}[Bi](e){if(e[Ti]===no.xhtml.id){this[Vr]=e;return!0}warn(`XFA - Invalid content in Text: ${e[Hi]}.`);return!1}[Di](e){this[Vr]instanceof XFAObject||super[Di](e)}[Qr](){"string"==typeof this[Vr]&&(this[Vr]=this[Vr].replaceAll("\r\n","\n"))}[oi](){return"string"==typeof this[Vr]?this[Vr].split(/[\u2029\u2028\n]/).filter(e=>!!e).join("\n"):this[Vr][$i]()}[Ji](e){if("string"==typeof this[Vr]){const e=valueToHtml(this[Vr]).html;if(this[Vr].includes("\u2029")){e.name="div";e.children=[];this[Vr].split("\u2029").map(e=>e.split(/[\u2028\n]/).flatMap(e=>[{name:"span",value:e},{name:"br"}])).forEach(t=>{e.children.push({name:"p",children:t})})}else if(/[\u2028\n]/.test(this[Vr])){e.name="div";e.children=[];this[Vr].split(/[\u2028\n]/).forEach(t=>{e.children.push({name:"span",value:t},{name:"br"})})}return HTMLResult.success(e)}return this[Vr][Ji](e)}}class TextEdit extends XFAObject{constructor(e){super(Mo,"textEdit",!0);this.allowRichText=getInteger({data:e.allowRichText,defaultValue:0,validate:e=>1===e});this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.multiLine=getInteger({data:e.multiLine,defaultValue:"",validate:e=>0===e||1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.vScrollPolicy=getStringOption(e.vScrollPolicy,["auto","off","on"]);this.border=null;this.comb=null;this.extras=null;this.margin=null}[Ji](e){const t=toStyle(this,"border","font","margin");let n;const a=this[mi]()[mi]();""===this.multiLine&&(this.multiLine=a instanceof Draw?1:0);n=1===this.multiLine?{name:"textarea",attributes:{dataId:a[$r]?.[eo]||a[eo],fieldId:a[eo],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}}:{name:"input",attributes:{type:"text",dataId:a[$r]?.[eo]||a[eo],fieldId:a[eo],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}};if(isRequired(a)){n.attributes["aria-required"]=!0;n.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[n]})}}class Time extends StringObject{constructor(e){super(Mo,"time");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Qr](){const e=this[Vr].trim();this[Vr]=e?new Date(e):null}[Ji](e){return valueToHtml(this[Vr]?this[Vr].toString():"")}}class TimeStamp extends XFAObject{constructor(e){super(Mo,"timeStamp");this.id=e.id||"";this.server=e.server||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class ToolTip extends StringObject{constructor(e){super(Mo,"toolTip");this.id=e.id||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Traversal extends XFAObject{constructor(e){super(Mo,"traversal",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.traverse=new XFAObjectArray}}class Traverse extends XFAObject{constructor(e){super(Mo,"traverse",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["next","back","down","first","left","right","up"]);this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.script=null}get name(){return this.operation}[Ci](){return!1}}class Ui extends XFAObject{constructor(e){super(Mo,"ui",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null;this.barcode=null;this.button=null;this.checkButton=null;this.choiceList=null;this.dateTimeEdit=null;this.defaultUi=null;this.imageEdit=null;this.numericEdit=null;this.passwordEdit=null;this.signature=null;this.textEdit=null}[oi](){if(void 0===this[Jr]){for(const e of Object.getOwnPropertyNames(this)){if("extras"===e||"picture"===e)continue;const t=this[e];if(t instanceof XFAObject){this[Jr]=t;return t}}this[Jr]=null}return this[Jr]}[Ji](e){const t=this[oi]();return t?t[Ji](e):HTMLResult.EMPTY}}class Validate extends XFAObject{constructor(e){super(Mo,"validate",!0);this.formatTest=getStringOption(e.formatTest,["warning","disabled","error"]);this.id=e.id||"";this.nullTest=getStringOption(e.nullTest,["disabled","error","warning"]);this.scriptTest=getStringOption(e.scriptTest,["error","disabled","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.picture=null;this.script=null}}class Value extends XFAObject{constructor(e){super(Mo,"value",!0);this.id=e.id||"";this.override=getInteger({data:e.override,defaultValue:0,validate:e=>1===e});this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.arc=null;this.boolean=null;this.date=null;this.dateTime=null;this.decimal=null;this.exData=null;this.float=null;this.image=null;this.integer=null;this.line=null;this.rectangle=null;this.text=null;this.time=null}[Gi](e){const t=this[mi]();if(t instanceof Field&&t.ui?.imageEdit){if(!this.image){this.image=new Image({});this[Lr](this.image)}this.image[Vr]=e[Vr];return}const n=e[Hi];if(null===this[n]){for(const e of Object.getOwnPropertyNames(this)){const t=this[e];if(t instanceof XFAObject){this[e]=null;this[Ni](t)}}this[e[Hi]]=e;this[Lr](e)}else this[n][Vr]=e[Vr]}[$i](){if(this.exData)return"string"==typeof this.exData[Vr]?this.exData[Vr].trim():this.exData[Vr][$i]().trim();for(const e of Object.getOwnPropertyNames(this)){if("image"===e)continue;const t=this[e];if(t instanceof XFAObject)return(t[Vr]||"").toString().trim()}return null}[Ji](e){for(const t of Object.getOwnPropertyNames(this)){const n=this[t];if(n instanceof XFAObject)return n[Ji](e)}return HTMLResult.EMPTY}}class Variables extends XFAObject{constructor(e){super(Mo,"variables",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.manifest=new XFAObjectArray;this.script=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[Ci](){return!0}}class TemplateNamespace{static[to](e,t){if(TemplateNamespace.hasOwnProperty(e)){const n=TemplateNamespace[e](t);n[Ki](t);return n}}static appearanceFilter(e){return new AppearanceFilter(e)}static arc(e){return new Arc(e)}static area(e){return new Area(e)}static assist(e){return new Assist(e)}static barcode(e){return new Barcode(e)}static bind(e){return new Bind(e)}static bindItems(e){return new BindItems(e)}static bookend(e){return new Bookend(e)}static boolean(e){return new BooleanElement(e)}static border(e){return new Border(e)}static break(e){return new Break(e)}static breakAfter(e){return new BreakAfter(e)}static breakBefore(e){return new BreakBefore(e)}static button(e){return new Button(e)}static calculate(e){return new Calculate(e)}static caption(e){return new Caption(e)}static certificate(e){return new Certificate(e)}static certificates(e){return new Certificates(e)}static checkButton(e){return new CheckButton(e)}static choiceList(e){return new ChoiceList(e)}static color(e){return new Color(e)}static comb(e){return new Comb(e)}static connect(e){return new Connect(e)}static contentArea(e){return new ContentArea(e)}static corner(e){return new Corner(e)}static date(e){return new DateElement(e)}static dateTime(e){return new DateTime(e)}static dateTimeEdit(e){return new DateTimeEdit(e)}static decimal(e){return new Decimal(e)}static defaultUi(e){return new DefaultUi(e)}static desc(e){return new Desc(e)}static digestMethod(e){return new DigestMethod(e)}static digestMethods(e){return new DigestMethods(e)}static draw(e){return new Draw(e)}static edge(e){return new Edge(e)}static encoding(e){return new Encoding(e)}static encodings(e){return new Encodings(e)}static encrypt(e){return new Encrypt(e)}static encryptData(e){return new EncryptData(e)}static encryption(e){return new Encryption(e)}static encryptionMethod(e){return new EncryptionMethod(e)}static encryptionMethods(e){return new EncryptionMethods(e)}static event(e){return new Event(e)}static exData(e){return new ExData(e)}static exObject(e){return new ExObject(e)}static exclGroup(e){return new ExclGroup(e)}static execute(e){return new Execute(e)}static extras(e){return new Extras(e)}static field(e){return new Field(e)}static fill(e){return new Fill(e)}static filter(e){return new Filter(e)}static float(e){return new Float(e)}static font(e){return new template_Font(e)}static format(e){return new Format(e)}static handler(e){return new Handler(e)}static hyphenation(e){return new Hyphenation(e)}static image(e){return new Image(e)}static imageEdit(e){return new ImageEdit(e)}static integer(e){return new Integer(e)}static issuers(e){return new Issuers(e)}static items(e){return new Items(e)}static keep(e){return new Keep(e)}static keyUsage(e){return new KeyUsage(e)}static line(e){return new Line(e)}static linear(e){return new Linear(e)}static lockDocument(e){return new LockDocument(e)}static manifest(e){return new Manifest(e)}static margin(e){return new Margin(e)}static mdp(e){return new Mdp(e)}static medium(e){return new Medium(e)}static message(e){return new Message(e)}static numericEdit(e){return new NumericEdit(e)}static occur(e){return new Occur(e)}static oid(e){return new Oid(e)}static oids(e){return new Oids(e)}static overflow(e){return new Overflow(e)}static pageArea(e){return new PageArea(e)}static pageSet(e){return new PageSet(e)}static para(e){return new Para(e)}static passwordEdit(e){return new PasswordEdit(e)}static pattern(e){return new template_Pattern(e)}static picture(e){return new Picture(e)}static proto(e){return new Proto(e)}static radial(e){return new Radial(e)}static reason(e){return new Reason(e)}static reasons(e){return new Reasons(e)}static rectangle(e){return new Rectangle(e)}static ref(e){return new RefElement(e)}static script(e){return new Script(e)}static setProperty(e){return new SetProperty(e)}static signData(e){return new SignData(e)}static signature(e){return new Signature(e)}static signing(e){return new Signing(e)}static solid(e){return new Solid(e)}static speak(e){return new Speak(e)}static stipple(e){return new Stipple(e)}static subform(e){return new Subform(e)}static subformSet(e){return new SubformSet(e)}static subjectDN(e){return new SubjectDN(e)}static subjectDNs(e){return new SubjectDNs(e)}static submit(e){return new Submit(e)}static template(e){return new Template(e)}static text(e){return new Text(e)}static textEdit(e){return new TextEdit(e)}static time(e){return new Time(e)}static timeStamp(e){return new TimeStamp(e)}static toolTip(e){return new ToolTip(e)}static traversal(e){return new Traversal(e)}static traverse(e){return new Traverse(e)}static ui(e){return new Ui(e)}static validate(e){return new Validate(e)}static value(e){return new Value(e)}static variables(e){return new Variables(e)}}const Lo=no.datasets.id;function createText(e){const t=new Text({});t[Vr]=e;return t}class Binder{constructor(e){this.root=e;this.datasets=e.datasets;this.data=e.datasets?.data||new XmlObject(no.datasets.id,"data");this.emptyMerge=0===this.data[fi]().length;this.root.form=this.form=e.template[Kr]()}_isConsumeData(){return!this.emptyMerge&&this._mergeMode}_isMatchTemplate(){return!this._isConsumeData()}bind(){this._bindElement(this.form,this.data);return this.form}getData(){return this.data}_bindValue(e,t,n){e[$r]=t;if(e[gi]())if(t[qi]()){const n=t[ii]();e[Gi](createText(n))}else if(e instanceof Field&&"multiSelect"===e.ui?.choiceList?.open){const n=t[fi]().map(e=>e[Vr].trim()).join("\n");e[Gi](createText(n))}else this._isConsumeData()&&warn("XFA - Nodes haven't the same type.");else!t[qi]()||this._isMatchTemplate()?this._bindElement(e,t):warn("XFA - Nodes haven't the same type.")}_findDataByNameToConsume(e,t,n,a){if(!e)return null;let s,r;for(let a=0;a<3;a++){s=n[li](e,!1,!0);for(;;){r=s.next().value;if(!r)break;if(t===r[qi]())return r}if(n[Ti]===no.datasets.id&&"data"===n[Hi])break;n=n[mi]()}if(!a)return null;s=this.data[li](e,!0,!1);r=s.next().value;if(r)return r;s=this.data[ei](e,!0);r=s.next().value;return r?.[qi]()?r:null}_setProperties(e,t){if(e.hasOwnProperty("setProperty"))for(const{ref:n,target:a,connection:s}of e.setProperty.children){if(s)continue;if(!n)continue;const r=searchNode(this.root,t,n,!1,!1);if(!r){warn(`XFA - Invalid reference: ${n}.`);continue}const[i]=r;if(!i[vi](this.data)){warn("XFA - Invalid node: must be a data node.");continue}const o=searchNode(this.root,e,a,!1,!1);if(!o){warn(`XFA - Invalid target: ${a}.`);continue}const[l]=o;if(!l[vi](e)){warn("XFA - Invalid target: must be a property or subproperty.");continue}const f=l[mi]();if(l instanceof SetProperty||f instanceof SetProperty){warn("XFA - Invalid target: cannot be a setProperty or one of its properties.");continue}if(l instanceof BindItems||f instanceof BindItems){warn("XFA - Invalid target: cannot be a bindItems or one of its properties.");continue}const c=i[$i](),h=l[Hi];if(l instanceof XFAAttribute){const e=Object.create(null);e[h]=c;const t=Reflect.construct(Object.getPrototypeOf(f).constructor,[e]);f[h]=t[h];continue}if(l.hasOwnProperty(Vr)){l[$r]=i;l[Vr]=c;l[Qr]()}else warn("XFA - Invalid node to use in setProperty")}}_bindItems(e,t){if(!e.hasOwnProperty("items")||!e.hasOwnProperty("bindItems")||e.bindItems.isEmpty())return;for(const t of e.items.children)e[Ni](t);e.items.clear();const n=new Items({}),a=new Items({});e[Lr](n);e.items.push(n);e[Lr](a);e.items.push(a);for(const{ref:s,labelRef:r,valueRef:i,connection:o}of e.bindItems.children){if(o)continue;if(!s)continue;const e=searchNode(this.root,t,s,!1,!1);if(e)for(const t of e){if(!t[vi](this.datasets)){warn(`XFA - Invalid ref (${s}): must be a datasets child.`);continue}const e=searchNode(this.root,t,r,!0,!1);if(!e){warn(`XFA - Invalid label: ${r}.`);continue}const[o]=e;if(!o[vi](this.datasets)){warn("XFA - Invalid label: must be a datasets child.");continue}const l=searchNode(this.root,t,i,!0,!1);if(!l){warn(`XFA - Invalid value: ${i}.`);continue}const[f]=l;if(!f[vi](this.datasets)){warn("XFA - Invalid value: must be a datasets child.");continue}const c=createText(o[$i]()),h=createText(f[$i]());n[Lr](c);n.text.push(c);a[Lr](h);a.text.push(h)}else warn(`XFA - Invalid reference: ${s}.`)}}_bindOccurrences(e,t,n){let a;if(t.length>1){a=e[Kr]();a[Ni](a.occur);a.occur=null}this._bindValue(e,t[0],n);this._setProperties(e,t[0]);this._bindItems(e,t[0]);if(1===t.length)return;const s=e[mi](),r=e[Hi],i=s[wi](e);for(let e=1,o=t.length;e<o;e++){const o=t[e],l=a[Kr]();s[r].push(l);s[ji](i+e,l);this._bindValue(l,o,n);this._setProperties(l,o);this._bindItems(l,o)}}_createOccurrences(e){if(!this.emptyMerge)return;const{occur:t}=e;if(!t||t.initial<=1)return;const n=e[mi](),a=e[Hi];if(!(n[a]instanceof XFAObjectArray))return;let s;s=e.name?n[a].children.filter(t=>t.name===e.name).length:n[a].children.length;const r=n[wi](e)+1,i=t.initial-s;if(i){const t=e[Kr]();t[Ni](t.occur);t.occur=null;n[a].push(t);n[ji](r,t);for(let e=1;e<i;e++){const s=t[Kr]();n[a].push(s);n[ji](r+e,s)}}}_getOccurInfo(e){const{name:t,occur:n}=e;if(!n||!t)return[1,1];const a=-1===n.max?1/0:n.max;return[n.min,a]}_setAndBind(e,t){this._setProperties(e,t);this._bindItems(e,t);this._bindElement(e,t)}_bindElement(e,t){const n=[];this._createOccurrences(e);for(const a of e[fi]()){if(a[$r])continue;if(void 0===this._mergeMode&&"subform"===a[Hi]){this._mergeMode="consumeData"===a.mergeMode;const e=t[fi]();if(e.length>0)this._bindOccurrences(a,[e[0]],null);else if(this.emptyMerge){const e=t[Ti]===Lo?-1:t[Ti],n=a[$r]=new XmlObject(e,a.name||"root");t[Lr](n);this._bindElement(a,n)}continue}if(!a[yi]())continue;let e=!1,s=null,r=null,i=null;if(a.bind){switch(a.bind.match){case"none":this._setAndBind(a,t);continue;case"global":e=!0;break;case"dataRef":if(!a.bind.ref){warn(`XFA - ref is empty in node ${a[Hi]}.`);this._setAndBind(a,t);continue}r=a.bind.ref}a.bind.picture&&(s=a.bind.picture[Vr])}const[o,l]=this._getOccurInfo(a);if(r){i=searchNode(this.root,t,r,!0,!1);if(null===i){i=createDataNode(this.data,t,r);if(!i)continue;this._isConsumeData()&&(i[Gr]=!0);this._setAndBind(a,i);continue}this._isConsumeData()&&(i=i.filter(e=>!e[Gr]));i.length>l?i=i.slice(0,l):0===i.length&&(i=null);i&&this._isConsumeData()&&i.forEach(e=>{e[Gr]=!0})}else{if(!a.name){this._setAndBind(a,t);continue}if(this._isConsumeData()){const n=[];for(;n.length<l;){const s=this._findDataByNameToConsume(a.name,a[gi](),t,e);if(!s)break;s[Gr]=!0;n.push(s)}i=n.length>0?n:null}else{i=t[li](a.name,!1,this.emptyMerge).next().value;if(!i){if(0===o){n.push(a);continue}const e=t[Ti]===Lo?-1:t[Ti];i=a[$r]=new XmlObject(e,a.name);this.emptyMerge&&(i[Gr]=!0);t[Lr](i);this._setAndBind(a,i);continue}this.emptyMerge&&(i[Gr]=!0);i=[i]}}i?this._bindOccurrences(a,i,s):o>0?this._setAndBind(a,t):n.push(a)}n.forEach(e=>e[mi]()[Ni](e))}}class DataHandler{constructor(e,t){this.data=t;this.dataset=e.datasets||null}serialize(e){const t=[[-1,this.data[fi]()]];for(;t.length>0;){const n=t.at(-1),[a,s]=n;if(a+1===s.length){t.pop();continue}const r=s[++n[0]],i=e.get(r[eo]);if(i)r[Gi](i);else{const t=r[ti]();for(const n of t.values()){const t=e.get(n[eo]);if(t){n[Gi](t);break}}}const o=r[fi]();o.length>0&&t.push([-1,o])}const n=['<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">'];if(this.dataset)for(const e of this.dataset[fi]())"data"!==e[Hi]&&e[Qi](n);this.data[Qi](n);n.push("</xfa:datasets>");return n.join("")}}const Uo=no.config.id;class Acrobat extends XFAObject{constructor(e){super(Uo,"acrobat",!0);this.acrobat7=null;this.autoSave=null;this.common=null;this.validate=null;this.validateApprovalSignatures=null;this.submitUrl=new XFAObjectArray}}class Acrobat7 extends XFAObject{constructor(e){super(Uo,"acrobat7",!0);this.dynamicRender=null}}class ADBE_JSConsole extends OptionObject{constructor(e){super(Uo,"ADBE_JSConsole",["delegate","Enable","Disable"])}}class ADBE_JSDebugger extends OptionObject{constructor(e){super(Uo,"ADBE_JSDebugger",["delegate","Enable","Disable"])}}class AddSilentPrint extends Option01{constructor(e){super(Uo,"addSilentPrint")}}class AddViewerPreferences extends Option01{constructor(e){super(Uo,"addViewerPreferences")}}class AdjustData extends Option10{constructor(e){super(Uo,"adjustData")}}class AdobeExtensionLevel extends IntegerObject{constructor(e){super(Uo,"adobeExtensionLevel",0,e=>e>=1&&e<=8)}}class Agent extends XFAObject{constructor(e){super(Uo,"agent",!0);this.name=e.name?e.name.trim():"";this.common=new XFAObjectArray}}class AlwaysEmbed extends ContentObject{constructor(e){super(Uo,"alwaysEmbed")}}class Amd extends StringObject{constructor(e){super(Uo,"amd")}}class config_Area extends XFAObject{constructor(e){super(Uo,"area");this.level=getInteger({data:e.level,defaultValue:0,validate:e=>e>=1&&e<=3});this.name=getStringOption(e.name,["","barcode","coreinit","deviceDriver","font","general","layout","merge","script","signature","sourceSet","templateCache"])}}class Attributes extends OptionObject{constructor(e){super(Uo,"attributes",["preserve","delegate","ignore"])}}class AutoSave extends OptionObject{constructor(e){super(Uo,"autoSave",["disabled","enabled"])}}class Base extends StringObject{constructor(e){super(Uo,"base")}}class BatchOutput extends XFAObject{constructor(e){super(Uo,"batchOutput");this.format=getStringOption(e.format,["none","concat","zip","zipCompress"])}}class BehaviorOverride extends ContentObject{constructor(e){super(Uo,"behaviorOverride")}[Qr](){this[Vr]=new Map(this[Vr].trim().split(/\s+/).filter(e=>e.includes(":")).map(e=>e.split(":",2)))}}class Cache extends XFAObject{constructor(e){super(Uo,"cache",!0);this.templateCache=null}}class Change extends Option01{constructor(e){super(Uo,"change")}}class Common extends XFAObject{constructor(e){super(Uo,"common",!0);this.data=null;this.locale=null;this.localeSet=null;this.messaging=null;this.suppressBanner=null;this.template=null;this.validationMessaging=null;this.versionControl=null;this.log=new XFAObjectArray}}class Compress extends XFAObject{constructor(e){super(Uo,"compress");this.scope=getStringOption(e.scope,["imageOnly","document"])}}class CompressLogicalStructure extends Option01{constructor(e){super(Uo,"compressLogicalStructure")}}class CompressObjectStream extends Option10{constructor(e){super(Uo,"compressObjectStream")}}class Compression extends XFAObject{constructor(e){super(Uo,"compression",!0);this.compressLogicalStructure=null;this.compressObjectStream=null;this.level=null;this.type=null}}class Config extends XFAObject{constructor(e){super(Uo,"config",!0);this.acrobat=null;this.present=null;this.trace=null;this.agent=new XFAObjectArray}}class Conformance extends OptionObject{constructor(e){super(Uo,"conformance",["A","B"])}}class ContentCopy extends Option01{constructor(e){super(Uo,"contentCopy")}}class Copies extends IntegerObject{constructor(e){super(Uo,"copies",1,e=>e>=1)}}class Creator extends StringObject{constructor(e){super(Uo,"creator")}}class CurrentPage extends IntegerObject{constructor(e){super(Uo,"currentPage",0,e=>e>=0)}}class Data extends XFAObject{constructor(e){super(Uo,"data",!0);this.adjustData=null;this.attributes=null;this.incrementalLoad=null;this.outputXSL=null;this.range=null;this.record=null;this.startNode=null;this.uri=null;this.window=null;this.xsl=null;this.excludeNS=new XFAObjectArray;this.transform=new XFAObjectArray}}class Debug extends XFAObject{constructor(e){super(Uo,"debug",!0);this.uri=null}}class DefaultTypeface extends ContentObject{constructor(e){super(Uo,"defaultTypeface");this.writingScript=getStringOption(e.writingScript,["*","Arabic","Cyrillic","EastEuropeanRoman","Greek","Hebrew","Japanese","Korean","Roman","SimplifiedChinese","Thai","TraditionalChinese","Vietnamese"])}}class Destination extends OptionObject{constructor(e){super(Uo,"destination",["pdf","pcl","ps","webClient","zpl"])}}class DocumentAssembly extends Option01{constructor(e){super(Uo,"documentAssembly")}}class Driver extends XFAObject{constructor(e){super(Uo,"driver",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class DuplexOption extends OptionObject{constructor(e){super(Uo,"duplexOption",["simplex","duplexFlipLongEdge","duplexFlipShortEdge"])}}class DynamicRender extends OptionObject{constructor(e){super(Uo,"dynamicRender",["forbidden","required"])}}class Embed extends Option01{constructor(e){super(Uo,"embed")}}class config_Encrypt extends Option01{constructor(e){super(Uo,"encrypt")}}class config_Encryption extends XFAObject{constructor(e){super(Uo,"encryption",!0);this.encrypt=null;this.encryptionLevel=null;this.permissions=null}}class EncryptionLevel extends OptionObject{constructor(e){super(Uo,"encryptionLevel",["40bit","128bit"])}}class Enforce extends StringObject{constructor(e){super(Uo,"enforce")}}class Equate extends XFAObject{constructor(e){super(Uo,"equate");this.force=getInteger({data:e.force,defaultValue:1,validate:e=>0===e});this.from=e.from||"";this.to=e.to||""}}class EquateRange extends XFAObject{constructor(e){super(Uo,"equateRange");this.from=e.from||"";this.to=e.to||"";this._unicodeRange=e.unicodeRange||""}get unicodeRange(){const e=[],t=/U\+([0-9a-fA-F]+)/,n=this._unicodeRange;for(let a of n.split(",").map(e=>e.trim()).filter(e=>!!e)){a=a.split("-",2).map(e=>{const n=e.match(t);return n?parseInt(n[1],16):0});1===a.length&&a.push(a[0]);e.push(a)}return shadow(this,"unicodeRange",e)}}class Exclude extends ContentObject{constructor(e){super(Uo,"exclude")}[Qr](){this[Vr]=this[Vr].trim().split(/\s+/).filter(e=>e&&["calculate","close","enter","exit","initialize","ready","validate"].includes(e))}}class ExcludeNS extends StringObject{constructor(e){super(Uo,"excludeNS")}}class FlipLabel extends OptionObject{constructor(e){super(Uo,"flipLabel",["usePrinterSetting","on","off"])}}class config_FontInfo extends XFAObject{constructor(e){super(Uo,"fontInfo",!0);this.embed=null;this.map=null;this.subsetBelow=null;this.alwaysEmbed=new XFAObjectArray;this.defaultTypeface=new XFAObjectArray;this.neverEmbed=new XFAObjectArray}}class FormFieldFilling extends Option01{constructor(e){super(Uo,"formFieldFilling")}}class GroupParent extends StringObject{constructor(e){super(Uo,"groupParent")}}class IfEmpty extends OptionObject{constructor(e){super(Uo,"ifEmpty",["dataValue","dataGroup","ignore","remove"])}}class IncludeXDPContent extends StringObject{constructor(e){super(Uo,"includeXDPContent")}}class IncrementalLoad extends OptionObject{constructor(e){super(Uo,"incrementalLoad",["none","forwardOnly"])}}class IncrementalMerge extends Option01{constructor(e){super(Uo,"incrementalMerge")}}class Interactive extends Option01{constructor(e){super(Uo,"interactive")}}class Jog extends OptionObject{constructor(e){super(Uo,"jog",["usePrinterSetting","none","pageSet"])}}class LabelPrinter extends XFAObject{constructor(e){super(Uo,"labelPrinter",!0);this.name=getStringOption(e.name,["zpl","dpl","ipl","tcpl"]);this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class Layout extends OptionObject{constructor(e){super(Uo,"layout",["paginate","panel"])}}class Level extends IntegerObject{constructor(e){super(Uo,"level",0,e=>e>0)}}class Linearized extends Option01{constructor(e){super(Uo,"linearized")}}class Locale extends StringObject{constructor(e){super(Uo,"locale")}}class LocaleSet extends StringObject{constructor(e){super(Uo,"localeSet")}}class Log extends XFAObject{constructor(e){super(Uo,"log",!0);this.mode=null;this.threshold=null;this.to=null;this.uri=null}}class MapElement extends XFAObject{constructor(e){super(Uo,"map",!0);this.equate=new XFAObjectArray;this.equateRange=new XFAObjectArray}}class MediumInfo extends XFAObject{constructor(e){super(Uo,"mediumInfo",!0);this.map=null}}class config_Message extends XFAObject{constructor(e){super(Uo,"message",!0);this.msgId=null;this.severity=null}}class Messaging extends XFAObject{constructor(e){super(Uo,"messaging",!0);this.message=new XFAObjectArray}}class Mode extends OptionObject{constructor(e){super(Uo,"mode",["append","overwrite"])}}class ModifyAnnots extends Option01{constructor(e){super(Uo,"modifyAnnots")}}class MsgId extends IntegerObject{constructor(e){super(Uo,"msgId",1,e=>e>=1)}}class NameAttr extends StringObject{constructor(e){super(Uo,"nameAttr")}}class NeverEmbed extends ContentObject{constructor(e){super(Uo,"neverEmbed")}}class NumberOfCopies extends IntegerObject{constructor(e){super(Uo,"numberOfCopies",null,e=>e>=2&&e<=5)}}class OpenAction extends XFAObject{constructor(e){super(Uo,"openAction",!0);this.destination=null}}class Output extends XFAObject{constructor(e){super(Uo,"output",!0);this.to=null;this.type=null;this.uri=null}}class OutputBin extends StringObject{constructor(e){super(Uo,"outputBin")}}class OutputXSL extends XFAObject{constructor(e){super(Uo,"outputXSL",!0);this.uri=null}}class Overprint extends OptionObject{constructor(e){super(Uo,"overprint",["none","both","draw","field"])}}class Packets extends StringObject{constructor(e){super(Uo,"packets")}[Qr](){"*"!==this[Vr]&&(this[Vr]=this[Vr].trim().split(/\s+/).filter(e=>["config","datasets","template","xfdf","xslt"].includes(e)))}}class PageOffset extends XFAObject{constructor(e){super(Uo,"pageOffset");this.x=getInteger({data:e.x,defaultValue:"useXDCSetting",validate:e=>!0});this.y=getInteger({data:e.y,defaultValue:"useXDCSetting",validate:e=>!0})}}class PageRange extends StringObject{constructor(e){super(Uo,"pageRange")}[Qr](){const e=this[Vr].trim().split(/\s+/).map(e=>parseInt(e,10)),t=[];for(let n=0,a=e.length;n<a;n+=2)t.push(e.slice(n,n+2));this[Vr]=t}}class Pagination extends OptionObject{constructor(e){super(Uo,"pagination",["simplex","duplexShortEdge","duplexLongEdge"])}}class PaginationOverride extends OptionObject{constructor(e){super(Uo,"paginationOverride",["none","forceDuplex","forceDuplexLongEdge","forceDuplexShortEdge","forceSimplex"])}}class Part extends IntegerObject{constructor(e){super(Uo,"part",1,e=>!1)}}class Pcl extends XFAObject{constructor(e){super(Uo,"pcl",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.pageOffset=null;this.staple=null;this.xdc=null}}class Pdf extends XFAObject{constructor(e){super(Uo,"pdf",!0);this.name=e.name||"";this.adobeExtensionLevel=null;this.batchOutput=null;this.compression=null;this.creator=null;this.encryption=null;this.fontInfo=null;this.interactive=null;this.linearized=null;this.openAction=null;this.pdfa=null;this.producer=null;this.renderPolicy=null;this.scriptModel=null;this.silentPrint=null;this.submitFormat=null;this.tagged=null;this.version=null;this.viewerPreferences=null;this.xdc=null}}class Pdfa extends XFAObject{constructor(e){super(Uo,"pdfa",!0);this.amd=null;this.conformance=null;this.includeXDPContent=null;this.part=null}}class Permissions extends XFAObject{constructor(e){super(Uo,"permissions",!0);this.accessibleContent=null;this.change=null;this.contentCopy=null;this.documentAssembly=null;this.formFieldFilling=null;this.modifyAnnots=null;this.plaintextMetadata=null;this.print=null;this.printHighQuality=null}}class PickTrayByPDFSize extends Option01{constructor(e){super(Uo,"pickTrayByPDFSize")}}class config_Picture extends StringObject{constructor(e){super(Uo,"picture")}}class PlaintextMetadata extends Option01{constructor(e){super(Uo,"plaintextMetadata")}}class Presence extends OptionObject{constructor(e){super(Uo,"presence",["preserve","dissolve","dissolveStructure","ignore","remove"])}}class Present extends XFAObject{constructor(e){super(Uo,"present",!0);this.behaviorOverride=null;this.cache=null;this.common=null;this.copies=null;this.destination=null;this.incrementalMerge=null;this.layout=null;this.output=null;this.overprint=null;this.pagination=null;this.paginationOverride=null;this.script=null;this.validate=null;this.xdp=null;this.driver=new XFAObjectArray;this.labelPrinter=new XFAObjectArray;this.pcl=new XFAObjectArray;this.pdf=new XFAObjectArray;this.ps=new XFAObjectArray;this.submitUrl=new XFAObjectArray;this.webClient=new XFAObjectArray;this.zpl=new XFAObjectArray}}class Print extends Option01{constructor(e){super(Uo,"print")}}class PrintHighQuality extends Option01{constructor(e){super(Uo,"printHighQuality")}}class PrintScaling extends OptionObject{constructor(e){super(Uo,"printScaling",["appdefault","noScaling"])}}class PrinterName extends StringObject{constructor(e){super(Uo,"printerName")}}class Producer extends StringObject{constructor(e){super(Uo,"producer")}}class Ps extends XFAObject{constructor(e){super(Uo,"ps",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.staple=null;this.xdc=null}}class Range extends ContentObject{constructor(e){super(Uo,"range")}[Qr](){this[Vr]=this[Vr].split(",",2).map(e=>e.split("-").map(e=>parseInt(e.trim(),10))).filter(e=>e.every(e=>!isNaN(e))).map(e=>{1===e.length&&e.push(e[0]);return e})}}class Record extends ContentObject{constructor(e){super(Uo,"record")}[Qr](){this[Vr]=this[Vr].trim();const e=parseInt(this[Vr],10);!isNaN(e)&&e>=0&&(this[Vr]=e)}}class Relevant extends ContentObject{constructor(e){super(Uo,"relevant")}[Qr](){this[Vr]=this[Vr].trim().split(/\s+/)}}class Rename extends ContentObject{constructor(e){super(Uo,"rename")}[Qr](){this[Vr]=this[Vr].trim();(this[Vr].toLowerCase().startsWith("xml")||new RegExp("[\\p{L}_][\\p{L}\\d._\\p{M}-]*","u").test(this[Vr]))&&warn("XFA - Rename: invalid XFA name")}}class RenderPolicy extends OptionObject{constructor(e){super(Uo,"renderPolicy",["server","client"])}}class RunScripts extends OptionObject{constructor(e){super(Uo,"runScripts",["both","client","none","server"])}}class config_Script extends XFAObject{constructor(e){super(Uo,"script",!0);this.currentPage=null;this.exclude=null;this.runScripts=null}}class ScriptModel extends OptionObject{constructor(e){super(Uo,"scriptModel",["XFA","none"])}}class Severity extends OptionObject{constructor(e){super(Uo,"severity",["ignore","error","information","trace","warning"])}}class SilentPrint extends XFAObject{constructor(e){super(Uo,"silentPrint",!0);this.addSilentPrint=null;this.printerName=null}}class Staple extends XFAObject{constructor(e){super(Uo,"staple");this.mode=getStringOption(e.mode,["usePrinterSetting","on","off"])}}class StartNode extends StringObject{constructor(e){super(Uo,"startNode")}}class StartPage extends IntegerObject{constructor(e){super(Uo,"startPage",0,e=>!0)}}class SubmitFormat extends OptionObject{constructor(e){super(Uo,"submitFormat",["html","delegate","fdf","xml","pdf"])}}class SubmitUrl extends StringObject{constructor(e){super(Uo,"submitUrl")}}class SubsetBelow extends IntegerObject{constructor(e){super(Uo,"subsetBelow",100,e=>e>=0&&e<=100)}}class SuppressBanner extends Option01{constructor(e){super(Uo,"suppressBanner")}}class Tagged extends Option01{constructor(e){super(Uo,"tagged")}}class config_Template extends XFAObject{constructor(e){super(Uo,"template",!0);this.base=null;this.relevant=null;this.startPage=null;this.uri=null;this.xsl=null}}class Threshold extends OptionObject{constructor(e){super(Uo,"threshold",["trace","error","information","warning"])}}class To extends OptionObject{constructor(e){super(Uo,"to",["null","memory","stderr","stdout","system","uri"])}}class TemplateCache extends XFAObject{constructor(e){super(Uo,"templateCache");this.maxEntries=getInteger({data:e.maxEntries,defaultValue:5,validate:e=>e>=0})}}class Trace extends XFAObject{constructor(e){super(Uo,"trace",!0);this.area=new XFAObjectArray}}class Transform extends XFAObject{constructor(e){super(Uo,"transform",!0);this.groupParent=null;this.ifEmpty=null;this.nameAttr=null;this.picture=null;this.presence=null;this.rename=null;this.whitespace=null}}class Type extends OptionObject{constructor(e){super(Uo,"type",["none","ascii85","asciiHex","ccittfax","flate","lzw","runLength","native","xdp","mergedXDP"])}}class Uri extends StringObject{constructor(e){super(Uo,"uri")}}class config_Validate extends OptionObject{constructor(e){super(Uo,"validate",["preSubmit","prePrint","preExecute","preSave"])}}class ValidateApprovalSignatures extends ContentObject{constructor(e){super(Uo,"validateApprovalSignatures")}[Qr](){this[Vr]=this[Vr].trim().split(/\s+/).filter(e=>["docReady","postSign"].includes(e))}}class ValidationMessaging extends OptionObject{constructor(e){super(Uo,"validationMessaging",["allMessagesIndividually","allMessagesTogether","firstMessageOnly","noMessages"])}}class Version extends OptionObject{constructor(e){super(Uo,"version",["1.7","1.6","1.5","1.4","1.3","1.2"])}}class VersionControl extends XFAObject{constructor(e){super(Uo,"VersionControl");this.outputBelow=getStringOption(e.outputBelow,["warn","error","update"]);this.sourceAbove=getStringOption(e.sourceAbove,["warn","error"]);this.sourceBelow=getStringOption(e.sourceBelow,["update","maintain"])}}class ViewerPreferences extends XFAObject{constructor(e){super(Uo,"viewerPreferences",!0);this.ADBE_JSConsole=null;this.ADBE_JSDebugger=null;this.addViewerPreferences=null;this.duplexOption=null;this.enforce=null;this.numberOfCopies=null;this.pageRange=null;this.pickTrayByPDFSize=null;this.printScaling=null}}class WebClient extends XFAObject{constructor(e){super(Uo,"webClient",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class Whitespace extends OptionObject{constructor(e){super(Uo,"whitespace",["preserve","ltrim","normalize","rtrim","trim"])}}class Window extends ContentObject{constructor(e){super(Uo,"window")}[Qr](){const e=this[Vr].split(",",2).map(e=>parseInt(e.trim(),10));if(e.some(e=>isNaN(e)))this[Vr]=[0,0];else{1===e.length&&e.push(e[0]);this[Vr]=e}}}class Xdc extends XFAObject{constructor(e){super(Uo,"xdc",!0);this.uri=new XFAObjectArray;this.xsl=new XFAObjectArray}}class Xdp extends XFAObject{constructor(e){super(Uo,"xdp",!0);this.packets=null}}class Xsl extends XFAObject{constructor(e){super(Uo,"xsl",!0);this.debug=null;this.uri=null}}class Zpl extends XFAObject{constructor(e){super(Uo,"zpl",!0);this.name=e.name?e.name.trim():"";this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class ConfigNamespace{static[to](e,t){if(ConfigNamespace.hasOwnProperty(e))return ConfigNamespace[e](t)}static acrobat(e){return new Acrobat(e)}static acrobat7(e){return new Acrobat7(e)}static ADBE_JSConsole(e){return new ADBE_JSConsole(e)}static ADBE_JSDebugger(e){return new ADBE_JSDebugger(e)}static addSilentPrint(e){return new AddSilentPrint(e)}static addViewerPreferences(e){return new AddViewerPreferences(e)}static adjustData(e){return new AdjustData(e)}static adobeExtensionLevel(e){return new AdobeExtensionLevel(e)}static agent(e){return new Agent(e)}static alwaysEmbed(e){return new AlwaysEmbed(e)}static amd(e){return new Amd(e)}static area(e){return new config_Area(e)}static attributes(e){return new Attributes(e)}static autoSave(e){return new AutoSave(e)}static base(e){return new Base(e)}static batchOutput(e){return new BatchOutput(e)}static behaviorOverride(e){return new BehaviorOverride(e)}static cache(e){return new Cache(e)}static change(e){return new Change(e)}static common(e){return new Common(e)}static compress(e){return new Compress(e)}static compressLogicalStructure(e){return new CompressLogicalStructure(e)}static compressObjectStream(e){return new CompressObjectStream(e)}static compression(e){return new Compression(e)}static config(e){return new Config(e)}static conformance(e){return new Conformance(e)}static contentCopy(e){return new ContentCopy(e)}static copies(e){return new Copies(e)}static creator(e){return new Creator(e)}static currentPage(e){return new CurrentPage(e)}static data(e){return new Data(e)}static debug(e){return new Debug(e)}static defaultTypeface(e){return new DefaultTypeface(e)}static destination(e){return new Destination(e)}static documentAssembly(e){return new DocumentAssembly(e)}static driver(e){return new Driver(e)}static duplexOption(e){return new DuplexOption(e)}static dynamicRender(e){return new DynamicRender(e)}static embed(e){return new Embed(e)}static encrypt(e){return new config_Encrypt(e)}static encryption(e){return new config_Encryption(e)}static encryptionLevel(e){return new EncryptionLevel(e)}static enforce(e){return new Enforce(e)}static equate(e){return new Equate(e)}static equateRange(e){return new EquateRange(e)}static exclude(e){return new Exclude(e)}static excludeNS(e){return new ExcludeNS(e)}static flipLabel(e){return new FlipLabel(e)}static fontInfo(e){return new config_FontInfo(e)}static formFieldFilling(e){return new FormFieldFilling(e)}static groupParent(e){return new GroupParent(e)}static ifEmpty(e){return new IfEmpty(e)}static includeXDPContent(e){return new IncludeXDPContent(e)}static incrementalLoad(e){return new IncrementalLoad(e)}static incrementalMerge(e){return new IncrementalMerge(e)}static interactive(e){return new Interactive(e)}static jog(e){return new Jog(e)}static labelPrinter(e){return new LabelPrinter(e)}static layout(e){return new Layout(e)}static level(e){return new Level(e)}static linearized(e){return new Linearized(e)}static locale(e){return new Locale(e)}static localeSet(e){return new LocaleSet(e)}static log(e){return new Log(e)}static map(e){return new MapElement(e)}static mediumInfo(e){return new MediumInfo(e)}static message(e){return new config_Message(e)}static messaging(e){return new Messaging(e)}static mode(e){return new Mode(e)}static modifyAnnots(e){return new ModifyAnnots(e)}static msgId(e){return new MsgId(e)}static nameAttr(e){return new NameAttr(e)}static neverEmbed(e){return new NeverEmbed(e)}static numberOfCopies(e){return new NumberOfCopies(e)}static openAction(e){return new OpenAction(e)}static output(e){return new Output(e)}static outputBin(e){return new OutputBin(e)}static outputXSL(e){return new OutputXSL(e)}static overprint(e){return new Overprint(e)}static packets(e){return new Packets(e)}static pageOffset(e){return new PageOffset(e)}static pageRange(e){return new PageRange(e)}static pagination(e){return new Pagination(e)}static paginationOverride(e){return new PaginationOverride(e)}static part(e){return new Part(e)}static pcl(e){return new Pcl(e)}static pdf(e){return new Pdf(e)}static pdfa(e){return new Pdfa(e)}static permissions(e){return new Permissions(e)}static pickTrayByPDFSize(e){return new PickTrayByPDFSize(e)}static picture(e){return new config_Picture(e)}static plaintextMetadata(e){return new PlaintextMetadata(e)}static presence(e){return new Presence(e)}static present(e){return new Present(e)}static print(e){return new Print(e)}static printHighQuality(e){return new PrintHighQuality(e)}static printScaling(e){return new PrintScaling(e)}static printerName(e){return new PrinterName(e)}static producer(e){return new Producer(e)}static ps(e){return new Ps(e)}static range(e){return new Range(e)}static record(e){return new Record(e)}static relevant(e){return new Relevant(e)}static rename(e){return new Rename(e)}static renderPolicy(e){return new RenderPolicy(e)}static runScripts(e){return new RunScripts(e)}static script(e){return new config_Script(e)}static scriptModel(e){return new ScriptModel(e)}static severity(e){return new Severity(e)}static silentPrint(e){return new SilentPrint(e)}static staple(e){return new Staple(e)}static startNode(e){return new StartNode(e)}static startPage(e){return new StartPage(e)}static submitFormat(e){return new SubmitFormat(e)}static submitUrl(e){return new SubmitUrl(e)}static subsetBelow(e){return new SubsetBelow(e)}static suppressBanner(e){return new SuppressBanner(e)}static tagged(e){return new Tagged(e)}static template(e){return new config_Template(e)}static templateCache(e){return new TemplateCache(e)}static threshold(e){return new Threshold(e)}static to(e){return new To(e)}static trace(e){return new Trace(e)}static transform(e){return new Transform(e)}static type(e){return new Type(e)}static uri(e){return new Uri(e)}static validate(e){return new config_Validate(e)}static validateApprovalSignatures(e){return new ValidateApprovalSignatures(e)}static validationMessaging(e){return new ValidationMessaging(e)}static version(e){return new Version(e)}static versionControl(e){return new VersionControl(e)}static viewerPreferences(e){return new ViewerPreferences(e)}static webClient(e){return new WebClient(e)}static whitespace(e){return new Whitespace(e)}static window(e){return new Window(e)}static xdc(e){return new Xdc(e)}static xdp(e){return new Xdp(e)}static xsl(e){return new Xsl(e)}static zpl(e){return new Zpl(e)}}const _o=no.connectionSet.id;class ConnectionSet extends XFAObject{constructor(e){super(_o,"connectionSet",!0);this.wsdlConnection=new XFAObjectArray;this.xmlConnection=new XFAObjectArray;this.xsdConnection=new XFAObjectArray}}class EffectiveInputPolicy extends XFAObject{constructor(e){super(_o,"effectiveInputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EffectiveOutputPolicy extends XFAObject{constructor(e){super(_o,"effectiveOutputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Operation extends StringObject{constructor(e){super(_o,"operation");this.id=e.id||"";this.input=e.input||"";this.name=e.name||"";this.output=e.output||"";this.use=e.use||"";this.usehref=e.usehref||""}}class RootElement extends StringObject{constructor(e){super(_o,"rootElement");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAction extends StringObject{constructor(e){super(_o,"soapAction");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAddress extends StringObject{constructor(e){super(_o,"soapAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class connection_set_Uri extends StringObject{constructor(e){super(_o,"uri");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlAddress extends StringObject{constructor(e){super(_o,"wsdlAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlConnection extends XFAObject{constructor(e){super(_o,"wsdlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.effectiveInputPolicy=null;this.effectiveOutputPolicy=null;this.operation=null;this.soapAction=null;this.soapAddress=null;this.wsdlAddress=null}}class XmlConnection extends XFAObject{constructor(e){super(_o,"xmlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.uri=null}}class XsdConnection extends XFAObject{constructor(e){super(_o,"xsdConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.rootElement=null;this.uri=null}}class ConnectionSetNamespace{static[to](e,t){if(ConnectionSetNamespace.hasOwnProperty(e))return ConnectionSetNamespace[e](t)}static connectionSet(e){return new ConnectionSet(e)}static effectiveInputPolicy(e){return new EffectiveInputPolicy(e)}static effectiveOutputPolicy(e){return new EffectiveOutputPolicy(e)}static operation(e){return new Operation(e)}static rootElement(e){return new RootElement(e)}static soapAction(e){return new SoapAction(e)}static soapAddress(e){return new SoapAddress(e)}static uri(e){return new connection_set_Uri(e)}static wsdlAddress(e){return new WsdlAddress(e)}static wsdlConnection(e){return new WsdlConnection(e)}static xmlConnection(e){return new XmlConnection(e)}static xsdConnection(e){return new XsdConnection(e)}}const Xo=no.datasets.id;class datasets_Data extends XmlObject{constructor(e){super(Xo,"data",e)}[Si](){return!0}}class Datasets extends XFAObject{constructor(e){super(Xo,"datasets",!0);this.data=null;this.Signature=null}[Bi](e){const t=e[Hi];("data"===t&&e[Ti]===Xo||"Signature"===t&&e[Ti]===no.signature.id)&&(this[t]=e);this[Lr](e)}}class DatasetsNamespace{static[to](e,t){if(DatasetsNamespace.hasOwnProperty(e))return DatasetsNamespace[e](t)}static datasets(e){return new Datasets(e)}static data(e){return new datasets_Data(e)}}const Wo=no.localeSet.id;class CalendarSymbols extends XFAObject{constructor(e){super(Wo,"calendarSymbols",!0);this.name="gregorian";this.dayNames=new XFAObjectArray(2);this.eraNames=null;this.meridiemNames=null;this.monthNames=new XFAObjectArray(2)}}class CurrencySymbol extends StringObject{constructor(e){super(Wo,"currencySymbol");this.name=getStringOption(e.name,["symbol","isoname","decimal"])}}class CurrencySymbols extends XFAObject{constructor(e){super(Wo,"currencySymbols",!0);this.currencySymbol=new XFAObjectArray(3)}}class DatePattern extends StringObject{constructor(e){super(Wo,"datePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class DatePatterns extends XFAObject{constructor(e){super(Wo,"datePatterns",!0);this.datePattern=new XFAObjectArray(4)}}class DateTimeSymbols extends ContentObject{constructor(e){super(Wo,"dateTimeSymbols")}}class Day extends StringObject{constructor(e){super(Wo,"day")}}class DayNames extends XFAObject{constructor(e){super(Wo,"dayNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.day=new XFAObjectArray(7)}}class Era extends StringObject{constructor(e){super(Wo,"era")}}class EraNames extends XFAObject{constructor(e){super(Wo,"eraNames",!0);this.era=new XFAObjectArray(2)}}class locale_set_Locale extends XFAObject{constructor(e){super(Wo,"locale",!0);this.desc=e.desc||"";this.name="isoname";this.calendarSymbols=null;this.currencySymbols=null;this.datePatterns=null;this.dateTimeSymbols=null;this.numberPatterns=null;this.numberSymbols=null;this.timePatterns=null;this.typeFaces=null}}class locale_set_LocaleSet extends XFAObject{constructor(e){super(Wo,"localeSet",!0);this.locale=new XFAObjectArray}}class Meridiem extends StringObject{constructor(e){super(Wo,"meridiem")}}class MeridiemNames extends XFAObject{constructor(e){super(Wo,"meridiemNames",!0);this.meridiem=new XFAObjectArray(2)}}class Month extends StringObject{constructor(e){super(Wo,"month")}}class MonthNames extends XFAObject{constructor(e){super(Wo,"monthNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.month=new XFAObjectArray(12)}}class NumberPattern extends StringObject{constructor(e){super(Wo,"numberPattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class NumberPatterns extends XFAObject{constructor(e){super(Wo,"numberPatterns",!0);this.numberPattern=new XFAObjectArray(4)}}class NumberSymbol extends StringObject{constructor(e){super(Wo,"numberSymbol");this.name=getStringOption(e.name,["decimal","grouping","percent","minus","zero"])}}class NumberSymbols extends XFAObject{constructor(e){super(Wo,"numberSymbols",!0);this.numberSymbol=new XFAObjectArray(5)}}class TimePattern extends StringObject{constructor(e){super(Wo,"timePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class TimePatterns extends XFAObject{constructor(e){super(Wo,"timePatterns",!0);this.timePattern=new XFAObjectArray(4)}}class TypeFace extends XFAObject{constructor(e){super(Wo,"typeFace",!0);this.name=""|e.name}}class TypeFaces extends XFAObject{constructor(e){super(Wo,"typeFaces",!0);this.typeFace=new XFAObjectArray}}class LocaleSetNamespace{static[to](e,t){if(LocaleSetNamespace.hasOwnProperty(e))return LocaleSetNamespace[e](t)}static calendarSymbols(e){return new CalendarSymbols(e)}static currencySymbol(e){return new CurrencySymbol(e)}static currencySymbols(e){return new CurrencySymbols(e)}static datePattern(e){return new DatePattern(e)}static datePatterns(e){return new DatePatterns(e)}static dateTimeSymbols(e){return new DateTimeSymbols(e)}static day(e){return new Day(e)}static dayNames(e){return new DayNames(e)}static era(e){return new Era(e)}static eraNames(e){return new EraNames(e)}static locale(e){return new locale_set_Locale(e)}static localeSet(e){return new locale_set_LocaleSet(e)}static meridiem(e){return new Meridiem(e)}static meridiemNames(e){return new MeridiemNames(e)}static month(e){return new Month(e)}static monthNames(e){return new MonthNames(e)}static numberPattern(e){return new NumberPattern(e)}static numberPatterns(e){return new NumberPatterns(e)}static numberSymbol(e){return new NumberSymbol(e)}static numberSymbols(e){return new NumberSymbols(e)}static timePattern(e){return new TimePattern(e)}static timePatterns(e){return new TimePatterns(e)}static typeFace(e){return new TypeFace(e)}static typeFaces(e){return new TypeFaces(e)}}const Ko=no.signature.id;class signature_Signature extends XFAObject{constructor(e){super(Ko,"signature",!0)}}class SignatureNamespace{static[to](e,t){if(SignatureNamespace.hasOwnProperty(e))return SignatureNamespace[e](t)}static signature(e){return new signature_Signature(e)}}const Go=no.stylesheet.id;class Stylesheet extends XFAObject{constructor(e){super(Go,"stylesheet",!0)}}class StylesheetNamespace{static[to](e,t){if(StylesheetNamespace.hasOwnProperty(e))return StylesheetNamespace[e](t)}static stylesheet(e){return new Stylesheet(e)}}const Vo=no.xdp.id;class xdp_Xdp extends XFAObject{constructor(e){super(Vo,"xdp",!0);this.uuid=e.uuid||"";this.timeStamp=e.timeStamp||"";this.config=null;this.connectionSet=null;this.datasets=null;this.localeSet=null;this.stylesheet=new XFAObjectArray;this.template=null}[Ri](e){const t=no[e[Hi]];return t&&e[Ti]===t.id}}class XdpNamespace{static[to](e,t){if(XdpNamespace.hasOwnProperty(e))return XdpNamespace[e](t)}static xdp(e){return new xdp_Xdp(e)}}const $o=no.xhtml.id,Yo=Symbol(),Jo=new Set(["color","font","font-family","font-size","font-stretch","font-style","font-weight","margin","margin-bottom","margin-left","margin-right","margin-top","letter-spacing","line-height","orphans","page-break-after","page-break-before","page-break-inside","tab-interval","tab-stop","text-align","text-decoration","text-indent","vertical-align","widows","kerning-mode","xfa-font-horizontal-scale","xfa-font-vertical-scale","xfa-spacerun","xfa-tab-stops"]),Qo=new Map([["page-break-after","breakAfter"],["page-break-before","breakBefore"],["page-break-inside","breakInside"],["kerning-mode",e=>"none"===e?"none":"normal"],["xfa-font-horizontal-scale",e=>`scaleX(${Math.max(0,parseInt(e)/100).toFixed(2)})`],["xfa-font-vertical-scale",e=>`scaleY(${Math.max(0,parseInt(e)/100).toFixed(2)})`],["xfa-spacerun",""],["xfa-tab-stops",""],["font-size",(e,t)=>measureToString(.99*(e=t.fontSize=Math.abs(getMeasurement(e))))],["letter-spacing",e=>measureToString(getMeasurement(e))],["line-height",e=>measureToString(getMeasurement(e))],["margin",e=>measureToString(getMeasurement(e))],["margin-bottom",e=>measureToString(getMeasurement(e))],["margin-left",e=>measureToString(getMeasurement(e))],["margin-right",e=>measureToString(getMeasurement(e))],["margin-top",e=>measureToString(getMeasurement(e))],["text-indent",e=>measureToString(getMeasurement(e))],["font-family",e=>e],["vertical-align",e=>measureToString(getMeasurement(e))]]),Zo=/\s+/g,el=/[\r\n]+/g,tl=/\r\n?/g;function mapStyle(e,t,n){const a=Object.create(null);if(!e)return a;const s=Object.create(null);for(const[t,n]of e.split(";").map(e=>e.split(":",2))){const e=Qo.get(t);if(""===e)continue;let r=n;e&&(r="string"==typeof e?e:e(n,s));t.endsWith("scale")?a.transform=a.transform?`${a[t]} ${r}`:r:a[t.replaceAll(/-([a-zA-Z])/g,(e,t)=>t.toUpperCase())]=r}a.fontFamily&&setFontFamily({typeface:a.fontFamily,weight:a.fontWeight||"normal",posture:a.fontStyle||"normal",size:s.fontSize||0},t,t[di].fontFinder,a);if(n&&a.verticalAlign&&"0px"!==a.verticalAlign&&a.fontSize){const e=.583,t=.333,n=getMeasurement(a.fontSize);a.fontSize=measureToString(n*e);a.verticalAlign=measureToString(Math.sign(getMeasurement(a.verticalAlign))*n*t)}n&&a.fontSize&&(a.fontSize=`calc(${a.fontSize} * var(--total-scale-factor))`);fixTextIndent(a);return a}const nl=new Set(["body","html"]);class XhtmlObject extends XmlObject{constructor(e,t){super($o,t);this[Yo]=!1;this.style=e.style||""}[_r](e){super[_r](e);this.style=function checkStyle(e){return e.style?e.style.split(";").filter(e=>!!e.trim()).map(e=>e.split(":",2).map(e=>e.trim())).filter(([t,n])=>{"font-family"===t&&e[di].usedTypefaces.add(n);return Jo.has(t)}).map(e=>e.join(":")).join(";"):""}(this)}[Nr](){return!nl.has(this[Hi])}[Di](e,t=!1){if(t)this[Yo]=!0;else{e=e.replaceAll(el,"");this.style.includes("xfa-spacerun:yes")||(e=e.replaceAll(Zo," "))}e&&(this[Vr]+=e)}[Mi](e,t=!0){const n=Object.create(null),a={top:NaN,bottom:NaN,left:NaN,right:NaN};let s=null;for(const[e,t]of this.style.split(";").map(e=>e.split(":",2)))switch(e){case"font-family":n.typeface=stripQuotes(t);break;case"font-size":n.size=getMeasurement(t);break;case"font-weight":n.weight=t;break;case"font-style":n.posture=t;break;case"letter-spacing":n.letterSpacing=getMeasurement(t);break;case"margin":const e=t.split(/ \t/).map(e=>getMeasurement(e));switch(e.length){case 1:a.top=a.bottom=a.left=a.right=e[0];break;case 2:a.top=a.bottom=e[0];a.left=a.right=e[1];break;case 3:a.top=e[0];a.bottom=e[2];a.left=a.right=e[1];break;case 4:a.top=e[0];a.left=e[1];a.bottom=e[2];a.right=e[3]}break;case"margin-top":a.top=getMeasurement(t);break;case"margin-bottom":a.bottom=getMeasurement(t);break;case"margin-left":a.left=getMeasurement(t);break;case"margin-right":a.right=getMeasurement(t);break;case"line-height":s=getMeasurement(t)}e.pushData(n,a,s);if(this[Vr])e.addString(this[Vr]);else for(const t of this[fi]())"#text"!==t[Hi]?t[Mi](e):e.addString(t[Vr]);t&&e.popFont()}[Ji](e){const t=[];this[Jr]={children:t};this[Ur]({});if(0===t.length&&!this[Vr])return HTMLResult.EMPTY;let n;n=this[Yo]?this[Vr]?this[Vr].replaceAll(tl,"\n"):void 0:this[Vr]||void 0;return HTMLResult.success({name:this[Hi],attributes:{href:this.href,style:mapStyle(this.style,this,this[Yo])},children:t,value:n})}}class A extends XhtmlObject{constructor(e){super(e,"a");this.href=fixURL(e.href)||""}}class B extends XhtmlObject{constructor(e){super(e,"b")}[Mi](e){e.pushFont({weight:"bold"});super[Mi](e);e.popFont()}}class Body extends XhtmlObject{constructor(e){super(e,"body")}[Ji](e){const t=super[Ji](e),{html:n}=t;if(!n)return HTMLResult.EMPTY;n.name="div";n.attributes.class=["xfaRich"];return t}}class Br extends XhtmlObject{constructor(e){super(e,"br")}[$i](){return"\n"}[Mi](e){e.addString("\n")}[Ji](e){return HTMLResult.success({name:"br"})}}class Html extends XhtmlObject{constructor(e){super(e,"html")}[Ji](e){const t=[];this[Jr]={children:t};this[Ur]({});if(0===t.length)return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},value:this[Vr]||""});if(1===t.length){const e=t[0];if(e.attributes?.class.includes("xfaRich"))return HTMLResult.success(e)}return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},children:t})}}class I extends XhtmlObject{constructor(e){super(e,"i")}[Mi](e){e.pushFont({posture:"italic"});super[Mi](e);e.popFont()}}class Li extends XhtmlObject{constructor(e){super(e,"li")}}class Ol extends XhtmlObject{constructor(e){super(e,"ol")}}class P extends XhtmlObject{constructor(e){super(e,"p")}[Mi](e){super[Mi](e,!1);e.addString("\n");e.addPara();e.popFont()}[$i](){return this[mi]()[fi]().at(-1)===this?super[$i]():super[$i]()+"\n"}}class Span extends XhtmlObject{constructor(e){super(e,"span")}}class Sub extends XhtmlObject{constructor(e){super(e,"sub")}}class Sup extends XhtmlObject{constructor(e){super(e,"sup")}}class Ul extends XhtmlObject{constructor(e){super(e,"ul")}}class XhtmlNamespace{static[to](e,t){if(XhtmlNamespace.hasOwnProperty(e))return XhtmlNamespace[e](t)}static a(e){return new A(e)}static b(e){return new B(e)}static body(e){return new Body(e)}static br(e){return new Br(e)}static html(e){return new Html(e)}static i(e){return new I(e)}static li(e){return new Li(e)}static ol(e){return new Ol(e)}static p(e){return new P(e)}static span(e){return new Span(e)}static sub(e){return new Sub(e)}static sup(e){return new Sup(e)}static ul(e){return new Ul(e)}}const al={config:ConfigNamespace,connection:ConnectionSetNamespace,datasets:DatasetsNamespace,localeSet:LocaleSetNamespace,signature:SignatureNamespace,stylesheet:StylesheetNamespace,template:TemplateNamespace,xdp:XdpNamespace,xhtml:XhtmlNamespace};class UnknownNamespace{constructor(e){this.namespaceId=e}[to](e,t){return new XmlObject(this.namespaceId,e,t)}}class Root extends XFAObject{constructor(e){super(-1,"root",Object.create(null));this.element=null;this[bi]=e}[Bi](e){this.element=e;return!0}[Qr](){super[Qr]();if(this.element.template instanceof Template){this[bi].set(zi,this.element);this.element.template[_i](this[bi]);this.element.template[bi]=this[bi]}}}class Empty extends XFAObject{constructor(){super(-1,"",Object.create(null))}[Bi](e){return!1}}class Builder{constructor(e=null){this._namespaceStack=[];this._nsAgnosticLevel=0;this._namespacePrefixes=new Map;this._namespaces=new Map;this._nextNsId=Math.max(...Object.values(no).map(({id:e})=>e));this._currentNamespace=e||new UnknownNamespace(++this._nextNsId)}buildRoot(e){return new Root(e)}build({nsPrefix:e,name:t,attributes:n,namespace:a,prefixes:s}){const r=null!==a;if(r){this._namespaceStack.push(this._currentNamespace);this._currentNamespace=this._searchNamespace(a)}s&&this._addNamespacePrefix(s);if(n.hasOwnProperty(Oi)){const e=al.datasets,t=n[Oi];let a=null;for(const[n,s]of Object.entries(t)){if(this._getNamespaceToUse(n)===e){a={xfa:s};break}}a?n[Oi]=a:delete n[Oi]}const i=this._getNamespaceToUse(e),o=i?.[to](t,n)||new Empty;o[Si]()&&this._nsAgnosticLevel++;(r||s||o[Si]())&&(o[Wr]={hasNamespace:r,prefixes:s,nsAgnostic:o[Si]()});return o}isNsAgnostic(){return this._nsAgnosticLevel>0}_searchNamespace(e){let t=this._namespaces.get(e);if(t)return t;for(const[n,{check:a}]of Object.entries(no))if(a(e)){t=al[n];if(t){this._namespaces.set(e,t);return t}break}t=new UnknownNamespace(++this._nextNsId);this._namespaces.set(e,t);return t}_addNamespacePrefix(e){for(const{prefix:t,value:n}of e){const e=this._searchNamespace(n);this._namespacePrefixes.getOrInsertComputed(t,makeArr).push(e)}}_getNamespaceToUse(e){if(!e)return this._currentNamespace;const t=this._namespacePrefixes.get(e);if(t?.length>0)return t.at(-1);warn(`Unknown namespace prefix: ${e}.`);return null}clean(e){const{hasNamespace:t,prefixes:n,nsAgnostic:a}=e;t&&(this._currentNamespace=this._namespaceStack.pop());n&&n.forEach(({prefix:e})=>{this._namespacePrefixes.get(e).pop()});a&&this._nsAgnosticLevel--}}class XFAParser extends XMLParserBase{constructor(e=null,t=!1){super();this._builder=new Builder(e);this._stack=[];this._globalData={usedTypefaces:new Set};this._ids=new Map;this._current=this._builder.buildRoot(this._ids);this._errorCode=xr;this._whiteRegex=/^\s+$/;this._nbsps=/\xa0+/g;this._richText=t}parse(e){this.parseXml(e);if(this._errorCode===xr){this._current[Qr]();return this._current.element}}onText(e){e=e.replace(this._nbsps,e=>e.slice(1)+" ");this._richText||this._current[Nr]()?this._current[Di](e,this._richText):this._whiteRegex.test(e)||this._current[Di](e.trim())}onCdata(e){this._current[Di](e)}_mkAttributes(e,t){let n=null,a=null;const s=Object.create({});for(const{name:r,value:i}of e)if("xmlns"===r)n?warn(`XFA - multiple namespace definition in <${t}>`):n=i;else if(r.startsWith("xmlns:")){const e=r.substring(6);a??=[];a.push({prefix:e,value:i})}else{const e=r.indexOf(":");if(-1===e)s[r]=i;else{const t=s[Oi]??=Object.create(null),[n,a]=[r.slice(0,e),r.slice(e+1)];(t[n]||=Object.create(null))[a]=i}}return[n,a,s]}_getNameAndPrefix(e,t){const n=e.indexOf(":");return-1===n?[e,null]:[e.substring(n+1),t?"":e.substring(0,n)]}onBeginElement(e,t,n){const[a,s,r]=this._mkAttributes(t,e),[i,o]=this._getNameAndPrefix(e,this._builder.isNsAgnostic()),l=this._builder.build({nsPrefix:o,name:i,attributes:r,namespace:a,prefixes:s});l[di]=this._globalData;if(n){l[Qr]();this._current[Bi](l)&&l[Wi](this._ids);l[_r](this._builder)}else{this._stack.push(this._current);this._current=l}}onEndElement(e){const t=this._current;if(t[ki]()&&"string"==typeof t[Vr]){const e=new XFAParser;e._globalData=this._globalData;const n=e.parse(t[Vr]);t[Vr]=null;t[Bi](n)}t[Qr]();this._current=this._stack.pop();this._current[Bi](t)&&t[Wi](this._ids);t[_r](this._builder)}onError(e){this._errorCode=e}}class XFAFactory{constructor(e){try{this.root=(new XFAParser).parse(XFAFactory._createDocument(e));const t=new Binder(this.root);this.form=t.bind();this.dataHandler=new DataHandler(this.root,t.getData());this.form[di].template=this.form}catch(e){warn(`XFA - an error occurred during parsing and binding: ${e}`)}}isValid(){return!(!this.root||!this.form)}_createPagesHelper(){const e=this.form[Yi]();return new Promise((t,n)=>{const nextIteration=()=>{try{const n=e.next();n.done?t(n.value):setTimeout(nextIteration,0)}catch(e){n(e)}};setTimeout(nextIteration,0)})}async _createPages(){try{this.pages=await this._createPagesHelper();this.dims=this.pages.children.map(e=>{const{width:t,height:n}=e.attributes.style;return[0,0,parseInt(t),parseInt(n)]})}catch(e){warn(`XFA - an error occurred during layout: ${e}`)}}getBoundingBox(e){return this.dims[e]}async getNumPages(){this.pages||await this._createPages();return this.dims.length}setImages(e){this.form[di].images=e}setFonts(e){this.form[di].fontFinder=new FontFinder(e);const t=[];for(let e of this.form[di].usedTypefaces){e=stripQuotes(e);this.form[di].fontFinder.find(e)||t.push(e)}return t.length>0?t:null}appendFonts(e,t){this.form[di].fontFinder.add(e,t)}async getPages(){this.pages||await this._createPages();const e=this.pages;this.pages=null;return e}serializeData(e){return this.dataHandler.serialize(e)}static _createDocument(e){return e["/xdp:xdp"]?Object.values(e).join(""):e["xdp:xdp"]}static getRichTextAsHtml(e){if(!e||"string"!=typeof e)return null;try{let t=new XFAParser(XhtmlNamespace,!0).parse(e);if(!["body","xhtml"].includes(t[Hi])){const e=XhtmlNamespace.body({});e[Lr](t);t=e}const n=t[Ji]();if(!n.success)return null;const{html:a}=n,{attributes:s}=a;if(s){s.class&&(s.class=s.class.filter(e=>!e.startsWith("xfa")));s.dir="auto"}return{html:a,str:t[$i]()}}catch(e){warn(`XFA - an error occurred during parsing of rich text: ${e}`)}return null}}class AnnotationFactory{static createGlobals(e){return Promise.all([e.ensureCatalog("acroForm"),e.ensureDoc("xfaDatasets"),e.ensureCatalog("structTreeRoot"),e.ensureCatalog("baseUrl"),e.ensureCatalog("attachments"),e.ensureCatalog("globalColorSpaceCache")]).then(([t,n,a,s,r,i])=>({pdfManager:e,acroForm:t instanceof Dict?t:Dict.empty,xfaDatasets:n,structTreeRoot:a,baseUrl:s,attachments:r,globalColorSpaceCache:i}),e=>{warn(`createGlobals: "${e}".`);return null})}static async create(e,t,n,a,s,r,i,o){const l=s?await this._getPageIndex(e,t,n.pdfManager):null;return n.pdfManager.ensure(this,"_create",[e,t,n,a,s,r,i,l,o])}static _create(e,t,n,a,s=!1,r=null,i=null,o=null,l=null){const f=e.fetchIfRef(t);if(!(f instanceof Dict))return;let c=f.get("Subtype");c=c instanceof Name?c.name:null;if(i&&!i.has(T[c?.toUpperCase()]))return null;const{acroForm:h,pdfManager:u}=n,m=t instanceof Ref?t.toString():`annot_${a.createObjId()}`,p={xref:e,ref:t,dict:f,subtype:c,id:m,annotationGlobals:n,collectFields:s,orphanFields:r,needAppearances:!s&&!0===h.get("NeedAppearances"),pageIndex:o,evaluatorOptions:u.evaluatorOptions,pageRef:l};switch(c){case"Link":return new LinkAnnotation(p);case"Text":return new TextAnnotation(p);case"Widget":let e=getInheritableProperty({dict:f,key:"FT"});e=e instanceof Name?e.name:null;switch(e){case"Tx":return new TextWidgetAnnotation(p);case"Btn":return new ButtonWidgetAnnotation(p);case"Ch":return new ChoiceWidgetAnnotation(p);case"Sig":return new SignatureWidgetAnnotation(p)}warn(`Unimplemented widget field type "${e}", falling back to base field type.`);return new WidgetAnnotation(p);case"Popup":return new PopupAnnotation(p);case"FreeText":return new FreeTextAnnotation(p);case"Line":return new LineAnnotation(p);case"Square":return new SquareAnnotation(p);case"Circle":return new CircleAnnotation(p);case"PolyLine":return new PolylineAnnotation(p);case"Polygon":return new PolygonAnnotation(p);case"Caret":return new CaretAnnotation(p);case"Ink":return new InkAnnotation(p);case"Highlight":return new HighlightAnnotation(p);case"Underline":return new UnderlineAnnotation(p);case"Squiggly":return new SquigglyAnnotation(p);case"StrikeOut":return new StrikeOutAnnotation(p);case"Stamp":return new StampAnnotation(p);case"FileAttachment":return new FileAttachmentAnnotation(p);default:s||warn(c?`Unimplemented annotation type "${c}", falling back to base annotation.`:"Annotation is missing the required /Subtype.");return new Annotation(p)}}static async _getPageIndex(e,t,n){try{const a=await e.fetchIfRefAsync(t);if(!(a instanceof Dict))return-1;const s=a.getRaw("P");if(s instanceof Ref)try{return await n.ensureCatalog("getPageIndex",[s])}catch(e){info(`_getPageIndex -- not a valid page reference: "${e}".`)}if(a.has("Kids"))return-1;const r=await n.ensureDoc("numPages");for(let e=0;e<r;e++){const a=await n.getPage(e),s=await n.ensure(a,"annotations");for(const n of s)if(n instanceof Ref&&isRefsEqual(n,t))return e}}catch(e){warn(`_getPageIndex: "${e}".`)}return-1}static generateImages(e,t,n){if(!n){warn("generateImages: OffscreenCanvas is not supported, cannot save or print some annotations with images.");return null}let a;for(const{bitmapId:n,bitmap:s}of e)if(s){a||=new Map;a.set(n,StampAnnotation.createImage(s,t))}return a}static async saveNewAnnotations(e,t,n,a,s){const r=e.xref;let i;const o=[],{isOffscreenCanvasSupported:l}=e.options;for(const f of n)if(!f.deleted)switch(f.annotationType){case p:if(!i){const e=new Dict(r);e.setIfName("BaseFont","Helvetica");e.setIfName("Type","Font");e.setIfName("Subtype","Type1");e.setIfName("Encoding","WinAnsiEncoding");i=r.getNewTemporaryRef();s.put(i,{data:e})}o.push(FreeTextAnnotation.createNewAnnotation(r,f,s,{evaluator:e,task:t,baseFontRef:i}));break;case d:f.quadPoints?o.push(HighlightAnnotation.createNewAnnotation(r,f,s)):o.push(InkAnnotation.createNewAnnotation(r,f,s));break;case b:o.push(InkAnnotation.createNewAnnotation(r,f,s));break;case g:const n=l?await(a?.get(f.bitmapId)):null;if(n?.imageStream){const{imageStream:e,smaskStream:t}=n;if(t){const n=r.getNewTemporaryRef();s.put(n,{data:t});e.dict.set("SMask",n)}const a=n.imageRef=r.getNewTemporaryRef();s.put(a,{data:e});n.imageStream=n.smaskStream=null}o.push(StampAnnotation.createNewAnnotation(r,f,s,{image:n}));break;case w:o.push(StampAnnotation.createNewAnnotation(r,f,s,{}))}return{annotations:(await Promise.all(o)).flat()}}static async printNewAnnotations(e,t,n,a,s){if(!a)return null;const{options:r,xref:i}=t,o=[];for(const l of a)if(!l.deleted)switch(l.annotationType){case p:o.push(FreeTextAnnotation.createNewPrintAnnotation(e,i,l,{evaluator:t,task:n,evaluatorOptions:r}));break;case d:l.quadPoints?o.push(HighlightAnnotation.createNewPrintAnnotation(e,i,l,{evaluatorOptions:r})):o.push(InkAnnotation.createNewPrintAnnotation(e,i,l,{evaluatorOptions:r}));break;case b:o.push(InkAnnotation.createNewPrintAnnotation(e,i,l,{evaluatorOptions:r}));break;case g:const a=r.isOffscreenCanvasSupported?await(s?.get(l.bitmapId)):null;if(a?.imageStream){const{imageStream:e,smaskStream:t}=a;t&&e.dict.set("SMask",t);a.imageRef=new JpegStream(e,e.length);a.imageStream=a.smaskStream=null}o.push(StampAnnotation.createNewPrintAnnotation(e,i,l,{image:a,evaluatorOptions:r}));break;case w:o.push(StampAnnotation.createNewPrintAnnotation(e,i,l,{evaluatorOptions:r}))}return Promise.all(o)}}function getRgbColor(e,t=new Uint8ClampedArray(3)){if(!Array.isArray(e))return t;const n=t||new Uint8ClampedArray(3);switch(e.length){case 0:return null;case 1:ColorSpaceUtils.gray.getRgbItem(e,0,n,0);return n;case 3:ColorSpaceUtils.rgb.getRgbItem(e,0,n,0);return n;case 4:ColorSpaceUtils.cmyk.getRgbItem(e,0,n,0);return n;default:return t}}function getPdfColorArray(e,t=null){return e&&Array.from(e,e=>e/255)||t}function getQuadPoints(e,t){const n=e.getArray("QuadPoints");if(!isNumberArray(n,null)||0===n.length||n.length%8>0)return null;const a=new Float32Array(n.length);for(let e=0,s=n.length;e<s;e+=8){const[s,r,i,o,l,f,c,h]=n.slice(e,e+8),u=Math.min(s,i,l,c),m=Math.max(s,i,l,c),p=Math.min(r,o,f,h),d=Math.max(r,o,f,h);if(null!==t&&(u<t[0]||m>t[2]||p<t[1]||d>t[3]))return null;a.set([u,d,m,d,u,p,m,p],e)}return a}function getTransformMatrix(e,t,n){const a=new Float32Array([1/0,1/0,-1/0,-1/0]);Util.axialAlignedBoundingBox(t,n,a);const[s,r,i,o]=a;if(s===i||r===o)return[1,0,0,1,e[0],e[1]];const l=(e[2]-e[0])/(i-s),f=(e[3]-e[1])/(o-r);return[l,0,0,f,e[0]-s*l,e[1]-r*f]}class Annotation{constructor(e){const{annotationGlobals:t,dict:n,orphanFields:a,ref:s,subtype:r,xref:i}=e,o=a?.get(s);o&&n.set("Parent",o);this.setTitle(n.get("T"));this.setContents(n.get("Contents"));this.setModificationDate(n.get("M"));this.setFlags(n.get("F"));this.setRectangle(n.getArray("Rect"));this.setColor(n.getArray("C"));this.setBorderStyle(n);this.setAppearance(n);this.setOptionalContent(n);const l=n.get("MK");this.setBorderAndBackgroundColors(l);this.setRotation(l,n);this.ref=e.ref instanceof Ref?e.ref:null;this._streams=[];this.appearance&&this._streams.push(this.appearance);const f=!!(this.flags&z),c=!!(this.flags&L);this.data={annotationType:T[r?.toUpperCase()],annotationFlags:this.flags,borderStyle:this.borderStyle,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,rotation:this.rotation,contentsObj:this._contents,hasAppearance:!!this.appearance,id:e.id,modificationDate:this.modificationDate,rect:this.rectangle,subtype:r,hasOwnCanvas:!1,noRotate:!!(this.flags&E),noHTML:f&&c,isEditable:!1,structParent:-1};if(t.structTreeRoot){let a=n.get("StructParent");this.data.structParent=a=Number.isInteger(a)&&a>=0?a:-1;t.structTreeRoot.addAnnotationIdToPage(e.pageRef,a)}if(e.collectFields){const t=n.get("Kids");if(Array.isArray(t)){const e=[];for(const n of t)n instanceof Ref&&e.push(n.toString());0!==e.length&&(this.data.kidIds=e)}this.data.actions=collectActions(i,n,se);this.data.fieldName=this._constructFieldName(n);this.data.pageIndex=e.pageIndex}const h=n.get("IT");h instanceof Name&&(this.data.it=h.name);this._isOffscreenCanvasSupported=e.evaluatorOptions.isOffscreenCanvasSupported;this._fallbackFontDict=null;this._needAppearances=!1}_hasFlag(e,t){return!!(e&t)}_buildFlags(e,t){let{flags:n}=this;if(void 0===e){if(void 0===t)return;return t?n&~M:n&~D|M}if(e){n|=M;return t?n&~N|D:n&~D|N}n&=~(D|N);return t?n&~M:n|M}_isViewable(e){return!this._hasFlag(e,R)&&!this._hasFlag(e,N)}_isPrintable(e){return this._hasFlag(e,M)&&!this._hasFlag(e,D)&&!this._hasFlag(e,R)}mustBeViewed(e,t){const n=e?.get(this.data.id)?.noView;return void 0!==n?!n:this.viewable&&!this._hasFlag(this.flags,D)}mustBePrinted(e){const t=e?.get(this.data.id)?.noPrint;return void 0!==t?!t:this.printable}mustBeViewedWhenEditing(e,t=null){return e?!this.data.isEditable:!t?.has(this.data.id)}get viewable(){return null!==this.data.quadPoints&&(0===this.flags||this._isViewable(this.flags))}get printable(){return null!==this.data.quadPoints&&(0!==this.flags&&this._isPrintable(this.flags))}_parseStringHelper(e){const t="string"==typeof e?stringToPDFString(e):"";return{str:t,dir:t&&"rtl"===bidi(t).dir?"rtl":"ltr"}}setDefaultAppearance(e){const{dict:t,annotationGlobals:n}=e,a=getInheritableProperty({dict:t,key:"DA"})||n.acroForm.get("DA");this._defaultAppearance="string"==typeof a?a:"";this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance)}setTitle(e){this._title=this._parseStringHelper(e)}setContents(e){this._contents=this._parseStringHelper(e)}setModificationDate(e){this.modificationDate="string"==typeof e?e:null}setFlags(e){this.flags=Number.isInteger(e)&&e>0?e:0;this.flags&R&&"Annotation"!==this.constructor.name&&(this.flags^=R)}hasFlag(e){return this._hasFlag(this.flags,e)}setRectangle(e){this.rectangle=lookupNormalRect(e,[0,0,0,0])}setColor(e){this.color=getRgbColor(e)}setLineEndings(e){this.lineEndings=["None","None"];if(Array.isArray(e)&&2===e.length)for(let t=0;t<2;t++){const n=e[t];if(n instanceof Name)switch(n.name){case"None":continue;case"Square":case"Circle":case"Diamond":case"OpenArrow":case"ClosedArrow":case"Butt":case"ROpenArrow":case"RClosedArrow":case"Slash":this.lineEndings[t]=n.name;continue}warn(`Ignoring invalid lineEnding: ${n}`)}}setRotation(e,t){this.rotation=0;let n=e instanceof Dict?e.get("R")||0:t.get("Rotate")||0;if(Number.isInteger(n)&&0!==n){n%=360;n<0&&(n+=360);n%90==0&&(this.rotation=n)}}setBorderAndBackgroundColors(e){if(e instanceof Dict){this.borderColor=getRgbColor(e.getArray("BC"),null);this.backgroundColor=getRgbColor(e.getArray("BG"),null)}else this.borderColor=this.backgroundColor=null}setBorderStyle(e){this.borderStyle=new AnnotationBorderStyle;if(e instanceof Dict)if(e.has("BS")){const t=e.get("BS");if(t instanceof Dict){const e=t.get("Type");if(!e||isName(e,"Border")){this.borderStyle.setWidth(t.get("W"),this.rectangle);this.borderStyle.setStyle(t.get("S"));this.borderStyle.setDashArray(t.getArray("D"))}}}else if(e.has("Border")){const t=e.getArray("Border");if(Array.isArray(t)&&t.length>=3){this.borderStyle.setHorizontalCornerRadius(t[0]);this.borderStyle.setVerticalCornerRadius(t[1]);this.borderStyle.setWidth(t[2],this.rectangle);4===t.length&&this.borderStyle.setDashArray(t[3],!0)}}else this.borderStyle.setWidth(0)}setAppearance(e){this.appearance=null;const t=e.get("AP");if(!(t instanceof Dict))return;const n=t.get("N");if(n instanceof BaseStream){this.appearance=n;return}if(!(n instanceof Dict))return;const a=e.get("AS");if(!(a instanceof Name&&n.has(a.name)))return;const s=n.get(a.name);s instanceof BaseStream&&(this.appearance=s)}setOptionalContent(e){this.oc=null;const t=e.get("OC");t instanceof Name?warn("setOptionalContent: Support for /Name-entry is not implemented."):t instanceof Dict&&(this.oc=t)}async loadResources(e,t){const n=await t.dict.getAsync("Resources");n&&await ObjectLoader.load(n,e,n.xref);return n}async getOperatorList(e,t,n,a){const{hasOwnCanvas:s,id:r,rect:o}=this.data;let l=this.appearance;const f=!!(s&&n&i);if(f&&(0===this.width||0===this.height)){this.data.hasOwnCanvas=!1;return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}if(!l){if(!f)return{opList:new OperatorList,separateForm:!1,separateCanvas:!1};l=new StringStream("");l.dict=new Dict}const c=l.dict,h=await this.loadResources(dn,l),u=lookupRect(c.getArray("BBox"),[0,0,1,1]),m=lookupMatrix(c.getArray("Matrix"),pn),p=getTransformMatrix(o,u,m),d=new OperatorList;let g;this.oc&&(g=await e.parseMarkedContentProps(this.oc,null));void 0!==g&&d.addOp(St,["OC",g]);d.addOp(Ot,[r,o,p,m,f]);await e.getOperatorList({stream:l,task:t,resources:h,operatorList:d,fallbackFontDict:this._fallbackFontDict});d.addOp(Bt,[]);void 0!==g&&d.addOp(xt,[]);this.reset();return{opList:d,separateForm:!1,separateCanvas:f}}async save(e,t,n,a){return null}get overlaysTextContent(){return!1}get hasTextContent(){return!1}async extractTextContent(e,t,n){if(!this.appearance)return;const a=await this.loadResources(gn,this.appearance),s=[],r=[];let i=null;const o={desiredSize:Math.Infinity,ready:!0,enqueue(e,t){for(const t of e.items)if(void 0!==t.str){i||=t.transform.slice(-2);r.push(t.str);if(t.hasEOL){s.push(r.join("").trimEnd());r.length=0}}}};await e.getTextContent({stream:this.appearance,task:t,resources:a,includeMarkedContent:!0,keepWhiteSpace:!0,sink:o,viewBox:n});this.reset();r.length&&s.push(r.join("").trimEnd());if(s.length>1||s[0]){const e=this.appearance.dict,t=lookupRect(e.getArray("BBox"),null),n=lookupMatrix(e.getArray("Matrix"),null);this.data.textPosition=this._transformPoint(i,t,n);this.data.textContent=s}}_transformPoint(e,t,n){const{rect:a}=this.data;t||=[0,0,1,1];n||=[1,0,0,1,0,0];const s=getTransformMatrix(a,t,n);s[4]-=a[0];s[5]-=a[1];const r=e.slice();Util.applyTransform(r,s);Util.applyTransform(r,n);return r}getFieldObject(){return this.data.kidIds?{id:this.data.id,actions:this.data.actions,name:this.data.fieldName,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,type:"",kidIds:this.data.kidIds,page:this.data.pageIndex,rotation:this.rotation}:null}reset(){for(const e of this._streams)e.reset()}_constructFieldName(e){if(!e.has("T")&&!e.has("Parent")){warn("Unknown field name, falling back to empty field name.");return""}if(!e.has("Parent"))return stringToPDFString(e.get("T"));const t=[];e.has("T")&&t.unshift(stringToPDFString(e.get("T")));let n=e;const a=new RefSet;e.objId&&a.put(e.objId);for(;n.has("Parent");){n=n.get("Parent");if(!(n instanceof Dict)||n.objId&&a.has(n.objId))break;n.objId&&a.put(n.objId);n.has("T")&&t.unshift(stringToPDFString(n.get("T")))}return t.join(".")}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}}class AnnotationBorderStyle{width=1;rawWidth=1;style=Z;dashArray=[3];horizontalCornerRadius=0;verticalCornerRadius=0;setWidth(e,t=[0,0,0,0]){if(e instanceof Name)this.width=0;else if("number"==typeof e){if(e>0){this.rawWidth=e;const n=(t[2]-t[0])/2,a=(t[3]-t[1])/2;if(n>0&&a>0&&(e>n||e>a)){warn(`AnnotationBorderStyle.setWidth - ignoring width: ${e}`);e=1}}this.width=e}}setStyle(e){if(e instanceof Name)switch(e.name){case"S":this.style=Z;break;case"D":this.style=ee;break;case"B":this.style=te;break;case"I":this.style=ne;break;case"U":this.style=ae}}setDashArray(e,t=!1){if(Array.isArray(e)){let n=!0,a=!0;for(const t of e){if(!(+t>=0)){n=!1;break}t>0&&(a=!1)}if(0===e.length||n&&!a){this.dashArray=e;t&&this.setStyle(Name.get("D"))}else this.width=0}else e&&(this.width=0)}setHorizontalCornerRadius(e){Number.isInteger(e)&&(this.horizontalCornerRadius=e)}setVerticalCornerRadius(e){Number.isInteger(e)&&(this.verticalCornerRadius=e)}}class MarkupAnnotation extends Annotation{constructor(e){super(e);const{dict:t}=e;if(t.has("IRT")){const e=t.getRaw("IRT");this.data.inReplyTo=e instanceof Ref?e.toString():null;const n=t.get("RT");this.data.replyType=n instanceof Name?n.name:O}let n=null;if(this.data.replyType===H){const e=t.get("IRT");this.setTitle(e.get("T"));this.data.titleObj=this._title;this.setContents(e.get("Contents"));this.data.contentsObj=this._contents;if(e.has("CreationDate")){this.setCreationDate(e.get("CreationDate"));this.data.creationDate=this.creationDate}else this.data.creationDate=null;if(e.has("M")){this.setModificationDate(e.get("M"));this.data.modificationDate=this.modificationDate}else this.data.modificationDate=null;n=e.getRaw("Popup");if(e.has("C")){this.setColor(e.getArray("C"));this.data.color=this.color}else this.data.color=null}else{this.data.titleObj=this._title;this.setCreationDate(t.get("CreationDate"));this.data.creationDate=this.creationDate;n=t.getRaw("Popup");t.has("C")||(this.data.color=null)}this.data.popupRef=n instanceof Ref?n.toString():null;t.has("RC")&&(this.data.richText=XFAFactory.getRichTextAsHtml(t.get("RC")))}setCreationDate(e){this.creationDate="string"==typeof e?e:null}_setDefaultAppearance({xref:e,extra:t,strokeColor:n,fillColor:a,blendMode:s,strokeAlpha:r,fillAlpha:i,pointsCallback:o}){const l=this.data.rect=[1/0,1/0,-1/0,-1/0],f=["q"];t&&f.push(t);n&&f.push(`${n[0]} ${n[1]} ${n[2]} RG`);a&&f.push(`${a[0]} ${a[1]} ${a[2]} rg`);const c=this.data.quadPoints||Float32Array.from([this.rectangle[0],this.rectangle[3],this.rectangle[2],this.rectangle[3],this.rectangle[0],this.rectangle[1],this.rectangle[2],this.rectangle[1]]);for(let e=0,t=c.length;e<t;e+=8){const t=o(f,c.subarray(e,e+8));Util.rectBoundingBox(...t,l)}f.push("Q");const h=new Dict(e),u=new Dict(e);u.setIfName("Subtype","Form");const m=new StringStream(f.join(" "));m.dict=u;h.set("Fm0",m);const p=new Dict(e);s&&p.setIfName("BM",s);p.setIfNumber("CA",r);p.setIfNumber("ca",i);const d=new Dict(e);d.set("GS0",p);const g=new Dict(e);g.set("ExtGState",d);g.set("XObject",h);const b=new Dict(e);b.set("Resources",g);b.set("BBox",l);this.appearance=new StringStream("/GS0 gs /Fm0 Do");this.appearance.dict=b;this._streams.push(this.appearance,m)}static async createNewAnnotation(e,t,n,a){const s=t.ref||=e.getNewTemporaryRef(),r=await this.createNewAppearanceStream(t,e,a);let i;if(r){const a=e.getNewTemporaryRef();i=this.createNewDict(t,e,{apRef:a});n.put(a,{data:r})}else i=this.createNewDict(t,e,{});Number.isInteger(t.parentTreeId)&&i.set("StructParent",t.parentTreeId);n.put(s,{data:i});const o={ref:s},{popup:l}=t;if(l){if(l.deleted){i.delete("Popup");i.delete("Contents");i.delete("RC");return o}const t=l.ref||=e.getNewTemporaryRef();l.parent=s;const a=PopupAnnotation.createNewDict(l,e);n.put(t,{data:a});i.setIfDefined("Contents",stringToAsciiOrUTF16BE(l.contents));i.set("Popup",t);return[o,{ref:t}]}return o}static async createNewPrintAnnotation(e,t,n,a){const s=await this.createNewAppearanceStream(n,t,a),r=this.createNewDict(n,t,s?{ap:s}:{}),i=new this.prototype.constructor({dict:r,xref:t,annotationGlobals:e,evaluatorOptions:a.evaluatorOptions});n.ref&&(i.ref=i.refToReplace=n.ref);return i}}class WidgetAnnotation extends Annotation{constructor(e){super(e);const{dict:t,xref:n,annotationGlobals:a}=e,s=this.data;this._needAppearances=e.needAppearances;void 0===s.fieldName&&(s.fieldName=this._constructFieldName(t));void 0===s.actions&&(s.actions=collectActions(n,t,se));let r=getInheritableProperty({dict:t,key:"V",getArray:!0});s.fieldValue=this._decodeFormValue(r);const i=getInheritableProperty({dict:t,key:"DV",getArray:!0});s.defaultFieldValue=this._decodeFormValue(i);if(void 0===r&&a.xfaDatasets){const e=this._title.str;if(e){this._hasValueFromXFA=!0;s.fieldValue=r=a.xfaDatasets.getValue(e)}}void 0===r&&null!==s.defaultFieldValue&&(s.fieldValue=s.defaultFieldValue);s.alternativeText=stringToPDFString(t.get("TU")||"");this.setDefaultAppearance(e);s.hasAppearance||=this._needAppearances&&void 0!==s.fieldValue&&null!==s.fieldValue;const o=getInheritableProperty({dict:t,key:"FT"});s.fieldType=o instanceof Name?o.name:null;const l=getInheritableProperty({dict:t,key:"DR"}),f=a.acroForm.get("DR"),c=this.appearance?.dict.get("Resources");this._fieldResources={localResources:l,acroFormResources:f,appearanceResources:c,mergedResources:Dict.merge({xref:n,dictArray:[l,c,f],mergeSubDicts:!0})};s.fieldFlags=getInheritableProperty({dict:t,key:"Ff"});(!Number.isInteger(s.fieldFlags)||s.fieldFlags<0)&&(s.fieldFlags=0);s.password=this.hasFieldFlag(W);s.readOnly=this.hasFieldFlag(U);s.required=this.hasFieldFlag(_);s.hidden=this._hasFlag(s.annotationFlags,D)||this._hasFlag(s.annotationFlags,N)}_decodeFormValue(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e).map(e=>stringToPDFString(e)):e instanceof Name?stringToPDFString(e.name):"string"==typeof e?stringToPDFString(e):null}hasFieldFlag(e){return!!(this.data.fieldFlags&e)}_isViewable(e){return!0}mustBeViewed(e,t){return t?this.viewable:super.mustBeViewed(e,t)&&!this._hasFlag(this.flags,N)}getRotationMatrix(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);return 0===t?pn:getRotationMatrix(t,this.width,this.height)}getBorderAndBackgroundAppearances(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(!this.backgroundColor&&!this.borderColor)return"";const n=0===t||180===t?`0 0 ${this.width} ${this.height} re`:`0 0 ${this.height} ${this.width} re`;let a="";this.backgroundColor&&(a=`${getPdfColor(this.backgroundColor,!0)} ${n} f `);if(this.borderColor){a+=`${this.borderStyle.width||1} w ${getPdfColor(this.borderColor,!1)} ${n} S `}return a}async getOperatorList(e,t,n,a){if(n&f&&!(this instanceof SignatureWidgetAnnotation)&&!this.data.noHTML&&!this.data.hasOwnCanvas)return{opList:new OperatorList,separateForm:!0,separateCanvas:!1};if(!this._hasText)return super.getOperatorList(e,t,n,a);const s=await this._getAppearance(e,t,n,a);if(this.appearance&&null===s)return super.getOperatorList(e,t,n,a);const r=new OperatorList;if(!this._defaultAppearance||null===s)return{opList:r,separateForm:!1,separateCanvas:!1};const o=!!(this.data.hasOwnCanvas&&n&i),l=[0,0,this.width,this.height],c=getTransformMatrix(this.data.rect,l,[1,0,0,1,0,0]);let h;this.oc&&(h=await e.parseMarkedContentProps(this.oc,null));void 0!==h&&r.addOp(St,["OC",h]);r.addOp(Ot,[this.data.id,this.data.rect,c,this.getRotationMatrix(a),o]);const u=new StringStream(s);await e.getOperatorList({stream:u,task:t,resources:this._fieldResources.mergedResources,operatorList:r});r.addOp(Bt,[]);void 0!==h&&r.addOp(xt,[]);return{opList:r,separateForm:!1,separateCanvas:o}}_getMKDict(e){const t=new Dict(null);e&&t.set("R",e);t.setIfArray("BC",getPdfColorArray(this.borderColor));t.setIfArray("BG",getPdfColorArray(this.backgroundColor));return t.size>0?t:null}amendSavedDict(e,t){}setValue(e,t,n,a){const{dict:s,ref:r}=function getParentToUpdate(e,t,n){const a=new RefSet,s=e,r={dict:null,ref:null};for(;e instanceof Dict&&!a.has(t);){a.put(t);if(e.has("T"))break;if(!((t=e.getRaw("Parent"))instanceof Ref))return r;e=n.fetch(t)}if(e instanceof Dict&&e!==s){r.dict=e;r.ref=t}return r}(e,this.ref,n);if(s){if(!a.has(r)){const e=s.clone();e.set("V",t);a.put(r,{data:e});return e}}else e.set("V",t);return null}async save(e,t,n,a){const s=n?.get(this.data.id),r=this._buildFlags(s?.noView,s?.noPrint);let i=s?.value,o=s?.rotation;if(i===this.data.fieldValue||void 0===i){if(!this._hasValueFromXFA&&void 0===o&&void 0===r)return;i||=this.data.fieldValue}if(void 0===o&&!this._hasValueFromXFA&&Array.isArray(i)&&Array.isArray(this.data.fieldValue)&&isArrayEqual(i,this.data.fieldValue)&&void 0===r)return;void 0===o&&(o=this.rotation);let f=null;if(!this._needAppearances){f=await this._getAppearance(e,t,l,n);if(null===f&&void 0===r)return}let c=!1;if(f?.needAppearances){c=!0;f=null}const{xref:h}=e,u=h.fetchIfRef(this.ref);if(!(u instanceof Dict))return;const m=new Dict(h);for(const e of u.getKeys())"AP"!==e&&m.set(e,u.getRaw(e));if(void 0!==r){m.set("F",r);if(null===f&&!c){const e=u.getRaw("AP");e&&m.set("AP",e)}}const p={path:this.data.fieldName,value:i},d=this.setValue(m,Array.isArray(i)?i.map(stringToAsciiOrUTF16BE):stringToAsciiOrUTF16BE(i),h,a);this.amendSavedDict(n,d||m);const g=this._getMKDict(o);g&&m.set("MK",g);a.put(this.ref,{data:m,xfa:p,needAppearances:c});if(null!==f){const e=h.getNewTemporaryRef(),t=new Dict(h);m.set("AP",t);t.set("N",e);const s=this._getSaveFieldResources(h),r=new StringStream(f),i=r.dict=new Dict(h);i.setIfName("Subtype","Form");i.set("Resources",s);const l=o%180==0?[0,0,this.width,this.height]:[0,0,this.height,this.width];i.set("BBox",l);const c=this.getRotationMatrix(n);c!==pn&&i.set("Matrix",c);a.put(e,{data:r,xfa:null,needAppearances:!1})}m.set("M",`D:${getModificationDate()}`)}async _getAppearance(e,t,n,a){if(this.data.password)return null;const r=a?.get(this.data.id);let i,o;if(r){i=r.formattedValue||r.value;o=r.rotation}if(void 0===o&&void 0===i&&!this._needAppearances&&(!this._hasValueFromXFA||this.appearance))return null;const f=this.getBorderAndBackgroundAppearances(a);if(void 0===i){i=this.data.fieldValue;if(!i)return`/Tx BMC q ${f}Q EMC`}Array.isArray(i)&&1===i.length&&(i=i[0]);assert("string"==typeof i,"Expected `value` to be a string.");i=i.trimEnd();if(this.data.combo){const e=this.data.options.find(({exportValue:e})=>i===e);i=e?.displayValue||i}if(""===i)return`/Tx BMC q ${f}Q EMC`;void 0===o&&(o=this.rotation);let c,h=-1;if(this.data.multiLine){c=i.split(/\r\n?|\n/).map(e=>e.normalize("NFC"));h=c.length}else c=[i.replace(/\r\n?|\n/,"").normalize("NFC")];let{width:u,height:m}=this;90!==o&&270!==o||([u,m]=[m,u]);this._defaultAppearance||(this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance="/Helvetica 0 Tf 0 g"));let p,d,g,b=await WidgetAnnotation._getFontData(e,t,this.data.defaultAppearanceData,this._fieldResources.mergedResources);const w=[];let j=!1;for(const e of c){const t=b.encodeString(e);t.length>1&&(j=!0);w.push(t.join(""))}if(j&&n&l)return{needAppearances:!0};if(j&&this._isOffscreenCanvasSupported){const n=this.data.comb?"monospace":"sans-serif",a=new FakeUnicodeFont(e.xref,n),s=a.createFontResources(c.join("")),r=s.getRaw("Font");if(this._fieldResources.mergedResources.has("Font")){const e=this._fieldResources.mergedResources.get("Font");for(const t of r.getKeys())e.set(t,r.getRaw(t))}else this._fieldResources.mergedResources.set("Font",r);const o=a.fontName.name;b=await WidgetAnnotation._getFontData(e,t,{fontName:o,fontSize:0},s);for(let e=0,t=w.length;e<t;e++)w[e]=stringToUTF16String(c[e]);const l=Object.assign(Object.create(null),this.data.defaultAppearanceData);this.data.defaultAppearanceData.fontSize=0;this.data.defaultAppearanceData.fontName=o;[p,d,g]=this._computeFontSize(m-2,u-4,i,b,h);this.data.defaultAppearanceData=l}else{this._isOffscreenCanvasSupported||warn("_getAppearance: OffscreenCanvas is not supported, annotation may not render correctly.");[p,d,g]=this._computeFontSize(m-2,u-4,i,b,h)}let k=b.descent;k=isNaN(k)?s*g:Math.max(s*g,Math.abs(k)*d);const y=Math.min(Math.floor((m-d)/2),1),q=this.data.textAlignment;if(this.data.multiLine)return this._getMultilineAppearance(p,w,b,d,u,m,q,2,y,k,g,a);if(this.data.comb)return this._getCombAppearance(p,b,w[0],d,u,m,2,y,k,g,a);const v=y+k;if(0===q||q>2)return`/Tx BMC q ${f}BT `+p+` 1 0 0 1 ${numberToString(2)} ${numberToString(v)} Tm (${escapeString(w[0])}) Tj ET Q EMC`;return`/Tx BMC q ${f}BT `+p+` 1 0 0 1 0 0 Tm ${this._renderText(w[0],b,d,u,q,{shift:0},2,v)} ET Q EMC`}static async _getFontData(e,t,n,a){const s=new OperatorList,r={font:null,clone(){return this}},{fontName:i,fontSize:o}=n;await e.handleSetFont(a,[i&&Name.get(i),o],null,s,t,r,null);return r.font}_getTextWidth(e,t){return Math.sumPrecise(t.charsToGlyphs(e).map(e=>e.width))/1e3}_computeFontSize(e,t,a,s,r){let{fontSize:i}=this.data.defaultAppearanceData,o=(i||12)*n,l=Math.round(e/o);if(!i){const roundWithTwoDigits=e=>Math.floor(100*e)/100;if(-1===r){const r=this._getTextWidth(a,s);i=roundWithTwoDigits(Math.min(e/n,t/r));l=1}else{const f=a.split(/\r\n?|\n/),c=[];for(const e of f){const t=s.encodeString(e).join(""),n=s.charsToGlyphs(t),a=s.getCharPositions(t);c.push({line:t,glyphs:n,positions:a})}const isTooBig=n=>{let a=0;for(const r of c){a+=this._splitLine(null,s,n,t,r).length*n;if(a>e)return!0}return!1};l=Math.max(l,r);for(;;){o=e/l;i=roundWithTwoDigits(o/n);if(!isTooBig(i))break;l++}}const{fontName:f,fontColor:c}=this.data.defaultAppearanceData;this._defaultAppearance=function createDefaultAppearance({fontSize:e,fontName:t,fontColor:n}){return`/${escapePDFName(t)} ${e} Tf ${getPdfColor(n,!0)}`}({fontSize:i,fontName:f,fontColor:c})}return[this._defaultAppearance,i,e/l]}_renderText(e,t,n,a,s,r,i,o){let l;if(1===s){l=(a-this._getTextWidth(e,t)*n)/2}else if(2===s){l=a-this._getTextWidth(e,t)*n-i}else l=i;const f=numberToString(l-r.shift);r.shift=l;return`${f} ${o=numberToString(o)} Td (${escapeString(e)}) Tj`}_getSaveFieldResources(e){const{localResources:t,appearanceResources:n,acroFormResources:a}=this._fieldResources,s=this.data.defaultAppearanceData?.fontName;if(!s)return t||Dict.empty;for(const e of[t,n])if(e instanceof Dict){const t=e.get("Font");if(t instanceof Dict&&t.has(s))return e}if(a instanceof Dict){const n=a.get("Font");if(n instanceof Dict&&n.has(s)){const a=new Dict(e);a.set(s,n.getRaw(s));const r=new Dict(e);r.set("Font",a);return Dict.merge({xref:e,dictArray:[r,t],mergeSubDicts:!0})}}return t||Dict.empty}getFieldObject(){return null}}class TextWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t}=e;if(t.has("PMD")){this.flags|=D;this.data.hidden=!0;warn("Barcodes are not supported")}this.data.hasOwnCanvas=this.data.readOnly&&!this.data.noHTML;this._hasText=!0;"string"!=typeof this.data.fieldValue&&(this.data.fieldValue="");let n=getInheritableProperty({dict:t,key:"Q"});(!Number.isInteger(n)||n<0||n>2)&&(n=null);this.data.textAlignment=n;let a=getInheritableProperty({dict:t,key:"MaxLen"});(!Number.isInteger(a)||a<0)&&(a=0);this.data.maxLen=a;this.data.multiLine=this.hasFieldFlag(X);this.data.comb=this.hasFieldFlag(Q)&&!this.data.multiLine&&!this.data.password&&!this.hasFieldFlag($)&&0!==this.data.maxLen;this.data.doNotScroll=this.hasFieldFlag(J);const{data:{actions:s}}=this;if(!s)return;const r=/^AF(Date|Time)_(?:Keystroke|Format)(?:Ex)?\(['"]?([^'"]+)['"]?\);$/;let i=!1;(1===s.Format?.length&&1===s.Keystroke?.length&&r.test(s.Format[0])&&r.test(s.Keystroke[0])||0===s.Format?.length&&1===s.Keystroke?.length&&r.test(s.Keystroke[0])||0===s.Keystroke?.length&&1===s.Format?.length&&r.test(s.Format[0]))&&(i=!0);const o=[];s.Format&&o.push(...s.Format);s.Keystroke&&o.push(...s.Keystroke);if(i){delete s.Keystroke;s.Format=o}for(const e of o){const t=e.match(r);if(!t)continue;const n="Date"===t[1];let a=t[2];const s=parseInt(a,10);isNaN(s)||Math.floor(Math.log10(s))+1!==t[2].length||(a=(n?vr:Sr)[s]??a);this.data.datetimeFormat=a;if(!i)break;if(n){if(/HH|MM|ss|h/.test(a)){this.data.datetimeType="datetime-local";this.data.timeStep=/ss/.test(a)?1:60}else this.data.datetimeType="date";break}this.data.datetimeType="time";this.data.timeStep=/ss/.test(a)?1:60;break}}get hasTextContent(){return!!this.appearance&&!this._needAppearances}_getCombAppearance(e,t,n,a,s,r,i,o,l,f,c){const h=s/this.data.maxLen,u=this.getBorderAndBackgroundAppearances(c),m=[],p=t.getCharPositions(n);for(const[e,t]of p)m.push(`(${escapeString(n.substring(e,t))}) Tj`);const d=m.join(` ${numberToString(h)} 0 Td `);return`/Tx BMC q ${u}BT `+e+` 1 0 0 1 ${numberToString(i)} ${numberToString(o+l)} Tm ${d} ET Q EMC`}_getMultilineAppearance(e,t,n,a,s,r,i,o,l,f,c,h){const u=[],m=s-2*o,p={shift:0};for(let e=0,r=t.length;e<r;e++){const r=t[e],h=this._splitLine(r,n,a,m);for(let t=0,r=h.length;t<r;t++){const r=h[t],m=0===e&&0===t?-l-(c-f):-c;u.push(this._renderText(r,n,a,s,i,p,o,m))}}const d=this.getBorderAndBackgroundAppearances(h),g=u.join("\n");return`/Tx BMC q ${d}BT `+e+` 1 0 0 1 0 ${numberToString(r)} Tm ${g} ET Q EMC`}_splitLine(e,t,n,a,s={}){e=s.line||e;const r=s.glyphs||t.charsToGlyphs(e);if(r.length<=1)return[e];const i=s.positions||t.getCharPositions(e),o=n/1e3,l=[];let f=-1,c=-1,h=-1,u=0,m=0;for(let t=0,n=r.length;t<n;t++){const[n,s]=i[t],p=r[t],d=p.width*o;if(" "===p.unicode)if(m+d>a){l.push(e.substring(u,n));u=n;m=d;f=-1;h=-1}else{m+=d;f=n;c=s;h=t}else if(m+d>a)if(-1!==f){l.push(e.substring(u,c));u=c;t=h+1;f=-1;m=0}else{l.push(e.substring(u,n));u=n;m=d}else m+=d}u<e.length&&l.push(e.substring(u,e.length));return l}async extractTextContent(e,t,n){await super.extractTextContent(e,t,n);const a=this.data.textContent;if(!a)return;const s=a.join("\n");if(s===this.data.fieldValue)return;const r=s.replaceAll(/([.*+?^${}()|[\]\\])|(\s+)/g,(e,t)=>t?`\\${t}`:"\\s+");new RegExp(`^\\s*${r}\\s*$`).test(this.data.fieldValue)&&(this.data.textContent=this.data.fieldValue.split("\n"))}getFieldObject(){return{id:this.data.id,value:this.data.fieldValue,defaultValue:this.data.defaultFieldValue||"",multiline:this.data.multiLine,password:this.data.password,charLimit:this.data.maxLen,comb:this.data.comb,editable:!this.data.readOnly,hidden:this.data.hidden,name:this.data.fieldName,rect:this.data.rect,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,datetimeFormat:this.data.datetimeFormat,hasDatetimeHTML:!!this.data.datetimeType,type:"text"}}}class ButtonWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);this.checkedAppearance=null;this.uncheckedAppearance=null;const t=this.hasFieldFlag(K),n=this.hasFieldFlag(G);this.data.checkBox=!t&&!n;this.data.radioButton=t&&!n;this.data.pushButton=n;this.data.isTooltipOnly=!1;if(this.data.checkBox)this._processCheckBox(e);else if(this.data.radioButton)this._processRadioButton(e);else if(this.data.pushButton){this.data.hasOwnCanvas=!0;this.data.noHTML=!1;this._processPushButton(e)}else warn("Invalid field flags for button widget annotation")}async getOperatorList(e,t,n,a){if(this.data.pushButton)return super.getOperatorList(e,t,n,!1,a);let s=null,r=null;if(a){const e=a.get(this.data.id);s=e?e.value:null;r=e?e.rotation:null}if(null===s&&this.appearance)return super.getOperatorList(e,t,n,a);null==s&&(s=this.data.checkBox?this.data.fieldValue===this.data.exportValue:this.data.fieldValue===this.data.buttonValue);const i=s?this.checkedAppearance:this.uncheckedAppearance;if(i){const s=this.appearance,o=lookupMatrix(i.dict.getArray("Matrix"),pn);r&&i.dict.set("Matrix",this.getRotationMatrix(a));this.appearance=i;const l=super.getOperatorList(e,t,n,a);this.appearance=s;i.dict.set("Matrix",o);return l}return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}async save(e,t,n,a){this.data.checkBox?this._saveCheckbox(e,t,n,a):this.data.radioButton&&this._saveRadioButton(e,t,n,a)}async _saveCheckbox(e,t,n,a){if(!n)return;const s=n.get(this.data.id),r=this._buildFlags(s?.noView,s?.noPrint);let i=s?.rotation,o=s?.value;if(void 0===i&&void 0===r){if(void 0===o)return;if(this.data.fieldValue===this.data.exportValue===o)return}let l=e.xref.fetchIfRef(this.ref);if(!(l instanceof Dict))return;l=l.clone();void 0===i&&(i=this.rotation);void 0===o&&(o=this.data.fieldValue===this.data.exportValue);const f={path:this.data.fieldName,value:o?this.data.exportValue:""},c=Name.get(o?this.data.exportValue:"Off");this.setValue(l,c,e.xref,a);l.set("AS",c);l.set("M",`D:${getModificationDate()}`);void 0!==r&&l.set("F",r);const h=this._getMKDict(i);h&&l.set("MK",h);a.put(this.ref,{data:l,xfa:f,needAppearances:!1})}async _saveRadioButton(e,t,n,a){if(!n)return;const s=n.get(this.data.id),r=this._buildFlags(s?.noView,s?.noPrint);let i=s?.rotation,o=s?.value;if(void 0===i&&void 0===r){if(void 0===o)return;if(this.data.fieldValue===this.data.buttonValue===o)return}let l=e.xref.fetchIfRef(this.ref);if(!(l instanceof Dict))return;l=l.clone();void 0===o&&(o=this.data.fieldValue===this.data.buttonValue);void 0===i&&(i=this.rotation);const f={path:this.data.fieldName,value:o?this.data.buttonValue:""},c=Name.get(o?this.data.buttonValue:"Off");o&&this.setValue(l,c,e.xref,a);l.set("AS",c);l.set("M",`D:${getModificationDate()}`);void 0!==r&&l.set("F",r);const h=this._getMKDict(i);h&&l.set("MK",h);a.put(this.ref,{data:l,xfa:f,needAppearances:!1})}_getDefaultCheckedAppearance(e,t){const{width:n,height:a}=this,s=[0,0,n,a],r=.8*Math.min(n,a);let i,o;if("check"===t){i={width:.755*r,height:.705*r};o="3"}else if("disc"===t){i={width:.791*r,height:.705*r};o="l"}else unreachable(`_getDefaultCheckedAppearance - unsupported type: ${t}`);const l=`q BT /PdfJsZaDb ${r} Tf 0 g ${numberToString((n-i.width)/2)} ${numberToString((a-i.height)/2)} Td (${o}) Tj ET Q`,f=new Dict(e.xref);f.set("FormType",1);f.setIfName("Subtype","Form");f.setIfName("Type","XObject");f.set("BBox",s);f.set("Matrix",[1,0,0,1,0,0]);f.set("Length",l.length);const c=new Dict(e.xref),h=new Dict(e.xref);h.set("PdfJsZaDb",this.fallbackFontDict);c.set("Font",h);f.set("Resources",c);this.checkedAppearance=new StringStream(l);this.checkedAppearance.dict=f;this._streams.push(this.checkedAppearance)}_processCheckBox(e){const t=e.dict.get("AP");if(!(t instanceof Dict))return;const n=t.get("N");if(!(n instanceof Dict))return;const a=this._decodeFormValue(e.dict.get("AS"));"string"==typeof a&&(this.data.fieldValue=a);const s=null!==this.data.fieldValue&&"Off"!==this.data.fieldValue?this.data.fieldValue:"Yes",r=this._decodeFormValue(n.getKeys());if(0===r.length)r.push("Off",s);else if(1===r.length)"Off"===r[0]?r.push(s):r.unshift("Off");else if(r.includes(s)){r.length=0;r.push("Off",s)}else{const e=r.find(e=>"Off"!==e);r.length=0;r.push("Off",e)}r.includes(this.data.fieldValue)||(this.data.fieldValue="Off");this.data.exportValue=r[1];const i=n.get(this.data.exportValue);this.checkedAppearance=i instanceof BaseStream?i:null;const o=n.get("Off");this.uncheckedAppearance=o instanceof BaseStream?o:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"check");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processRadioButton(e){this.data.buttonValue=null;const t=e.dict.get("Parent");if(t instanceof Dict){this.parent=e.dict.getRaw("Parent");const n=t.get("V");n instanceof Name&&(this.data.fieldValue=this._decodeFormValue(n))}const n=e.dict.get("AP");if(!(n instanceof Dict))return;const a=n.get("N");if(!(a instanceof Dict))return;for(const e of a.getKeys())if("Off"!==e){this.data.buttonValue=this._decodeFormValue(e);break}const s=a.get(this.data.buttonValue);this.checkedAppearance=s instanceof BaseStream?s:null;const r=a.get("Off");this.uncheckedAppearance=r instanceof BaseStream?r:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"disc");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processPushButton(e){const{dict:t,annotationGlobals:n}=e;if(t.has("A")||t.has("AA")||this.data.alternativeText){this.data.isTooltipOnly=!t.has("A")&&!t.has("AA");Catalog.parseDestDictionary({destDict:t,resultObj:this.data,docBaseUrl:n.baseUrl,docAttachments:n.attachments})}else warn("Push buttons without action dictionaries are not supported")}getFieldObject(){let e,t="button";if(this.data.checkBox){t="checkbox";e=this.data.exportValue}else if(this.data.radioButton){t="radiobutton";e=this.data.buttonValue}return{id:this.data.id,value:this.data.fieldValue||"Off",defaultValue:this.data.defaultFieldValue,exportValues:e,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,hidden:this.data.hidden,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:t}}get fallbackFontDict(){const e=new Dict;e.setIfName("BaseFont","ZapfDingbats");e.setIfName("Type","FallbackType");e.setIfName("Subtype","FallbackType");e.setIfName("Encoding","ZapfDingbatsEncoding");return shadow(this,"fallbackFontDict",e)}}class ChoiceWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t,xref:n}=e;this.indices=t.getArray("I");this.hasIndices=Array.isArray(this.indices)&&this.indices.length>0;this.data.options=[];const a=getInheritableProperty({dict:t,key:"Opt"});if(Array.isArray(a))for(let e=0,t=a.length;e<t;e++){const t=n.fetchIfRef(a[e]),s=Array.isArray(t);this.data.options[e]={exportValue:this._decodeFormValue(s?n.fetchIfRef(t[0]):t),displayValue:this._decodeFormValue(s?n.fetchIfRef(t[1]):t)}}if(this.hasIndices){this.data.fieldValue=[];const e=this.data.options.length;for(const t of this.indices)Number.isInteger(t)&&t>=0&&t<e&&this.data.fieldValue.push(this.data.options[t].exportValue)}else"string"==typeof this.data.fieldValue?this.data.fieldValue=[this.data.fieldValue]:this.data.fieldValue||=[];0===this.data.options.length&&this.data.fieldValue.length>0&&(this.data.options=this.data.fieldValue.map(e=>({exportValue:e,displayValue:e})));this.data.combo=this.hasFieldFlag(V);this.data.multiSelect=this.hasFieldFlag(Y);this._hasText=!0}getFieldObject(){const e=this.data.combo?"combobox":"listbox",t=this.data.fieldValue.length>0?this.data.fieldValue[0]:null;return{id:this.data.id,value:t,defaultValue:this.data.defaultFieldValue,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,numItems:this.data.fieldValue.length,multipleSelection:this.data.multiSelect,hidden:this.data.hidden,actions:this.data.actions,items:this.data.options,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:e}}amendSavedDict(e,t){if(!this.hasIndices)return;let n=e?.get(this.data.id)?.value;Array.isArray(n)||(n=[n]);const a=[],{options:s}=this.data;for(let e=0,t=0,r=s.length;e<r;e++)if(s[e].exportValue===n[t]){a.push(e);t+=1}t.set("I",a)}async _getAppearance(e,t,a,s){if(this.data.combo)return super._getAppearance(e,t,a,s);let r,i;const o=s?.get(this.data.id);if(o){i=o.rotation;r=o.value}if(void 0===i&&void 0===r&&!this._needAppearances)return null;void 0===r?r=this.data.fieldValue:Array.isArray(r)||(r=[r]);let{width:l,height:f}=this;90!==i&&270!==i||([l,f]=[f,l]);const c=this.data.options.length,h=[];for(let e=0;e<c;e++){const{exportValue:t}=this.data.options[e];r.includes(t)&&h.push(e)}this._defaultAppearance||(this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance="/Helvetica 0 Tf 0 g"));const u=await WidgetAnnotation._getFontData(e,t,this.data.defaultAppearanceData,this._fieldResources.mergedResources);let m,{fontSize:p}=this.data.defaultAppearanceData;if(p)m=this._defaultAppearance;else{const e=(f-1)/c;let t,n=-1;for(const{displayValue:e}of this.data.options){const a=this._getTextWidth(e,u);if(a>n){n=a;t=e}}[m,p]=this._computeFontSize(e,l-4,t,u,-1)}const d=p*n,g=(d-p)/2,b=Math.floor(f/d);let w=0;if(h.length>0){const e=Math.min(...h),t=Math.max(...h);w=Math.max(0,t-b+1);w>e&&(w=e)}const j=Math.min(w+b+1,c),k=["/Tx BMC q",`1 1 ${l} ${f} re W n`];if(h.length){k.push("0.600006 0.756866 0.854904 rg");for(const e of h)w<=e&&e<j&&k.push(`1 ${f-(e-w+1)*d} ${l} ${d} re f`)}k.push("BT",m,`1 0 0 1 0 ${f} Tm`);const y={shift:0};for(let e=w;e<j;e++){const{displayValue:t}=this.data.options[e],n=e===w?g:0;k.push(this._renderText(t,u,p,l,0,y,2,-d+n))}k.push("ET Q EMC");return k.join("\n")}}class SignatureWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);this.data.fieldValue=null;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!this.data.hasOwnCanvas}getFieldObject(){return{id:this.data.id,value:null,page:this.data.pageIndex,type:"signature"}}}class TextAnnotation extends MarkupAnnotation{constructor(e){super(e);this.data.noRotate=!0;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;const{dict:t}=e;if(this.data.hasAppearance)this.data.name="NoIcon";else{this.data.rect[1]=this.data.rect[3]-22;this.data.rect[2]=this.data.rect[0]+22;this.data.name=t.has("Name")?t.get("Name").name:"Note"}if(t.has("State")){this.data.state=t.get("State")||null;this.data.stateModel=t.get("StateModel")||null}else{this.data.state=null;this.data.stateModel=null}}}class LinkAnnotation extends Annotation{constructor(e){super(e);const{dict:t,annotationGlobals:n}=e;this.data.noHTML=!1;const a=getQuadPoints(t,this.rectangle);a&&(this.data.quadPoints=a);this.data.borderColor||=this.data.color;Catalog.parseDestDictionary({destDict:t,resultObj:this.data,docBaseUrl:n.baseUrl,docAttachments:n.attachments})}get overlaysTextContent(){return!0}}class PopupAnnotation extends Annotation{constructor(e){super(e);const{dict:t}=e;this.data.noHTML=!1;0!==this.width&&0!==this.height||(this.data.rect=null);let n=t.get("Parent");if(!n){warn("Popup annotation has a missing or invalid parent annotation.");return}this.data.parentRect=lookupNormalRect(n.getArray("Rect"),null);this.data.creationDate=n.get("CreationDate")||"";isName(n.get("RT"),H)&&(n=n.get("IRT"));if(n.has("M")){this.setModificationDate(n.get("M"));this.data.modificationDate=this.modificationDate}else this.data.modificationDate=null;if(n.has("C")){this.setColor(n.getArray("C"));this.data.color=this.color}else this.data.color=null;if(!this.viewable){const e=n.get("F");this._isViewable(e)&&this.setFlags(e)}this.setTitle(n.get("T"));this.data.titleObj=this._title;this.setContents(n.get("Contents"));this.data.contentsObj=this._contents;n.has("RC")&&(this.data.richText=XFAFactory.getRichTextAsHtml(n.get("RC")));this.data.open=!!t.get("Open")}static createNewDict(e,t,n){const{oldAnnotation:a,rect:s,parent:r}=e,i=a||new Dict(t);i.setIfNotExists("Type",Name.get("Annot"));i.setIfNotExists("Subtype",Name.get("Popup"));i.setIfNotExists("Open",!1);i.setIfArray("Rect",s);i.set("Parent",r);return i}static async createNewAppearanceStream(e,t,n){return null}}class FreeTextAnnotation extends MarkupAnnotation{constructor(e){super(e);this.data.hasOwnCanvas=this.data.noRotate;this.data.isEditable=!this.data.noHTML;this.data.noHTML=!1;const{annotationGlobals:t,evaluatorOptions:n,xref:a}=e;this.setDefaultAppearance(e);this._hasAppearance=!!this.appearance;if(this._hasAppearance){const{fontColor:e,fontSize:s}=function parseAppearanceStream(e,t,n,a){return new AppearanceStreamEvaluator(e,t,n,a).parse()}(this.appearance,n,a,t.globalColorSpaceCache);this.data.defaultAppearanceData.fontColor=e;this.data.defaultAppearanceData.fontSize=s||10}else{this.data.defaultAppearanceData.fontSize||=10;const{fontColor:t,fontSize:n}=this.data.defaultAppearanceData;if(this._contents.str){this.data.textContent=this._contents.str.split(/\r\n?|\n/).map(e=>e.trimEnd());const{coords:e,bbox:t,matrix:a}=FakeUnicodeFont.getFirstPositionInfo(this.rectangle,this.rotation,n);this.data.textPosition=this._transformPoint(e,t,a)}if(this._isOffscreenCanvasSupported){const s=e.dict.get("CA"),r=new FakeUnicodeFont(a,"sans-serif");this.appearance=r.createAppearance(this._contents.str,this.rectangle,this.rotation,n,t,s);this._streams.push(this.appearance)}else warn("FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly.")}}get hasTextContent(){return this._hasAppearance}static createNewDict(e,t,{apRef:n,ap:a}){const{color:s,date:r,fontSize:i,oldAnnotation:o,rect:l,rotation:f,user:c,value:h}=e,u=o||new Dict(t);u.setIfNotExists("Type",Name.get("Annot"));u.setIfNotExists("Subtype",Name.get("FreeText"));u.set(o?"M":"CreationDate",`D:${getModificationDate(r)}`);o&&u.delete("RC");u.setIfArray("Rect",l);const m=`/Helv ${i} Tf ${getPdfColor(s,!0)}`;u.set("DA",m);u.setIfDefined("Contents",stringToAsciiOrUTF16BE(h));u.setIfNotExists("F",4);u.setIfNotExists("Border",[0,0,0]);u.setIfNumber("Rotate",f);u.setIfDefined("T",stringToAsciiOrUTF16BE(c));if(n||a){const e=new Dict(t);u.set("AP",e);e.set("N",n||a)}return u}static async createNewAppearanceStream(e,t,a){const{baseFontRef:s,evaluator:r,task:i}=a,{color:o,fontSize:l,rect:f,rotation:c,value:h}=e;if(!o)return null;const u=new Dict(t),m=new Dict(t);if(s)m.set("Helv",s);else{const e=new Dict(t);e.setIfName("BaseFont","Helvetica");e.setIfName("Type","Font");e.setIfName("Subtype","Type1");e.setIfName("Encoding","WinAnsiEncoding");m.set("Helv",e)}u.set("Font",m);const p=await WidgetAnnotation._getFontData(r,i,{fontName:"Helv",fontSize:l},u),[d,g,b,w]=f;let j=b-d,k=w-g;c%180!=0&&([j,k]=[k,j]);const y=h.split("\n"),q=l/1e3;let v=-1/0;const S=[];for(let e of y){const t=p.encodeString(e);if(t.length>1)return null;e=t.join("");S.push(e);let n=0;const a=p.charsToGlyphs(e);for(const e of a)n+=e.width*q;v=Math.max(v,n)}let x=1;v>j&&(x=j/v);let C=1;const F=n*l,T=1*l,H=F*y.length;H>k&&(C=k/H);const O=l*Math.min(x,C);let R,D,M;switch(c){case 0:M=[1,0,0,1];D=[f[0],f[1],j,k];R=[f[0],f[3]-T];break;case 90:M=[0,1,-1,0];D=[f[1],-f[2],j,k];R=[f[1],-f[0]-T];break;case 180:M=[-1,0,0,-1];D=[-f[2],-f[3],j,k];R=[-f[2],-f[1]-T];break;case 270:M=[0,-1,1,0];D=[-f[3],f[0],j,k];R=[-f[3],f[2]-T]}const E=["q",`${M.join(" ")} 0 0 cm`,`${D.join(" ")} re W n`,"BT",`${getPdfColor(o,!0)}`,`0 Tc /Helv ${numberToString(O)} Tf`];E.push(`${R.join(" ")} Td (${escapeString(S[0])}) Tj`);const N=numberToString(F);for(let e=1,t=S.length;e<t;e++){const t=S[e];E.push(`0 -${N} Td (${escapeString(t)}) Tj`)}E.push("ET","Q");const z=E.join("\n"),L=new Dict(t);L.set("FormType",1);L.setIfName("Subtype","Form");L.setIfName("Type","XObject");L.set("BBox",f);L.set("Resources",u);L.set("Matrix",[1,0,0,1,-f[0],-f[1]]);const U=new StringStream(z);U.dict=L;return U}}class LineAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:n}=e;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;const a=lookupRect(t.getArray("L"),[0,0,0,0]);this.data.lineCoordinates=Util.normalizeRect(a);this.setLineEndings(t.getArray("LE"));this.data.lineEndings=this.lineEndings;if(!this.appearance){const e=getPdfColorArray(this.color,[0,0,0]),s=t.get("CA"),r=getPdfColorArray(getRgbColor(t.getArray("IC"),null)),i=r?s:null,o=this.borderStyle.width||1,l=2*o,f=[this.data.lineCoordinates[0]-l,this.data.lineCoordinates[1]-l,this.data.lineCoordinates[2]+l,this.data.lineCoordinates[3]+l];Util.intersect(this.rectangle,f)||(this.rectangle=f);this._setDefaultAppearance({xref:n,extra:`${o} w`,strokeColor:e,fillColor:r,strokeAlpha:s,fillAlpha:i,pointsCallback:(e,t)=>{e.push(`${a[0]} ${a[1]} m`,`${a[2]} ${a[3]} l`,"S");return[t[0]-o,t[7]-o,t[2]+o,t[3]+o]}})}}}class SquareAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:n}=e;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;if(!this.appearance){const e=getPdfColorArray(this.color,[0,0,0]),a=t.get("CA"),s=getPdfColorArray(getRgbColor(t.getArray("IC"),null)),r=s?a:null;if(0===this.borderStyle.width&&!s)return;this._setDefaultAppearance({xref:n,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:s,strokeAlpha:a,fillAlpha:r,pointsCallback:(e,t)=>{const n=t[4]+this.borderStyle.width/2,a=t[5]+this.borderStyle.width/2,r=t[6]-t[4]-this.borderStyle.width,i=t[3]-t[7]-this.borderStyle.width;e.push(`${n} ${a} ${r} ${i} re`);s?e.push("B"):e.push("S");return[t[0],t[7],t[2],t[3]]}})}}}class CircleAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:n}=e;if(!this.appearance){const e=getPdfColorArray(this.color,[0,0,0]),a=t.get("CA"),s=getPdfColorArray(getRgbColor(t.getArray("IC"),null)),r=s?a:null;if(0===this.borderStyle.width&&!s)return;const i=4/3*Math.tan(Math.PI/8);this._setDefaultAppearance({xref:n,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:s,strokeAlpha:a,fillAlpha:r,pointsCallback:(e,t)=>{const n=t[0]+this.borderStyle.width/2,a=t[1]-this.borderStyle.width/2,r=t[6]-this.borderStyle.width/2,o=t[7]+this.borderStyle.width/2,l=n+(r-n)/2,f=a+(o-a)/2,c=(r-n)/2*i,h=(o-a)/2*i;e.push(`${l} ${o} m`,`${l+c} ${o} ${r} ${f+h} ${r} ${f} c`,`${r} ${f-h} ${l+c} ${a} ${l} ${a} c`,`${l-c} ${a} ${n} ${f-h} ${n} ${f} c`,`${n} ${f+h} ${l-c} ${o} ${l} ${o} c`,"h");s?e.push("B"):e.push("S");return[t[0],t[7],t[2],t[3]]}})}}}class PolylineAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:n}=e;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;this.data.vertices=null;if(!(this instanceof PolygonAnnotation)){this.setLineEndings(t.getArray("LE"));this.data.lineEndings=this.lineEndings}const a=t.getArray("Vertices");if(!isNumberArray(a,null))return;const s=this.data.vertices=Float32Array.from(a);if(!this.appearance){const e=getPdfColorArray(this.color,[0,0,0]),a=t.get("CA");let r,i=getRgbColor(t.getArray("IC"),null);i&&(i=getPdfColorArray(i));r=i?this.color?i.every((t,n)=>t===e[n])?"f":"B":"f":"S";const o=this.borderStyle.width||1,l=2*o,f=[1/0,1/0,-1/0,-1/0];for(let e=0,t=s.length;e<t;e+=2)Util.rectBoundingBox(s[e]-l,s[e+1]-l,s[e]+l,s[e+1]+l,f);Util.intersect(this.rectangle,f)||(this.rectangle=f);this._setDefaultAppearance({xref:n,extra:`${o} w`,strokeColor:e,strokeAlpha:a,fillColor:i,fillAlpha:i?a:null,pointsCallback:(e,t)=>{for(let t=0,n=s.length;t<n;t+=2)e.push(`${s[t]} ${s[t+1]} ${0===t?"m":"l"}`);e.push(r);return[t[0],t[7],t[2],t[3]]}})}}}class PolygonAnnotation extends PolylineAnnotation{}class CaretAnnotation extends MarkupAnnotation{}class InkAnnotation extends MarkupAnnotation{constructor(e){super(e);this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;const{dict:t,xref:n}=e;this.data.inkLists=[];this.data.isEditable=!this.data.noHTML;this.data.noHTML=!1;this.data.opacity=t.get("CA")||1;const a=t.getArray("InkList");if(Array.isArray(a)){for(let e=0,t=a.length;e<t;++e){if(!Array.isArray(a[e]))continue;const t=new Float32Array(a[e].length);this.data.inkLists.push(t);for(let s=0,r=a[e].length;s<r;s+=2){const r=n.fetchIfRef(a[e][s]),i=n.fetchIfRef(a[e][s+1]);if("number"==typeof r&&"number"==typeof i){t[s]=r;t[s+1]=i}}}if(!this.appearance){const e=getPdfColorArray(this.color,[0,0,0]),a=t.get("CA"),s=this.borderStyle.width||1,r=2*s,i=[1/0,1/0,-1/0,-1/0];for(const e of this.data.inkLists)for(let t=0,n=e.length;t<n;t+=2)Util.rectBoundingBox(e[t]-r,e[t+1]-r,e[t]+r,e[t+1]+r,i);Util.intersect(this.rectangle,i)||(this.rectangle=i);this._setDefaultAppearance({xref:n,extra:`${s} w`,strokeColor:e,strokeAlpha:a,pointsCallback:(e,t)=>{for(const t of this.data.inkLists){for(let n=0,a=t.length;n<a;n+=2)e.push(`${t[n]} ${t[n+1]} ${0===n?"m":"l"}`);e.push("S")}return[t[0],t[7],t[2],t[3]]}})}}}static createNewDict(e,t,{apRef:n,ap:a}){const{oldAnnotation:s,color:r,date:i,opacity:o,paths:l,outlines:f,rect:c,rotation:h,thickness:u,user:m}=e,p=s||new Dict(t);p.setIfNotExists("Type",Name.get("Annot"));p.setIfNotExists("Subtype",Name.get("Ink"));p.set(s?"M":"CreationDate",`D:${getModificationDate(i)}`);p.setIfArray("Rect",c);p.setIfArray("InkList",f?.points||l?.points);p.setIfNotExists("F",4);p.setIfNumber("Rotate",h);p.setIfDefined("T",stringToAsciiOrUTF16BE(m));f&&p.setIfName("IT","InkHighlight");if(u>0){const e=new Dict(t);p.set("BS",e);e.set("W",u)}p.setIfArray("C",getPdfColorArray(r));p.setIfNumber("CA",o);if(a||n){const e=new Dict(t);p.set("AP",e);e.set("N",n||a)}return p}static async createNewAppearanceStream(e,t,n){if(e.outlines)return this.createNewAppearanceStreamForHighlight(e,t,n);const{color:a,rect:s,paths:r,thickness:i,opacity:o}=e;if(!a)return null;const l=[`${i} w 1 J 1 j`,`${getPdfColor(a,!1)}`];1!==o&&l.push("/R0 gs");for(const e of r.lines){l.push(`${numberToString(e[4])} ${numberToString(e[5])} m`);for(let t=6,n=e.length;t<n;t+=6)if(isNaN(e[t]))l.push(`${numberToString(e[t+4])} ${numberToString(e[t+5])} l`);else{const[n,a,s,r,i,o]=e.slice(t,t+6);l.push([n,a,s,r,i,o].map(numberToString).join(" ")+" c")}6===e.length&&l.push(`${numberToString(e[4])} ${numberToString(e[5])} l`)}l.push("S");const f=l.join("\n"),c=new Dict(t);c.set("FormType",1);c.setIfName("Subtype","Form");c.setIfName("Type","XObject");c.set("BBox",s);c.set("Length",f.length);if(1!==o){const e=new Dict(t),n=new Dict(t),a=new Dict(t);a.set("CA",o);a.setIfName("Type","ExtGState");n.set("R0",a);e.set("ExtGState",n);c.set("Resources",e)}const h=new StringStream(f);h.dict=c;return h}static async createNewAppearanceStreamForHighlight(e,t,n){const{color:a,rect:s,outlines:{outline:r},opacity:i}=e;if(!a)return null;const o=[`${getPdfColor(a,!0)}`,"/R0 gs"];o.push(`${numberToString(r[4])} ${numberToString(r[5])} m`);for(let e=6,t=r.length;e<t;e+=6)if(isNaN(r[e]))o.push(`${numberToString(r[e+4])} ${numberToString(r[e+5])} l`);else{const[t,n,a,s,i,l]=r.slice(e,e+6);o.push([t,n,a,s,i,l].map(numberToString).join(" ")+" c")}o.push("h f");const l=o.join("\n"),f=new Dict(t);f.set("FormType",1);f.setIfName("Subtype","Form");f.setIfName("Type","XObject");f.set("BBox",s);f.set("Length",l.length);const c=new Dict(t),h=new Dict(t);c.set("ExtGState",h);f.set("Resources",c);const u=new Dict(t);h.set("R0",u);u.setIfName("BM","Multiply");if(1!==i){u.set("ca",i);u.setIfName("Type","ExtGState")}const m=new StringStream(l);m.dict=f;return m}}class HighlightAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:n}=e;this.data.isEditable=!this.data.noHTML;this.data.noHTML=!1;this.data.opacity=t.get("CA")||1;if(this.data.quadPoints=getQuadPoints(t,null)){const e=this.appearance?.dict.get("Resources");if(!this.appearance||!e?.has("ExtGState")){this.appearance&&warn("HighlightAnnotation - ignoring built-in appearance stream.");const e=getPdfColorArray(this.color,[1,1,0]),a=t.get("CA");this._setDefaultAppearance({xref:n,fillColor:e,blendMode:"Multiply",fillAlpha:a,pointsCallback:(e,t)=>{e.push(`${t[0]} ${t[1]} m`,`${t[2]} ${t[3]} l`,`${t[6]} ${t[7]} l`,`${t[4]} ${t[5]} l`,"f");return[t[0],t[7],t[2],t[3]]}})}}else this.data.popupRef=null}get overlaysTextContent(){return!0}static createNewDict(e,t,{apRef:n,ap:a}){const{color:s,date:r,oldAnnotation:i,opacity:o,rect:l,rotation:f,user:c,quadPoints:h}=e,u=i||new Dict(t);u.setIfNotExists("Type",Name.get("Annot"));u.setIfNotExists("Subtype",Name.get("Highlight"));u.set(i?"M":"CreationDate",`D:${getModificationDate(r)}`);u.setIfArray("Rect",l);u.setIfNotExists("F",4);u.setIfNotExists("Border",[0,0,0]);u.setIfNumber("Rotate",f);u.setIfArray("QuadPoints",h);u.setIfArray("C",getPdfColorArray(s));u.setIfNumber("CA",o);u.setIfDefined("T",stringToAsciiOrUTF16BE(c));if(n||a){const e=new Dict(t);u.set("AP",e);e.set("N",n||a)}return u}static async createNewAppearanceStream(e,t,n){const{color:a,rect:s,outlines:r,opacity:i}=e;if(!a)return null;const o=[`${getPdfColor(a,!0)}`,"/R0 gs"],l=[];for(const e of r){l.length=0;l.push(`${numberToString(e[0])} ${numberToString(e[1])} m`);for(let t=2,n=e.length;t<n;t+=2)l.push(`${numberToString(e[t])} ${numberToString(e[t+1])} l`);l.push("h");o.push(l.join("\n"))}o.push("f*");const f=o.join("\n"),c=new Dict(t);c.set("FormType",1);c.setIfName("Subtype","Form");c.setIfName("Type","XObject");c.set("BBox",s);c.set("Length",f.length);const h=new Dict(t),u=new Dict(t);h.set("ExtGState",u);c.set("Resources",h);const m=new Dict(t);u.set("R0",m);m.setIfName("BM","Multiply");if(1!==i){m.set("ca",i);m.setIfName("Type","ExtGState")}const p=new StringStream(f);p.dict=c;return p}}class UnderlineAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:n}=e;if(this.data.quadPoints=getQuadPoints(t,null)){if(!this.appearance){const e=getPdfColorArray(this.color,[0,0,0]),a=t.get("CA");this._setDefaultAppearance({xref:n,extra:"[] 0 d 0.571 w",strokeColor:e,strokeAlpha:a,pointsCallback:(e,t)=>{e.push(`${t[4]} ${t[5]+1.3} m`,`${t[6]} ${t[7]+1.3} l`,"S");return[t[0],t[7],t[2],t[3]]}})}}else this.data.popupRef=null}get overlaysTextContent(){return!0}}class SquigglyAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:n}=e;if(this.data.quadPoints=getQuadPoints(t,null)){if(!this.appearance){const e=getPdfColorArray(this.color,[0,0,0]),a=t.get("CA");this._setDefaultAppearance({xref:n,extra:"[] 0 d 1 w",strokeColor:e,strokeAlpha:a,pointsCallback:(e,t)=>{const n=(t[1]-t[5])/6;let a=n,s=t[4];const r=t[5],i=t[6];e.push(`${s} ${r+a} m`);do{s+=2;a=0===a?n:0;e.push(`${s} ${r+a} l`)}while(s<i);e.push("S");return[t[4],r-2*n,i,r+2*n]}})}}else this.data.popupRef=null}get overlaysTextContent(){return!0}}class StrikeOutAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:n}=e;if(this.data.quadPoints=getQuadPoints(t,null)){if(!this.appearance){const e=getPdfColorArray(this.color,[0,0,0]),a=t.get("CA");this._setDefaultAppearance({xref:n,extra:"[] 0 d 1 w",strokeColor:e,strokeAlpha:a,pointsCallback:(e,t)=>{e.push((t[0]+t[4])/2+" "+(t[1]+t[5])/2+" m",(t[2]+t[6])/2+" "+(t[3]+t[7])/2+" l","S");return[t[0],t[7],t[2],t[3]]}})}}else this.data.popupRef=null}get overlaysTextContent(){return!0}}class StampAnnotation extends MarkupAnnotation{#Re=null;constructor(e){super(e);this.data.hasOwnCanvas=this.data.noRotate;this.data.isEditable=!this.data.noHTML;this.data.noHTML=!1}mustBeViewedWhenEditing(e,t=null){if(e){if(!this.data.isEditable)return!0;this.#Re??=this.data.hasOwnCanvas;this.data.hasOwnCanvas=!0;return!0}if(null!==this.#Re){this.data.hasOwnCanvas=this.#Re;this.#Re=null}return!t?.has(this.data.id)}static async createImage(e,t){const{width:n,height:a}=e,s=new OffscreenCanvas(n,a),r=s.getContext("2d",{alpha:!0});r.drawImage(e,0,0);const i=r.getImageData(0,0,n,a).data,o=new Uint32Array(i.buffer),l=o.some(FeatureTest.isLittleEndian?e=>e>>>24!=255:e=>!!(255&~e));if(l){r.fillStyle="white";r.fillRect(0,0,n,a);r.drawImage(e,0,0)}const f=s.convertToBlob({type:"image/jpeg",quality:1}).then(e=>e.arrayBuffer()),c=Name.get("XObject"),h=Name.get("Image"),u=new Dict(t);u.set("Type",c);u.set("Subtype",h);u.set("BitsPerComponent",8);u.setIfName("ColorSpace","DeviceRGB");u.setIfName("Filter","DCTDecode");u.set("BBox",[0,0,n,a]);u.set("Width",n);u.set("Height",a);let m=null;if(l){const e=new Uint8Array(o.length);if(FeatureTest.isLittleEndian)for(let t=0,n=o.length;t<n;t++)e[t]=o[t]>>>24;else for(let t=0,n=o.length;t<n;t++)e[t]=255&o[t];const s=new Dict(t);s.set("Type",c);s.set("Subtype",h);s.set("BitsPerComponent",8);s.setIfName("ColorSpace","DeviceGray");s.set("Width",n);s.set("Height",a);m=new Stream(e,0,0,s)}return{imageStream:new Stream(await f,0,0,u),smaskStream:m,width:n,height:a}}static createNewDict(e,t,{apRef:n,ap:a}){const{date:s,oldAnnotation:r,rect:i,rotation:o,user:l}=e,f=r||new Dict(t);f.setIfNotExists("Type",Name.get("Annot"));f.setIfNotExists("Subtype",Name.get("Stamp"));f.set(r?"M":"CreationDate",`D:${getModificationDate(s)}`);f.setIfArray("Rect",i);f.setIfNotExists("F",4);f.setIfNotExists("Border",[0,0,0]);f.setIfNumber("Rotate",o);f.setIfDefined("T",stringToAsciiOrUTF16BE(l));if(n||a){const e=new Dict(t);f.set("AP",e);e.set("N",n||a)}return f}static async#De(e,t){const{areContours:n,color:a,rect:s,lines:r,thickness:i}=e;if(!a)return null;const o=[`${i} w 1 J 1 j`,`${getPdfColor(a,n)}`];for(const e of r){o.push(`${numberToString(e[4])} ${numberToString(e[5])} m`);for(let t=6,n=e.length;t<n;t+=6)if(isNaN(e[t]))o.push(`${numberToString(e[t+4])} ${numberToString(e[t+5])} l`);else{const[n,a,s,r,i,l]=e.slice(t,t+6);o.push([n,a,s,r,i,l].map(numberToString).join(" ")+" c")}6===e.length&&o.push(`${numberToString(e[4])} ${numberToString(e[5])} l`)}o.push(n?"F":"S");const l=o.join("\n"),f=new Dict(t);f.set("FormType",1);f.setIfName("Subtype","Form");f.setIfName("Type","XObject");f.set("BBox",s);f.set("Length",l.length);const c=new StringStream(l);c.dict=f;return c}static async createNewAppearanceStream(e,t,n){if(e.oldAnnotation)return null;if(e.isSignature)return this.#De(e,t);const{rotation:a}=e,{imageRef:s,width:r,height:i}=n.image,o=new Dict(t),l=new Dict(t);o.set("XObject",l);l.set("Im0",s);const f=`q ${r} 0 0 ${i} 0 0 cm /Im0 Do Q`,c=new Dict(t);c.set("FormType",1);c.setIfName("Subtype","Form");c.setIfName("Type","XObject");c.set("BBox",[0,0,r,i]);c.set("Resources",o);if(a){const e=getRotationMatrix(a,r,i);c.set("Matrix",e)}const h=new StringStream(f);h.dict=c;return h}}class FileAttachmentAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t}=e,n=new FileSpec(t.get("FS"));this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;this.data.file=n.serializable;const a=t.get("Name");this.data.name=a instanceof Name?stringToPDFString(a.name):"PushPin";const s=t.get("ca");this.data.fillAlpha="number"==typeof s&&s>=0&&s<=1?s:null}}const sl={get r(){return shadow(this,"r",new Uint8Array([7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21]))},get k(){return shadow(this,"k",new Int32Array([-680876936,-389564586,606105819,-1044525330,-176418897,1200080426,-1473231341,-45705983,1770035416,-1958414417,-42063,-1990404162,1804603682,-40341101,-1502002290,1236535329,-165796510,-1069501632,643717713,-373897302,-701558691,38016083,-660478335,-405537848,568446438,-1019803690,-187363961,1163531501,-1444681467,-51403784,1735328473,-1926607734,-378558,-2022574463,1839030562,-35309556,-1530992060,1272893353,-155497632,-1094730640,681279174,-358537222,-722521979,76029189,-640364487,-421815835,530742520,-995338651,-198630844,1126891415,-1416354905,-57434055,1700485571,-1894986606,-1051523,-2054922799,1873313359,-30611744,-1560198380,1309151649,-145523070,-1120210379,718787259,-343485551]))}};function calculateMD5(e,t,n){let a=1732584193,s=-271733879,r=-1732584194,i=271733878;const o=n+72&-64,l=new Uint8Array(o);let f,c;for(f=0;f<n;++f)l[f]=e[t++];l[f++]=128;const h=o-8;f<h&&(f=h);l[f++]=n<<3&255;l[f++]=n>>5&255;l[f++]=n>>13&255;l[f++]=n>>21&255;l[f++]=n>>>29&255;f+=3;const u=new Int32Array(16),{k:m,r:p}=sl;for(f=0;f<o;){for(c=0;c<16;++c,f+=4)u[c]=l[f]|l[f+1]<<8|l[f+2]<<16|l[f+3]<<24;let e,t,n=a,o=s,h=r,d=i;for(c=0;c<64;++c){if(c<16){e=o&h|~o&d;t=c}else if(c<32){e=d&o|~d&h;t=5*c+1&15}else if(c<48){e=o^h^d;t=3*c+5&15}else{e=h^(o|~d);t=7*c&15}const a=d,s=n+e+m[c]+u[t]|0,r=p[c];d=h;h=o;o=o+(s<<r|s>>>32-r)|0;n=a}a=a+n|0;s=s+o|0;r=r+h|0;i=i+d|0}return new Uint8Array([255&a,a>>8&255,a>>16&255,a>>>24&255,255&s,s>>8&255,s>>16&255,s>>>24&255,255&r,r>>8&255,r>>16&255,r>>>24&255,255&i,i>>8&255,i>>16&255,i>>>24&255])}function decodeString(e){try{return stringToUTF8String(e)}catch(t){warn(`UTF-8 decoding failed: "${t}".`);return e}}class DatasetXMLParser extends SimpleXMLParser{node=null;onEndElement(e){const t=super.onEndElement(e);if(t&&"xfa:datasets"===e){this.node=t;throw new Error("Aborting DatasetXMLParser.")}}}class DatasetReader{constructor(e){if(e.datasets)this.node=new SimpleXMLParser({hasAttributes:!0}).parseFromString(e.datasets).documentElement;else{const t=new DatasetXMLParser({hasAttributes:!0});try{t.parseFromString(e["xdp:xdp"])}catch{}this.node=t.node}}getValue(e){if(!this.node||!e)return"";const t=this.node.searchNode(parseXFAPath(e),0);if(!t)return"";const n=t.firstChild;return"value"===n?.nodeName?t.children.map(e=>decodeString(e.textContent)):decodeString(t.textContent)}}class SingleIntersector{#Me;minX=1/0;minY=1/0;maxX=-1/0;maxY=-1/0;#Pe=null;#Ee=[];#Ne=[];#ze=-1;#Le=!1;constructor(e){this.#Me=e;const t=e.data.quadPoints;if(t){for(let e=0,n=t.length;e<n;e+=8){this.minX=Math.min(this.minX,t[e]);this.maxX=Math.max(this.maxX,t[e+2]);this.minY=Math.min(this.minY,t[e+5]);this.maxY=Math.max(this.maxY,t[e+1])}t.length>8&&(this.#Pe=t)}else[this.minX,this.minY,this.maxX,this.maxY]=e.data.rect}#Ue(e,t){if(this.minX>=e||this.maxX<=e||this.minY>=t||this.maxY<=t)return!1;const n=this.#Pe;if(!n)return!0;if(this.#ze>=0){const a=this.#ze;if(!(n[a]>=e||n[a+2]<=e||n[a+5]>=t||n[a+1]<=t))return!0;this.#ze=-1}for(let a=0,s=n.length;a<s;a+=8)if(!(n[a]>=e||n[a+2]<=e||n[a+5]>=t||n[a+1]<=t)){this.#ze=a;return!0}return!1}addGlyph(e,t,n){if(!this.#Ue(e,t)){this.disableExtraChars();return!1}if(this.#Ne.length>0){this.#Ee.push(this.#Ne.join(""));this.#Ne.length=0}this.#Ee.push(n);this.#Le=!0;return!0}addExtraChar(e){this.#Le&&this.#Ne.push(e)}disableExtraChars(){if(this.#Le){this.#Le=!1;this.#Ne.length=0}}setText(){this.#Me.data.overlaidText=this.#Ee.join("")}}const rl=64;class Intersector{#_e=[];#Xe=[];#We;#Ke;#Ge;#Ve;#$e;#Ye;constructor(e){let t=1/0,n=1/0,a=-1/0,s=-1/0;const r=this.#_e;for(const i of e){if(!i.data.quadPoints&&!i.data.rect)continue;const e=new SingleIntersector(i);r.push(e);t=Math.min(t,e.minX);n=Math.min(n,e.minY);a=Math.max(a,e.maxX);s=Math.max(s,e.maxY)}this.#We=t;this.#Ge=n;this.#Ke=a;this.#Ve=s;this.#$e=63/(a-t);this.#Ye=63/(s-n);for(const e of r){const t=this.#Je(e.minX,e.minY),n=this.#Je(e.maxX,e.maxY),a=(n-t)%rl,s=Math.floor((n-t)/rl);for(let n=t;n<=t+s*rl;n+=rl)for(let t=0;t<=a;t++){let a=this.#Xe[n+t];a||(this.#Xe[n+t]=a=[]);a.push(e)}}}#Je(e,t){return Math.floor((e-this.#We)*this.#$e)+Math.floor((t-this.#Ge)*this.#Ye)*rl}addGlyph(e,t,n,a){const s=e[4]+t/2,r=e[5]+n/2;if(s<this.#We||r<this.#Ge||s>this.#Ke||r>this.#Ve)return;const i=this.#Xe[this.#Je(s,r)];if(i)for(const e of i)e.addGlyph(s,r,a)}addExtraChar(e){for(const t of this.#_e)t.addExtraChar(e)}setText(){for(const e of this.#_e)e.setText()}}class Word64{constructor(e,t){this.high=0|e;this.low=0|t}and(e){this.high&=e.high;this.low&=e.low}xor(e){this.high^=e.high;this.low^=e.low}shiftRight(e){if(e>=32){this.low=this.high>>>e-32|0;this.high=0}else{this.low=this.low>>>e|this.high<<32-e;this.high=this.high>>>e|0}}rotateRight(e){let t,n;if(32&e){n=this.low;t=this.high}else{t=this.low;n=this.high}e&=31;this.low=t>>>e|n<<32-e;this.high=n>>>e|t<<32-e}not(){this.high=~this.high;this.low=~this.low}add(e){const t=(this.low>>>0)+(e.low>>>0);let n=(this.high>>>0)+(e.high>>>0);t>4294967295&&(n+=1);this.low=0|t;this.high=0|n}copyTo(e,t){e[t]=this.high>>>24&255;e[t+1]=this.high>>16&255;e[t+2]=this.high>>8&255;e[t+3]=255&this.high;e[t+4]=this.low>>>24&255;e[t+5]=this.low>>16&255;e[t+6]=this.low>>8&255;e[t+7]=255&this.low}assign(e){this.high=e.high;this.low=e.low}}const il={get k(){return shadow(this,"k",[new Word64(1116352408,3609767458),new Word64(1899447441,602891725),new Word64(3049323471,3964484399),new Word64(3921009573,2173295548),new Word64(961987163,4081628472),new Word64(1508970993,3053834265),new Word64(2453635748,2937671579),new Word64(2870763221,3664609560),new Word64(3624381080,2734883394),new Word64(310598401,1164996542),new Word64(607225278,1323610764),new Word64(1426881987,3590304994),new Word64(1925078388,4068182383),new Word64(2162078206,991336113),new Word64(2614888103,633803317),new Word64(3248222580,3479774868),new Word64(3835390401,2666613458),new Word64(4022224774,944711139),new Word64(264347078,2341262773),new Word64(604807628,2007800933),new Word64(770255983,1495990901),new Word64(1249150122,1856431235),new Word64(1555081692,3175218132),new Word64(1996064986,2198950837),new Word64(2554220882,3999719339),new Word64(2821834349,766784016),new Word64(2952996808,2566594879),new Word64(3210313671,3203337956),new Word64(3336571891,1034457026),new Word64(3584528711,2466948901),new Word64(113926993,3758326383),new Word64(338241895,168717936),new Word64(666307205,1188179964),new Word64(773529912,1546045734),new Word64(1294757372,1522805485),new Word64(1396182291,2643833823),new Word64(1695183700,2343527390),new Word64(1986661051,1014477480),new Word64(2177026350,1206759142),new Word64(2456956037,344077627),new Word64(2730485921,1290863460),new Word64(2820302411,3158454273),new Word64(3259730800,3505952657),new Word64(3345764771,106217008),new Word64(3516065817,3606008344),new Word64(3600352804,1432725776),new Word64(4094571909,1467031594),new Word64(275423344,851169720),new Word64(430227734,3100823752),new Word64(506948616,1363258195),new Word64(659060556,3750685593),new Word64(883997877,3785050280),new Word64(958139571,3318307427),new Word64(1322822218,3812723403),new Word64(1537002063,2003034995),new Word64(1747873779,3602036899),new Word64(1955562222,1575990012),new Word64(2024104815,1125592928),new Word64(2227730452,2716904306),new Word64(2361852424,442776044),new Word64(2428436474,593698344),new Word64(2756734187,3733110249),new Word64(3204031479,2999351573),new Word64(3329325298,3815920427),new Word64(3391569614,3928383900),new Word64(3515267271,566280711),new Word64(3940187606,3454069534),new Word64(4118630271,4000239992),new Word64(116418474,1914138554),new Word64(174292421,2731055270),new Word64(289380356,3203993006),new Word64(460393269,320620315),new Word64(685471733,587496836),new Word64(852142971,1086792851),new Word64(1017036298,365543100),new Word64(1126000580,2618297676),new Word64(1288033470,3409855158),new Word64(1501505948,4234509866),new Word64(1607167915,987167468),new Word64(1816402316,1246189591)])}};function ch(e,t,n,a,s){e.assign(t);e.and(n);s.assign(t);s.not();s.and(a);e.xor(s)}function maj(e,t,n,a,s){e.assign(t);e.and(n);s.assign(t);s.and(a);e.xor(s);s.assign(n);s.and(a);e.xor(s)}function sigma(e,t,n){e.assign(t);e.rotateRight(28);n.assign(t);n.rotateRight(34);e.xor(n);n.assign(t);n.rotateRight(39);e.xor(n)}function sigmaPrime(e,t,n){e.assign(t);e.rotateRight(14);n.assign(t);n.rotateRight(18);e.xor(n);n.assign(t);n.rotateRight(41);e.xor(n)}function littleSigma(e,t,n){e.assign(t);e.rotateRight(1);n.assign(t);n.rotateRight(8);e.xor(n);n.assign(t);n.shiftRight(7);e.xor(n)}function littleSigmaPrime(e,t,n){e.assign(t);e.rotateRight(19);n.assign(t);n.rotateRight(61);e.xor(n);n.assign(t);n.shiftRight(6);e.xor(n)}function calculateSHA512(e,t,n,a=!1){let s,r,i,o,l,f,c,h;if(a){s=new Word64(3418070365,3238371032);r=new Word64(1654270250,914150663);i=new Word64(2438529370,812702999);o=new Word64(355462360,4144912697);l=new Word64(1731405415,4290775857);f=new Word64(2394180231,1750603025);c=new Word64(3675008525,1694076839);h=new Word64(1203062813,3204075428)}else{s=new Word64(1779033703,4089235720);r=new Word64(3144134277,2227873595);i=new Word64(1013904242,4271175723);o=new Word64(2773480762,1595750129);l=new Word64(1359893119,2917565137);f=new Word64(2600822924,725511199);c=new Word64(528734635,4215389547);h=new Word64(1541459225,327033209)}const u=128*Math.ceil((n+17)/128),m=new Uint8Array(u);let p,d;for(p=0;p<n;++p)m[p]=e[t++];m[p++]=128;const g=u-16;p<g&&(p=g);p+=11;m[p++]=n>>>29&255;m[p++]=n>>21&255;m[p++]=n>>13&255;m[p++]=n>>5&255;m[p++]=n<<3&255;const b=new Array(80);for(p=0;p<80;p++)b[p]=new Word64(0,0);const{k:w}=il;let j=new Word64(0,0),k=new Word64(0,0),y=new Word64(0,0),q=new Word64(0,0),v=new Word64(0,0),S=new Word64(0,0),x=new Word64(0,0),C=new Word64(0,0);const F=new Word64(0,0),T=new Word64(0,0),H=new Word64(0,0),O=new Word64(0,0);let R,D;for(p=0;p<u;){for(d=0;d<16;++d){b[d].high=m[p]<<24|m[p+1]<<16|m[p+2]<<8|m[p+3];b[d].low=m[p+4]<<24|m[p+5]<<16|m[p+6]<<8|m[p+7];p+=8}for(d=16;d<80;++d){R=b[d];littleSigmaPrime(R,b[d-2],O);R.add(b[d-7]);littleSigma(H,b[d-15],O);R.add(H);R.add(b[d-16])}j.assign(s);k.assign(r);y.assign(i);q.assign(o);v.assign(l);S.assign(f);x.assign(c);C.assign(h);for(d=0;d<80;++d){F.assign(C);sigmaPrime(H,v,O);F.add(H);ch(H,v,S,x,O);F.add(H);F.add(w[d]);F.add(b[d]);sigma(T,j,O);maj(H,j,k,y,O);T.add(H);R=C;C=x;x=S;S=v;q.add(F);v=q;q=y;y=k;k=j;R.assign(F);R.add(T);j=R}s.add(j);r.add(k);i.add(y);o.add(q);l.add(v);f.add(S);c.add(x);h.add(C)}if(a){D=new Uint8Array(48);s.copyTo(D,0);r.copyTo(D,8);i.copyTo(D,16);o.copyTo(D,24);l.copyTo(D,32);f.copyTo(D,40)}else{D=new Uint8Array(64);s.copyTo(D,0);r.copyTo(D,8);i.copyTo(D,16);o.copyTo(D,24);l.copyTo(D,32);f.copyTo(D,40);c.copyTo(D,48);h.copyTo(D,56)}return D}function calculateSHA384(e,t,n){return calculateSHA512(e,t,n,!0)}const ol={get k(){return shadow(this,"k",[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298])}};function rotr(e,t){return e>>>t|e<<32-t}function calculate_sha256_ch(e,t,n){return e&t^~e&n}function calculate_sha256_maj(e,t,n){return e&t^e&n^t&n}function calculate_sha256_sigma(e){return rotr(e,2)^rotr(e,13)^rotr(e,22)}function calculate_sha256_sigmaPrime(e){return rotr(e,6)^rotr(e,11)^rotr(e,25)}function calculate_sha256_littleSigma(e){return rotr(e,7)^rotr(e,18)^e>>>3}function calculate_sha256_littleSigmaPrime(e){return rotr(e,17)^rotr(e,19)^e>>>10}function calculateSHA256(e,t,n){let a=1779033703,s=3144134277,r=1013904242,i=2773480762,o=1359893119,l=2600822924,f=528734635,c=1541459225;const h=64*Math.ceil((n+9)/64),u=new Uint8Array(h);let m,p;for(m=0;m<n;++m)u[m]=e[t++];u[m++]=128;const d=h-8;m<d&&(m=d);m+=3;u[m++]=n>>>29&255;u[m++]=n>>21&255;u[m++]=n>>13&255;u[m++]=n>>5&255;u[m++]=n<<3&255;const g=new Uint32Array(64),{k:b}=ol;for(m=0;m<h;){for(p=0;p<16;++p){g[p]=u[m]<<24|u[m+1]<<16|u[m+2]<<8|u[m+3];m+=4}for(p=16;p<64;++p)g[p]=calculate_sha256_littleSigmaPrime(g[p-2])+g[p-7]+calculate_sha256_littleSigma(g[p-15])+g[p-16]|0;let e,t,n=a,h=s,d=r,w=i,j=o,k=l,y=f,q=c;for(p=0;p<64;++p){e=q+calculate_sha256_sigmaPrime(j)+calculate_sha256_ch(j,k,y)+b[p]+g[p];t=calculate_sha256_sigma(n)+calculate_sha256_maj(n,h,d);q=y;y=k;k=j;j=w+e|0;w=d;d=h;h=n;n=e+t|0}a=a+n|0;s=s+h|0;r=r+d|0;i=i+w|0;o=o+j|0;l=l+k|0;f=f+y|0;c=c+q|0}return new Uint8Array([a>>24&255,a>>16&255,a>>8&255,255&a,s>>24&255,s>>16&255,s>>8&255,255&s,r>>24&255,r>>16&255,r>>8&255,255&r,i>>24&255,i>>16&255,i>>8&255,255&i,o>>24&255,o>>16&255,o>>8&255,255&o,l>>24&255,l>>16&255,l>>8&255,255&l,f>>24&255,f>>16&255,f>>8&255,255&f,c>>24&255,c>>16&255,c>>8&255,255&c])}class DecryptStream extends DecodeStream{constructor(e,t,n){super(t);this.stream=e;this.dict=e.dict;this.decrypt=n;this.nextChunk=null;this.initialized=!1}readBlock(){let e;if(this.initialized)e=this.nextChunk;else{e=this.stream.getBytes(512);this.initialized=!0}if(!e?.length){this.eof=!0;return}this.nextChunk=this.stream.getBytes(512);const t=this.nextChunk?.length>0;e=(0,this.decrypt)(e,!t);const n=this.bufferLength,a=n+e.length;this.ensureBuffer(a).set(e,n);this.bufferLength=a}getOriginalStream(){return this}}class ARCFourCipher{a=0;b=0;constructor(e){const t=new Uint8Array(256),n=e.length;for(let e=0;e<256;++e)t[e]=e;for(let a=0,s=0;a<256;++a){const r=t[a];s=s+r+e[a%n]&255;t[a]=t[s];t[s]=r}this.s=t}encryptBlock(e){let t=this.a,n=this.b;const a=this.s,s=e.length,r=new Uint8Array(s);for(let i=0;i<s;++i){t=t+1&255;const s=a[t];n=n+s&255;const o=a[n];a[t]=o;a[n]=s;r[i]=e[i]^a[s+o&255]}this.a=t;this.b=n;return r}decryptBlock(e){return this.encryptBlock(e)}encrypt(e){return this.encryptBlock(e)}}class NullCipher{decryptBlock(e){return e}encrypt(e){return e}}class AESBaseCipher{_s=new Uint8Array([99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22]);_inv_s=new Uint8Array([82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125]);_mix=new Uint32Array([0,235474187,470948374,303765277,941896748,908933415,607530554,708780849,1883793496,2118214995,1817866830,1649639237,1215061108,1181045119,1417561698,1517767529,3767586992,4003061179,4236429990,4069246893,3635733660,3602770327,3299278474,3400528769,2430122216,2664543715,2362090238,2193862645,2835123396,2801107407,3035535058,3135740889,3678124923,3576870512,3341394285,3374361702,3810496343,3977675356,4279080257,4043610186,2876494627,2776292904,3076639029,3110650942,2472011535,2640243204,2403728665,2169303058,1001089995,899835584,666464733,699432150,59727847,226906860,530400753,294930682,1273168787,1172967064,1475418501,1509430414,1942435775,2110667444,1876241833,1641816226,2910219766,2743034109,2976151520,3211623147,2505202138,2606453969,2302690252,2269728455,3711829422,3543599269,3240894392,3475313331,3843699074,3943906441,4178062228,4144047775,1306967366,1139781709,1374988112,1610459739,1975683434,2076935265,1775276924,1742315127,1034867998,866637845,566021896,800440835,92987698,193195065,429456164,395441711,1984812685,2017778566,1784663195,1683407248,1315562145,1080094634,1383856311,1551037884,101039829,135050206,437757123,337553864,1042385657,807962610,573804783,742039012,2531067453,2564033334,2328828971,2227573024,2935566865,2700099354,3001755655,3168937228,3868552805,3902563182,4203181171,4102977912,3736164937,3501741890,3265478751,3433712980,1106041591,1340463100,1576976609,1408749034,2043211483,2009195472,1708848333,1809054150,832877231,1068351396,766945465,599762354,159417987,126454664,361929877,463180190,2709260871,2943682380,3178106961,3009879386,2572697195,2538681184,2236228733,2336434550,3509871135,3745345300,3441850377,3274667266,3910161971,3877198648,4110568485,4211818798,2597806476,2497604743,2261089178,2295101073,2733856160,2902087851,3202437046,2968011453,3936291284,3835036895,4136440770,4169408201,3535486456,3702665459,3467192302,3231722213,2051518780,1951317047,1716890410,1750902305,1113818384,1282050075,1584504582,1350078989,168810852,67556463,371049330,404016761,841739592,1008918595,775550814,540080725,3969562369,3801332234,4035489047,4269907996,3569255213,3669462566,3366754619,3332740144,2631065433,2463879762,2160117071,2395588676,2767645557,2868897406,3102011747,3069049960,202008497,33778362,270040487,504459436,875451293,975658646,675039627,641025152,2084704233,1917518562,1615861247,1851332852,1147550661,1248802510,1484005843,1451044056,933301370,967311729,733156972,632953703,260388950,25965917,328671808,496906059,1206477858,1239443753,1543208500,1441952575,2144161806,1908694277,1675577880,1842759443,3610369226,3644379585,3408119516,3307916247,4011190502,3776767469,4077384432,4245618683,2809771154,2842737049,3144396420,3043140495,2673705150,2438237621,2203032232,2370213795]);_mixCol=new Uint8Array(256).map((e,t)=>t<128?t<<1:t<<1^27);constructor(){this.buffer=new Uint8Array(16);this.bufferPosition=0}_expandKey(e){unreachable("Cannot call `_expandKey` on the base class")}_decrypt(e,t){let n,a,s;const r=new Uint8Array(16);r.set(e);for(let e=0,n=this._keySize;e<16;++e,++n)r[e]^=t[n];for(let e=this._cyclesOfRepetition-1;e>=1;--e){n=r[13];r[13]=r[9];r[9]=r[5];r[5]=r[1];r[1]=n;n=r[14];a=r[10];r[14]=r[6];r[10]=r[2];r[6]=n;r[2]=a;n=r[15];a=r[11];s=r[7];r[15]=r[3];r[11]=n;r[7]=a;r[3]=s;for(let e=0;e<16;++e)r[e]=this._inv_s[r[e]];for(let n=0,a=16*e;n<16;++n,++a)r[n]^=t[a];for(let e=0;e<16;e+=4){const t=this._mix[r[e]],a=this._mix[r[e+1]],s=this._mix[r[e+2]],i=this._mix[r[e+3]];n=t^a>>>8^a<<24^s>>>16^s<<16^i>>>24^i<<8;r[e]=n>>>24&255;r[e+1]=n>>16&255;r[e+2]=n>>8&255;r[e+3]=255&n}}n=r[13];r[13]=r[9];r[9]=r[5];r[5]=r[1];r[1]=n;n=r[14];a=r[10];r[14]=r[6];r[10]=r[2];r[6]=n;r[2]=a;n=r[15];a=r[11];s=r[7];r[15]=r[3];r[11]=n;r[7]=a;r[3]=s;for(let e=0;e<16;++e){r[e]=this._inv_s[r[e]];r[e]^=t[e]}return r}_encrypt(e,t){const n=this._s;let a,s,r;const i=new Uint8Array(16);i.set(e);for(let e=0;e<16;++e)i[e]^=t[e];for(let e=1;e<this._cyclesOfRepetition;e++){for(let e=0;e<16;++e)i[e]=n[i[e]];r=i[1];i[1]=i[5];i[5]=i[9];i[9]=i[13];i[13]=r;r=i[2];s=i[6];i[2]=i[10];i[6]=i[14];i[10]=r;i[14]=s;r=i[3];s=i[7];a=i[11];i[3]=i[15];i[7]=r;i[11]=s;i[15]=a;for(let e=0;e<16;e+=4){const t=i[e],n=i[e+1],s=i[e+2],r=i[e+3];a=t^n^s^r;i[e]^=a^this._mixCol[t^n];i[e+1]^=a^this._mixCol[n^s];i[e+2]^=a^this._mixCol[s^r];i[e+3]^=a^this._mixCol[r^t]}for(let n=0,a=16*e;n<16;++n,++a)i[n]^=t[a]}for(let e=0;e<16;++e)i[e]=n[i[e]];r=i[1];i[1]=i[5];i[5]=i[9];i[9]=i[13];i[13]=r;r=i[2];s=i[6];i[2]=i[10];i[6]=i[14];i[10]=r;i[14]=s;r=i[3];s=i[7];a=i[11];i[3]=i[15];i[7]=r;i[11]=s;i[15]=a;for(let e=0,n=this._keySize;e<16;++e,++n)i[e]^=t[n];return i}_decryptBlock2(e,t){const n=e.length;let a=this.buffer,s=this.bufferPosition;const r=[];let i=this.iv;for(let t=0;t<n;++t){a[s]=e[t];++s;if(s<16)continue;const n=this._decrypt(a,this._key);for(let e=0;e<16;++e)n[e]^=i[e];i=a;r.push(n);a=new Uint8Array(16);s=0}this.buffer=a;this.bufferLength=s;this.iv=i;if(0===r.length)return new Uint8Array(0);let o=16*r.length;if(t){const e=r.at(-1);let t=e[15];if(t<=16){for(let n=15,a=16-t;n>=a;--n)if(e[n]!==t){t=0;break}o-=t;r[r.length-1]=e.subarray(0,16-t)}}const l=new Uint8Array(o);for(let e=0,t=0,n=r.length;e<n;++e,t+=16)l.set(r[e],t);return l}decryptBlock(e,t,n=null){const a=e.length,s=this.buffer;let r=this.bufferPosition;if(n)this.iv=n;else{for(let t=0;r<16&&t<a;++t,++r)s[r]=e[t];if(r<16){this.bufferLength=r;return new Uint8Array(0)}this.iv=s;e=e.subarray(16)}this.buffer=new Uint8Array(16);this.bufferLength=0;this.decryptBlock=this._decryptBlock2;return this.decryptBlock(e,t)}encrypt(e,t){const n=e.length;let a=this.buffer,s=this.bufferPosition;const r=[];t||=new Uint8Array(16);for(let i=0;i<n;++i){a[s]=e[i];++s;if(s<16)continue;for(let e=0;e<16;++e)a[e]^=t[e];const n=this._encrypt(a,this._key);t=n;r.push(n);a=new Uint8Array(16);s=0}this.buffer=a;this.bufferLength=s;this.iv=t;if(0===r.length)return new Uint8Array(0);const i=16*r.length,o=new Uint8Array(i);for(let e=0,t=0,n=r.length;e<n;++e,t+=16)o.set(r[e],t);return o}}class AES128Cipher extends AESBaseCipher{_rcon=new Uint8Array([141,1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145,57,114,228,211,189,97,194,159,37,74,148,51,102,204,131,29,58,116,232,203,141,1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145,57,114,228,211,189,97,194,159,37,74,148,51,102,204,131,29,58,116,232,203,141,1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145,57,114,228,211,189,97,194,159,37,74,148,51,102,204,131,29,58,116,232,203,141,1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145,57,114,228,211,189,97,194,159,37,74,148,51,102,204,131,29,58,116,232,203,141,1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145,57,114,228,211,189,97,194,159,37,74,148,51,102,204,131,29,58,116,232,203,141]);constructor(e){super();this._cyclesOfRepetition=10;this._keySize=160;this._key=this._expandKey(e)}_expandKey(e){const t=this._s,n=this._rcon,a=new Uint8Array(176);a.set(e);for(let e=16,s=1;e<176;++s){let r=a[e-3],i=a[e-2],o=a[e-1],l=a[e-4];r=t[r];i=t[i];o=t[o];l=t[l];r^=n[s];for(let t=0;t<4;++t){a[e]=r^=a[e-16];e++;a[e]=i^=a[e-16];e++;a[e]=o^=a[e-16];e++;a[e]=l^=a[e-16];e++}}return a}}class AES256Cipher extends AESBaseCipher{constructor(e){super();this._cyclesOfRepetition=14;this._keySize=224;this._key=this._expandKey(e)}_expandKey(e){const t=this._s,n=new Uint8Array(240);n.set(e);let a,s,r,i,o=1;for(let e=32,l=1;e<240;++l){if(e%32==16){a=t[a];s=t[s];r=t[r];i=t[i]}else if(e%32==0){a=n[e-3];s=n[e-2];r=n[e-1];i=n[e-4];a=t[a];s=t[s];r=t[r];i=t[i];a^=o;(o<<=1)>=256&&(o=255&(27^o))}for(let t=0;t<4;++t){n[e]=a^=n[e-32];e++;n[e]=s^=n[e-32];e++;n[e]=r^=n[e-32];e++;n[e]=i^=n[e-32];e++}}return n}}class PDFBase{_hash(e,t,n){unreachable("Abstract method `_hash` called")}checkOwnerPassword(e,t,n,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(n,e.length+t.length);return isArrayEqual(this._hash(e,s,n),a)}checkUserPassword(e,t,n){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);return isArrayEqual(this._hash(e,a,[]),n)}getOwnerKey(e,t,n,a){const s=new Uint8Array(e.length+56);s.set(e,0);s.set(t,e.length);s.set(n,e.length+t.length);const r=this._hash(e,s,n);return new AES256Cipher(r).decryptBlock(a,!1,new Uint8Array(16))}getUserKey(e,t,n){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);const s=this._hash(e,a,[]);return new AES256Cipher(s).decryptBlock(n,!1,new Uint8Array(16))}}class PDF17 extends PDFBase{_hash(e,t,n){return calculateSHA256(t,0,t.length)}}class PDF20 extends PDFBase{_hash(e,t,n){let a=calculateSHA256(t,0,t.length).subarray(0,32),s=[0],r=0;for(;r<64||s.at(-1)>r-32;){const t=e.length+a.length+n.length,i=new Uint8Array(t);let o=0;i.set(e,o);o+=e.length;i.set(a,o);o+=a.length;i.set(n,o);const l=new Uint8Array(64*t);for(let e=0,n=0;e<64;e++,n+=t)l.set(i,n);s=new AES128Cipher(a.subarray(0,16)).encrypt(l,a.subarray(16,32));const f=Math.sumPrecise(s.slice(0,16))%3;0===f?a=calculateSHA256(s,0,s.length):1===f?a=calculateSHA384(s,0,s.length):2===f&&(a=calculateSHA512(s,0,s.length));r++}return a.subarray(0,32)}}class CipherTransform{constructor(e,t){this.StringCipherConstructor=e;this.StreamCipherConstructor=t}createStream(e,t){const n=new this.StreamCipherConstructor;return new DecryptStream(e,t,function cipherTransformDecryptStream(e,t){return n.decryptBlock(e,t)})}decryptString(e){const t=new this.StringCipherConstructor;let n=stringToBytes(e);n=t.decryptBlock(n,!0);return bytesToString(n)}encryptString(e){const t=new this.StringCipherConstructor;if(t instanceof AESBaseCipher){const n=16-e.length%16;e+=String.fromCharCode(n).repeat(n);const a=new Uint8Array(16);crypto.getRandomValues(a);let s=stringToBytes(e);s=t.encrypt(s,a);const r=new Uint8Array(16+s.length);r.set(a);r.set(s,16);return bytesToString(r)}let n=stringToBytes(e);n=t.encrypt(n);return bytesToString(n)}}class CipherTransformFactory{static get _defaultPasswordBytes(){return shadow(this,"_defaultPasswordBytes",new Uint8Array([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]))}#Qe(e,t,n,a,s,r,i,o,l,f,c,h){if(t){const e=Math.min(127,t.length);t=t.subarray(0,e)}else t=[];const u=6===e?new PDF20:new PDF17;return u.checkUserPassword(t,o,i)?u.getUserKey(t,l,c):t.length&&u.checkOwnerPassword(t,a,r,n)?u.getOwnerKey(t,s,r,f):null}#Ze(e,t,n,a,s,r,i,o){const l=40+n.length+e.length,f=new Uint8Array(l);let c,h,u=0;if(t){h=Math.min(32,t.length);for(;u<h;++u)f[u]=t[u]}c=0;for(;u<32;)f[u++]=CipherTransformFactory._defaultPasswordBytes[c++];f.set(n,u);u+=n.length;f[u++]=255&s;f[u++]=s>>8&255;f[u++]=s>>16&255;f[u++]=s>>>24&255;f.set(e,u);u+=e.length;if(r>=4&&!o){f.fill(255,u,u+4);u+=4}let m=calculateMD5(f,0,u);const p=i>>3;if(r>=3)for(c=0;c<50;++c)m=calculateMD5(m,0,p);const d=m.subarray(0,p);let g,b;if(r>=3){u=0;f.set(CipherTransformFactory._defaultPasswordBytes,u);u+=32;f.set(e,u);u+=e.length;g=new ARCFourCipher(d);b=g.encryptBlock(calculateMD5(f,0,u));h=d.length;const t=new Uint8Array(h);for(c=1;c<=19;++c){for(let e=0;e<h;++e)t[e]=d[e]^c;g=new ARCFourCipher(t);b=g.encryptBlock(b)}}else{g=new ARCFourCipher(d);b=g.encryptBlock(CipherTransformFactory._defaultPasswordBytes)}return b.every((e,t)=>a[t]===e)?d:null}#et(e,t,n,a){const s=new Uint8Array(32);let r=0;const i=Math.min(32,e.length);for(;r<i;++r)s[r]=e[r];let o=0;for(;r<32;)s[r++]=CipherTransformFactory._defaultPasswordBytes[o++];let l=calculateMD5(s,0,r);const f=a>>3;if(n>=3)for(o=0;o<50;++o)l=calculateMD5(l,0,l.length);let c,h;if(n>=3){h=t;const e=new Uint8Array(f);for(o=19;o>=0;o--){for(let t=0;t<f;++t)e[t]=l[t]^o;c=new ARCFourCipher(e);h=c.encryptBlock(h)}}else{c=new ARCFourCipher(l.subarray(0,f));h=c.encryptBlock(t)}return h}#tt(e,t,n,a=!1){const s=n.length,r=new Uint8Array(s+9);r.set(n);let i=s;r[i++]=255&e;r[i++]=e>>8&255;r[i++]=e>>16&255;r[i++]=255&t;r[i++]=t>>8&255;if(a){r[i++]=115;r[i++]=65;r[i++]=108;r[i++]=84}return calculateMD5(r,0,i).subarray(0,Math.min(s+5,16))}#nt(e,t,n,a,s){if(!(t instanceof Name))throw new FormatError("Invalid crypt filter name.");const r=this,i=e.get(t.name),o=i?.get("CFM");if(!o||"None"===o.name)return function(){return new NullCipher};if("V2"===o.name)return function(){return new ARCFourCipher(r.#tt(n,a,s,!1))};if("AESV2"===o.name)return function(){return new AES128Cipher(r.#tt(n,a,s,!0))};if("AESV3"===o.name)return function(){return new AES256Cipher(s)};throw new FormatError("Unknown crypto method")}constructor(e,t,n){const a=e.get("Filter");if(!isName(a,"Standard"))throw new FormatError("unknown encryption method");this.filterName=a.name;this.dict=e;const s=e.get("V");if(!Number.isInteger(s)||1!==s&&2!==s&&4!==s&&5!==s)throw new FormatError("unsupported encryption algorithm");this.algorithm=s;let r=e.get("Length");if(!r)if(s<=3)r=40;else{const t=e.get("CF"),n=e.get("StmF");if(t instanceof Dict&&n instanceof Name){t.suppressEncryption=!0;const e=t.get(n.name);r=e?.get("Length")||128;r<40&&(r<<=3)}}if(!Number.isInteger(r)||r<40||r%8!=0)throw new FormatError("invalid key length");const i=stringToBytes(e.get("O")),o=stringToBytes(e.get("U")),l=i.subarray(0,32),f=o.subarray(0,32),c=e.get("P"),h=e.get("R"),u=(4===s||5===s)&&!1!==e.get("EncryptMetadata");this.encryptMetadata=u;const m=stringToBytes(t);let p,d;if(n){if(6===h)try{n=utf8StringToString(n)}catch{warn("CipherTransformFactory: Unable to convert UTF8 encoded password.")}p=stringToBytes(n)}if(5!==s)d=this.#Ze(m,p,l,f,c,h,r,u);else{const t=i.subarray(32,40),n=i.subarray(40,48),a=o.subarray(0,48),s=o.subarray(32,40),r=o.subarray(40,48),c=stringToBytes(e.get("OE")),u=stringToBytes(e.get("UE")),m=stringToBytes(e.get("Perms"));d=this.#Qe(h,p,l,t,n,a,f,s,r,c,u,m)}if(!d){if(!n)throw new PasswordException("No password given",Jt);const e=this.#et(p,l,h,r);d=this.#Ze(m,e,l,f,c,h,r,u)}if(!d)throw new PasswordException("Incorrect Password",Qt);if(4===s&&d.length<16){this.encryptionKey=new Uint8Array(16);this.encryptionKey.set(d)}else this.encryptionKey=d;if(s>=4){const t=e.get("CF");t instanceof Dict&&(t.suppressEncryption=!0);this.cf=t;this.stmf=e.get("StmF")||Name.get("Identity");this.strf=e.get("StrF")||Name.get("Identity");this.eff=e.get("EFF")||this.stmf}}createCipherTransform(e,t){if(4===this.algorithm||5===this.algorithm)return new CipherTransform(this.#nt(this.cf,this.strf,e,t,this.encryptionKey),this.#nt(this.cf,this.stmf,e,t,this.encryptionKey));const n=this.#tt(e,t,this.encryptionKey,!1),cipherConstructor=function(){return new ARCFourCipher(n)};return new CipherTransform(cipherConstructor,cipherConstructor)}}class XRef{constructor(e,t){this.stream=e;this.pdfManager=t;this.entries=[];this._xrefStms=new Set;this._cacheMap=new Map;this._pendingRefs=new RefSet;this._newPersistentRefNum=null;this._newTemporaryRefNum=null;this._persistentRefsCache=null}getNewPersistentRef(e){null===this._newPersistentRefNum&&(this._newPersistentRefNum=this.entries.length||1);const t=this._newPersistentRefNum++;this._cacheMap.set(t,e);return Ref.get(t,0)}getNewTemporaryRef(){if(null===this._newTemporaryRefNum){this._newTemporaryRefNum=this.entries.length||1;if(this._newPersistentRefNum){this._persistentRefsCache=new Map;for(let e=this._newTemporaryRefNum;e<this._newPersistentRefNum;e++){this._persistentRefsCache.set(e,this._cacheMap.get(e));this._cacheMap.delete(e)}}}return Ref.get(this._newTemporaryRefNum++,0)}resetNewTemporaryRef(){this._newTemporaryRefNum=null;if(this._persistentRefsCache)for(const[e,t]of this._persistentRefsCache)this._cacheMap.set(e,t);this._persistentRefsCache=null}setStartXRef(e){this.startXRefQueue=[e]}parse(e=!1){let t,n,a;if(e){warn("Indexing all PDF objects");t=this.indexObjects()}else t=this.readXRef();t.assignXref(this);this.trailer=t;try{n=t.get("Encrypt")}catch(e){if(e instanceof MissingDataException)throw e;warn(`XRef.parse - Invalid "Encrypt" reference: "${e}".`)}if(n instanceof Dict){const e=t.get("ID"),a=e?.length?e[0]:"";n.suppressEncryption=!0;this.encrypt=new CipherTransformFactory(n,a,this.pdfManager.password)}try{a=t.get("Root")}catch(e){if(e instanceof MissingDataException)throw e;warn(`XRef.parse - Invalid "Root" reference: "${e}".`)}if(a instanceof Dict)try{if(a.get("Pages")instanceof Dict){this.root=a;return}}catch(e){if(e instanceof MissingDataException)throw e;warn(`XRef.parse - Invalid "Pages" reference: "${e}".`)}if(!e)throw new XRefParseException;throw new InvalidPDFException("Invalid Root reference.")}processXRefTable(e){"tableState"in this||(this.tableState={entryNum:0,streamPos:e.lexer.stream.pos,parserBuf1:e.buf1,parserBuf2:e.buf2});if(!isCmd(this.readXRefTable(e),"trailer"))throw new FormatError("Invalid XRef table: could not find trailer dictionary");let t=e.getObj();t instanceof Dict||!t.dict||(t=t.dict);if(!(t instanceof Dict))throw new FormatError("Invalid XRef table: could not parse trailer dictionary");delete this.tableState;return t}readXRefTable(e){const t=e.lexer.stream,n=this.tableState;t.pos=n.streamPos;e.buf1=n.parserBuf1;e.buf2=n.parserBuf2;let a;for(;;){if(!("firstEntryNum"in n)||!("entryCount"in n)){if(isCmd(a=e.getObj(),"trailer"))break;n.firstEntryNum=a;n.entryCount=e.getObj()}let s=n.firstEntryNum;const r=n.entryCount;if(!Number.isInteger(s)||!Number.isInteger(r))throw new FormatError("Invalid XRef table: wrong types in subsection header");for(let a=n.entryNum;a<r;a++){n.streamPos=t.pos;n.entryNum=a;n.parserBuf1=e.buf1;n.parserBuf2=e.buf2;const i={};i.offset=e.getObj();i.gen=e.getObj();const o=e.getObj();if(o instanceof Cmd)switch(o.cmd){case"f":i.free=!0;break;case"n":i.uncompressed=!0}if(!Number.isInteger(i.offset)||!Number.isInteger(i.gen)||!i.free&&!i.uncompressed)throw new FormatError(`Invalid entry in XRef subsection: ${s}, ${r}`);0===a&&i.free&&1===s&&(s=0);this.entries[a+s]||(this.entries[a+s]=i)}n.entryNum=0;n.streamPos=t.pos;n.parserBuf1=e.buf1;n.parserBuf2=e.buf2;delete n.firstEntryNum;delete n.entryCount}if(this.entries[0]&&!this.entries[0].free)throw new FormatError("Invalid XRef table: unexpected first object");return a}processXRefStream(e){if(!("streamState"in this)){const{dict:t,pos:n}=e,a=t.get("W"),s=t.get("Index")||[0,t.get("Size")];this.streamState={entryRanges:s,byteWidths:a,entryNum:0,streamPos:n}}this.readXRefStream(e);delete this.streamState;return e.dict}readXRefStream(e){const t=this.streamState;e.pos=t.streamPos;const[n,a,s]=t.byteWidths,r=t.entryRanges;for(;r.length>0;){const[i,o]=r;if(!Number.isInteger(i)||!Number.isInteger(o))throw new FormatError(`Invalid XRef range fields: ${i}, ${o}`);if(!Number.isInteger(n)||!Number.isInteger(a)||!Number.isInteger(s))throw new FormatError(`Invalid XRef entry fields length: ${i}, ${o}`);for(let r=t.entryNum;r<o;++r){t.entryNum=r;t.streamPos=e.pos;let o=0,l=0,f=0;for(let t=0;t<n;++t){const t=e.getByte();if(-1===t)throw new FormatError("Invalid XRef byteWidths 'type'.");o=o<<8|t}0===n&&(o=1);for(let t=0;t<a;++t){const t=e.getByte();if(-1===t)throw new FormatError("Invalid XRef byteWidths 'offset'.");l=l<<8|t}for(let t=0;t<s;++t){const t=e.getByte();if(-1===t)throw new FormatError("Invalid XRef byteWidths 'generation'.");f=f<<8|t}const c={};c.offset=l;c.gen=f;switch(o){case 0:c.free=!0;break;case 1:c.uncompressed=!0;break;case 2:break;default:throw new FormatError(`Invalid XRef entry type: ${o}`)}this.entries[i+r]||(this.entries[i+r]=c)}t.entryNum=0;t.streamPos=e.pos;r.splice(0,2)}}indexObjects(){function readToken(e,t){let n="",a=e[t];for(;10!==a&&13!==a&&60!==a&&!(++t>=e.length);){n+=String.fromCharCode(a);a=e[t]}return n}function skipUntil(e,t,n){const a=n.length,s=e.length;let r=0;for(;t<s;){let s=0;for(;s<a&&e[t+s]===n[s];)++s;if(s>=a)break;t++;r++}return r}const e=/\b(endobj|\d+\s+\d+\s+obj|xref|trailer\s*<<)\b/g,t=/\b(startxref|\d+\s+\d+\s+obj)\b/g,n=/^(\d+)\s+(\d+)\s+obj\b/,a=new Uint8Array([116,114,97,105,108,101,114]),s=new Uint8Array([115,116,97,114,116,120,114,101,102]),r=new Uint8Array([47,88,82,101,102]);this.entries.length=0;this._cacheMap.clear();const i=this.stream;i.pos=0;const o=i.getBytes(),l=bytesToString(o),f=o.length;let c=i.start;const h=[],u=[];for(;c<f;){let m=o[c];if(9===m||10===m||13===m||32===m){++c;continue}if(37===m){do{++c;if(c>=f)break;m=o[c]}while(10!==m&&13!==m);continue}const p=readToken(o,c);let d;if(p.startsWith("xref")&&(4===p.length||/\s/.test(p[4]))){c+=skipUntil(o,c,a);h.push(c);c+=skipUntil(o,c,s)}else if(d=n.exec(p)){const t=0|d[1],n=0|d[2],a=c+p.length;let s,h=!1;if(this.entries[t]){if(this.entries[t].gen===n)try{new Parser({lexer:new Lexer(i.makeSubStream(a))}).getObj();h=!0}catch(e){e instanceof ParserEOFException?warn(`indexObjects -- checking object (${p}): "${e}".`):h=!0}}else h=!0;h&&(this.entries[t]={offset:c-i.start,gen:n,uncompressed:!0});e.lastIndex=a;const m=e.exec(l);if(m){s=e.lastIndex+1-c;if("endobj"!==m[1]){warn(`indexObjects: Found "${m[1]}" inside of another "obj", caused by missing "endobj" -- trying to recover.`);s-=m[1].length+1}}else s=f-c;const g=o.subarray(c,c+s),b=skipUntil(g,0,r);if(b<s&&g[b+5]<64){u.push(c-i.start);this._xrefStms.add(c-i.start)}c+=s}else if(p.startsWith("trailer")&&(7===p.length||/\s/.test(p[7]))){h.push(c);const e=c+p.length;let n;t.lastIndex=e;const a=t.exec(l);if(a){n=t.lastIndex+1-c;if("startxref"!==a[1]){warn(`indexObjects: Found "${a[1]}" after "trailer", caused by missing "startxref" -- trying to recover.`);n-=a[1].length+1}}else n=f-c;c+=n}else c+=p.length+1}for(const e of u){this.startXRefQueue.push(e);this.readXRef(!0)}const m=[];let p,d,g=!1;for(const e of h){i.pos=e;const t=new Parser({lexer:new Lexer(i),xref:this,allowStreams:!0,recoveryMode:!0});if(!isCmd(t.getObj(),"trailer"))continue;const n=t.getObj();if(n instanceof Dict){m.push(n);n.has("Encrypt")&&(g=!0)}}for(const e of[...m,"genFallback",...m]){if("genFallback"===e){if(!d)break;this._generationFallback=!0;continue}let t=!1;try{const n=e.get("Root");if(!(n instanceof Dict))continue;const a=n.get("Pages");if(!(a instanceof Dict))continue;const s=a.get("Count");Number.isInteger(s)&&(t=!0)}catch(e){d=e;continue}if(t&&(!g||e.has("Encrypt"))&&e.has("ID"))return e;p=e}if(p)return p;if(this.topDict)return this.topDict;if(!m.length)for(const e in this.entries){const t=this.entries[e];if(!t)continue;const n=Ref.get(parseInt(e),t.gen);let a;try{a=this.fetch(n)}catch{continue}a instanceof BaseStream&&(a=a.dict);if(a instanceof Dict&&a.has("Root"))return a}throw new InvalidPDFException("Invalid PDF structure.")}readXRef(e=!1){const t=this.stream,n=new Set;for(;this.startXRefQueue.length;){try{const e=this.startXRefQueue[0];if(n.has(e)){warn("readXRef - skipping XRef table since it was already parsed.");this.startXRefQueue.shift();continue}n.add(e);t.pos=e+t.start;const a=new Parser({lexer:new Lexer(t),xref:this,allowStreams:!0});let s,r=a.getObj();if(isCmd(r,"xref")){s=this.processXRefTable(a);this.topDict||(this.topDict=s);r=s.get("XRefStm");if(Number.isInteger(r)&&!this._xrefStms.has(r)){this._xrefStms.add(r);this.startXRefQueue.push(r)}}else{if(!Number.isInteger(r))throw new FormatError("Invalid XRef stream header");if(!(Number.isInteger(a.getObj())&&isCmd(a.getObj(),"obj")&&(r=a.getObj())instanceof BaseStream))throw new FormatError("Invalid XRef stream");s=this.processXRefStream(r);this.topDict||(this.topDict=s);if(!s)throw new FormatError("Failed to read XRef stream")}r=s.get("Prev");Number.isInteger(r)?this.startXRefQueue.push(r):r instanceof Ref&&this.startXRefQueue.push(r.num)}catch(e){if(e instanceof MissingDataException)throw e;info("(while reading XRef): "+e)}this.startXRefQueue.shift()}if(this.topDict)return this.topDict;if(!e)throw new XRefParseException}getEntry(e){const t=this.entries[e];return t&&!t.free&&t.offset?t:null}fetchIfRef(e,t=!1){return e instanceof Ref?this.fetch(e,t):e}fetch(e,t=!1){if(!(e instanceof Ref))throw new Error("ref object is not a reference");const n=e.num,a=this._cacheMap.get(n);if(void 0!==a){a instanceof Dict&&!a.objId&&(a.objId=e.toString());return a}let s=this.getEntry(n);if(null===s)return s;if(this._pendingRefs.has(e)){this._pendingRefs.remove(e);warn(`Ignoring circular reference: ${e}.`);return rn}this._pendingRefs.put(e);try{s=s.uncompressed?this.fetchUncompressed(e,s,t):this.fetchCompressed(e,s,t);this._pendingRefs.remove(e)}catch(t){this._pendingRefs.remove(e);throw t}s instanceof Dict?s.objId=e.toString():s instanceof BaseStream&&(s.dict.objId=e.toString());return s}fetchUncompressed(e,t,n=!1){const a=e.gen;let s=e.num;if(t.gen!==a){const r=`Inconsistent generation in XRef: ${e}`;if(this._generationFallback&&t.gen<a){warn(r);return this.fetchUncompressed(Ref.get(s,t.gen),t,n)}throw new XRefEntryException(r)}const r=this.stream.makeSubStream(t.offset+this.stream.start),i=new Parser({lexer:new Lexer(r),xref:this,allowStreams:!0}),o=i.getObj(),l=i.getObj(),f=i.getObj();if(o!==s||l!==a||!(f instanceof Cmd))throw new XRefEntryException(`Bad (uncompressed) XRef entry: ${e}`);if("obj"!==f.cmd){if(f.cmd.startsWith("obj")){s=parseInt(f.cmd.substring(3),10);if(!Number.isNaN(s))return s}throw new XRefEntryException(`Bad (uncompressed) XRef entry: ${e}`)}(t=this.encrypt&&!n?i.getObj(this.encrypt.createCipherTransform(s,a)):i.getObj())instanceof BaseStream||this._cacheMap.set(s,t);return t}fetchCompressed(e,t,n=!1){const a=t.offset,s=this.fetch(Ref.get(a,0));if(!(s instanceof BaseStream))throw new FormatError("bad ObjStm stream");const r=s.dict.get("First"),i=s.dict.get("N");if(!Number.isInteger(r)||!Number.isInteger(i))throw new FormatError("invalid first and n parameters for ObjStm stream");let o=new Parser({lexer:new Lexer(s),xref:this,allowStreams:!0});const l=new Array(i),f=new Array(i);for(let e=0;e<i;++e){const t=o.getObj();if(!Number.isInteger(t))throw new FormatError(`invalid object number in the ObjStm stream: ${t}`);const n=o.getObj();if(!Number.isInteger(n))throw new FormatError(`invalid object offset in the ObjStm stream: ${n}`);l[e]=t;const s=this.getEntry(t);s?.offset===a&&s.gen!==e&&(s.gen=e);f[e]=n}const c=(s.start||0)+r,h=new Array(i);for(let e=0;e<i;++e){const t=e<i-1?f[e+1]-f[e]:void 0;if(t<0)throw new FormatError("Invalid offset in the ObjStm stream.");o=new Parser({lexer:new Lexer(s.makeSubStream(c+f[e],t,s.dict)),xref:this,allowStreams:!0});const n=o.getObj();h[e]=n;if(n instanceof BaseStream)continue;const r=l[e],u=this.entries[r];u&&u.offset===a&&u.gen===e&&this._cacheMap.set(r,n)}if(void 0===(t=h[t.gen]))throw new XRefEntryException(`Bad (compressed) XRef entry: ${e}`);return t}async fetchIfRefAsync(e,t){return e instanceof Ref?this.fetchAsync(e,t):e}async fetchAsync(e,t){try{return this.fetch(e,t)}catch(n){if(!(n instanceof MissingDataException))throw n;await this.pdfManager.requestRange(n.begin,n.end);return this.fetchAsync(e,t)}}getCatalogObj(){return this.root}}const ll=[0,0,612,792];class Page{#at=!1;#st=null;constructor({pdfManager:e,xref:t,pageIndex:n,pageDict:a,ref:s,globalIdFactory:r,fontCache:i,builtInCMapCache:o,standardFontDataCache:l,globalColorSpaceCache:f,globalImageCache:c,systemFontCache:h,nonBlendModesSet:u,xfaFactory:m}){this.pdfManager=e;this.pageIndex=n;this.pageDict=a;this.xref=t;this.ref=s;this.fontCache=i;this.builtInCMapCache=o;this.standardFontDataCache=l;this.globalColorSpaceCache=f;this.globalImageCache=c;this.systemFontCache=h;this.nonBlendModesSet=u;this.evaluatorOptions=e.evaluatorOptions;this.xfaFactory=m;const p={obj:0};this._localIdFactory=class extends r{static createObjId(){return`p${n}_${++p.obj}`}static getPageObjId(){return`p${s.toString()}`}}}#rt(e,t=this.pageIndex){return new PartialEvaluator({xref:this.xref,handler:e,pageIndex:t,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalColorSpaceCache:this.globalColorSpaceCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions})}#it(e,t=!1){const n=getInheritableProperty({dict:this.pageDict,key:e,getArray:t,stopWhenFound:!1});return Array.isArray(n)?1!==n.length&&n[0]instanceof Dict?Dict.merge({xref:this.xref,dictArray:n}):n[0]:n}get content(){return this.pageDict.getArray("Contents")}get resources(){const e=this.#it("Resources");return shadow(this,"resources",e instanceof Dict?e:Dict.empty)}getBoundingBox(e){if(this.xfaData)return this.xfaData.bbox;const t=lookupNormalRect(this.#it(e,!0),null);if(t){if(t[2]-t[0]>0&&t[3]-t[1]>0)return t;warn(`Empty, or invalid, /${e} entry.`)}return null}get mediaBox(){return shadow(this,"mediaBox",this.getBoundingBox("MediaBox")||ll)}get cropBox(){return shadow(this,"cropBox",this.getBoundingBox("CropBox")||this.mediaBox)}get userUnit(){const e=this.pageDict.get("UserUnit");return shadow(this,"userUnit","number"==typeof e&&e>0?e:1)}get view(){const{cropBox:e,mediaBox:t}=this;if(e!==t&&!isArrayEqual(e,t)){const n=Util.intersect(e,t);if(n&&n[2]-n[0]>0&&n[3]-n[1]>0)return shadow(this,"view",n);warn("Empty /CropBox and /MediaBox intersection.")}return shadow(this,"view",t)}get rotate(){let e=this.#it("Rotate")||0;e%90!=0?e=0:e>=360?e%=360:e<0&&(e=(e%360+360)%360);return shadow(this,"rotate",e)}#ot(e,t){if(!this.evaluatorOptions.ignoreErrors)throw e;warn(`getContentStream - ignoring sub-stream (${t}): "${e}".`)}async getContentStream(){const e=await this.pdfManager.ensure(this,"content");if(e instanceof BaseStream&&!e.isImageStream){if(e.isAsync){const t=await e.asyncGetBytes();if(t)return new Stream(t,0,t.length,e.dict)}return e}if(Array.isArray(e)){const t=[];for(let n=0,a=e.length;n<a;n++){const a=e[n];a instanceof BaseStream&&a.isAsync&&t.push(a.asyncGetBytes().then(t=>{t&&(e[n]=new Stream(t,0,t.length,a.dict))}))}t.length>0&&await Promise.all(t);return new StreamsSequenceStream(e,this.#ot.bind(this))}return new NullStream}get xfaData(){return shadow(this,"xfaData",this.xfaFactory?{bbox:this.xfaFactory.getBoundingBox(this.pageIndex)}:null)}async#lt(e,t,n){const a=[];for(const s of e)if(s.id){const e=Ref.fromString(s.id);if(!e){warn(`A non-linked annotation cannot be modified: ${s.id}`);continue}if(s.deleted){t.put(e,e);if(s.popupRef){const e=Ref.fromString(s.popupRef);e&&t.put(e,e)}continue}if(s.popup?.deleted){const e=Ref.fromString(s.popupRef);e&&t.put(e,e)}n?.put(e);s.ref=e;a.push(this.xref.fetchAsync(e).then(e=>{e instanceof Dict&&(s.oldAnnotation=e.clone())},()=>{warn(`Cannot fetch \`oldAnnotation\` for: ${e}.`)}));delete s.id}await Promise.all(a)}async saveNewAnnotations(e,t,n,a,s){if(this.xfaFactory)throw new Error("XFA: Cannot save new annotations.");const r=this.#rt(e),i=new RefSetCache,o=new RefSet;await this.#lt(n,i,o);const l=this.pageDict,f=this.annotations.filter(e=>!(e instanceof Ref&&i.has(e))),c=await AnnotationFactory.saveNewAnnotations(r,t,n,a,s);for(const{ref:e}of c.annotations)e instanceof Ref&&!o.has(e)&&f.push(e);const h=l.clone();h.set("Annots",f);s.put(this.ref,{data:h});for(const e of i)s.put(e,{data:null})}async save(e,t,n,a){const s=this.#rt(e),r=await this._parsedAnnotations,i=[];for(const e of r)i.push(e.save(s,t,n,a).catch(function(e){warn(`save - ignoring annotation data during "${t.name}" task: "${e}".`);return null}));return Promise.all(i)}async loadResources(e){await(this.#st??=this.pdfManager.ensure(this,"resources"));await ObjectLoader.load(this.resources,e,this.xref)}async#ft(e,t){const n=e?.get("Resources");if(!(n instanceof Dict&&n.size))return this.resources;await ObjectLoader.load(n,t,this.xref);return Dict.merge({xref:this.xref,dictArray:[n,this.resources],mergeSubDicts:!0})}async getOperatorList({handler:e,sink:t,task:n,intent:a,cacheKey:s,pageIndex:l=this.pageIndex,annotationStorage:u=null,modifiedIds:p=null}){const d=this.getContentStream(),g=this.loadResources(dn),b=this.#rt(e,l),w=this.xfaFactory?null:getNewAnnotationsMap(u),j=w?.get(this.pageIndex);let k=Promise.resolve(null),y=null;if(j){const e=this.pdfManager.ensureDoc("annotationGlobals");let t;const a=new Set;for(const{bitmapId:e,bitmap:t}of j)!e||t||a.has(e)||a.add(e);const{isOffscreenCanvasSupported:s}=this.evaluatorOptions;if(a.size>0){const e=j.slice();for(const[t,n]of u)t.startsWith(m)&&n.bitmap&&a.has(n.bitmapId)&&e.push(n);t=AnnotationFactory.generateImages(e,this.xref,s)}else t=AnnotationFactory.generateImages(j,this.xref,s);y=new RefSet;k=Promise.all([e,this.#lt(j,y,null)]).then(([e])=>e?AnnotationFactory.printNewAnnotations(e,b,n,j,t):null)}const q=Promise.all([d,g]).then(async([r])=>{const i=await this.#ft(r.dict,dn),o=new OperatorList(a,t);e.send("StartRenderPage",{transparency:b.hasBlendModes(i,this.nonBlendModesSet),pageIndex:l,cacheKey:s});await b.getOperatorList({stream:r,task:n,resources:i,operatorList:o});return o});let[v,S,x]=await Promise.all([q,this._parsedAnnotations,k]);if(x){S=S.filter(e=>!(e.ref&&y.has(e.ref)));for(let e=0,t=x.length;e<t;e++){const n=x[e];if(n.refToReplace){const a=S.findIndex(e=>e.ref&&isRefsEqual(e.ref,n.refToReplace));if(a>=0){S.splice(a,1,n);x.splice(e--,1);t--}}}S=S.concat(x)}if(0===S.length||a&c){v.flush(!0);return{length:v.totalLength}}const C=!!(a&f),F=!!(a&h),T=!!(a&r),H=!!(a&i),O=!!(a&o),R=[];for(const e of S)(T||H&&e.mustBeViewed(u,C)&&e.mustBeViewedWhenEditing(F,p)||O&&e.mustBePrinted(u))&&R.push(e.getOperatorList(b,n,a,u).catch(function(e){warn(`getOperatorList - ignoring annotation data during "${n.name}" task: "${e}".`);return{opList:null,separateForm:!1,separateCanvas:!1}}));const D=await Promise.all(R);let M=!1,E=!1;for(const{opList:e,separateForm:t,separateCanvas:n}of D){v.addOpList(e);M||=t;E||=n}v.flush(!0,{form:M,canvas:E});return{length:v.totalLength}}async extractTextContent({handler:e,task:t,includeMarkedContent:n,disableNormalization:a,sink:s,intersector:r=null}){const i=this.getContentStream(),o=this.loadResources(gn),l=this.pdfManager.ensureCatalog("lang"),[f,,c]=await Promise.all([i,o,l]),h=await this.#ft(f.dict,gn);return this.#rt(e).getTextContent({stream:f,task:t,resources:h,includeMarkedContent:n,disableNormalization:a,sink:s,viewBox:this.view,lang:c,intersector:r})}async getStructTree(){const e=await this.pdfManager.ensureCatalog("structTreeRoot");if(!e)return null;await this._parsedAnnotations;try{const t=await this.pdfManager.ensure(this,"_parseStructTree",[e]);return await this.pdfManager.ensure(t,"serializable")}catch(e){warn(`getStructTree: "${e}".`);return null}}_parseStructTree(e){const t=new StructTreePage(e,this.pageDict);t.parse(this.ref);return t}async getAnnotationsData(e,t,n){const a=await this._parsedAnnotations;if(0===a.length)return a;const s=[],l=[];let f;const c=!!(n&r),h=!!(n&i),u=!!(n&o),m=[];for(const n of a){const a=c||h&&n.viewable;(a||u&&n.printable)&&s.push(n.data);if(n.hasTextContent&&a){f??=this.#rt(e);l.push(n.extractTextContent(f,t,[-1/0,-1/0,1/0,1/0]).catch(function(e){warn(`getAnnotationsData - ignoring textContent during "${t.name}" task: "${e}".`)}))}else n.overlaysTextContent&&a&&m.push(n)}if(m.length>0){const n=new Intersector(m);l.push(this.extractTextContent({handler:e,task:t,includeMarkedContent:!1,disableNormalization:!1,sink:null,viewBox:this.view,lang:null,intersector:n}).then(()=>{n.setText()}))}await Promise.all(l);return s}get annotations(){const e=this.#it("Annots");return shadow(this,"annotations",Array.isArray(e)?e:[])}get _parsedAnnotations(){const e=this.pdfManager.ensure(this,"annotations").then(async e=>{if(0===e.length)return e;const[t,n]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureDoc("fieldObjects")]);if(!t)return[];const a=n?.orphanFields,s=[];for(const n of e)s.push(AnnotationFactory.create(this.xref,n,t,this._localIdFactory,!1,a,null,this.ref).catch(function(e){warn(`_parsedAnnotations: "${e}".`);return null}));const r=[];let i,o;for(const e of await Promise.all(s))e&&(e instanceof WidgetAnnotation?(o||=[]).push(e):e instanceof PopupAnnotation?(i||=[]).push(e):r.push(e));o&&r.push(...o);i&&r.push(...i);return r});this.#at=!0;return shadow(this,"_parsedAnnotations",e)}get jsActions(){return shadow(this,"jsActions",collectActions(this.xref,this.pageDict,ie))}async collectAnnotationsByType(e,t,n,a,s){const{pageIndex:r}=this;if(this.#at){const e=await this._parsedAnnotations;for(const{data:t}of e)if(!n||n.has(t.annotationType)){t.pageIndex=r;a.push(Promise.resolve(t))}return}const i=await this.pdfManager.ensure(this,"annotations");for(const o of i)a.push(AnnotationFactory.create(this.xref,o,s,this._localIdFactory,!1,null,n,this.ref).then(async n=>{if(!n)return null;n.data.pageIndex=r;if(n.hasTextContent&&n.viewable){const a=this.#rt(e);await n.extractTextContent(a,t,[-1/0,-1/0,1/0,1/0])}return n.data}).catch(function(e){warn(`collectAnnotationsByType: "${e}".`);return null}))}}const fl=new Uint8Array([37,80,68,70,45]),cl=new Uint8Array([115,116,97,114,116,120,114,101,102]),hl=new Uint8Array([101,110,100,111,98,106]);function find(e,t,n=1024,a=!1){const s=t.length,r=e.peekBytes(n),i=r.length-s;if(i<=0)return!1;if(a){const n=s-1;let a=r.length-1;for(;a>=n;){let i=0;for(;i<s&&r[a-i]===t[n-i];)i++;if(i>=s){e.pos+=a-n;return!0}a--}}else{let n=0;for(;n<=i;){let a=0;for(;a<s&&r[n+a]===t[a];)a++;if(a>=s){e.pos+=n;return!0}n++}}return!1}class PDFDocument{#ct=new Map;#ht=null;constructor(e,t){if(t.length<=0)throw new InvalidPDFException("The PDF file is empty, i.e. its size is zero bytes.");this.pdfManager=e;this.stream=t;this.xref=new XRef(t,e);const n={font:0};this._globalIdFactory=class{static getDocId(){return`g_${e.docId}`}static createFontId(){return"f"+ ++n.font}static createObjId(){unreachable("Abstract method `createObjId` called.")}static getPageObjId(){unreachable("Abstract method `getPageObjId` called.")}}}parse(e){this.xref.parse(e);this.catalog=new Catalog(this.pdfManager,this.xref)}get linearization(){let e=null;try{e=Linearization.create(this.stream)}catch(e){if(e instanceof MissingDataException)throw e;info(e)}return shadow(this,"linearization",e)}get startXRef(){const e=this.stream;let t=0;if(this.linearization){e.reset();if(find(e,hl)){e.skip(6);let n=e.peekByte();for(;isWhiteSpace(n);){e.pos++;n=e.peekByte()}t=e.pos-e.start}}else{const n=1024,a=cl.length;let s=!1,r=e.end;for(;!s&&r>0;){r-=n-a;r<0&&(r=0);e.pos=r;s=find(e,cl,n,!0)}if(s){e.skip(9);let n;do{n=e.getByte()}while(isWhiteSpace(n));let a="";for(;n>=32&&n<=57;){a+=String.fromCharCode(n);n=e.getByte()}t=parseInt(a,10);isNaN(t)&&(t=0)}}return shadow(this,"startXRef",t)}checkHeader(){const e=this.stream;e.reset();if(!find(e,fl))return;e.moveStart();e.skip(fl.length);let t,n="";for(;(t=e.getByte())>32&&n.length<7;)n+=String.fromCharCode(t);un.test(n)?this.#ht=n:warn(`Invalid PDF header version: ${n}`)}parseStartXRef(){this.xref.setStartXRef(this.startXRef)}get numPages(){let e=0;e=this.catalog.hasActualNumPages?this.catalog.numPages:this.xfaFactory?this.xfaFactory.getNumPages():this.linearization?this.linearization.numPages:this.catalog.numPages;return shadow(this,"numPages",e)}#ut(e,t=0){return!!Array.isArray(e)&&e.every(e=>{if(!((e=this.xref.fetchIfRef(e))instanceof Dict))return!1;if(e.has("Kids")){if(++t>10){warn("#hasOnlyDocumentSignatures: maximum recursion depth reached");return!1}return this.#ut(e.get("Kids"),t)}const n=isName(e.get("FT"),"Sig"),a=e.get("Rect"),s=Array.isArray(a)&&a.every(e=>0===e);return n&&s})}get _xfaStreams(){const{acroForm:e}=this.catalog;if(!e)return null;const t=e.get("XFA"),n=new Map(["xdp:xdp","template","datasets","config","connectionSet","localeSet","stylesheet","/xdp:xdp"].map(e=>[e,null]));if(t instanceof BaseStream&&!t.isEmpty){n.set("xdp:xdp",t);return n}if(!Array.isArray(t)||0===t.length)return null;for(let e=0,a=t.length;e<a;e+=2){let s;s=0===e?"xdp:xdp":e===a-2?"/xdp:xdp":t[e];if(!n.has(s))continue;const r=this.xref.fetchIfRef(t[e+1]);r instanceof BaseStream&&!r.isEmpty&&n.set(s,r)}return n}get xfaDatasets(){const e=this._xfaStreams;if(!e)return shadow(this,"xfaDatasets",null);for(const t of["datasets","xdp:xdp"]){const n=e.get(t);if(n)try{const e=stringToUTF8String(n.getString());return shadow(this,"xfaDatasets",new DatasetReader({[t]:e}))}catch{warn("XFA - Invalid utf-8 string.");break}}return shadow(this,"xfaDatasets",null)}get xfaData(){const e=this._xfaStreams;if(!e)return null;const t=Object.create(null);for(const[n,a]of e)if(a)try{t[n]=stringToUTF8String(a.getString())}catch{warn("XFA - Invalid utf-8 string.");return null}return t}get xfaFactory(){let e;this.pdfManager.enableXfa&&this.catalog.needsRendering&&this.formInfo.hasXfa&&!this.formInfo.hasAcroForm&&(e=this.xfaData);return shadow(this,"xfaFactory",e?new XFAFactory(e):null)}get isPureXfa(){return!!this.xfaFactory&&this.xfaFactory.isValid()}get htmlForXfa(){return this.xfaFactory?this.xfaFactory.getPages():null}async#mt(){const e=await this.pdfManager.ensureCatalog("xfaImages");e&&this.xfaFactory.setImages(e)}async#pt(e,t){const n=await this.pdfManager.ensureCatalog("acroForm");if(!n)return;const a=await n.getAsync("DR");if(!(a instanceof Dict))return;await ObjectLoader.load(a,["Font"],this.xref);const s=a.get("Font");if(!(s instanceof Dict))return;const r=Object.assign(Object.create(null),this.pdfManager.evaluatorOptions,{useSystemFonts:!1}),{builtInCMapCache:i,fontCache:o,standardFontDataCache:l}=this.catalog,f=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:-1,idFactory:this._globalIdFactory,fontCache:o,builtInCMapCache:i,standardFontDataCache:l,options:r}),c=new OperatorList,h=[],u={get font(){return h.at(-1)},set font(e){h.push(e)},clone(){return this}},parseFont=(e,n,s)=>f.handleSetFont(a,[Name.get(e),1],null,c,t,u,n,s).catch(e=>{warn(`loadXfaFonts: "${e}".`);return null}),m=[];for(const[e,t]of s){const n=t.get("FontDescriptor");if(!(n instanceof Dict))continue;let a=n.get("FontFamily");a=a.replaceAll(/[ ]+(\d)/g,"$1");const s={fontFamily:a,fontWeight:n.get("FontWeight"),italicAngle:-n.get("ItalicAngle")};validateCSSFont(s)&&m.push(parseFont(e,null,s))}await Promise.all(m);const p=this.xfaFactory.setFonts(h);if(!p)return;r.ignoreErrors=!0;m.length=0;h.length=0;const d=new Set;for(const e of p)getXfaFontName(`${e}-Regular`)||d.add(e);d.size&&p.push("PdfJS-Fallback");for(const e of p)if(!d.has(e))for(const t of[{name:"Regular",fontWeight:400,italicAngle:0},{name:"Bold",fontWeight:700,italicAngle:0},{name:"Italic",fontWeight:400,italicAngle:12},{name:"BoldItalic",fontWeight:700,italicAngle:12}]){const n=`${e}-${t.name}`;m.push(parseFont(n,getXfaFontDict(n),{fontFamily:e,fontWeight:t.fontWeight,italicAngle:t.italicAngle}))}await Promise.all(m);this.xfaFactory.appendFonts(h,d)}loadXfaResources(e,t){return Promise.all([this.#pt(e,t).catch(()=>{}),this.#mt()])}serializeXfaData(e){return this.xfaFactory?this.xfaFactory.serializeData(e):null}get version(){return this.catalog.version||this.#ht}get formInfo(){const e={hasFields:!1,hasAcroForm:!1,hasXfa:!1,hasSignatures:!1},{acroForm:t}=this.catalog;if(!t)return shadow(this,"formInfo",e);try{const n=t.get("Fields"),a=Array.isArray(n)&&n.length>0;e.hasFields=a;const s=t.get("XFA");e.hasXfa=Array.isArray(s)&&s.length>0||s instanceof BaseStream&&!s.isEmpty;const r=!!(1&t.get("SigFlags")),i=r&&this.#ut(n);e.hasAcroForm=a&&!i;e.hasSignatures=r}catch(e){if(e instanceof MissingDataException)throw e;warn(`Cannot fetch form information: "${e}".`)}return shadow(this,"formInfo",e)}get documentInfo(){const{catalog:e,formInfo:t,xref:n}=this,a={PDFFormatVersion:this.version,Language:e.lang,EncryptFilterName:n.encrypt?.filterName??null,IsLinearized:!!this.linearization,IsAcroFormPresent:t.hasAcroForm,IsXFAPresent:t.hasXfa,IsCollectionPresent:!!e.collection,IsSignaturesPresent:t.hasSignatures};let s;try{s=n.trailer.get("Info")}catch(e){if(e instanceof MissingDataException)throw e;info("The document information dictionary is invalid.")}if(!(s instanceof Dict))return shadow(this,"documentInfo",a);for(const[e,t]of s){switch(e){case"Title":case"Author":case"Subject":case"Keywords":case"Creator":case"Producer":case"CreationDate":case"ModDate":if("string"==typeof t){a[e]=stringToPDFString(t);continue}break;case"Trapped":if(t instanceof Name){a[e]=t;continue}break;default:let n;switch(typeof t){case"string":n=stringToPDFString(t);break;case"number":case"boolean":n=t;break;default:t instanceof Name&&(n=t)}if(void 0===n){warn(`Bad value, for custom key "${e}", in Info: ${t}.`);continue}a.Custom??=Object.create(null);a.Custom[e]=n;continue}warn(`Bad value, for key "${e}", in Info: ${t}.`)}return shadow(this,"documentInfo",a)}get fingerprints(){const e="\0".repeat(16);function validate(t){return"string"==typeof t&&16===t.length&&t!==e}const t=this.xref.trailer.get("ID");let n,a;if(Array.isArray(t)&&validate(t[0])){n=stringToBytes(t[0]);t[1]!==t[0]&&validate(t[1])&&(a=stringToBytes(t[1]))}else n=calculateMD5(this.stream.getByteRange(0,1024),0,1024);return shadow(this,"fingerprints",[n.toHex(),a?.toHex()??null])}async#dt(e){const{catalog:t,linearization:n,xref:a}=this,s=Ref.get(n.objectNumberFirst,0);try{const e=await a.fetchAsync(s);if(e instanceof Dict){let n=e.getRaw("Type");n instanceof Ref&&(n=await a.fetchAsync(n));if(isName(n,"Page")||!e.has("Type")&&!e.has("Kids")&&e.has("Contents")){t.pageKidsCountCache.has(s)||t.pageKidsCountCache.put(s,1);t.pageIndexCache.has(s)||t.pageIndexCache.put(s,0);return[e,s]}}throw new FormatError("The Linearization dictionary doesn't point to a valid Page dictionary.")}catch(n){warn(`_getLinearizationPage: "${n.message}".`);return t.getPageDict(e)}}getPage(e){const t=this.#ct.get(e);if(t)return t;const{catalog:n,linearization:a,xfaFactory:s}=this;let r;r=s?Promise.resolve([Dict.empty,null]):a?.pageFirst===e?this.#dt(e):n.getPageDict(e);r=r.then(([t,a])=>new Page({pdfManager:this.pdfManager,xref:this.xref,pageIndex:e,pageDict:t,ref:a,globalIdFactory:this._globalIdFactory,fontCache:n.fontCache,builtInCMapCache:n.builtInCMapCache,standardFontDataCache:n.standardFontDataCache,globalColorSpaceCache:n.globalColorSpaceCache,globalImageCache:n.globalImageCache,systemFontCache:n.systemFontCache,nonBlendModesSet:n.nonBlendModesSet,xfaFactory:s}));this.#ct.set(e,r);return r}async checkFirstPage(e=!1){if(!e)try{await this.getPage(0)}catch(e){if(e instanceof XRefEntryException){this.#ct.delete(0);await this.cleanup();throw new XRefParseException}}}async checkLastPage(e=!1){const{catalog:t,pdfManager:n}=this;t.setActualNumPages();let a;try{await Promise.all([n.ensureDoc("xfaFactory"),n.ensureDoc("linearization"),n.ensureCatalog("numPages")]);if(this.xfaFactory)return;a=this.linearization?this.linearization.numPages:t.numPages;if(!Number.isInteger(a))throw new FormatError("Page count is not an integer.");if(a<=1)return;await this.getPage(a-1)}catch(s){this.#ct.delete(a-1);await this.cleanup();if(s instanceof XRefEntryException&&!e)throw new XRefParseException;warn(`checkLastPage - invalid /Pages tree /Count: ${a}.`);let r;try{r=await t.getAllPageDicts(e)}catch(n){if(n instanceof XRefEntryException&&!e)throw new XRefParseException;t.setActualNumPages(1);return}for(const[e,[a,s]]of r){let r;if(a instanceof Error){r=Promise.reject(a);r.catch(()=>{})}else r=Promise.resolve(new Page({pdfManager:n,xref:this.xref,pageIndex:e,pageDict:a,ref:s,globalIdFactory:this._globalIdFactory,fontCache:t.fontCache,builtInCMapCache:t.builtInCMapCache,standardFontDataCache:t.standardFontDataCache,globalColorSpaceCache:this.globalColorSpaceCache,globalImageCache:t.globalImageCache,systemFontCache:t.systemFontCache,nonBlendModesSet:t.nonBlendModesSet,xfaFactory:null}));this.#ct.set(e,r)}t.setActualNumPages(r.size)}}async fontFallback(e,t){const{catalog:n,pdfManager:a}=this;for(const s of await Promise.all(n.fontCache))if(s.loadedName===e){s.fallback(t,a.evaluatorOptions);return}}async cleanup(e=!1){return this.catalog?this.catalog.cleanup(e):clearGlobalCaches()}async#gt(e,t,n,a,s,r,i){const{xref:o}=this;if(!(n instanceof Ref)||r.has(n))return;r.put(n);const l=await o.fetchAsync(n);if(!(l instanceof Dict))return;let f=await l.getAsync("Subtype");f=f instanceof Name?f.name:null;if("Link"===f)return;if(l.has("T")){const t=stringToPDFString(await l.getAsync("T"));e=""===e?t:`${e}.${t}`}else{let n=l;for(;;){n=n.getRaw("Parent")||t;if(n instanceof Ref){if(r.has(n))break;n=await o.fetchAsync(n)}if(!(n instanceof Dict))break;if(n.has("T")){const t=stringToPDFString(await n.getAsync("T"));e=""===e?t:`${e}.${t}`;break}}}t&&!l.has("Parent")&&isName(l.get("Subtype"),"Widget")&&i.put(n,t);a.getOrInsertComputed(e,makeArr).push(AnnotationFactory.create(o,n,s,null,!0,i,null,null).then(e=>e?.getFieldObject()).catch(function(e){warn(`#collectFieldObjects: "${e}".`);return null}));if(!l.has("Kids"))return;const c=await l.getAsync("Kids");if(Array.isArray(c))for(const t of c)await this.#gt(e,n,t,a,s,r,i)}get fieldObjects(){return shadow(this,"fieldObjects",this.pdfManager.ensureDoc("formInfo").then(async e=>{if(!e.hasFields)return null;const t=await this.annotationGlobals;if(!t)return null;const{acroForm:n}=t,a=new RefSet,s=Object.create(null),r=new Map,i=new RefSetCache;for(const e of n.get("Fields"))await this.#gt("",null,e,r,t,a,i);const o=[];for(const[e,t]of r)o.push(Promise.all(t).then(t=>{(t=t.filter(e=>!!e)).length>0&&(s[e]=t)}));await Promise.all(o);return{allFields:objectSize(s)>0?s:null,orphanFields:i}}))}get hasJSActions(){return shadow(this,"hasJSActions",this.pdfManager.ensureDoc("_parseHasJSActions"))}async _parseHasJSActions(){const[e,t]=await Promise.all([this.pdfManager.ensureCatalog("jsActions"),this.pdfManager.ensureDoc("fieldObjects")]);return!!e||!!t?.allFields&&Object.values(t.allFields).some(e=>e.some(e=>null!==e.actions))}get calculationOrderIds(){const e=this.catalog.acroForm?.get("CO");if(!Array.isArray(e)||0===e.length)return shadow(this,"calculationOrderIds",null);const t=[];for(const n of e)n instanceof Ref&&t.push(n.toString());return shadow(this,"calculationOrderIds",t.length?t:null)}get annotationGlobals(){return shadow(this,"annotationGlobals",AnnotationFactory.createGlobals(this.pdfManager))}}class BasePdfManager{constructor({docBaseUrl:e,docId:t,enableXfa:n,evaluatorOptions:a,handler:s,password:r}){this._docBaseUrl=function parseDocBaseUrl(e){if(e){const t=createValidAbsoluteUrl(e);if(t)return t.href;warn(`Invalid absolute docBaseUrl: "${e}".`)}return null}(e);this._docId=t;this._password=r;this.enableXfa=n;a.isOffscreenCanvasSupported&&=FeatureTest.isOffscreenCanvasSupported;a.isImageDecoderSupported&&=FeatureTest.isImageDecoderSupported;this.evaluatorOptions=Object.freeze(a);ImageResizer.setOptions(a);JpegStream.setOptions(a);OperatorList.setOptions(a);const i={...a,handler:s};JpxImage.setOptions(i);IccColorSpace.setOptions(i);CmykICCBasedCS.setOptions(i);JBig2CCITTFaxWasmImage.setOptions(i)}get docId(){return this._docId}get password(){return this._password}get docBaseUrl(){return this._docBaseUrl}ensureDoc(e,t){return this.ensure(this.pdfDocument,e,t)}ensureXRef(e,t){return this.ensure(this.pdfDocument.xref,e,t)}ensureCatalog(e,t){return this.ensure(this.pdfDocument.catalog,e,t)}getPage(e){return this.pdfDocument.getPage(e)}fontFallback(e,t){return this.pdfDocument.fontFallback(e,t)}cleanup(e=!1){return this.pdfDocument.cleanup(e)}async ensure(e,t,n){unreachable("Abstract method `ensure` called")}requestRange(e,t){unreachable("Abstract method `requestRange` called")}requestLoadedStream(e=!1){unreachable("Abstract method `requestLoadedStream` called")}sendProgressiveData(e){unreachable("Abstract method `sendProgressiveData` called")}updatePassword(e){this._password=e}terminate(e){unreachable("Abstract method `terminate` called")}}class LocalPdfManager extends BasePdfManager{constructor(e){super(e);const t=new Stream(e.source);this.pdfDocument=new PDFDocument(this,t);this._loadedStreamPromise=Promise.resolve(t)}async ensure(e,t,n){const a=e[t];return"function"==typeof a?a.apply(e,n):a}requestRange(e,t){return Promise.resolve()}requestLoadedStream(e=!1){return this._loadedStreamPromise}terminate(e){}}class NetworkPdfManager extends BasePdfManager{constructor(e){super(e);this.streamManager=new ChunkedStreamManager(e.source,{msgHandler:e.handler,length:e.length,disableAutoFetch:e.disableAutoFetch,rangeChunkSize:e.rangeChunkSize});this.pdfDocument=new PDFDocument(this,this.streamManager.getStream())}async ensure(e,t,n){try{const a=e[t];return"function"==typeof a?a.apply(e,n):a}catch(a){if(!(a instanceof MissingDataException))throw a;await this.requestRange(a.begin,a.end);return this.ensure(e,t,n)}}requestRange(e,t){return this.streamManager.requestRange(e,t)}requestLoadedStream(e=!1){return this.streamManager.requestAllChunks(e)}sendProgressiveData(e){this.streamManager.onReceiveData({chunk:e})}terminate(e){this.streamManager.abort(e)}}const ul=1,ml=2,pl=1,dl=2,gl=3,bl=4,wl=5,jl=6,kl=7,yl=8;function onFn(){}function wrapReason(e){if(e instanceof AbortException||e instanceof InvalidPDFException||e instanceof PasswordException||e instanceof ResponseException||e instanceof UnknownErrorException)return e;e instanceof Error||"object"==typeof e&&null!==e||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(e.name){case"AbortException":return new AbortException(e.message);case"InvalidPDFException":return new InvalidPDFException(e.message);case"PasswordException":return new PasswordException(e.message,e.code);case"ResponseException":return new ResponseException(e.message,e.status,e.missing);case"UnknownErrorException":return new UnknownErrorException(e.message,e.details)}return new UnknownErrorException(e.message,e.toString())}class MessageHandler{#bt=new AbortController;constructor(e,t,n){this.sourceName=e;this.targetName=t;this.comObj=n;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);n.addEventListener("message",this.#wt.bind(this),{signal:this.#bt.signal})}#wt({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#jt(e);return}if(e.callback){const t=e.callbackId,n=this.callbackCapabilities[t];if(!n)throw new Error(`Cannot resolve callback ${t}`);delete this.callbackCapabilities[t];if(e.callback===ul)n.resolve(e.data);else{if(e.callback!==ml)throw new Error("Unexpected callback case");n.reject(wrapReason(e.reason))}return}const t=this.actionHandler[e.action];if(!t)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const n=this.sourceName,a=e.sourceName,s=this.comObj;Promise.try(t,e.data).then(function(t){s.postMessage({sourceName:n,targetName:a,callback:ul,callbackId:e.callbackId,data:t})},function(t){s.postMessage({sourceName:n,targetName:a,callback:ml,callbackId:e.callbackId,reason:wrapReason(t)})});return}e.streamId?this.#kt(e):t(e.data)}on(e,t){const n=this.actionHandler;if(n[e])throw new Error(`There is already an actionName called "${e}"`);n[e]=t}send(e,t,n){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},n)}sendWithPromise(e,t,n){const a=this.callbackId++,s=Promise.withResolvers();this.callbackCapabilities[a]=s;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:a,data:t},n)}catch(e){s.reject(e)}return s.promise}sendWithStream(e,t,n,a){const s=this.streamId++,r=this.sourceName,i=this.targetName,o=this.comObj;return new ReadableStream({start:n=>{const l=Promise.withResolvers();this.streamControllers[s]={controller:n,startCall:l,pullCall:null,cancelCall:null,isClosed:!1};o.postMessage({sourceName:r,targetName:i,action:e,streamId:s,data:t,desiredSize:n.desiredSize},a);return l.promise},pull:e=>{const t=Promise.withResolvers();this.streamControllers[s].pullCall=t;o.postMessage({sourceName:r,targetName:i,stream:jl,streamId:s,desiredSize:e.desiredSize});return t.promise},cancel:e=>{assert(e instanceof Error,"cancel must have a valid reason");const t=Promise.withResolvers();this.streamControllers[s].cancelCall=t;this.streamControllers[s].isClosed=!0;o.postMessage({sourceName:r,targetName:i,stream:pl,streamId:s,reason:wrapReason(e)});return t.promise}},n)}#kt(e){const t=e.streamId,n=this.sourceName,a=e.sourceName,s=this.comObj,r=this,i=this.actionHandler[e.action],o={enqueue(e,r=1,i){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=r;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}s.postMessage({sourceName:n,targetName:a,stream:bl,streamId:t,chunk:e},i)},close(){if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:n,targetName:a,stream:gl,streamId:t});delete r.streamSinks[t]}},error(e){assert(e instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:n,targetName:a,stream:wl,streamId:t,reason:wrapReason(e)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};o.sinkCapability.resolve();o.ready=o.sinkCapability.promise;this.streamSinks[t]=o;Promise.try(i,e.data,o).then(function(){s.postMessage({sourceName:n,targetName:a,stream:yl,streamId:t,success:!0})},function(e){s.postMessage({sourceName:n,targetName:a,stream:yl,streamId:t,reason:wrapReason(e)})})}#jt(e){const t=e.streamId,n=this.sourceName,a=e.sourceName,s=this.comObj,r=this.streamControllers[t],i=this.streamSinks[t];switch(e.stream){case yl:e.success?r.startCall.resolve():r.startCall.reject(wrapReason(e.reason));break;case kl:e.success?r.pullCall.resolve():r.pullCall.reject(wrapReason(e.reason));break;case jl:if(!i){s.postMessage({sourceName:n,targetName:a,stream:kl,streamId:t,success:!0});break}i.desiredSize<=0&&e.desiredSize>0&&i.sinkCapability.resolve();i.desiredSize=e.desiredSize;Promise.try(i.onPull||onFn).then(function(){s.postMessage({sourceName:n,targetName:a,stream:kl,streamId:t,success:!0})},function(e){s.postMessage({sourceName:n,targetName:a,stream:kl,streamId:t,reason:wrapReason(e)})});break;case bl:assert(r,"enqueue should have stream controller");if(r.isClosed)break;r.controller.enqueue(e.chunk);break;case gl:assert(r,"close should have stream controller");if(r.isClosed)break;r.isClosed=!0;r.controller.close();this.#yt(r,t);break;case wl:assert(r,"error should have stream controller");r.controller.error(wrapReason(e.reason));this.#yt(r,t);break;case dl:e.success?r.cancelCall.resolve():r.cancelCall.reject(wrapReason(e.reason));this.#yt(r,t);break;case pl:if(!i)break;const o=wrapReason(e.reason);Promise.try(i.onCancel||onFn,o).then(function(){s.postMessage({sourceName:n,targetName:a,stream:dl,streamId:t,success:!0})},function(e){s.postMessage({sourceName:n,targetName:a,stream:dl,streamId:t,reason:wrapReason(e)})});i.sinkCapability.reject(o);i.isCancelled=!0;delete this.streamSinks[t];break;default:throw new Error("Unexpected stream case")}}async#yt(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]);delete this.streamControllers[t]}destroy(){this.#bt?.abort();this.#bt=null}}async function writeObject(e,t,n,{encrypt:a=null,encryptRef:s=null}){const r=a&&s!==e?a.createCipherTransform(e.num,e.gen):null;n.push(`${e.num} ${e.gen} obj\n`);await writeValue(t,n,r);n.push("\nendobj\n")}async function writeDict(e,t,n){t.push("<<");for(const[a,s]of e.getRawEntries()){t.push(` /${escapePDFName(a)} `);await writeValue(s,t,n)}t.push(">>")}async function writeValue(e,t,n){if(e instanceof Name)t.push(`/${escapePDFName(e.name)}`);else if(e instanceof Ref)t.push(`${e.num} ${e.gen} R`);else if(Array.isArray(e)||ArrayBuffer.isView(e))await async function writeArray(e,t,n){t.push("[");for(let a=0,s=e.length;a<s;a++){await writeValue(e[a],t,n);a<s-1&&t.push(" ")}t.push("]")}(e,t,n);else if("string"==typeof e){n&&(e=n.encryptString(e));t.push(`(${escapeString(e)})`)}else"number"==typeof e||"boolean"==typeof e?t.push(e.toString()):e instanceof Dict?await writeDict(e,t,n):e instanceof BaseStream?await async function writeStream(e,t,n){(e=e.getOriginalStream()).reset();let a=e.getBytes();const{dict:s}=e,[r,i]=await Promise.all([s.getAsync("Filter"),s.getAsync("DecodeParms")]),o=isName(Array.isArray(r)?await s.xref.fetchIfRefAsync(r[0]):r,"FlateDecode");if(a.length>=256&&!o)try{const e=new CompressionStream("deflate"),t=e.writable.getWriter();await t.ready;t.write(a).then(async()=>{await t.ready;await t.close()}).catch(()=>{});const n=await new Response(e.readable).arrayBuffer();a=new Uint8Array(n);let l,f;if(r){if(!o){l=Array.isArray(r)?[Name.get("FlateDecode"),...r]:[Name.get("FlateDecode"),r];i&&(f=Array.isArray(i)?[null,...i]:[null,i])}}else l=Name.get("FlateDecode");l&&s.set("Filter",l);f&&s.set("DecodeParms",f)}catch(e){info(`writeStream - cannot compress data: "${e}".`)}let l=bytesToString(a);n&&(l=n.encryptString(l));s.set("Length",l.length);await writeDict(s,t,n);t.push(" stream\n",l,"\nendstream")}(e,t,n):null===e?t.push("null"):warn(`Unhandled value in writer: ${typeof e}, please file a bug.`)}function writeInt(e,t,n,a){for(let s=t+n-1;s>n-1;s--){a[s]=255&e;e>>=8}return n+t}function writeString(e,t,n){const a=e.length;for(let s=0;s<a;s++)n[t+s]=255&e.charCodeAt(s);return t+a}function updateXFA({xfaData:e,xfaDatasetsRef:t,changes:n,xref:a}){if(null===e){e=function writeXFADataForAcroform(e,t){const n=new SimpleXMLParser({hasAttributes:!0}).parseFromString(e);for(const{xfa:e}of t){if(!e)continue;const{path:t,value:a}=e;if(!t)continue;const s=parseXFAPath(t);let r=n.documentElement.searchNode(s,0);!r&&s.length>1&&(r=n.documentElement.searchNode([s.at(-1)],0));r?r.childNodes=Array.isArray(a)?a.map(e=>new SimpleDOMNode("value",e)):[new SimpleDOMNode("#text",a)]:warn(`Node not found for path: ${t}`)}const a=[];n.documentElement.dump(a);return a.join("")}(a.fetchIfRef(t).getString(),n)}const s=new StringStream(e);s.dict=new Dict(a);s.dict.setIfName("Type","EmbeddedFile");n.put(t,{data:s})}function getIndexes(e){const t=[];for(const{ref:n}of e)n.num===t.at(-2)+t.at(-1)?t[t.length-1]+=1:t.push(n.num,1);return t}function computeIDs(e,t,n){if(Array.isArray(t.fileIds)&&t.fileIds.length>0){const a=function computeMD5(e,t){const n=Math.floor(Date.now()/1e3),a=t.filename||"",s=[n.toString(),a,e.toString(),...t.infoMap.values()],r=Math.sumPrecise(s.map(e=>e.length)),i=new Uint8Array(r);let o=0;for(const e of s)o=writeString(e,o,i);return bytesToString(calculateMD5(i,0,i.length))}(e,t);n.set("ID",[t.fileIds[0]||a,a])}}async function incrementalUpdate({originalData:e,xrefInfo:t,changes:n,xref:a=null,hasXfa:s=!1,xfaDatasetsRef:r=null,hasXfaDatasetsEntry:i=!1,needAppearances:o,acroFormRef:l=null,acroForm:f=null,xfaData:c=null,useXrefStream:h=!1}){await async function updateAcroform({xref:e,acroForm:t,acroFormRef:n,hasXfa:a,hasXfaDatasetsEntry:s,xfaDatasetsRef:r,needAppearances:i,changes:o}){!a||s||r||warn("XFA - Cannot save it");if(!i&&(!a||!r||s))return;const l=t.clone();if(a&&!s){const e=t.get("XFA").slice();e.splice(2,0,"datasets");e.splice(3,0,r);l.set("XFA",e)}i&&l.set("NeedAppearances",!0);o.put(n,{data:l})}({xref:a,acroForm:f,acroFormRef:l,hasXfa:s,hasXfaDatasetsEntry:i,xfaDatasetsRef:r,needAppearances:o,changes:n});s&&updateXFA({xfaData:c,xfaDatasetsRef:r,changes:n,xref:a});const u=function getTrailerDict(e,t,n){const a=new Dict(null);a.setIfDefined("Prev",e?.startXRef);const s=e.newRef;if(n){t.put(s,{data:""});a.set("Size",s.num+1);a.setIfName("Type","XRef")}else a.set("Size",s.num);a.setIfDefined("Root",e?.rootRef);a.setIfDefined("Info",e?.infoRef);a.setIfDefined("Encrypt",e?.encryptRef);return a}(t,n,h),m=[],p=await async function writeChanges(e,t,n=[]){const a=[];for(const[s,{data:r,objStreamRef:i,index:o}]of e.items())if(i)a.push({ref:s,data:r,objStreamRef:i,index:o});else if(null!==r&&"string"!=typeof r){await writeObject(s,r,n,t);a.push({ref:s,data:n.join("")});n.length=0}else a.push({ref:s,data:r});return a.sort((e,t)=>e.ref.num-t.ref.num)}(n,a,m);let d=e.length;const g=e.at(-1);if(10!==g&&13!==g){m.push("\n");d+=1}for(const{data:e}of p)null!==e&&m.push(e);await(h?async function getXRefStreamTable(e,t,n,a,s){const r=[];let i=0,o=0;for(const{ref:e,data:a,objStreamRef:s,index:l}of n){let n;i=Math.max(i,t);if(s){n=l;r.push([2,s.num,n])}else if(null!==a){n=Math.min(e.gen,65535);r.push([1,t,n]);t+=a.length}else{n=Math.min(e.gen+1,65535);r.push([0,0,n])}o=Math.max(o,n)}a.set("Index",getIndexes(n));const l=[1,getSizeInBytes(i),getSizeInBytes(o)];a.set("W",l);computeIDs(t,e,a);const f=Math.sumPrecise(l),c=new Uint8Array(f*r.length),h=new Stream(c);h.dict=a;let u=0;for(const[e,t,n]of r){u=writeInt(e,l[0],u,c);u=writeInt(t,l[1],u,c);u=writeInt(n,l[2],u,c)}await writeObject(e.newRef,h,s,{});s.push("startxref\n",t.toString(),"\n%%EOF\n")}(t,d,p,u,m):async function getXRefTable(e,t,n,a,s){s.push("xref\n");const r=getIndexes(n);let i=0;for(const{ref:e,data:a}of n){if(e.num===r[i]){s.push(`${r[i]} ${r[i+1]}\n`);i+=2}if(null!==a){s.push(`${t.toString().padStart(10,"0")} ${Math.min(e.gen,65535).toString().padStart(5,"0")} n\r\n`);t+=a.length}else s.push(`0000000000 ${Math.min(e.gen+1,65535).toString().padStart(5,"0")} f\r\n`)}computeIDs(t,e,a);s.push("trailer\n");await writeDict(a,s,null);s.push("\nstartxref\n",t.toString(),"\n%%EOF\n")}(t,d,p,u,m));const b=e.length+Math.sumPrecise(m.map(e=>e.length)),w=new Uint8Array(b);w.set(e);let j=e.length;for(const e of m)j=writeString(e,j,w);return w}class PageData{constructor(e,t){this.page=e;this.documentData=t;this.annotations=null;this.pointingNamedDestinations=null;t.pagesMap.put(e.ref,this)}}class DocumentData{constructor(e){this.document=e;this.destinations=null;this.pageLabels=null;this.pagesMap=new RefSetCache;this.oldRefMapping=new RefSetCache;this.dedupNamedDestinations=new Map;this.usedNamedDestinations=new Set;this.postponedRefCopies=new RefSetCache;this.usedStructParents=new Set;this.oldStructParentMapping=new Map;this.structTreeRoot=null;this.parentTree=null;this.idTree=null;this.roleMap=null;this.classMap=null;this.namespaces=null;this.structTreeAF=null;this.structTreePronunciationLexicon=[]}}class XRefWrapper{constructor(e){this.entries=e}fetch(e){return e instanceof Ref?this.entries[e.num]:e}}class PDFEditor{hasSingleFile=!1;currentDocument=null;oldPages=[];newPages=[];xref=[null];xrefWrapper=new XRefWrapper(this.xref);newRefCount=1;namesDict=null;version="1.7";pageLabels=null;namedDestinations=new Map;parentTree=new Map;structTreeKids=[];idTree=new Map;classMap=new Dict;roleMap=new Dict;namespaces=new Map;structTreeAF=[];structTreePronunciationLexicon=[];constructor({useObjectStreams:e=!0,title:t="",author:n=""}={}){[this.rootRef,this.rootDict]=this.newDict;[this.infoRef,this.infoDict]=this.newDict;[this.pagesRef,this.pagesDict]=this.newDict;this.useObjectStreams=e;this.objStreamRefs=e?new Set:null;this.title=t;this.author=n}get newRef(){return Ref.get(this.newRefCount++,0)}get newDict(){const e=this.newRef;return[e,this.xref[e.num]=new Dict]}async#qt(e,t){const n=this.newRef;this.xref[n.num]=await this.#vt(e,!0,t);return n}cloneDict(e){const t=e.clone();t.xref=this.xrefWrapper;return t}async#vt(e,t,n){if(e instanceof Ref){const{currentDocument:{oldRefMapping:t}}=this;let a=t.get(e);if(a)return a;const s=e;if("number"==typeof(e=await n.fetchAsync(s)))return e;a=this.newRef;t.put(s,a);this.xref[a.num]=await this.#vt(e,!0,n);return a}const a=[],{currentDocument:{postponedRefCopies:s}}=this;if(Array.isArray(e)){t&&(e=e.slice());for(let t=0,r=e.length;t<r;t++){const r=s.get(e[t]);r?r.push(n=>e[t]=n):a.push(this.#vt(e[t],!0,n).then(n=>e[t]=n))}await Promise.all(a);return e}let r;if(e instanceof BaseStream){({dict:r}=e=e.getOriginalStream().clone());r.xref=this.xrefWrapper}else if(e instanceof Dict){t&&((e=e.clone()).xref=this.xrefWrapper);r=e}if(r){for(const[e,t]of r.getRawEntries()){const i=s.get(t);i?i.push(t=>r.set(e,t)):a.push(this.#vt(t,!0,n).then(t=>r.set(e,t)))}await Promise.all(a)}return e}async#St(e,t,n,a,s,r,i,o=new RefSet){const{currentDocument:{pagesMap:l,oldRefMapping:f}}=this,c=t.getRaw("Pg");if(c instanceof Ref&&!l.has(c))return null;let h;const u=h=t.getRaw("K");if(u instanceof Ref){if(o.has(u))return null;h=await n.fetchAsync(u);Array.isArray(h)||(h=[u])}h=Array.isArray(h)?h:[h];const m=[],p=[];for(let t of h){const c=t instanceof Ref?t:null;if(c){if(o.has(c))continue;o.put(c);t=await n.fetchAsync(c)}if("number"==typeof t){m.push(t);continue}if(!(t instanceof Dict))continue;const h=t.getRaw("Pg");if(h instanceof Ref&&!l.has(h))continue;const u=t.get("Type");if(!u||isName(u,"StructElem")){let e=!1;if(c&&a.has(c)){if(!isName(t.get("S"),"Link"))continue;e=!0}const l=await this.#St(c,t,n,a,s,r,i,o);if(l){p.push(m.length);m.push(l);c&&f.put(c,l);e&&this.xref[l.num].setIfName("S","Span")}continue}if(isName(u,"OBJR")){if(!c)continue;const t=f.get(c);if(!t)continue;const n=this.xref[t.num].getRaw("Obj");if(n instanceof Ref){const t=this.xref[n.num];if(t instanceof Dict&&!t.has("StructParent")&&e){const n=this.parentTree.size;this.parentTree.set(n,[f,e]);t.set("StructParent",n)}}m.push(t);continue}if(isName(u,"MCR")){const e=await this.#vt(c||t,!0,n);m.push(e);continue}if(c){const e=await this.#vt(c,!0,n);m.push(e)}}if(0!==h.length&&0===m.length)return null;const d=this.newRef,g=this.xref[d.num]=this.cloneDict(t);g.delete("ID");g.delete("C");g.delete("K");g.delete("P");g.delete("S");await this.#vt(g,!1,n);const b=t.get("C");if(b instanceof Name){const e=r.get(b.name);e?g.set("C",Name.get(e)):g.set("C",b)}else if(Array.isArray(b)){const e=[];for(const t of b)if(t instanceof Name){const n=r.get(t.name);n?e.push(Name.get(n)):e.push(t)}g.set("C",e)}const w=t.get("S");if(w instanceof Name){const e=i.get(w.name);e?g.set("S",Name.get(e)):g.set("S",w)}const j=t.get("ID");if("string"==typeof j){const e=stringToPDFString(j,!1),t=s.get(e);t?g.set("ID",stringToAsciiOrUTF16BE(t)):g.set("ID",j)}let k=g.get("A");if(k){Array.isArray(k)||(k=[k]);for(let e of k){e=this.xrefWrapper.fetch(e);if(isName(e.get("O"),"Table")&&e.has("Headers")){const t=this.xrefWrapper.fetch(e.getRaw("Headers"));if(Array.isArray(t))for(let e=0,n=t.length;e<n;e++){const n=s.get(stringToPDFString(t[e],!1));n&&(t[e]=n)}}}}for(const e of p){const t=m[e];this.xref[t.num].set("P",d)}1===m.length?g.set("K",m[0]):m.length>1&&g.set("K",m);return d}async extractPages(e){const t=[];let n=0;this.hasSingleFile=1===e.length;const a=[];for(const{document:s,includePages:r,excludePages:i,pageIndices:o}of e){if(!s)continue;o&&(n=-1);const e=new DocumentData(s);a.push(e);t.push(this.#xt(e));let l,f,c,h;for(const e of r||[])Array.isArray(e)?(f||=[]).push(e):(l||=new Set).add(e);for(const e of i||[])Array.isArray(e)?(h||=[]).push(e):(c||=new Set).add(e);let u=0;for(let a=0,r=s.numPages;a<r;a++){if(c?.has(a))continue;if(h){let e=!1;for(const[t,n]of h)if(a>=t&&a<=n){e=!0;break}if(e)continue}let r,i=!1;l&&(i=l.has(a));if(!i&&f)for(const[e,t]of f)if(a>=e&&a<=t){i=!0;break}i||l||f||(i=!0);if(i){o&&(r=o[u++]);if(void 0===r)if(-1!==n)r=n++;else for(r=0;void 0===this.oldPages[r];r++);t.push(s.getPage(a).then(t=>{this.oldPages[r]=new PageData(t,e)}))}}}await Promise.all(t);t.length=0;this.#At(a);this.#Ct();for(const e of this.oldPages)t.push(this.#It(e));await Promise.all(t);this.#Ft();this.#Tt(a);for(let e=0,t=this.oldPages.length;e<t;e++)this.newPages[e]=await this.#Ht(e,null);this.#Ot(a);await this.#Bt(a);return this.writePDF()}async#xt(e){const{document:{pdfManager:t,xref:n}}=e;await Promise.all([t.ensureCatalog("destinations").then(t=>e.destinations=t),t.ensureCatalog("rawPageLabels").then(t=>e.pageLabels=t),t.ensureCatalog("structTreeRoot").then(t=>e.structTreeRoot=t)]);const a=e.structTreeRoot;if(a){const t=a.dict,s=t.get("ParentTree");if(s){const t=new NumberTree(s,n);e.parentTree=t.getAll(!0)}const r=t.get("IDTree");if(r){const t=new NameTree(r,n);e.idTree=t.getAll(!0)}e.roleMap=t.get("RoleMap")||null;e.classMap=t.get("ClassMap")||null;let i=t.get("Namespaces")||null;i&&!Array.isArray(i)&&(i=[i]);e.namespaces=i;e.structTreeAF=t.get("AF")||null;e.structTreePronunciationLexicon=t.get("PronunciationLexicon")||null}}async#It(e){const{page:{xref:t,annotations:n},documentData:{pagesMap:a,destinations:s,usedNamedDestinations:r}}=e;if(!n)return;const i=[];let o=[],l=0;for(const e of n){const n=l++;i.push(t.fetchIfRefAsync(e).then(async t=>{if(!isName(t.get("Subtype"),"Link")){o[n]=e;return}const i=t.get("A"),l=i instanceof Dict?i.get("D"):t.get("Dest");if(l&&(!Array.isArray(l)||l[0]instanceof Ref&&!a.has(l[0]))){if("string"==typeof l){const t=stringToPDFString(l,!0);if(s.has(t)){o[n]=e;r.add(t)}}}else o[n]=e}))}await Promise.all(i);o=o.filter(e=>!!e);e.annotations=o.length>0?o:null}#Tt(e){for(const{postponedRefCopies:t,pagesMap:n}of e)for(const e of n.keys())t.put(e,[])}#Ot(e){for(const{postponedRefCopies:t,oldRefMapping:n}of e){for(const[e,a]of t.items()){const t=n.get(e);for(const e of a)e(t)}t.clear()}}#Rt(e,t,n=new RefSet){if(e instanceof Ref){if(!n.has(e)){n.put(e);this.#Rt(this.xref[e.num],t,n)}return}if(Array.isArray(e)){for(const a of e)this.#Rt(a,t,n);return}let a;e instanceof BaseStream?({dict:a}=e):e instanceof Dict&&(a=e);if(a){t(a);for(const e of a.getRawValues())this.#Rt(e,t,n)}}async#Bt(e){let t=0;const{parentTree:n}=this;for(let e=0,a=this.newPages.length;e<a;e++){const{documentData:{parentTree:a,oldRefMapping:s,oldStructParentMapping:r,usedStructParents:i,document:{xref:o}}}=this.oldPages[e];if(!a)continue;const l=this.newPages[e],f=this.xref[l.num];this.#Rt(f,e=>{const l=e.get("StructParent")??e.get("StructParents");if("number"!=typeof l)return;i.add(l);let f=a.get(l);const c=f instanceof Ref?f:null;if(c){const e=o.fetch(c);Array.isArray(e)&&(f=e)}Array.isArray(f)&&f.every(e=>null===e)&&(f=null);if(!f){e.has("StructParent")?e.delete("StructParent"):e.delete("StructParents");return}let h=r.get(l);if(void 0===h){h=t++;r.set(l,h);n.set(h,[s,f])}e.has("StructParent")?e.set("StructParent",h):e.set("StructParents",h)})}const{structTreeKids:a,idTree:s,classMap:r,roleMap:i,namespaces:o,structTreeAF:l,structTreePronunciationLexicon:f}=this;for(const t of e){const{document:{xref:e},oldRefMapping:n,parentTree:c,usedStructParents:h,structTreeRoot:u,idTree:m,classMap:p,roleMap:d,namespaces:g,structTreeAF:b,structTreePronunciationLexicon:w}=t;if(!u)continue;this.currentDocument=t;const j=new RefSet;for(const[e,t]of c||[])!h.has(e)&&t instanceof Ref&&j.put(t);const k=new Map;for(const[e,t]of m||[]){let n=e;if(s.has(e))for(let t=1;;t++){const a=`${e}_${t}`;if(!s.has(a)){k.set(e,a);n=a;break}}s.set(n,t)}const y=new Map;if(p?.size>0)for(let[t,n]of p){n=await this.#vt(n,!0,e);if(r.has(t))for(let e=1;;e++){const n=`${t}_${e}`;if(!r.has(n)){y.set(t,n);t=n;break}}r.set(t,n)}const q=new Map;if(d?.size>0)for(const[e,t]of d){const n=i.get(e);if(n){if(n!==t)for(let n=1;;n++){const a=`${e}_${n}`;if(!i.has(a)){q.set(e,a);i.set(a,t);break}}}else i.set(e,t)}if(g?.length>0)for(const t of g){const n=await e.fetchIfRefAsync(t);let a=n.get("NS");if(!a||o.has(a))continue;a=stringToPDFString(a,!1);const s=await this.#vt(n,!0,e);o.set(a,s)}if(b)for(const t of b)l.push(await this.#vt(t,!0,e));if(w)for(const t of w)f.push(await this.#vt(t,!0,e));let v=u.dict.get("K");if(v){v=Array.isArray(v)?v:[v];for(let t of v){const n=t instanceof Ref?t:null;if(n&&j.has(n))continue;t=await e.fetchIfRefAsync(t);const s=await this.#St(n,t,e,j,k,y,q);s&&a.push(s)}for(const[e,t]of m||[]){const a=n.get(t),r=k.get(e)||e;a?s.set(r,a):s.delete(r)}}}for(const[e,[t,a]]of n){if(!a){n.delete(e);continue}if(!Array.isArray(a)){const s=t.get(a);void 0===s?n.delete(e):n.set(e,s);continue}const s=a.map(e=>e instanceof Ref&&t.get(e)||null);0===s.length||s.every(e=>null===e)?n.delete(e):n.set(e,s)}this.currentDocument=null}#At(e){for(const t of e){if(!t.destinations)continue;const{destinations:e,pagesMap:n}=t,a=t.destinations=new Map;for(const[t,s]of Object.entries(e)){const e=s[0],r=n.get(e);if(r){(r.pointingNamedDestinations||=new Set).add(t);a.set(t,s)}}}}#Ft(){const{namedDestinations:e}=this;for(let t=0,n=this.oldPages.length;t<n;t++){const n=this.oldPages[t],{documentData:{destinations:a,dedupNamedDestinations:s,usedNamedDestinations:r}}=n;let{pointingNamedDestinations:i}=n;if(i){n.pointingNamedDestinations=i=i.intersection(r);for(const n of i){if(!r.has(n))continue;const i=a.get(n).slice();if(!e.has(n)){e.set(n,i);continue}const o=`${n}_p${t+1}`;s.set(n,o);e.set(o,i)}}}}#Dt(e,t){if(0===t.size)return;const fixDestination=(e,n,a)=>{"string"==typeof a&&e.set(n,t.get(stringToPDFString(a,!0))||a)};for(const t of e){const e=this.xref[t.num];if(!isName(e.get("Subtype"),"Link"))continue;const n=e.get("A");if(n instanceof Dict&&n.has("D")){const e=n.get("D");fixDestination(n,"D",e);continue}const a=e.get("Dest");fixDestination(e,"Dest",a)}}async#Ct(){if(!this.hasSingleFile)return;const{documentData:{document:e,pageLabels:t}}=this.oldPages[0];if(!t)return;const n=e.numPages,a=[],s=new Set(this.oldPages.map(({page:{pageIndex:e}})=>e));let r=null,i=-1;for(let e=0;e<n;e++){const n=t.get(e);if(n){r=n;i=r.has("St")?e:-1}if(s.has(e)){if(-1!==i){const t=r.get("St");r=this.cloneDict(r);r.set("St",t+(e-i));i=-1}a.push(r)}}r=a[0];let o=0;const l=this.pageLabels=[[0,r]];for(let e=0,t=a.length;e<t;e++){const t=a[e];if(t!==r){o=e;r=t;l.push([o,r])}}}async#Ht(e){const{page:t,documentData:n,annotations:a,pointingNamedDestinations:s}=this.oldPages[e];this.currentDocument=n;const{dedupNamedDestinations:r,oldRefMapping:i}=n,{xref:o,rotate:l,mediaBox:f,resources:c,ref:h}=t,u=this.newRef,m=this.xref[u.num]=this.cloneDict(t.pageDict);i.put(h,u);if(s)for(const e of s){const t=r.get(e)||e;this.namedDestinations.get(t)[0]=u}for(const e of["Rotate","MediaBox","CropBox","BleedBox","TrimBox","ArtBox","Resources","Annots","Parent","UserUnit"])m.delete(e);const p=this.newRefCount;await this.#vt(m,!1,o);m.set("Rotate",l);m.set("MediaBox",f);for(const e of["CropBox","BleedBox","TrimBox","ArtBox"]){const n=t.getBoundingBox(e);n?.some((e,t)=>e!==f[t])&&m.set(e,n)}const d=t.userUnit;1!==d&&m.set("UserUnit",d);m.setIfDict("Resources",await this.#vt(c,!0,o));if(a){const e=await this.#vt(a,!0,o);this.#Dt(e,r);m.setIfArray("Annots",e)}if(this.useObjectStreams){const e=this.newRefCount,t=[];for(let n=p;n<e;n++){this.xref[n]instanceof BaseStream||t.push(Ref.get(n,0))}for(let e=0;e<t.length;e+=65535){const n=this.newRef;this.objStreamRefs.add(n.num);this.xref[n.num]=t.slice(e,e+65535)}}this.currentDocument=null;return u}#Mt(){const{newPages:e,rootDict:t,pagesRef:n,pagesDict:a}=this;t.set("Pages",n);a.setIfName("Type","Pages");a.set("Count",e.length);const s=[{dict:a,kids:e,parentRef:n}];for(;s.length>0;){const{dict:e,kids:t,parentRef:n}=s.pop();if(t.length<=16){e.set("Kids",t);for(const e of t)this.xref[e.num].set("Parent",n);continue}const a=Math.max(16,Math.ceil(t.length/16)),r=[];for(let e=0;e<t.length;e+=a)r.push(t.slice(e,e+a));const i=[];e.set("Kids",i);for(const e of r){const[t,a]=this.newDict;i.push(t);a.setIfName("Type","Pages");a.set("Parent",n);a.set("Count",e.length);s.push({dict:a,kids:e,parentRef:t})}}}#Pt(e,t){const n=e.sort(t?([e],[t])=>e.localeCompare(t):([e],[t])=>e-t),[a,s]=this.newDict,r=[{dict:s,entries:n}],i=t?"Names":"Nums";for(;r.length>0;){const{dict:e,entries:t}=r.pop();if(t.length<=64){e.set("Limits",[t[0][0],t.at(-1)[0]]);e.set(i,t.flat());continue}const n=[],a=Math.max(64,Math.ceil(t.length/64));for(let e=0;e<t.length;e+=a)n.push(t.slice(e,e+a));const s=[];e.set("Kids",s);for(const e of n){const[t,n]=this.newDict;s.push(t);n.set("Limits",[e[0][0],e.at(-1)[0]]);r.push({dict:n,entries:e})}}return a}#Et(){const{pageLabels:e}=this;if(!e||0===e.length)return;const{rootDict:t}=this,n=this.#Pt(this.pageLabels,!1);t.set("PageLabels",n)}#Nt(){const{namedDestinations:e}=this;if(0!==e.size){if(!this.namesDict){[this.namesRef,this.namesDict]=this.newDict;this.rootDict.set("Names",this.namesRef)}this.namesDict.set("Dests",this.#Pt(Array.from(e.entries()),!0))}}#zt(){const{structTreeKids:e}=this;if(!e||0===e.length)return;const{rootDict:t}=this,n=this.newRef,a=this.xref[n.num]=new Dict;a.setIfName("Type","StructTreeRoot");a.setIfArray("K",e);for(const t of e){const e=this.xref[t.num],a=e.get("Type");a&&!isName(a,"StructElem")||e.set("P",n)}if(this.parentTree.size>0){const e=this.#Pt(Array.from(this.parentTree.entries()),!1);this.xref[e.num].setIfName("Type","ParentTree");a.set("ParentTree",e);a.set("ParentTreeNextKey",this.parentTree.size)}if(this.idTree.size>0){const e=this.#Pt(Array.from(this.idTree.entries()),!0);this.xref[e.num].setIfName("Type","IDTree");a.set("IDTree",e)}if(this.classMap.size>0){const e=this.newRef;this.xref[e.num]=this.classMap;a.set("ClassMap",e)}if(this.roleMap.size>0){const e=this.newRef;this.xref[e.num]=this.roleMap;a.set("RoleMap",e)}if(this.namespaces.size>0){const e=this.newRef;this.xref[e.num]=Array.from(this.namespaces.values());a.set("Namespaces",e)}if(this.structTreeAF.length>0){const e=this.newRef;this.xref[e.num]=this.structTreeAF;a.set("AF",e)}if(this.structTreePronunciationLexicon.length>0){const e=this.newRef;this.xref[e.num]=this.structTreePronunciationLexicon;a.set("PronunciationLexicon",e)}t.set("StructTreeRoot",n)}async#Lt(){const{rootDict:e}=this;e.setIfName("Type","Catalog");e.setIfName("Version",this.version);this.#Mt();this.#Et();this.#Nt();this.#zt()}#Ut(){const e=new Map;if(this.hasSingleFile){const{xref:{trailer:t}}=this.oldPages[0].documentData.document,n=t.get("Info");for(const[t,a]of n||[])"string"==typeof a&&e.set(t,stringToPDFString(a))}e.delete("ModDate");e.set("CreationDate",getModificationDate());e.set("Creator","PDF.js");e.set("Producer","Firefox");this.author&&e.set("Author",this.author);this.title&&e.set("Title",this.title);for(const[t,n]of e)this.infoDict.set(t,stringToAsciiOrUTF16BE(n));return e}async#_t(){if(!this.hasSingleFile)return[null,null,null];const{documentData:e}=this.oldPages[0],{document:{xref:{trailer:t,encrypt:n}}}=e;if(!t.has("Encrypt"))return[null,null,null];const a=t.get("Encrypt");if(!(a instanceof Dict))return[null,null,null];this.currentDocument=e;const s=[await this.#qt(a,t.xref),n,t.get("ID")];this.currentDocument=null;return s}async#Xt(){const e=new RefSetCache;e.put(Ref.get(0,65535),{data:null});for(let t=1,n=this.xref.length;t<n;t++)this.objStreamRefs?.has(t)?await this.#Wt(Ref.get(t,0),this.xref[t],e):e.put(Ref.get(t,0),{data:this.xref[t]});return[e,this.newRef]}async#Wt(e,t,n){const a=[""],s=[];let r=0;const i=[];for(let o=0,l=t.length;o<l;o++){const l=t[o];n.put(l,{data:null,objStreamRef:e,index:o});s.push(`${l.num} ${r}`);const f=this.xref[l.num];await writeValue(f,i,null);const c=i.join("");i.length=0;a.push(c);r+=c.length+1}a[0]=s.join("\n");const o=new StringStream(a.join("\n")),l=o.dict=new Dict;l.setIfName("Type","ObjStm");l.set("N",t.length);l.set("First",a[0].length+1);n.put(e,{data:o})}async writePDF(){await this.#Lt();const e=this.#Ut(),[t,n,a]=await this.#_t(),[s,r]=await this.#Xt(),i=[...`%PDF-${this.version}\n%`.split("").map(e=>e.charCodeAt(0)),250,222,250,206];return incrementalUpdate({originalData:new Uint8Array(i),changes:s,xrefInfo:{startXRef:null,rootRef:this.rootRef,infoRef:this.infoRef,encryptRef:t,newRef:r,fileIds:a||[null,null],infoMap:e},useXrefStream:this.useObjectStreams,xref:{encrypt:n,encryptRef:t}})}}class BasePDFStream{#Kt=null;#Gt=null;_fullReader=null;_rangeReaders=new Set;_source=null;constructor(e,t,n){this._source=e;this.#Kt=t;this.#Gt=n}get _progressiveDataLength(){return this._fullReader?._loaded??0}getFullReader(){assert(!this._fullReader,"BasePDFStream.getFullReader can only be called once.");return this._fullReader=new this.#Kt(this)}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;const n=new this.#Gt(this,e,t);this._rangeReaders.add(n);return n}cancelAllRequests(e){this._fullReader?.cancel(e);for(const t of new Set(this._rangeReaders))t.cancel(e)}}class BasePDFStreamReader{onProgress=null;_contentLength=0;_filename=null;_headersCapability=Promise.withResolvers();_isRangeSupported=!1;_isStreamingSupported=!1;_loaded=0;_stream=null;constructor(e){this._stream=e}_callOnProgress(){this.onProgress?.({loaded:this._loaded,total:this._contentLength})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){unreachable("Abstract method `read` called")}cancel(e){unreachable("Abstract method `cancel` called")}}class BasePDFStreamRangeReader{_stream=null;constructor(e,t,n){this._stream=e}async read(){unreachable("Abstract method `read` called")}cancel(e){unreachable("Abstract method `cancel` called")}}class PDFWorkerStream extends BasePDFStream{constructor(e){super(e,PDFWorkerStreamReader,PDFWorkerStreamRangeReader)}}class PDFWorkerStreamReader extends BasePDFStreamReader{_reader=null;constructor(e){super(e);const{msgHandler:t}=e._source,n=t.sendWithStream("GetReader");this._reader=n.getReader();t.sendWithPromise("ReaderHeadersReady").then(e=>{this._contentLength=e.contentLength;this._isStreamingSupported=e.isStreamingSupported;this._isRangeSupported=e.isRangeSupported;this._headersCapability.resolve()},this._headersCapability.reject)}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class PDFWorkerStreamRangeReader extends BasePDFStreamRangeReader{_reader=null;constructor(e,t,n){super(e,t,n);const{msgHandler:a}=e._source,s=a.sendWithStream("GetRangeReader",{begin:t,end:n});this._reader=s.getReader()}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class WorkerTask{constructor(e){this.name=e;this.terminated=!1;this._capability=Promise.withResolvers()}get finished(){return this._capability.promise}finish(){this._capability.resolve()}terminate(){this.terminated=!0}ensureNotTerminated(){if(this.terminated)throw new Error("Worker task was terminated")}}class WorkerMessageHandler{static{"undefined"==typeof window&&!e&&"undefined"!=typeof self&&"function"==typeof self.postMessage&&"onmessage"in self&&this.initializeFromPort(self)}static setup(e,t){let n=!1;e.on("test",t=>{if(!n){n=!0;e.send("test",t instanceof Uint8Array)}});e.on("configure",e=>{!function setVerbosityLevel(e){Number.isInteger(e)&&(Zt=e)}(e.verbosity)});e.on("GetDocRequest",e=>this.createDocumentHandler(e,t))}static createDocumentHandler(e,t){let n,a=!1,s=null;const r=new Set,i=getVerbosityLevel(),{docId:o,apiVersion:l}=e,f="5.5.207";if(l!==f)throw new Error(`The API version "${l}" does not match the Worker version "${f}".`);const buildMsg=(e,t)=>`The \`${e}.prototype\` contains unexpected enumerable property "${t}", thus breaking e.g. \`for...in\` iteration of ${e}s.`;for(const e in{})throw new Error(buildMsg("Object",e));for(const e in[])throw new Error(buildMsg("Array",e));const c=o+"_worker";let h=new MessageHandler(c,o,t);function ensureNotTerminated(){if(a)throw new Error("Worker was terminated")}function startWorkerTask(e){r.add(e)}function finishWorkerTask(e){e.finish();r.delete(e)}async function loadDocument(e){await n.ensureDoc("checkHeader");await n.ensureDoc("parseStartXRef");await n.ensureDoc("parse",[e]);await n.ensureDoc("checkFirstPage",[e]);await n.ensureDoc("checkLastPage",[e]);const t=await n.ensureDoc("isPureXfa");if(t){const e=new WorkerTask("loadXfaResources");startWorkerTask(e);await n.ensureDoc("loadXfaResources",[h,e]);finishWorkerTask(e)}const[a,s]=await Promise.all([n.ensureDoc("numPages"),n.ensureDoc("fingerprints")]);return{numPages:a,fingerprints:s,htmlForXfa:t?await n.ensureDoc("htmlForXfa"):null}}function setupDoc(e){function onSuccess(e){ensureNotTerminated();h.send("GetDoc",{pdfInfo:e})}function onFailure(e){if(!a)if(e instanceof PasswordException){const t=new WorkerTask(`PasswordException: response ${e.code}`);startWorkerTask(t);h.sendWithPromise("PasswordRequest",e).then(function({password:e}){finishWorkerTask(t);n.updatePassword(e);pdfManagerReady()}).catch(function(){finishWorkerTask(t);h.send("DocException",e)})}else h.send("DocException",wrapReason(e))}function pdfManagerReady(){ensureNotTerminated();loadDocument(!1).then(onSuccess,function(e){ensureNotTerminated();e instanceof XRefParseException?n.requestLoadedStream().then(function(){ensureNotTerminated();loadDocument(!0).then(onSuccess,onFailure)}):onFailure(e)})}ensureNotTerminated();(async function getPdfManager({data:e,password:t,disableAutoFetch:n,rangeChunkSize:a,length:r,docBaseUrl:i,enableXfa:l,evaluatorOptions:f}){const c={source:null,disableAutoFetch:n,docBaseUrl:i,docId:o,enableXfa:l,evaluatorOptions:f,handler:h,length:r,password:t,rangeChunkSize:a};if(e){c.source=e;return new LocalPdfManager(c)}const u=new PDFWorkerStream({msgHandler:h}),m=u.getFullReader(),p=Promise.withResolvers();let d,g=[],b=0;m.headersReady.then(function(){if(m.isRangeSupported){c.source=u;c.length=m.contentLength;c.disableAutoFetch||=m.isStreamingSupported;d=new NetworkPdfManager(c);for(const e of g)d.sendProgressiveData(e);g=[];p.resolve(d);s=null}}).catch(function(e){p.reject(e);s=null});new Promise(function(e,t){const readChunk=function({value:e,done:n}){try{ensureNotTerminated();if(n){if(!d){const e=arrayBuffersToBytes(g);g=[];r&&e.length!==r&&warn("reported HTTP length is different from actual");c.source=e;d=new LocalPdfManager(c);p.resolve(d)}s=null;return}b+=e.byteLength;m.isStreamingSupported||h.send("DocProgress",{loaded:b,total:Math.max(b,m.contentLength||0)});d?d.sendProgressiveData(e):g.push(e);m.read().then(readChunk,t)}catch(e){t(e)}};m.read().then(readChunk,t)}).catch(function(e){p.reject(e);s=null});s=e=>{u.cancelAllRequests(e)};return p.promise})(e).then(function(e){if(a){e.terminate(new AbortException("Worker was terminated."));throw new Error("Worker was terminated")}n=e;n.requestLoadedStream(!0).then(e=>{h.send("DataLoaded",{length:e.bytes.byteLength})})}).then(pdfManagerReady,onFailure)}h.on("GetPage",function(e){return n.getPage(e.pageIndex).then(function(e){return Promise.all([n.ensure(e,"rotate"),n.ensure(e,"ref"),n.ensure(e,"userUnit"),n.ensure(e,"view")]).then(function([e,t,n,a]){return{rotate:e,ref:t,refStr:t?.toString()??null,userUnit:n,view:a}})})});h.on("GetPageIndex",function(e){const t=Ref.get(e.num,e.gen);return n.ensureCatalog("getPageIndex",[t])});h.on("GetDestinations",function(e){return n.ensureCatalog("destinations")});h.on("GetDestination",function(e){return n.ensureCatalog("getDestination",[e.id])});h.on("GetPageLabels",function(e){return n.ensureCatalog("pageLabels")});h.on("GetPageLayout",function(e){return n.ensureCatalog("pageLayout")});h.on("GetPageMode",function(e){return n.ensureCatalog("pageMode")});h.on("GetViewerPreferences",function(e){return n.ensureCatalog("viewerPreferences")});h.on("GetOpenAction",function(e){return n.ensureCatalog("openAction")});h.on("GetAttachments",function(e){return n.ensureCatalog("attachments")});h.on("GetDocJSActions",function(e){return n.ensureCatalog("jsActions")});h.on("GetPageJSActions",function({pageIndex:e}){return n.getPage(e).then(e=>n.ensure(e,"jsActions"))});h.on("GetAnnotationsByType",async function({types:e,pageIndexesToSkip:t}){const[a,s]=await Promise.all([n.ensureDoc("numPages"),n.ensureDoc("annotationGlobals")]);if(!s)return null;const r=[],i=[];let o=null;try{for(let l=0,f=a;l<f;l++)if(!t?.has(l)){if(!o){o=new WorkerTask("GetAnnotationsByType");startWorkerTask(o)}r.push(n.getPage(l).then(async t=>t&&t.collectAnnotationsByType(h,o,e,i,s)||[]))}await Promise.all(r);return(await Promise.all(i)).filter(e=>!!e)}finally{o&&finishWorkerTask(o)}});h.on("GetOutline",function(e){return n.ensureCatalog("documentOutline")});h.on("GetOptionalContentConfig",function(e){return n.ensureCatalog("optionalContentConfig")});h.on("GetPermissions",function(e){return n.ensureCatalog("permissions")});h.on("GetMetadata",function(e){return Promise.all([n.ensureDoc("documentInfo"),n.ensureCatalog("metadata"),n.ensureCatalog("hasStructTree")])});h.on("GetMarkInfo",function(e){return n.ensureCatalog("markInfo")});h.on("GetData",function(e){return n.requestLoadedStream().then(e=>e.bytes)});h.on("GetAnnotations",function({pageIndex:e,intent:t}){return n.getPage(e).then(function(n){const a=new WorkerTask(`GetAnnotations: page ${e}`);startWorkerTask(a);return n.getAnnotationsData(h,a,t).then(e=>{finishWorkerTask(a);return e},e=>{finishWorkerTask(a);throw e})})});h.on("GetFieldObjects",function(e){return n.ensureDoc("fieldObjects").then(e=>e?.allFields||null)});h.on("HasJSActions",function(e){return n.ensureDoc("hasJSActions")});h.on("GetCalculationOrderIds",function(e){return n.ensureDoc("calculationOrderIds")});h.on("ExtractPages",async function({pageInfos:e}){if(!e){warn("extractPages: nothing to extract.");return null}Array.isArray(e)||(e=[e]);let t=0;for(const a of e)if(null===a.document)a.document=n.pdfDocument;else if(ArrayBuffer.isView(a.document)){const e=new LocalPdfManager({source:a.document,docId:`${o}_extractPages_${t++}`,handler:h,password:a.password??null,evaluatorOptions:Object.assign({},n.evaluatorOptions)});let s=!1,r=!0;for(;;)try{await e.requestLoadedStream();await e.ensureDoc("checkHeader");await e.ensureDoc("parseStartXRef");await e.ensureDoc("parse",[s]);break}catch(t){if(t instanceof XRefParseException){if(!1===s){s=!0;continue}r=!1;warn("extractPages: XRefParseException.")}else if(t instanceof PasswordException){const n=new WorkerTask(`PasswordException: response ${t.code}`);startWorkerTask(n);try{const{password:n}=await h.sendWithPromise("PasswordRequest",t);e.updatePassword(n)}catch{r=!1;warn("extractPages: invalid password.")}finally{finishWorkerTask(n)}}else{r=!1;warn("extractPages: invalid document.")}if(!r)break}r||(a.document=null);if(await e.ensureDoc("isPureXfa")){a.document=null;warn("extractPages does not support pure XFA documents.")}else a.document=e.pdfDocument}else warn("extractPages: invalid document.");try{const t=new PDFEditor;return await t.extractPages(e)}catch(e){console.error(e);return null}});h.on("SaveDocument",async function({isPureXfa:e,numPages:t,annotationStorage:a,filename:s}){const r=[n.requestLoadedStream(),n.ensureCatalog("acroForm"),n.ensureCatalog("acroFormRef"),n.ensureDoc("startXRef"),n.ensureDoc("xref"),n.ensureCatalog("structTreeRoot")],i=new RefSetCache,o=[],l=e?null:getNewAnnotationsMap(a),[f,c,u,m,p,d]=await Promise.all(r),g=p.trailer.getRaw("Root")||null;let b;if(l){d?await d.canUpdateStructTree({pdfManager:n,newAnnotationsByPage:l})&&(b=d):await StructTreeRoot.canCreateStructureTree({catalogRef:g,pdfManager:n,newAnnotationsByPage:l})&&(b=null);const e=AnnotationFactory.generateImages(a.values(),p,n.evaluatorOptions.isOffscreenCanvasSupported),t=void 0===b?o:[];for(const[a,s]of l)t.push(n.getPage(a).then(t=>{const n=new WorkerTask(`Save (editor): page ${a}`);startWorkerTask(n);return t.saveNewAnnotations(h,n,s,e,i).finally(function(){finishWorkerTask(n)})}));null===b?o.push(Promise.all(t).then(async()=>{await StructTreeRoot.createStructureTree({newAnnotationsByPage:l,xref:p,catalogRef:g,pdfManager:n,changes:i})})):b&&o.push(Promise.all(t).then(async()=>{await b.updateStructureTree({newAnnotationsByPage:l,pdfManager:n,changes:i})}))}if(e)o.push(n.ensureDoc("serializeXfaData",[a]));else for(let e=0;e<t;e++)o.push(n.getPage(e).then(function(t){const n=new WorkerTask(`Save: page ${e}`);startWorkerTask(n);return t.save(h,n,a,i).finally(function(){finishWorkerTask(n)})}));const w=await Promise.all(o);let j=null;if(e){j=w[0];if(!j)return f.bytes}else if(0===i.size)return f.bytes;const k=u&&c instanceof Dict&&i.values().some(e=>e.needAppearances),y=c instanceof Dict&&c.get("XFA")||null;let q=null,v=!1;if(Array.isArray(y)){for(let e=0,t=y.length;e<t;e+=2)if("datasets"===y[e]){q=y[e+1];v=!0}null===q&&(q=p.getNewTemporaryRef())}else y&&warn("Unsupported XFA type.");let S=Object.create(null);if(p.trailer){const e=new Map,t=p.trailer.get("Info")||null;if(t instanceof Dict)for(const[n,a]of t)"string"==typeof a&&e.set(n,stringToPDFString(a));S={rootRef:g,encryptRef:p.trailer.getRaw("Encrypt")||null,newRef:p.getNewTemporaryRef(),infoRef:p.trailer.getRaw("Info")||null,infoMap:e,fileIds:p.trailer.get("ID")||null,startXRef:m,filename:s}}return incrementalUpdate({originalData:f.bytes,xrefInfo:S,changes:i,xref:p,hasXfa:!!y,xfaDatasetsRef:q,hasXfaDatasetsEntry:v,needAppearances:k,acroFormRef:u,acroForm:c,xfaData:j,useXrefStream:isDict(p.topDict,"XRef")}).finally(()=>{p.resetNewTemporaryRef()})});h.on("GetOperatorList",function(e,t){const{pageId:a,pageIndex:s}=e;n.getPage(a).then(function(n){const a=new WorkerTask(`GetOperatorList: page ${s}`);startWorkerTask(a);const r=i>=le?Date.now():0;n.getOperatorList({handler:h,sink:t,task:a,intent:e.intent,cacheKey:e.cacheKey,annotationStorage:e.annotationStorage,modifiedIds:e.modifiedIds,pageIndex:s}).then(function(e){finishWorkerTask(a);r&&info(`page=${s+1} - getOperatorList: time=${Date.now()-r}ms, len=${e.length}`);t.close()},function(e){finishWorkerTask(a);a.terminated||t.error(e)})})});h.on("GetTextContent",function(e,t){const{pageId:a,pageIndex:s,includeMarkedContent:r,disableNormalization:o}=e;n.getPage(a).then(function(e){const n=new WorkerTask("GetTextContent: page "+s);startWorkerTask(n);const a=i>=le?Date.now():0;e.extractTextContent({handler:h,task:n,sink:t,includeMarkedContent:r,disableNormalization:o}).then(function(){finishWorkerTask(n);a&&info(`page=${s+1} - getTextContent: time=`+(Date.now()-a)+"ms");t.close()},function(e){finishWorkerTask(n);n.terminated||t.error(e)})})});h.on("GetStructTree",function(e){return n.getPage(e.pageIndex).then(e=>n.ensure(e,"getStructTree"))});h.on("FontFallback",function(e){return n.fontFallback(e.id,h)});h.on("Cleanup",function(e){return n.cleanup(!0)});h.on("Terminate",function(e){a=!0;const t=[];if(n){n.terminate(new AbortException("Worker was terminated."));const e=n.cleanup();t.push(e);n=null}else clearGlobalCaches();s?.(new AbortException("Worker was terminated."));for(const e of r){t.push(e.finished);e.terminate()}return Promise.all(t).then(function(){h.destroy();h=null})});h.on("Ready",function(t){setupDoc(e);e=null});return c}static initializeFromPort(e){const t=new MessageHandler("worker","main",e);this.setup(t,e);t.send("ready",null)}}globalThis.pdfjsWorker={WorkerMessageHandler};export{WorkerMessageHandler}; \ No newline at end of file diff --git a/go/cmd/kjol-web/frontend/vendor/pdfjs-dist/package.json b/go/cmd/kjol-web/frontend/vendor/pdfjs-dist/package.json new file mode 100644 index 00000000..04a7769b --- /dev/null +++ b/go/cmd/kjol-web/frontend/vendor/pdfjs-dist/package.json @@ -0,0 +1,34 @@ +{ + "name": "pdfjs-dist", + "version": "5.5.207", + "main": "build/pdf.mjs", + "types": "types/src/pdf.d.ts", + "description": "Generic build of Mozilla's PDF.js library.", + "keywords": [ + "Mozilla", + "pdf", + "pdf.js" + ], + "homepage": "https://mozilla.github.io/pdf.js/", + "bugs": "https://github.com/mozilla/pdf.js/issues", + "license": "Apache-2.0", + "optionalDependencies": { + "@napi-rs/canvas": "^0.1.95", + "node-readable-to-web-readable-stream": "^0.4.2" + }, + "browser": { + "canvas": false, + "fs": false, + "http": false, + "https": false, + "url": false + }, + "repository": { + "type": "git", + "url": "git+https://github.com/mozilla/pdf.js.git" + }, + "engines": { + "node": ">=20.19.0 || >=22.13.0 || >=24" + }, + "scripts": {} +} \ No newline at end of file diff --git a/go/cmd/kjol-web/frontend/vendor/vendor.json b/go/cmd/kjol-web/frontend/vendor/vendor.json new file mode 100644 index 00000000..e70f842e --- /dev/null +++ b/go/cmd/kjol-web/frontend/vendor/vendor.json @@ -0,0 +1,12 @@ +{ + "//": "This app's vendored packages, MERGED on top of kjol's base manifest (go/jsruntime/runtime/vendor.json), which pins solid-js, solid-js/web, solid-js/html, solid-js/store, @solidjs/router and solid-refresh. kjol's manifest is searched FIRST, so its solid-js wins and there is exactly one reactive instance — a split instance does not error, it silently stops flushing effects, so onMount never fires and nothing updates.", + + "//2": "pdf-lib and pdfjs-dist are here because @ui/AutoTable imports them at the TOP LEVEL for PDF export. That makes them a hard dependency of the kit, not an optional extra: leave them out and esbuild emits a bare `import ... from \"pdf-lib\"`, the browser cannot resolve it, and the entire bundle fails to evaluate — you get an empty page and one line in the console. Any app that uses AutoTable must vendor these two.", + + "//3": "Only the files the bundler actually pins are vendored, not the whole npm packages — 3.5 MB rather than 62 MB of type definitions, CJS builds and documentation. If a subpath import is ever added that reaches outside dist/ or build/, this is the first place it will fail.", + + "entrypoints": { + "pdf-lib": "pdf-lib/dist/pdf-lib.esm.js", + "pdfjs-dist": "pdfjs-dist/build/pdf.mjs" + } +} diff --git a/go/cmd/kjol-web/go.mod b/go/cmd/kjol-web/go.mod new file mode 100644 index 00000000..c27fee21 --- /dev/null +++ b/go/cmd/kjol-web/go.mod @@ -0,0 +1,28 @@ +// The example is its own module so its go-chart dependency (and freetype / +// x/image) stays out of the kjol module — kjol's engine packages are +// stdlib-only. kjol is resolved locally via the replace below (no publish step). +module kjolweb + +go 1.26.3 + +require ( + github.com/wcharczuk/go-chart/v2 v2.1.2 + kjol v0.0.0 +) + +require ( + github.com/dlclark/regexp2/v2 v2.2.1 // indirect + github.com/dop251/goja v0.0.0-20260618133527-c9b2ea77db59 // indirect + github.com/evanw/esbuild v0.28.0 // indirect + github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect + github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect + github.com/google/pprof v0.0.0-20230207041349-798e818bf904 // indirect + github.com/tdewolff/minify/v2 v2.24.13 // indirect + github.com/tdewolff/parse/v2 v2.8.13 // indirect + golang.org/x/image v0.18.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/sys v0.45.0 // indirect + golang.org/x/text v0.37.0 // indirect +) + +replace kjol => ../.. diff --git a/go/cmd/examples/go-wasm-web/go.sum b/go/cmd/kjol-web/go.sum similarity index 70% rename from go/cmd/examples/go-wasm-web/go.sum rename to go/cmd/kjol-web/go.sum index d8c9226a..aee5218a 100644 --- a/go/cmd/examples/go-wasm-web/go.sum +++ b/go/cmd/kjol-web/go.sum @@ -1,6 +1,26 @@ +github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE= +github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/dlclark/regexp2/v2 v2.2.1 h1:mf4KkFUj0gJuarK8P+LgiS+Lit7m9N1yAwEfPbee7R0= +github.com/dlclark/regexp2/v2 v2.2.1/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU= +github.com/dop251/goja v0.0.0-20260618133527-c9b2ea77db59 h1:DjKLmvKK9u15djHZ88N8M0DhgnHVgJJ8bnEe0h7Lga8= +github.com/dop251/goja v0.0.0-20260618133527-c9b2ea77db59/go.mod h1:Sc+QOu1WruvaaeT/cxFez/pXHpI9ZDjg/E8QNfSVveI= +github.com/evanw/esbuild v0.28.0 h1:V96ghtc5p5JnNUQIUsc5H3kr+AcFcMqOJll2ZmJW6Lo= +github.com/evanw/esbuild v0.28.0/go.mod h1:D2vIQZqV/vIf/VRHtViaUtViZmG7o+kKmlBfVQuRi48= +github.com/go-sourcemap/sourcemap v2.1.3+incompatible h1:W1iEw64niKVGogNgBN3ePyLFfuisuzeidWPMPWmECqU= +github.com/go-sourcemap/sourcemap v2.1.3+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg= +github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= +github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/pprof v0.0.0-20230207041349-798e818bf904 h1:4/hN5RUoecvl+RmJRE2YxKWtnnQls6rQjjW5oV7qg2U= +github.com/google/pprof v0.0.0-20230207041349-798e818bf904/go.mod h1:uglQLonpP8qtYCYyzA+8c/9qtqgA3qsXGYqCPKARAFg= +github.com/tdewolff/minify/v2 v2.24.13 h1:xrcF7gKDnUszseEY9WX9mUlZII2v2Go/QAcAwRASw58= +github.com/tdewolff/minify/v2 v2.24.13/go.mod h1:emvwoYeIl8bfAKqRU5ww95LX9Gpggpqv/naal9a8Yq0= +github.com/tdewolff/parse/v2 v2.8.13 h1:si/8rLw5BZZTWCCiMm9A3f6x+RmqYfrkEeXCgpX5ick= +github.com/tdewolff/parse/v2 v2.8.13/go.mod h1:XdsoSFThlVIRIajAuqz1evNY7bagZS8LBOPA3aVopwQ= +github.com/tdewolff/test v1.0.12 h1:7F21DqIajswxuche0geHdrUZRCWE4oko4b7bcmkkrxk= +github.com/tdewolff/test v1.0.12/go.mod h1:XPuWBzvdUzhCuxWO1ojpXsyzsA5bFoS3tO/Q3kFuTG8= github.com/wcharczuk/go-chart/v2 v2.1.2 h1:Y17/oYNuXwZg6TFag06qe8sBajwwsuvPiJJXcUcLL6E= github.com/wcharczuk/go-chart/v2 v2.1.2/go.mod h1:Zi4hbaqlWpYajnXB2K22IUYVXRXaLfSGNNR7P4ukyyQ= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= @@ -24,6 +44,8 @@ golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -34,12 +56,15 @@ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY= +golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= @@ -57,6 +82,8 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= diff --git a/go/cmd/kjol-web/internal/handlers/public.go b/go/cmd/kjol-web/internal/handlers/public.go new file mode 100644 index 00000000..5daf12ca --- /dev/null +++ b/go/cmd/kjol-web/internal/handlers/public.go @@ -0,0 +1,117 @@ +// Package handlers serves the server-rendered public pages of the Kjol JS Web +// section. +// +// This file is the APP side of a coupling inversion. kjol's bundler renders each +// public page at build time and generates public_pages.gen.go — a list of routes, +// titles, baked HTML, and (for dynamic pages) the render bundle. It does not know +// what a page is served as: no document shell, no stylesheet paths, no data. That +// is all here, because all of it is the application's business. +// +// The generated file declares `var publicPages = []publicPage{...}` and nothing +// else. The TYPE is ours — which is what lets the shape of a page be an app concern +// while the rendering of one stays the framework's. +package handlers + +import ( + "encoding/json" + "fmt" + "log" + "net/http" + "time" + + "kjol/jsbundler" + "kjol/webui" +) + +// publicPage is the app-side shape the generated registry is written against. +// Field names and order are the generator's contract (jsbundler/genssr.go). +type publicPage struct { + route string // URL path, e.g. "/js/ssr" + title string // <title> text + module string // page module relative to frontend/src (informational) + component string // exported body component name (informational) + html string // pre-rendered, data-free page body (PublicLayout + page content) + renderJS string // bundled render entry; baked ONLY for dynamic (ISR) pages +} + +// buildInfo is the payload injected into the /js/ssr page. It mirrors the +// `BuildInfo` interface the component reads via serverData<T>() — the two have to +// agree, and the JSON tags are the whole of that agreement. +type buildInfo struct { + RenderedAt string `json:"renderedAt"` + Stage string `json:"stage"` +} + +// RegisterPublicPages binds every generated public page to its route. +// +// A page with a render bundle is rendered PER REQUEST with live data (the ISR +// path). A page without one serves the skeleton that was baked at build time. Both +// ship complete HTML; the difference is only whether the numbers in it are fresh. +func RegisterPublicPages(mux *http.ServeMux) { + for _, p := range publicPages { + mux.HandleFunc("GET "+p.route, servePublicPage(p)) + } +} + +func servePublicPage(p publicPage) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + body := p.html + data := "" + + // The ISR path. The SAME Solid component that was baked at build time is run + // again here, in goja, with data injected — so the server's markup is not a + // template with holes punched in it, it is the component's own output. + if p.renderJS != "" { + payload, err := json.Marshal(buildInfo{ + RenderedAt: time.Now().UTC().Format("2006-01-02 15:04:05 UTC"), + Stage: "request time, in goja", + }) + if err != nil { + log.Printf("public page %s: marshalling data: %v", p.route, err) + } else if rendered, err := jsbundler.RenderBundleWithData(p.renderJS, string(payload)); err != nil { + // Fall through to the baked skeleton rather than 500. A page that cannot + // render with data is still a page; serving nothing helps no one. + log.Printf("public page %s: ISR render failed, serving skeleton: %v", p.route, err) + } else { + body, data = rendered, string(payload) + } + } + + w.Header().Set("Content-Type", "text/html; charset=utf-8") + fmt.Fprint(w, document(p.title, body, data)) + } +} + +// document wraps a rendered body in the page shell. +// +// __SERVER_DATA__ is inlined BEFORE the bundle, and it is the same JSON the server +// just rendered with. That is what makes the client takeover silent: public.tsx +// re-renders the identical component against the identical data and produces the +// identical markup, so the swap is invisible. Omit it and the page would render, then +// visibly collapse back to its loading skeleton the moment the bundle loaded. +func document(title, body, data string) string { + serverData := "" + if data != "" { + serverData = "\n<script>window.__SERVER_DATA__ = " + data + ";</script>" + } + + // webui.ThemeBootScript is the Go/WASM kit's — reused verbatim, because it reads the + // same "kjol-theme" key the Solid kit's controller writes. One script, one key, and a + // reader's choice of theme survives crossing between two front-ends that share + // nothing else. It goes BEFORE the stylesheet, or a dark-mode reader gets a white + // page until the CSS lands. + return `<!DOCTYPE html> +<html lang="en"> +<head> +<meta charset="utf-8" /> +<meta name="viewport" content="width=device-width, initial-scale=1" /> +<title>` + title + ` +` + webui.ThemeBootScript + ` + + + +
` + body + `
` + serverData + ` + + +` +} diff --git a/go/cmd/examples/go-wasm-web/server/main.go b/go/cmd/kjol-web/server/main.go similarity index 50% rename from go/cmd/examples/go-wasm-web/server/main.go rename to go/cmd/kjol-web/server/main.go index 1869a709..4aeb02f4 100644 --- a/go/cmd/examples/go-wasm-web/server/main.go +++ b/go/cmd/kjol-web/server/main.go @@ -1,4 +1,4 @@ -// Command server runs the go-wasm-web example on kjol's reusable wasmdevserver: +// Command server runs the kjol-web site on kjol's reusable wasmdevserver: // it SSRs the app's static routes, hosts the /rsc server-component endpoint, and // hot-swaps the wasm into the browser on change. It shows the coupling // inversion — the framework (wasmdevserver) imports no app code; the app injects @@ -6,11 +6,12 @@ // // Run it from THIS directory (the relative paths below are resolved against it): // -// go run ./server # from cmd/examples/go-wasm-web +// go run ./server # from go/cmd/kjol-web package main import ( "flag" + "fmt" "log" "net/http" @@ -19,8 +20,9 @@ import ( "kjol/wasmdevserver" "kjol/webui" - "gowasmweb/app" - "gowasmweb/buildsteps" + "kjolweb/app" + "kjolweb/buildsteps" + "kjolweb/internal/handlers" ) func main() { @@ -29,27 +31,69 @@ func main() { flag.Parse() log.Fatal(wasmdevserver.Serve(wasmdevserver.Config{ - Addr: *addr, - Dir: "./wwwroot", - Watch: *watch, - WatchDirs: []string{"app", "wasm", "css", "../../../webui", "../../../vdom", "../../../wasmruntime", "../../../rsc"}, // example + kjol engine + kit - Build: buildsteps.All, - BuildCSS: buildsteps.Tailwind, // a .css save skips codegen+wasm and hot-swaps the stylesheet - Render: render, - Document: document, - Handle: apiRoutes, + Addr: *addr, + Dir: "./wwwroot", + Watch: *watch, + WatchDirs: []string{ + "app", "wasm", "css", // this app's Go/WASM half + "frontend", // its Solid half — a .tsx save rebuilds the JS bundle + "../../webui", "../../vdom", "../../wasmruntime", "../../rsc", // the wasm engine + "../../jsruntime/uikit", "../../jsruntime/styles", // the Solid kit + the shared theme + }, + Build: buildsteps.All, + BuildCSS: buildsteps.Tailwind, // a .css save skips codegen+wasm and hot-swaps the stylesheet + Render: render, + Document: document, + Handle: routes, })) } -// apiRoutes registers the example's API endpoints. /api/quotes responds with a -// gob-encoded []app.Quote (via httputil.RespondGob) — the /data page fetches and -// decodes it on the client with encoding/gob (Go types end to end, no JSON). -func apiRoutes(mux *http.ServeMux) { +// routes registers everything the WASM app does not own. +// +// Order does not matter here — Go's ServeMux picks the most specific pattern, not the +// first — but the shape does: /js/* belongs to a completely different front-end, and it +// is claimed BEFORE the wasm app's "/" catch-all ever sees it. Two SPAs, one server, no +// argument about who owns a URL. +func routes(mux *http.ServeMux) { + handlers.RegisterPublicPages(mux) // the SSR'd public pages (/js/ssr) + mux.HandleFunc("GET /js/", serveJSApp) + mux.HandleFunc("GET /js", serveJSApp) + + // /api/quotes responds with a gob-encoded []app.Quote (via httputil.RespondGob) — + // the /wasm/data page fetches and decodes it on the client with encoding/gob (Go + // types end to end, no JSON). mux.HandleFunc("GET /api/quotes", func(w http.ResponseWriter, r *http.Request) { httputil.RespondGob(w, http.StatusOK, sampleQuotes()) }) } +// serveJSApp ships the shell for the Solid SPA. Every /js/* route gets the SAME empty +// document — the client router reads the URL and decides what to render, which is what +// makes it a single-page app. +// +// It carries no server-rendered markup, and that is a real difference from the Go/WASM +// half rather than an oversight: this section is a docs section behind a click, where a +// blank first frame costs nothing. Where it WOULD cost something, the public-page path +// (see internal/handlers) renders on the server instead — /js/ssr is that, and it is +// registered above, so it never reaches this handler. +func serveJSApp(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + fmt.Fprint(w, ` + + + + +Kjol JS Web +`+webui.ThemeBootScript+` + + + +
+ + +`) +} + func sampleQuotes() []app.Quote { return []app.Quote{ {Author: "Rob Pike", Text: "A little copying is better than a little dependency."}, @@ -86,7 +130,7 @@ func document(inner string) string { -Kjol Web — Go + WASM +kjol — a shared base layer ` + webui.ThemeBootScript + ` diff --git a/go/cmd/examples/go-wasm-web/wasm/main.go b/go/cmd/kjol-web/wasm/main.go similarity index 98% rename from go/cmd/examples/go-wasm-web/wasm/main.go rename to go/cmd/kjol-web/wasm/main.go index 2157ef2d..a5c3833b 100644 --- a/go/cmd/examples/go-wasm-web/wasm/main.go +++ b/go/cmd/kjol-web/wasm/main.go @@ -5,7 +5,7 @@ package main import ( - "gowasmweb/app" + "kjolweb/app" "kjol/vdom" "kjol/wasmruntime" ) diff --git a/go/cmd/examples/go-wasm-web/wasm/main_native.go b/go/cmd/kjol-web/wasm/main_native.go similarity index 100% rename from go/cmd/examples/go-wasm-web/wasm/main_native.go rename to go/cmd/kjol-web/wasm/main_native.go diff --git a/go/cmd/examples/go-wasm-web/wwwroot/fonts/lora-latin-ext-italic.woff2 b/go/cmd/kjol-web/wwwroot/fonts/lora-latin-ext-italic.woff2 similarity index 100% rename from go/cmd/examples/go-wasm-web/wwwroot/fonts/lora-latin-ext-italic.woff2 rename to go/cmd/kjol-web/wwwroot/fonts/lora-latin-ext-italic.woff2 diff --git a/go/cmd/examples/go-wasm-web/wwwroot/fonts/lora-latin-ext-normal.woff2 b/go/cmd/kjol-web/wwwroot/fonts/lora-latin-ext-normal.woff2 similarity index 100% rename from go/cmd/examples/go-wasm-web/wwwroot/fonts/lora-latin-ext-normal.woff2 rename to go/cmd/kjol-web/wwwroot/fonts/lora-latin-ext-normal.woff2 diff --git a/go/cmd/examples/go-wasm-web/wwwroot/fonts/lora-latin-italic.woff2 b/go/cmd/kjol-web/wwwroot/fonts/lora-latin-italic.woff2 similarity index 100% rename from go/cmd/examples/go-wasm-web/wwwroot/fonts/lora-latin-italic.woff2 rename to go/cmd/kjol-web/wwwroot/fonts/lora-latin-italic.woff2 diff --git a/go/cmd/examples/go-wasm-web/wwwroot/fonts/lora-latin-normal.woff2 b/go/cmd/kjol-web/wwwroot/fonts/lora-latin-normal.woff2 similarity index 100% rename from go/cmd/examples/go-wasm-web/wwwroot/fonts/lora-latin-normal.woff2 rename to go/cmd/kjol-web/wwwroot/fonts/lora-latin-normal.woff2 diff --git a/go/cmd/examples/go-wasm-web/wwwroot/wasmboot.js b/go/cmd/kjol-web/wwwroot/wasmboot.js similarity index 100% rename from go/cmd/examples/go-wasm-web/wwwroot/wasmboot.js rename to go/cmd/kjol-web/wwwroot/wasmboot.js diff --git a/go/cmd/twcss/main.go b/go/cmd/twcss/main.go index 899ed982..80e9b440 100644 --- a/go/cmd/twcss/main.go +++ b/go/cmd/twcss/main.go @@ -2,7 +2,7 @@ // scanning explicit content globs for utility candidates. Unlike the app bundler // (which is wired to the frontend tree) it takes the entry, output, and content // globs as flags/args, so it works for markup authored in any language — used by -// the go-wasm-web example, whose UI is written in Go. +// the kjol-web site, whose Go/WASM half writes its UI in Go. // // Usage (globs are relative to -base; pass "**" for a recursive walk): // diff --git a/go/webbundler/alias.go b/go/jsbundler/alias.go similarity index 90% rename from go/webbundler/alias.go rename to go/jsbundler/alias.go index 6ff46d80..b8b564cb 100644 --- a/go/webbundler/alias.go +++ b/go/jsbundler/alias.go @@ -1,4 +1,4 @@ -package webbundler +package jsbundler import ( "fmt" @@ -11,8 +11,8 @@ import ( // aliasRoots maps the framework import prefixes to absolute filesystem roots: // -// @ui/* -> kjol web kit (shared Solid components) -// @kjol/* -> kjol web root (auth, utils, hooks, ssr, env.ts, ...) +// @ui/* -> kjol JS kit (shared Solid components) +// @kjol/* -> kjol JS root (auth, utils, hooks, ssr, env.ts, ...) // @appgen/* -> the app's generated dir (faIcons registry etc. — app-owned) // // In single-tree mode @ui/@kjol resolve back under the app frontend. @@ -49,7 +49,7 @@ func resolveAlias(root, rest string) (string, bool) { } // aliasPlugin resolves @ui / @kjol / @appgen imports to absolute paths across the -// app and kjol web trees. It sits before the vendor resolvers; the Solid +// app and kjol JS trees. It sits before the vendor resolvers; the Solid // compiler's OnLoad then compiles any .tsx/.jsx it points at. func aliasPlugin() esbuild.Plugin { roots := aliasRoots() diff --git a/go/webbundler/build.go b/go/jsbundler/build.go similarity index 96% rename from go/webbundler/build.go rename to go/jsbundler/build.go index 4cd6ab0e..199fdc00 100644 --- a/go/webbundler/build.go +++ b/go/jsbundler/build.go @@ -1,4 +1,4 @@ -// Package bundler is the frontend build system: it drives esbuild's Go API for +// Package jsbundler is the frontend build system: it drives esbuild's Go API for // JS bundling, compiles Solid JSX/TSX and Tailwind v4 CSS with Go-native // compilers (no Node, no Babel, no goja on the build path), and bakes the // public-page SSR (which does still use goja to execute components). The @@ -18,7 +18,7 @@ // genssr.go public-page SSR bake + Go registry generation // ssr.go/renderer.go the goja SSR engine (also used by the server at runtime) // watch.go poll-and-rebuild watch loop -package webbundler +package jsbundler import ( "fmt" @@ -34,7 +34,7 @@ type bundleStats struct { // Build runs the full one-shot build: FA icon subset, public-route generation, // the JS/CSS bundles, and the SSR bake, printing a stats summary. c selects the -// app + kjol web trees (see Config); zero-value fields fall back to the +// app + kjol JS trees (see Config); zero-value fields fall back to the // single-tree defaults. func Build(c Config) error { Configure(c) diff --git a/go/webbundler/compile_solid.go b/go/jsbundler/compile_solid.go similarity index 99% rename from go/webbundler/compile_solid.go rename to go/jsbundler/compile_solid.go index 038cdddc..643491e0 100644 --- a/go/webbundler/compile_solid.go +++ b/go/jsbundler/compile_solid.go @@ -1,4 +1,4 @@ -package webbundler +package jsbundler // Go-native Solid JSX compiler (replaces babel-preset-solid running in goja). // diff --git a/go/webbundler/compile_solid_gen.go b/go/jsbundler/compile_solid_gen.go similarity index 94% rename from go/webbundler/compile_solid_gen.go rename to go/jsbundler/compile_solid_gen.go index 66768e8f..c66b8a0e 100644 --- a/go/webbundler/compile_solid_gen.go +++ b/go/jsbundler/compile_solid_gen.go @@ -1,4 +1,4 @@ -package webbundler +package jsbundler // Go-native Solid codegen: JSX tree -> dom-expressions runtime output. // @@ -950,25 +950,61 @@ func isDOMChild(ch *jsxNode) bool { // collapseText applies JSX whitespace normalization: lines are trimmed and // joined by a single space; text that is only whitespace-with-newline vanishes. +// collapseText applies JSX's whitespace rules to one text child. It is a port of +// Babel's cleanJSXElementLiteralChild, and it has to be, because the rules are not +// what you would guess: +// +// leading whitespace is stripped from every line EXCEPT the first, +// trailing whitespace is stripped from every line EXCEPT the last. +// +// That asymmetry is the whole point. In +// +// +// +// the text before the expression is "\n Clicked " and the text after it is +// " times\n". The indentation must go; the single space before `{` and after `}` +// must NOT — they are the spaces between the words. Trimming both ends of every +// line (as this did) renders "Clicked0times", and it does it silently, in every +// multi-line component in the codebase. +// +// Blank lines vanish, and the surviving lines are joined with a single space, so a +// paragraph broken across source lines still reads as a sentence. func collapseText(s string) string { - if strings.TrimSpace(s) == "" { - if strings.ContainsAny(s, "\n") { - return "" - } - return s // significant single-line whitespace (e.g. "a {x} b") - } - if !strings.ContainsAny(s, "\n") { - return s - } + s = strings.ReplaceAll(s, "\r\n", "\n") + s = strings.ReplaceAll(s, "\r", "\n") lines := strings.Split(s, "\n") - var kept []string - for _, l := range lines { - l = strings.Trim(l, " \t\r") - if l != "" { - kept = append(kept, l) + + // The last line with any non-whitespace on it. Every kept line before this one + // gets a separating space; this one does not, or every text child would end in a + // trailing space. Starts at 0 (not -1) so an all-whitespace chunk is left exactly + // as it is — " " between two elements is a real, significant space. + lastNonEmpty := 0 + for i, l := range lines { + if strings.Trim(l, " \t") != "" { + lastNonEmpty = i } } - return strings.Join(kept, " ") + + var b strings.Builder + for i, l := range lines { + line := strings.ReplaceAll(l, "\t", " ") + if i != 0 { + line = strings.TrimLeft(line, " ") + } + if i != len(lines)-1 { + line = strings.TrimRight(line, " ") + } + if line == "" { + continue + } + if i != lastNonEmpty { + line += " " + } + b.WriteString(line) + } + return b.String() } func escapeTemplateText(s string) string { diff --git a/go/webbundler/compile_solid_render_test.go b/go/jsbundler/compile_solid_render_test.go similarity index 84% rename from go/webbundler/compile_solid_render_test.go rename to go/jsbundler/compile_solid_render_test.go index 7a265f6d..bb911c5b 100644 --- a/go/webbundler/compile_solid_render_test.go +++ b/go/jsbundler/compile_solid_render_test.go @@ -1,4 +1,4 @@ -package webbundler +package jsbundler import ( "os" @@ -42,6 +42,23 @@ func assertRenderEquivalent(t *testing.T, name, src string) { if err != nil { t.Fatal(err) } + // Point the bundler at kjol's own vendored Solid before chdir'ing — the path is + // relative to the package dir, and Configure stores it for vendorDirs(). + // + // Without this the oracle silently never ran: webDir defaults to "", so + // vendorDirs() resolved to /frontend/vendor — a directory kjol does not + // have and never had (it is a framework; there is no app frontend here). Every + // render then failed to resolve solid-js/web. It only looked green if a test + // that calls Configure happened to run first, and none does: the sole callers + // are in crosstree_test.go, which sorts after this file. + webAbs, err := filepath.Abs(filepath.Join("..", "jsruntime")) + if err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(webAbs, "runtime", "vendor.json")); err != nil { + t.Skipf("kjol vendored solid runtime not present (%v)", err) + } + Configure(Config{WebDir: webAbs}) t.Chdir(root) babelJS, err := Compile(src, name+".tsx") @@ -77,6 +94,33 @@ func TestGoCompilerRenderCore(t *testing.T) { {"list", `export const A = () => { const items = ["a", "b", "c"]; return
    {items.map((i) =>
  • {i}
  • )}
; };`}, {"deep-static", `export const A = () =>

Title

body text

;`}, {"multi-attr", `export const A = () => ;`}, + + // Multi-line children. Every case above is written on ONE line, which is why + // they all passed while the compiler was eating the spaces around an expression + // the moment the JSX was indented — i.e. in essentially all real code. These + // pin JSX's asymmetric whitespace rule: indentation goes, the space between the + // words stays. + {"ml-text-around-expr", `export const A = () => { const c = () => 0; return ( + + ); };`}, + {"ml-text-before-el", `export const A = () => ( +

+ selected: day +

+ );`}, + {"ml-wrapped-prose", `export const A = () => ( +

+ one two + three four +

+ );`}, + {"ml-expr-both-sides", `export const A = () => { const x = () => "X"; const y = () => "Y"; return ( +
+ a {x()} b {y()} c +
+ ); };`}, } for _, c := range cases { c := c diff --git a/go/webbundler/compile_solid_test.go b/go/jsbundler/compile_solid_test.go similarity index 99% rename from go/webbundler/compile_solid_test.go rename to go/jsbundler/compile_solid_test.go index 26cd05fb..bbbc040c 100644 --- a/go/webbundler/compile_solid_test.go +++ b/go/jsbundler/compile_solid_test.go @@ -1,4 +1,4 @@ -package webbundler +package jsbundler import "testing" diff --git a/go/webbundler/config.go b/go/jsbundler/config.go similarity index 67% rename from go/webbundler/config.go rename to go/jsbundler/config.go index a98cddfb..9ce0bcb5 100644 --- a/go/webbundler/config.go +++ b/go/jsbundler/config.go @@ -1,18 +1,18 @@ -package webbundler +package jsbundler import "path/filepath" -// Config tells the bundler where the application tree and the shared kjol web +// Config tells the bundler where the application tree and the shared kjol JS // tree live. The bundler always runs from the app root, so relative paths are // resolved against that working directory (absolute paths also work). // // When WebDir is empty the bundler runs in single-tree mode: the kit, vendored // runtime, icons, and styles are expected under AppFrontend (the pre-extraction -// layout). When WebDir points at kjol/web, those come from the shared tree and -// the app supplies only its pages/routes/brand. +// layout). When WebDir points at kjol/go/jsruntime, those come from the shared +// tree and the app supplies only its pages/routes/brand. type Config struct { AppFrontend string // app frontend source root (default "frontend") - WebDir string // path to kjol/web; "" => single-tree under AppFrontend + WebDir string // path to kjol/go/jsruntime; "" => single-tree under AppFrontend Output string // build output dir (default "wwwroot") GenGoDir string // dir for generated Go, e.g. public_pages.gen.go (default "internal/handlers") GenTSDir string // dir for generated TS, e.g. faIcons.ts (default AppFrontend/src/ui/generated) @@ -24,7 +24,7 @@ type Config struct { var ( frontendDir = "frontend" outputDir = "wwwroot" - webDir = "" // kjol/web; empty => single-tree + webDir = "" // kjol/go/jsruntime; empty => single-tree genGoDir = "internal/handlers" genTSDir = filepath.Join("frontend", "src", "ui", "generated") ) @@ -48,7 +48,7 @@ func Configure(c Config) { } } -// webRoot is the kjol web tree (@kjol/* root), falling back to the app frontend +// webRoot is the kjol JS tree (@kjol/* root), falling back to the app frontend // in single-tree mode. func webRoot() string { if webDir != "" { @@ -65,12 +65,23 @@ func uikitDir() string { return filepath.Join(frontendDir, "src", "ui") } -// iconsDir is the FontAwesome SVG source kit. -func iconsDir() string { +// iconsDirs lists the FontAwesome SVG source roots in resolution precedence +// order: the app's own kit first, kjol's second. +// +// The app has to win. kjol ships a SUBSET — the icons its own kit and example +// reference — while an app carries the full FontAwesome kit it licensed. If kjol +// were searched first (or searched alone, as this used to be when WebDir was +// set), an app adopting the shared tree would silently regenerate its registry +// from kjol's few dozen icons and lose every other icon it uses, with no error: +// the registry would simply come back smaller and the icons would render blank. +// +// Searching both, app-first, means an app-side icon of the same name overrides +// kjol's, and an icon kjol has never heard of still resolves. +func iconsDirs() []string { if webDir != "" { - return filepath.Join(webDir, "icons") + return []string{filepath.Join(frontendDir, "icons"), filepath.Join(webDir, "icons")} } - return filepath.Join(frontendDir, "icons") + return []string{filepath.Join(frontendDir, "icons")} } // vendorDirs lists the vendored-runtime roots in resolution precedence order. diff --git a/go/webbundler/crosstree_test.go b/go/jsbundler/crosstree_test.go similarity index 87% rename from go/webbundler/crosstree_test.go rename to go/jsbundler/crosstree_test.go index b1d5cd4d..b9d43af5 100644 --- a/go/webbundler/crosstree_test.go +++ b/go/jsbundler/crosstree_test.go @@ -1,4 +1,4 @@ -package webbundler +package jsbundler import ( "os" @@ -9,16 +9,16 @@ import ( // TestCrossTreeJSBundle proves the bundler resolves the shared kit across the // app/kjol tree boundary: a temp app entry imports @ui/Buttons, which pulls the -// real kjol web/uikit (Buttons -> ./Icons -> @appgen/faIcons stub) and the solid -// runtime from web/runtime. If the alias plugin, merged vendor manifest, and +// real kjol jsruntime/uikit (Buttons -> ./Icons -> @appgen/faIcons stub) and the solid +// runtime from jsruntime/runtime. If the alias plugin, merged vendor manifest, and // multi-dir NodePaths all work, esbuild produces a non-empty bundle. func TestCrossTreeJSBundle(t *testing.T) { - webAbs, err := filepath.Abs(filepath.Join("..", "..", "web")) + webAbs, err := filepath.Abs(filepath.Join("..", "jsruntime")) if err != nil { t.Fatal(err) } if _, err := os.Stat(filepath.Join(webAbs, "uikit", "Buttons.tsx")); err != nil { - t.Skipf("kjol web kit not present (%v)", err) + t.Skipf("kjol JS kit not present (%v)", err) } app := t.TempDir() @@ -58,12 +58,12 @@ func TestCrossTreeJSBundle(t *testing.T) { // for utility candidates across the boundary (WebDir set) without error, and // that an app-side utility class makes it into the output. func TestCrossTreeCSS(t *testing.T) { - webAbs, err := filepath.Abs(filepath.Join("..", "..", "web")) + webAbs, err := filepath.Abs(filepath.Join("..", "jsruntime")) if err != nil { t.Fatal(err) } if _, err := os.Stat(filepath.Join(webAbs, "uikit")); err != nil { - t.Skipf("kjol web kit not present (%v)", err) + t.Skipf("kjol JS kit not present (%v)", err) } app := t.TempDir() diff --git a/go/webbundler/css.go b/go/jsbundler/css.go similarity index 97% rename from go/webbundler/css.go rename to go/jsbundler/css.go index 80092803..78599423 100644 --- a/go/webbundler/css.go +++ b/go/jsbundler/css.go @@ -1,4 +1,4 @@ -package webbundler +package jsbundler // CSS pipeline: compiles the Tailwind entry stylesheet (frontend/css/style.css) // with the native Go Tailwind v4 engine (tailwind.go — twCompile/scanSources, no @@ -78,7 +78,7 @@ func compileCSSBundle(label string, twSources []string, outName string) (bundleS kitCands := tw.Scan(uikitDir(), []string{"**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx"}) candidates = dedupStrings(append(candidates, kitCands...)) - // Prepend the shared @theme scaffold (kjol web/styles/theme.css) ahead of the + // Prepend the shared @theme scaffold (kjol jsruntime/styles/theme.css) ahead of the // app's brand style.css so its tokens/vars are in scope. Absent in single-tree // mode (the app's style.css is already complete). input := string(src) diff --git a/go/webbundler/export_shim.go b/go/jsbundler/export_shim.go similarity index 99% rename from go/webbundler/export_shim.go rename to go/jsbundler/export_shim.go index a4cc6008..1dc446fe 100644 --- a/go/webbundler/export_shim.go +++ b/go/jsbundler/export_shim.go @@ -1,4 +1,4 @@ -package webbundler +package jsbundler // defaultExportShimPlugin bridges two ESM-strictness mismatches that // existed in the previous custom bundler: diff --git a/go/webbundler/faicons.go b/go/jsbundler/faicons.go similarity index 82% rename from go/webbundler/faicons.go rename to go/jsbundler/faicons.go index af9df873..8158771d 100644 --- a/go/webbundler/faicons.go +++ b/go/jsbundler/faicons.go @@ -1,4 +1,4 @@ -package webbundler +package jsbundler import ( "fmt" @@ -13,19 +13,20 @@ import ( // Tree-shaken FontAwesome. Instead of shipping the 41.5 MB `all.min.js` kit and // looking icons up by runtime string, we scan the app for the icon names it // actually references and emit a registry of just those icons' SVG data, pulled -// from the FontAwesome SVGs under frontend/icons/. Icons.tsx looks up that +// from the FontAwesome SVGs under the icon roots. Icons.tsx looks up that // registry exactly like it used to call FontAwesome.findIconDefinition. -// FA prefix -> frontend/icons/. cdrateline renders classic far/fas; a Sharp +// FA prefix -> /. cdrateline renders classic far/fas; a Sharp // project (fasr/fass) would add "fasr": "sharp-regular", "fass": "sharp-solid". var faStyleDirs = map[string]string{ "far": "regular", "fas": "solid", } -// The FA SVG source dir (iconsDir) and the generated registry output path -// (faOutPath) are resolved from Config — see config.go. Only the styles in -// faStyleDirs are read; the rest of the kit is unused. +// The FA SVG source roots (iconsDirs — the app's kit, then kjol's) and the +// generated registry output path (faOutPath) are resolved from Config — see +// config.go. Only the styles in faStyleDirs are read; the rest of the kit is +// unused. var ( // icon="name" / icon: "name" @@ -39,10 +40,34 @@ var ( reRegisterIcon = regexp.MustCompile(`registerIcon\(\s*"([a-z0-9][a-z0-9-]*)"`) ) +// presentIconsDirs is iconsDirs filtered to the roots that actually exist, so a +// missing kit is skipped rather than failing every icon lookup against it. +func presentIconsDirs() []string { + var roots []string + for _, d := range iconsDirs() { + if _, err := os.Stat(d); err == nil { + roots = append(roots, d) + } + } + return roots +} + +// readIconSVG returns the first /