@embedpdf/plugin-actions 3.0.0-next.13 → 3.0.0-next.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/contract/host.cjs +13 -1
  2. package/dist/contract/host.cjs.map +1 -1
  3. package/dist/contract/host.d.cts +3 -7
  4. package/dist/contract/host.d.ts +3 -7
  5. package/dist/contract/host.js +10 -3
  6. package/dist/contract/host.js.map +1 -1
  7. package/dist/contract-CNKZHb6w.d.ts +547 -0
  8. package/dist/contract-CwN3NAXU.js +175 -0
  9. package/dist/contract-CwN3NAXU.js.map +1 -0
  10. package/dist/contract-DSQysTqU.d.cts +547 -0
  11. package/dist/contract-_HB_UliT.cjs +210 -0
  12. package/dist/contract-_HB_UliT.cjs.map +1 -0
  13. package/dist/contract.cjs +5 -4
  14. package/dist/contract.d.cts +2 -3
  15. package/dist/contract.d.ts +2 -3
  16. package/dist/contract.js +2 -3
  17. package/dist/host-contract-CRNO2oZN.d.ts +165 -0
  18. package/dist/host-contract-DJ8TqDr3.d.cts +165 -0
  19. package/dist/index.cjs +1524 -1076
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +11 -9
  22. package/dist/index.d.ts +11 -9
  23. package/dist/index.js +1522 -1076
  24. package/dist/index.js.map +1 -1
  25. package/package.json +6 -10
  26. package/dist/contract-C1K3H4RP.cjs +0 -89
  27. package/dist/contract-C1K3H4RP.cjs.map +0 -1
  28. package/dist/contract-COk-w3Fo.d.ts +0 -50
  29. package/dist/contract-DAem-EST.js +0 -78
  30. package/dist/contract-DAem-EST.js.map +0 -1
  31. package/dist/contract-Os5y4NaD.d.cts +0 -50
  32. package/dist/internal.cjs +0 -3
  33. package/dist/internal.d.cts +0 -3
  34. package/dist/internal.d.ts +0 -3
  35. package/dist/internal.js +0 -2
  36. package/dist/types-BXJLAKXi.cjs +0 -52
  37. package/dist/types-BXJLAKXi.cjs.map +0 -1
  38. package/dist/types-D-DoiESj.d.cts +0 -504
  39. package/dist/types-D-DoiESj.d.ts +0 -504
  40. package/dist/types-DgBMy5nE.js +0 -35
  41. package/dist/types-DgBMy5nE.js.map +0 -1
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/script-environment.ts","../src/capability.ts","../src/reducer.ts","../src/actions.plugin.ts"],"sourcesContent":["import {\n createScriptHost,\n DEFAULT_SCRIPT_BUDGET,\n resolveScriptIdentity,\n seedFrom,\n type ScriptBudget,\n type ScriptHost,\n} from '@embedpdf/core-acrojs';\nimport type { DocumentHandle } from '@embedpdf/engine-core/runtime';\n\nimport type { ActionsPluginConfig, ScriptRealmTarget } from './types';\n\nexport type JavaScriptConfig = NonNullable<ActionsPluginConfig['javascript']>;\n\n/**\n * The scripting ENVIRONMENT — the session-level half of the JavaScript\n * switch: sandbox factory, identity, clock, timezone, seed, and budget.\n * Policy (`enabled`) decides whether one exists; realms are minted from it.\n *\n * One environment mints any number of realms: the owning document's own\n * host, and DETACHED realms for documents that are not the viewer document\n * (a stamp asset, a template). Every realm gets a FRESH sandbox from the\n * factory — same policy and environment, isolated globals (WP4).\n *\n * Identity closes over the OWNING document: who the user is, is a session\n * fact resolved from the owner's claims plus the embedder decoration —\n * never from a detached document's (authority-less) handle.\n */\nexport interface ScriptRealmFactory {\n realmFor(target: ScriptRealmTarget): ScriptHost;\n /** The embedder's budget (or the default) — the per-run budget every\n * minted realm enforces AND the transaction aggregate consumers apply. */\n readonly budget: ScriptBudget;\n}\n\nexport function createScriptRealmFactory(\n js: JavaScriptConfig,\n identityDoc: DocumentHandle,\n): ScriptRealmFactory {\n const sandboxFactory =\n js.sandboxFactory ??\n (() =>\n import('@embedpdf/core-js-sandbox').then(({ createQuickJsSandbox }) =>\n createQuickJsSandbox(),\n ));\n const budget = js.budget ?? DEFAULT_SCRIPT_BUDGET;\n return {\n budget,\n realmFor: (target) =>\n createScriptHost({\n sandboxFactory,\n document: () => {\n const meta = target.document();\n return {\n id: target.doc.id,\n fileName: js.fileName?.() ?? meta?.name ?? 'document.pdf',\n pageCount: meta?.pageCount ?? 0,\n pageNumber: 0,\n };\n },\n identity: () => resolveScriptIdentity(identityDoc, js.identity),\n environment: (sequence) => {\n const nowMs = js.now?.() ?? Date.now();\n return {\n nowMs,\n utcOffsetMinutes: js.utcOffsetMinutes?.() ?? -new Date(nowMs).getTimezoneOffset(),\n randomSeed: js.randomSeed?.() ?? seedFrom(target.doc.id, sequence),\n };\n },\n bootSources: target.bootSources,\n budget,\n }),\n };\n}\n","import {\n createEventHook,\n createSerialQueue,\n DocumentsToken,\n type PluginContext,\n type Unsubscribe,\n} from '@embedpdf/core';\nimport { javaScriptProgramFromActionTree, scriptFieldsFromSnapshot } from '@embedpdf/core-acrojs';\nimport type {\n ScriptAnnotInput,\n ScriptColorArray,\n ScriptDiagnostic,\n ScriptEventInput,\n ScriptExecutionError,\n ScriptOutput,\n ScriptUiEffect,\n ScriptWorldInput,\n} from '@embedpdf/core-acrojs';\nimport type {\n AnnotationRef,\n DocumentActionsSnapshot,\n FormSnapshot,\n FormSubmissionRequest,\n PageObjectNumber,\n PdfActionNode,\n PdfActionTree,\n PdfActionType,\n PdfAnnotationActions,\n PdfPageActions,\n SubmitFormPayload,\n} from '@embedpdf/engine-core/runtime';\n\nimport { createScriptRealmFactory } from './script-environment';\nimport { eventOf, originOf } from './types';\nimport type {\n ActionContext,\n ActionDiagnostic,\n ActionDispatchResult,\n ActionExecutor,\n ActionNodeResult,\n ActionNodeStatus,\n ActionOrigin,\n ActionPolicy,\n ActionPolicyDecision,\n ActionPolicyRow,\n ActionsAction,\n ActionsCapability,\n ActionsHostCapability,\n ActionsPluginConfig,\n ActionsState,\n ActionSource,\n ActionStepResult,\n ActionSubmitHandler,\n ActionSubmitRequest,\n ActionTrigger,\n ActionTriggerResult,\n ActionUiAdapter,\n AnnotCommitEntry,\n AnnotCommitSink,\n DocumentTriggerEvent,\n FormCommitSink,\n PageStateReport,\n ScriptCommitSurface,\n ScriptRealmKind,\n ScriptSurfaceResult,\n SubmitIntent,\n SubmitResolver,\n} from './types';\n\nconst ALLOW_ALL: ActionPolicyRow = { user: 'allow', hover: 'allow', lifecycle: 'allow' };\n\nconst DEFAULT_POLICY: ActionPolicy = {\n goto: ALLOW_ALL,\n named: ALLOW_ALL,\n hide: ALLOW_ALL,\n 'reset-form': ALLOW_ALL,\n javascript: ALLOW_ALL,\n // No auto-opened tabs: only a real user activation reaches the adapter.\n uri: { user: 'adapter', hover: 'report', lifecycle: 'report' },\n // The Named Print verb: adapter on user gestures, blocked otherwise.\n print: { user: 'adapter', hover: 'block', lifecycle: 'block' },\n // The sink chain (handler → the document's home → blocked) on user\n // gestures only; hover/lifecycle submits never leave the viewer.\n 'submit-form': { user: 'adapter', hover: 'block', lifecycle: 'block' },\n};\n\n/** Never executable, not configurable — diagnostics only. */\nconst NEVER_TYPES: ReadonlySet<PdfActionType> = new Set([\n 'launch',\n 'goto-remote',\n 'goto-embedded',\n 'sound',\n 'movie',\n 'import-data',\n]);\n\n/** Recognized types with no Phase-1 interpreter. */\nconst UNSUPPORTED_TYPES: ReadonlySet<PdfActionType> = new Set([\n 'rendition',\n 'thread',\n 'set-ocg-state',\n 'transition',\n 'goto-3d-view',\n 'unknown',\n]);\n\n/** Document-lifetime node types: engine mutations, committed in walk order. */\nconst DOCUMENT_TYPES: ReadonlySet<PdfActionType> = new Set(['reset-form', 'javascript']);\n\nconst sameRef = (left: AnnotationRef, right: AnnotationRef): boolean => {\n if (left.kind === 'objectNumber' && right.kind === 'objectNumber') {\n return left.annotObjectNumber === right.annotObjectNumber;\n }\n if (left.kind === 'nm' && right.kind === 'nm') {\n return left.pageObjectNumber === right.pageObjectNumber && left.nm === right.nm;\n }\n if (left.kind === 'index' && right.kind === 'index') {\n return left.pageObjectNumber === right.pageObjectNumber && left.index === right.index;\n }\n return false;\n};\n\nconst isPrintVerb = (node: PdfActionNode): boolean =>\n node.type === 'named' && node.name === 'Print';\n\nexport function createActionsCapability(\n ctx: PluginContext<ActionsState, ActionsAction>,\n config: ActionsPluginConfig = {},\n): ActionsHostCapability {\n const policy: ActionPolicy = { ...DEFAULT_POLICY, ...config.policy };\n const enqueue = createSerialQueue();\n const executors = new Map<PdfActionType, ActionExecutor>();\n let annotCommitSink: AnnotCommitSink | null = null;\n let formCommitSink: FormCommitSink | null = null;\n let uiAdapter: ActionUiAdapter | null = null;\n /** Sink 1 of the submit chain (consent = installation). */\n let submitHandler: ActionSubmitHandler | null = null;\n /** The form plugin's dataset resolver (D7's one door). */\n let submitResolver: SubmitResolver | null = null;\n /** D3's document-print latch: while a print event wrapper is active, a\n * nested print request is SUPPRESSED (`reentrant-print`) — the adapter\n * opens exactly one dialog per outer request. */\n let docPrintEventActive = false;\n /** D11's deterministic aggregate: JS nodes run in the CURRENT dispatch. */\n let jsNodesThisDispatch = 0;\n\n const actionHook = createEventHook<import('./types').ActionDispatchEvent>((error) =>\n globalThis.console?.error('[actions] onAction observer failed:', error),\n );\n const diagnosticHook = createEventHook<ActionDiagnostic>((error) =>\n globalThis.console?.error('[actions] onDiagnostic observer failed:', error),\n );\n const scriptDiagnosticHook = createEventHook<ScriptDiagnostic>((error) =>\n globalThis.console?.error('[actions] onScriptDiagnostic observer failed:', error),\n );\n const scriptErrorHook = createEventHook<ScriptExecutionError>((error) =>\n globalThis.console?.error('[actions] onScriptError observer failed:', error),\n );\n ctx.cleanup(() => {\n actionHook.dispose();\n diagnosticHook.dispose();\n scriptDiagnosticHook.dispose();\n scriptErrorHook.dispose();\n });\n\n /** Policy lookup — `null` means \"recognized, no interpreter\" (inert). */\n const decisionFor = (\n node: PdfActionNode,\n origin: ActionOrigin,\n ): ActionPolicyDecision | 'never' | 'unsupported' => {\n if (NEVER_TYPES.has(node.type)) return 'never';\n if (UNSUPPORTED_TYPES.has(node.type)) return 'unsupported';\n if (isPrintVerb(node)) return policy.print[origin];\n const row = policy[node.type as keyof ActionPolicy] as ActionPolicyRow | undefined;\n return row ? row[origin] : 'unsupported';\n };\n\n const allowsPrint = (): boolean =>\n ctx.tryGet(DocumentsToken)?.allows('doc.print', ctx.documentId ?? undefined) ?? true;\n\n // ── the ONE catalog-actions read (D11) ──────────────────────────────────\n // The catalog /AA is immutable in-session (no writer exists in the\n // stack), so the open sequence, boot sources, and the five document\n // events share one memoized read. A REJECTED read is evicted so a\n // transient failure cannot poison every future lifecycle event.\n let actionsSnapshotPromise: Promise<DocumentActionsSnapshot | null> | null = null;\n const readDocumentActions = (): Promise<DocumentActionsSnapshot | null> => {\n if (!actionsSnapshotPromise) {\n const doc = ctx.doc;\n const read: Promise<DocumentActionsSnapshot | null> = doc?.actions\n ? Promise.resolve(doc.actions.read())\n : Promise.resolve(null);\n const memo: Promise<DocumentActionsSnapshot | null> = read.catch((error: unknown) => {\n if (actionsSnapshotPromise === memo) actionsSnapshotPromise = null;\n throw error;\n });\n actionsSnapshotPromise = memo;\n }\n return actionsSnapshotPromise;\n };\n\n /** The Table-200 key for each verb-shaped document trigger event. */\n const DOC_EVENT_TREES = {\n 'will-save': 'willSave',\n 'did-save': 'didSave',\n 'will-print': 'willPrint',\n 'did-print': 'didPrint',\n 'will-close': 'willClose',\n } as const;\n\n // ── the submit pipeline (D7): one intent, one resolver, one sink chain ──\n const nowMs = (): number => js?.now?.() ?? Date.now();\n\n const intentOfPayload = (payload: SubmitFormPayload): SubmitIntent => ({\n url: payload.url,\n fields: payload.fields,\n exclude: payload.flags.exclude,\n includeNoValueFields: payload.flags.includeNoValueFields,\n format: payload.flags.format,\n method: payload.flags.method,\n flagsRaw: payload.flags.raw,\n ...(payload.charSet === undefined ? {} : { charSet: payload.charSet }),\n });\n\n const toFormSubmissionRequest = (request: ActionSubmitRequest): FormSubmissionRequest => ({\n entries: request.entries,\n intent: {\n url: request.url,\n format: request.format,\n method: request.method,\n flagsRaw: request.flagsRaw,\n ...(request.charSet === undefined ? {} : { charSet: request.charSet }),\n },\n origin: request.origin,\n clientTimeMs: nowMs(),\n });\n\n /**\n * The ONE submit door — both sources land here after policy. Sink order:\n * embedder handler (explicit beats ambient; detached-promise contract) →\n * the document's home (`doc.forms.submit`, engine-asserted, AWAITED — a\n * real op with a real receipt) → blocked with `no-submit-sink`. Never a\n * network call from this plugin.\n */\n const performSubmit = async (\n intent: SubmitIntent,\n actionCtx: ActionContext,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<{ status: ActionNodeStatus; detail?: string }> => {\n const decision = policy['submit-form'][actionCtx.origin];\n if (decision !== 'adapter' && decision !== 'allow') {\n diagnose({\n code: 'blocked',\n message: `submit-form: policy '${decision}' for origin '${actionCtx.origin}'`,\n });\n return { status: 'blocked' };\n }\n if (!submitResolver) {\n diagnose({\n code: 'no-submit-resolver',\n message: 'submit-form: no dataset resolver registered (form plugin missing?)',\n });\n return { status: 'blocked', detail: 'no dataset resolver' };\n }\n let request: ActionSubmitRequest;\n try {\n request = await submitResolver(intent, actionCtx, diagnose);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n diagnose({ code: 'executor-failed', message: `submit-form: dataset resolution: ${detail}` });\n return { status: 'failed', detail };\n }\n const doc = ctx.doc;\n const homeSubmit =\n doc && typeof doc.forms.submit === 'function'\n ? () => Promise.resolve(doc.forms.submit!(toFormSubmissionRequest(request)))\n : null;\n if (submitHandler) {\n try {\n const outcome = submitHandler(request, { submitToDocumentHome: homeSubmit });\n if (outcome && typeof (outcome as Promise<void>).then === 'function') {\n // DETACHED by contract: `executed` means \"handed to the embedder\";\n // a later rejection is observability, never a node-result rewrite.\n void (outcome as Promise<void>).catch((error: unknown) => {\n diagnosticHook.emit({\n code: 'executor-failed',\n message: `submit handler rejected (detached): ${\n error instanceof Error ? error.message : String(error)\n }`,\n });\n });\n }\n return { status: 'executed' };\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n diagnose({ code: 'executor-failed', message: `submit handler threw: ${detail}` });\n return { status: 'failed', detail };\n }\n }\n if (homeSubmit) {\n try {\n await homeSubmit();\n return { status: 'executed' };\n } catch (error) {\n // The engine's refusal (authority, transport) surfaced on the node —\n // enforcement lives at the home's boundary, we just report it.\n const detail = error instanceof Error ? error.message : String(error);\n diagnose({ code: 'executor-failed', message: `document home refused submit: ${detail}` });\n return { status: 'failed', detail };\n }\n }\n diagnose({\n code: 'no-submit-sink',\n message: 'submit-form: no handler installed and the document has no submit-capable home',\n });\n return { status: 'blocked', detail: 'no submit sink' };\n };\n\n // ── the ONE per-document ScriptHost (D8) ────────────────────────────────\n // Policy (`enabled`) decides whether a realm factory exists; the factory\n // carries the session environment and mints this document's own realm\n // here, and detached realms on demand (host lens) — one environment, any\n // number of isolated realms.\n const js = config.javascript;\n const realms = js?.enabled && ctx.doc ? createScriptRealmFactory(js, ctx.doc) : null;\n const scriptHost =\n realms && ctx.doc\n ? realms.realmFor({\n doc: ctx.doc,\n document: () => ctx.document(),\n bootSources: async () => {\n const snapshot = await readDocumentActions();\n return (snapshot?.nameTreeScripts ?? []).map(({ action }) =>\n javaScriptProgramFromActionTree(action),\n );\n },\n })\n : null;\n if (scriptHost) ctx.cleanup(() => scriptHost.dispose());\n\n // ── surface door (D9): the ONE UI/diagnostic port for script results ────\n // Print and submitForm effects arriving from the ACTIONS plane never\n // reach this door (the js executor extracts them and routes through\n // `firePrintThroughAdapter` / `performSubmit` post-transaction — the\n // WP/DP wrap and the post-commit dataset need to run outside the host\n // transaction). Effects here come from the FORM pipeline's K/V/C/F path.\n const surfaceScriptResult = (result: ScriptSurfaceResult): void => {\n const uiContext = { origin: result.origin, phase: result.phase };\n for (const effect of result.uiEffects) {\n // A DETACHED realm has no document surface: the document it scripted\n // is not displayed, and this door's print/goto/submit act on THIS\n // document. Only alerts have a valid target (the user); everything\n // else is suppressed, observably — never routed to the wrong document.\n if (result.realm === 'detached' && effect.kind !== 'alert') {\n scriptDiagnosticHook.emit({\n code: 'ui-effect-suppressed',\n message: `script ${effect.kind} request from a detached realm suppressed: no document surface`,\n });\n continue;\n }\n if (effect.kind === 'submitForm') {\n // Form-pipeline scripted submit: same door, DETACHED (the form\n // queue must not await into submit sinks). Policy + sinks +\n // diagnostics all live inside performSubmit.\n void performSubmit(\n intentOfSubmitEffect(effect),\n {\n origin: result.origin,\n source: { kind: 'api' },\n event: { scope: 'activate' },\n },\n (diagnostic) => diagnosticHook.emit(diagnostic),\n );\n continue;\n }\n // PERMISSION, not preference: a print request without doc.print\n // authority reaches no adapter — non-overridable, observable.\n if (effect.kind === 'print' && !allowsPrint()) {\n scriptDiagnosticHook.emit({\n code: 'ui-effect-suppressed',\n message: 'script print request withheld: doc.print is not allowed',\n });\n continue;\n }\n // D3's latch: a WillPrint/DidPrint script (or anything running while\n // a print wrapper is active) printing again is suppressed — one\n // dialog per outer request.\n if (effect.kind === 'print' && docPrintEventActive) {\n scriptDiagnosticHook.emit({\n code: 'ui-effect-suppressed',\n message: 'script print request during a document print event — suppressed (reentrant)',\n });\n continue;\n }\n if (!uiAdapter) {\n diagnosticHook.emit({\n code: 'no-adapter',\n message: `script ${effect.kind}: no UI adapter installed`,\n });\n continue;\n }\n if (effect.kind === 'alert') {\n uiAdapter.alert?.(effect.message, {\n ...uiContext,\n icon: effect.icon,\n ...(effect.title !== undefined ? { title: effect.title } : {}),\n });\n } else if (effect.kind === 'gotoPage') {\n uiAdapter.gotoPage?.(effect.page, uiContext);\n } else {\n uiAdapter.print(uiContext);\n }\n }\n for (const diagnostic of result.diagnostics) scriptDiagnosticHook.emit(diagnostic);\n if (result.error) scriptErrorHook.emit(result.error);\n };\n\n /** A K/V/C/F commit surfaces as up to two results: the boot phase (only\n * when it produced effects) and the user phase (always — it carries the\n * diagnostics and the error). */\n const surfaceScriptCommit = (\n commit: ScriptCommitSurface,\n context: { origin: ActionOrigin; realm: ScriptRealmKind },\n ): void => {\n const phases: Array<'boot' | 'user'> = ['boot', 'user'];\n for (const phase of phases) {\n const uiEffects = commit.uiEffects.filter((effect) => effect.phase === phase);\n if (uiEffects.length === 0 && phase === 'boot') continue;\n surfaceScriptResult({\n uiEffects,\n diagnostics: phase === 'user' ? commit.diagnostics : [],\n ...(phase === 'user' && commit.error ? { error: commit.error } : {}),\n origin: context.origin,\n phase,\n realm: context.realm,\n });\n }\n };\n\n /** Script `doc.submitForm(...)` → the one normalized intent. Script field\n * names are include-mode by definition (Acrobat's aFields). */\n const intentOfSubmitEffect = (\n effect: Extract<ScriptUiEffect, { kind: 'submitForm' }>,\n ): SubmitIntent => {\n const format = effect.format ?? 'fdf';\n return {\n url: effect.url,\n fields: effect.fieldNames?.map((name) => ({ kind: 'name' as const, name })) ?? null,\n exclude: false,\n includeNoValueFields: effect.includeEmpty,\n format,\n method: effect.method ?? 'post',\n flagsRaw: 0,\n };\n };\n\n // ── script world building (D6: page-scoped prefetch) ────────────────────\n const engineColorToArray = (\n color: { r: number; g: number; b: number } | null | undefined,\n ): ScriptColorArray => (color ? ['RGB', color.r / 255, color.g / 255, color.b / 255] : ['T']);\n\n const pageIndexOf = (pon: PageObjectNumber): number =>\n ctx.document()?.pages.findIndex((page) => page.pageObjectNumber === pon) ?? -1;\n\n const scriptWorldFor = async (\n pon: PageObjectNumber,\n ): Promise<{ snapshot: FormSnapshot; world: Omit<ScriptWorldInput, 'event'> }> => {\n const doc = ctx.doc!;\n const snapshot = await doc.forms.list();\n const pageIndex = Math.max(0, pageIndexOf(pon));\n const { annotations } = await doc.page(pon).annotations.list();\n const annots: ScriptAnnotInput[] = annotations\n // Script-addressable = everything EXCEPT link and widget (they are\n // Link/Field objects in Acrobat and separate planes here).\n .filter((a) => a.subtype !== 'link' && !a.subtype.startsWith('widget'))\n .map((a) => {\n const styled = a as unknown as {\n color?: { r: number; g: number; b: number };\n interiorColor?: { r: number; g: number; b: number } | null;\n opacity?: number;\n strokeWidth?: number;\n borderStyle?: string;\n dashArray?: number[];\n };\n return {\n ref: a.ref,\n name: a.nm ?? '',\n subtype: a.subtype,\n page: pageIndex,\n rect: [a.rect.left, a.rect.bottom, a.rect.right, a.rect.top] as [\n number,\n number,\n number,\n number,\n ],\n contents: a.contents ?? '',\n author: a.author ?? '',\n subject: a.subject ?? '',\n strokeColor: engineColorToArray(styled.color),\n fillColor: engineColorToArray(styled.interiorColor),\n opacity: styled.opacity ?? 1,\n width: styled.strokeWidth ?? 1,\n borderStyle: styled.borderStyle === 'dashed' ? ('D' as const) : ('S' as const),\n dash: styled.dashArray ?? [],\n hidden: a.flags.hidden,\n print: a.flags.print,\n readOnly: a.flags.readOnly,\n locked: a.flags.locked,\n noView: a.flags.noView,\n toggleNoView: a.flags.toggleNoView,\n opaqueBody: a.subtype === 'stamp',\n };\n });\n return {\n snapshot,\n world: {\n fields: scriptFieldsFromSnapshot(snapshot),\n annots,\n annotPages: [pageIndex],\n annotsCoverDocument: (ctx.document()?.pageCount ?? 0) <= 1,\n },\n };\n };\n\n const ANNOTATION_EVENT_NAMES: Record<string, string> = {\n cursorEnter: 'Mouse Enter',\n cursorExit: 'Mouse Exit',\n mouseDown: 'Mouse Down',\n mouseUp: 'Mouse Up',\n focus: 'Focus',\n blur: 'Blur',\n };\n const PAGE_EVENT_NAMES: Record<string, string> = {\n open: 'Open',\n close: 'Close',\n // No Acrobat equivalent for the PV/PI names — EmbedPDF extension.\n visible: 'Visible',\n invisible: 'Invisible',\n };\n // The two-standard bridge (D5): the /AA keys are ISO 32000-2 Table 200;\n // the camelCase event names live in the JS API layer (ISO 21757-1 /\n // Acrobat) — only the key half is verifiable against the in-repo spec.\n const DOC_EVENT_NAMES: Record<string, string> = {\n open: 'Open',\n 'will-save': 'WillSave',\n 'did-save': 'DidSave',\n 'will-print': 'WillPrint',\n 'did-print': 'DidPrint',\n 'will-close': 'WillClose',\n };\n\n const scriptEventFor = (actionCtx: ActionContext, snapshot: FormSnapshot): ScriptEventInput => {\n const provenance = actionCtx.event;\n const type =\n provenance.scope === 'page'\n ? 'Page'\n : provenance.scope === 'document'\n ? 'Doc'\n : actionCtx.source.kind === 'widget'\n ? 'Field'\n : actionCtx.source.kind === 'link'\n ? 'Link'\n : 'Annot'; // EmbedPDF extension — Acrobat has no plain-annot type\n const name =\n provenance.scope === 'activate'\n ? 'Mouse Up'\n : provenance.scope === 'annotation'\n ? (ANNOTATION_EVENT_NAMES[provenance.name] ?? 'Mouse Up')\n : provenance.scope === 'page'\n ? (PAGE_EVENT_NAMES[provenance.name] ?? 'Open')\n : (DOC_EVENT_NAMES[provenance.name] ?? 'Open');\n const targetRef = actionCtx.source.kind === 'widget' ? actionCtx.source.field : undefined;\n const targetField = targetRef\n ? snapshot.fields.find((field) =>\n targetRef.kind === 'objectNumber' && field.ref.kind === 'objectNumber'\n ? field.ref.fieldObjectNumber === targetRef.fieldObjectNumber\n : targetRef.kind === 'fqn' && field.name === targetRef.name,\n )\n : undefined;\n return {\n kind: 'widget-activate',\n type,\n name,\n ...(targetRef ? { target: targetRef, source: targetRef } : {}),\n ...(targetField && targetField.valueEntry.kind === 'scalar'\n ? { value: targetField.valueEntry.value }\n : {}),\n };\n };\n\n /** Commit one run's document effects through the owner sinks in the\n * DECLARED order (form first, then annot); the first failure skips the\n * rest across BOTH streams. Returns the failure summary, if any. */\n const commitScriptOutput = async (\n output: ScriptOutput,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<string | null> => {\n let failure: string | null = null;\n if (output.formEffects.length > 0) {\n if (!formCommitSink) {\n diagnose({\n code: 'no-commit-sink',\n message: `script form effects dropped: no form commit sink registered (${output.formEffects.length})`,\n });\n } else {\n const result = await formCommitSink(output.formEffects);\n const bad = result.results.find(\n (entry) => entry.status === 'failed' || entry.status === 'rejected',\n );\n if (bad) failure = `form effect ${bad.index}: ${bad.error?.message ?? bad.status}`;\n }\n }\n if (output.annotEffects.length > 0) {\n if (failure) {\n diagnose({\n code: 'executor-failed',\n message: `script annot effects skipped after form failure (${output.annotEffects.length})`,\n });\n } else if (!annotCommitSink) {\n diagnose({\n code: 'no-commit-sink',\n message: `script annot effects dropped: no annotation commit sink registered (${output.annotEffects.length})`,\n });\n } else {\n const entries: AnnotCommitEntry[] = output.annotEffects.map((effect) => ({\n annotObjectNumber: effect.ref.kind === 'objectNumber' ? effect.ref.annotObjectNumber : -1,\n ...(effect.ref.kind === 'objectNumber'\n ? { pageObjectNumber: effect.ref.pageObjectNumber }\n : {}),\n patch: effect.patch,\n }));\n const result = await annotCommitSink(entries);\n const bad = result.results.find((entry) => entry.status === 'failed');\n if (bad) failure = `annotation ${bad.annotObjectNumber}: ${bad.error ?? 'failed'}`;\n }\n }\n if (failure) diagnose({ code: 'executor-failed', message: `script commit: ${failure}` });\n return failure;\n };\n\n // ── the REAL `javascript` executor: one node = one host transaction with\n // prefetch → boot? → run → commit → surface INSIDE the boundary ───────\n if (scriptHost) {\n const nodeCap = js?.maxScriptNodesPerDispatch ?? 16;\n executors.set('javascript', async (node, actionCtx) => {\n if (node.type !== 'javascript') return { status: 'inert', reason: 'not a JS node' };\n const doc = ctx.doc;\n if (!doc) return { status: 'inert', reason: 'no document' };\n if (jsNodesThisDispatch >= nodeCap) {\n return {\n status: 'inert',\n reason: `dispatch script budget exhausted (${nodeCap} JS nodes)`,\n };\n }\n jsNodesThisDispatch += 1;\n const source = actionCtx.source;\n const pon =\n source.kind === 'widget'\n ? source.pon\n : source.kind === 'link' || source.kind === 'annotation'\n ? (source.pon ?? ctx.document()?.pages[0]?.pageObjectNumber)\n : source.kind === 'page'\n ? source.pon\n : ctx.document()?.pages[0]?.pageObjectNumber;\n if (pon === undefined) return { status: 'inert', reason: 'no page to anchor the world on' };\n const diagnose = (diagnostic: ActionDiagnostic): void => diagnosticHook.emit(diagnostic);\n // Print/submit effects are EXTERNAL: the WP/DP wrap runs action trees\n // (which may need their own host transactions) and the submit dataset\n // must be resolved from POST-COMMIT truth — both must run after the\n // transaction releases, still inside this queued dispatch op.\n const pendingExternal: Array<{\n effect: Extract<ScriptUiEffect, { kind: 'print' | 'submitForm' }>;\n phase: 'boot' | 'user';\n }> = [];\n const splitExternal = (output: ScriptOutput, phase: 'boot' | 'user'): ScriptUiEffect[] =>\n output.uiEffects.filter((effect) => {\n if (effect.kind === 'print' || effect.kind === 'submitForm') {\n pendingExternal.push({ effect, phase });\n return false;\n }\n return true;\n });\n const outcome = await scriptHost.transaction<\n { status: 'executed' } | { status: 'failed'; error: string }\n >(async (txn) => {\n let built = await scriptWorldFor(pon);\n const boot = await txn.boot({\n ...built.world,\n event: { kind: 'name-tree-boot', type: 'Doc', name: 'Open' },\n });\n if (boot) {\n // Boot effects belong to this first transaction; a boot fault only\n // degrades (never bricks). Refetch the world afterwards so the run\n // sees post-boot truth.\n await commitScriptOutput(boot, diagnose);\n surfaceScriptResult({\n uiEffects: splitExternal(boot, 'boot'),\n diagnostics: boot.diagnostics,\n ...(boot.error ? { error: boot.error } : {}),\n origin: actionCtx.origin,\n phase: 'boot',\n realm: 'document',\n });\n if (boot.formEffects.length || boot.annotEffects.length) {\n built = await scriptWorldFor(pon);\n }\n }\n const output = await txn.run(node.script, {\n ...built.world,\n event: scriptEventFor(actionCtx, built.snapshot),\n });\n surfaceScriptResult({\n uiEffects: splitExternal(output, 'user'),\n diagnostics: output.diagnostics,\n ...(output.error ? { error: output.error } : {}),\n origin: actionCtx.origin,\n phase: 'user',\n realm: 'document',\n });\n if (output.error) return { status: 'failed', error: output.error.message };\n const failure = await commitScriptOutput(output, diagnose);\n return failure ? { status: 'failed', error: failure } : { status: 'executed' };\n });\n for (const entry of pendingExternal) {\n if (entry.effect.kind === 'print') {\n await firePrintThroughAdapter({ origin: actionCtx.origin, phase: entry.phase }, diagnose);\n } else {\n await performSubmit(intentOfSubmitEffect(entry.effect), actionCtx, diagnose);\n }\n }\n return outcome;\n });\n }\n\n async function run(tree: PdfActionTree, actionCtx: ActionContext): Promise<ActionDispatchResult> {\n const diagnostics: ActionDiagnostic[] = [];\n const diagnose = (diagnostic: ActionDiagnostic): void => {\n diagnostics.push(diagnostic);\n diagnosticHook.emit(diagnostic);\n };\n\n // The law: never execute an incomplete tree — not even its root.\n if (tree.incomplete) {\n diagnose({ code: 'incomplete-tree', message: 'refused: the action tree is incomplete' });\n return { status: 'refused', nodes: [], diagnostics };\n }\n if (!tree.root) return { status: 'inert', nodes: [], diagnostics };\n\n const nodes: ActionNodeResult[] = [];\n // Navigation and external effects are DEFERRED thunks — fired only after\n // every document-lifetime node succeeded, in node order, so navigation\n // can never yank the user away from a failed write.\n const deferred: Array<{ result: ActionNodeResult; fire: () => Promise<void> | void }> = [];\n let documentFailed = false;\n\n const settle = (\n result: ActionNodeResult,\n outcome: import('./types').ActionExecutorResult,\n ): void => {\n if (outcome.status === 'executed') result.status = 'executed';\n else if (outcome.status === 'inert') {\n result.status = 'inert';\n result.detail = outcome.reason;\n diagnose({ code: 'executor-inert', message: `${result.type}: ${outcome.reason}` });\n } else {\n result.status = 'failed';\n result.detail = outcome.error;\n diagnose({ code: 'executor-failed', message: `${result.type}: ${outcome.error}` });\n }\n };\n\n // Full ISO (D7): a Hide action SETS/CLEARS the document Hidden state\n // (12.6.4.11) — a real mutation through the OWNING plane's commit sink,\n // authority-gated by the engine like every other write. Widgets are the\n // FORMS plane's visibility (the engine's field-level `setDisplay` —\n // Acrobat's `field.display`; there is no per-widget annotation patch);\n // plain annotations are flag patches through the annotation sink.\n const interpretHide = async (\n node: Extract<PdfActionNode, { type: 'hide' }>,\n ): Promise<{ status: ActionNodeStatus; detail?: string }> => {\n const doc = ctx.doc;\n const display = node.hide ? ('hidden' as const) : ('visible' as const);\n const fieldRefs: Array<{ kind: 'objectNumber'; fieldObjectNumber: number }> = [];\n const annotEntries: AnnotCommitEntry[] = [];\n const names: string[] = [];\n const bareObjectNumbers: number[] = [];\n for (const target of node.targets) {\n if (target.kind === 'objectNumber') bareObjectNumbers.push(target.objectNumber);\n else names.push(target.name);\n }\n if ((names.length || bareObjectNumbers.length) && doc) {\n const snapshot = names.length || bareObjectNumbers.length ? await doc.forms.list() : null;\n for (const name of names) {\n const field = snapshot?.fields.find((candidate) => candidate.name === name);\n if (!field) {\n diagnose({ code: 'unresolved-target', message: `hide: no field named '${name}'` });\n continue;\n }\n fieldRefs.push({ kind: 'objectNumber', fieldObjectNumber: field.fieldObjectNumber });\n }\n for (const objectNumber of bareObjectNumbers) {\n // A bare object number may be a WIDGET (its field's display) or a\n // plain annotation (its own flags) — the forms snapshot decides.\n const owner = snapshot?.fields.find((field) =>\n field.widgets.some((widget) => widget.annotObjectNumber === objectNumber),\n );\n if (owner) {\n fieldRefs.push({ kind: 'objectNumber', fieldObjectNumber: owner.fieldObjectNumber });\n } else {\n annotEntries.push({\n annotObjectNumber: objectNumber,\n patch: { flags: { hidden: node.hide } },\n });\n }\n }\n }\n let failedDetail: string | undefined;\n if (fieldRefs.length) {\n if (!formCommitSink) {\n diagnose({\n code: 'no-commit-sink',\n message: 'hide: no form commit sink registered (form plugin absent)',\n });\n return { status: 'no-executor' };\n }\n const result = await formCommitSink(\n fieldRefs.map((ref) => ({ kind: 'setDisplay', ref, display })),\n );\n const bad = result.results.find(\n (entry) => entry.status === 'failed' || entry.status === 'rejected',\n );\n if (bad) {\n failedDetail = bad.error?.message ?? bad.status;\n diagnose({ code: 'executor-failed', message: `hide: ${failedDetail}` });\n }\n }\n if (annotEntries.length && !failedDetail) {\n if (!annotCommitSink) {\n diagnose({\n code: 'no-commit-sink',\n message: 'hide: no annotation commit sink registered (annotation plugin absent)',\n });\n return { status: 'no-executor' };\n }\n const committed = await annotCommitSink(annotEntries);\n const failed = committed.results.filter((entry) => entry.status === 'failed');\n for (const failure of failed) {\n diagnose({\n code: 'executor-failed',\n message: `hide: annotation ${failure.annotObjectNumber}: ${failure.error ?? 'failed'}`,\n });\n }\n if (failed.length === committed.results.length && failed.length > 0) {\n failedDetail = failed[0]?.error;\n }\n }\n if (failedDetail) return { status: 'failed', detail: failedDetail };\n return { status: 'executed' };\n };\n\n const interpret = async (node: PdfActionNode, path: number[]): Promise<void> => {\n const result: ActionNodeResult = { path, type: node.type, status: 'blocked' };\n nodes.push(result);\n const decision = decisionFor(node, actionCtx.origin);\n\n if (decision === 'never' || decision === 'block' || decision === 'report') {\n result.status = 'blocked';\n diagnose({\n code: 'blocked',\n message: `${node.type}: ${decision === 'never' ? 'never executable' : `policy '${decision}' for origin '${actionCtx.origin}'`}`,\n });\n return;\n }\n if (decision === 'unsupported') {\n result.status = 'no-executor';\n return;\n }\n\n if (node.type === 'hide') {\n // A document mutation now: an earlier document failure skips it, and\n // its failure stops later document work (the §3.9 ordering law).\n if (documentFailed) {\n result.status = 'skipped';\n return;\n }\n const outcome = await interpretHide(node);\n result.status = outcome.status;\n if (outcome.detail) result.detail = outcome.detail;\n if (outcome.status === 'failed') documentFailed = true;\n return;\n }\n\n if (DOCUMENT_TYPES.has(node.type)) {\n if (documentFailed) {\n result.status = 'skipped';\n return;\n }\n const executor = executors.get(node.type);\n if (!executor) {\n result.status = node.type === 'javascript' ? 'inert' : 'no-executor';\n diagnose({\n code: 'no-executor',\n message: `${node.type}: no executor registered${node.type === 'javascript' ? ' (scripting unavailable)' : ''}`,\n });\n return;\n }\n try {\n settle(result, await executor(node, actionCtx));\n } catch (error) {\n settle(result, {\n status: 'failed',\n error: error instanceof Error ? error.message : String(error),\n });\n }\n if (result.status === 'failed') documentFailed = true;\n return;\n }\n\n if (node.type === 'submit-form') {\n if (!node.payload) {\n // Older-runtime extraction (pin lag): exactly the pre-payload\n // behavior — recognized-inert, honestly diagnosed.\n result.status = 'inert';\n result.detail = 'submit payload unavailable (older runtime extraction)';\n diagnose({\n code: 'submit-payload-unavailable',\n message: 'submit-form: payload unavailable (older runtime extraction) — node inert',\n });\n return;\n }\n const payload = node.payload;\n // External like print/uri: deferred until every document-lifetime\n // node succeeded — a submission must never carry a half-failed\n // form state.\n result.status = 'skipped'; // provisional until fired\n deferred.push({\n result,\n fire: async () => {\n const outcome = await performSubmit(intentOfPayload(payload), actionCtx, diagnose);\n result.status = outcome.status;\n if (outcome.detail) result.detail = outcome.detail;\n },\n });\n return;\n }\n\n if (isPrintVerb(node) || node.type === 'uri') {\n // External: adapter-routed, deferred.\n result.status = 'skipped'; // provisional until fired\n deferred.push({\n result,\n fire: async () => {\n if (node.type === 'uri') {\n if (!uiAdapter) {\n result.status = 'no-executor';\n diagnose({ code: 'no-adapter', message: `${node.type}: no UI adapter installed` });\n return;\n }\n uiAdapter.openUri(node.uri, { isMap: node.isMap, origin: actionCtx.origin });\n result.status = 'executed';\n return;\n }\n // The Print verb: WP → adapter (exactly once) → DP, one latch\n // (D3). Authority/adapter/reentrancy verdicts come back as the\n // node's status.\n const outcome = await firePrintThroughAdapter(undefined, diagnose);\n result.status = outcome.status;\n if (outcome.detail) result.detail = outcome.detail;\n },\n });\n return;\n }\n\n // goto + named page verbs: navigation, executor-routed, deferred.\n result.status = 'skipped'; // provisional until fired\n deferred.push({\n result,\n fire: async () => {\n const executor = executors.get(node.type);\n if (!executor) {\n result.status = 'no-executor';\n diagnose({ code: 'no-executor', message: `${node.type}: no executor registered` });\n return;\n }\n try {\n settle(result, await executor(node, actionCtx));\n } catch (error) {\n settle(result, {\n status: 'failed',\n error: error instanceof Error ? error.message : String(error),\n });\n }\n },\n });\n };\n\n const walk = async (node: PdfActionNode, path: number[]): Promise<void> => {\n await interpret(node, path);\n for (let index = 0; index < node.next.length; index++) {\n await walk(node.next[index], [...path, index]);\n }\n };\n await walk(tree.root, []);\n\n if (!documentFailed) {\n for (const entry of deferred) await entry.fire();\n }\n\n const anyExecuted = nodes.some((node) => node.status === 'executed');\n const anyFailedOrSkipped = nodes.some(\n (node) => node.status === 'failed' || node.status === 'skipped',\n );\n const status: ActionDispatchResult['status'] = anyExecuted\n ? anyFailedOrSkipped\n ? 'partial'\n : 'executed'\n : anyFailedOrSkipped\n ? 'partial'\n : 'inert';\n return { status, nodes, diagnostics };\n }\n\n /** run + seq + event — the shared per-tree unit (queued by execute; called\n * inline per step by the queued trigger resolver). */\n const runAndEmit = async (\n tree: PdfActionTree,\n actionCtx: ActionContext,\n ): Promise<ActionDispatchResult> => {\n const result = await run(tree, actionCtx);\n ctx.dispatch({ type: 'ACTIONS_DISPATCHED' });\n actionHook.emit({ ctx: actionCtx, tree, result });\n return result;\n };\n\n const execute = (\n tree: PdfActionTree,\n actionCtx: ActionContext,\n ): Promise<ActionDispatchResult> => {\n // BEFORE enqueueing: a real user gesture arms the open-sequence latch\n // (its barrier op then lands ahead of this action in the queue) and\n // resets the cascade budget.\n if (actionCtx.origin === 'user') noteUserActivity();\n return enqueue(() => {\n jsNodesThisDispatch = 0; // D11: one aggregate per dispatch\n return runAndEmit(tree, actionCtx);\n });\n };\n\n const canExecute = (tree: PdfActionTree, actionCtx: ActionContext): boolean => {\n if (tree.incomplete || !tree.root) return false;\n const decision = decisionFor(tree.root, actionCtx.origin);\n return decision === 'allow' || decision === 'adapter';\n };\n\n // ── trigger machinery ─────────────────────────────────────────────────\n\n const triggerEnabled = (trigger: ActionTrigger): boolean => {\n switch (trigger.scope) {\n case 'activate':\n return true; // the Phase-1 core door — never gated\n case 'annotation':\n return config.triggers?.annotation !== false;\n case 'page':\n return config.triggers?.page !== false;\n case 'document':\n return config.triggers?.document !== false;\n }\n };\n\n /**\n * Per-pon cache of annotations bearing page-lifecycle trees (PO/PC/PV/PI)\n * — the fan-out's read amplifier. Invalidated wholesale on any\n * `annotation.*` document event and on `stream.desynced` (gap events never\n * arrive, so every cached page may be stale); rebuilt lazily per pon.\n */\n type LifecycleAnnot = { ref: AnnotationRef; actions: PdfAnnotationActions };\n const lifecycleCache = new Map<PageObjectNumber, LifecycleAnnot[]>();\n const lifecycleTreesFor = async (pon: PageObjectNumber): Promise<LifecycleAnnot[]> => {\n const hit = lifecycleCache.get(pon);\n if (hit) return hit;\n const doc = ctx.doc;\n if (!doc) return [];\n const { annotations } = await doc.page(pon).annotations.list();\n const bearing = annotations\n .filter(\n (a) =>\n a.actions &&\n (a.actions.pageOpen?.root ||\n a.actions.pageClose?.root ||\n a.actions.pageVisible?.root ||\n a.actions.pageInvisible?.root),\n )\n .map((a) => ({ ref: a.ref, actions: a.actions! }));\n lifecycleCache.set(pon, bearing);\n return bearing;\n };\n {\n // Optional-chained end to end: unit harnesses fake `ctx.doc` without an\n // event stream; a real DocumentHandle always carries one.\n const unsubscribe = ctx.doc?.events?.subscribe((event) => {\n if (event.type.startsWith('annotation.') || event.type === 'stream.desynced') {\n lifecycleCache.clear();\n }\n });\n if (unsubscribe) ctx.cleanup(unsubscribe);\n }\n\n /**\n * ISO order, verified against 32000-2 Table 197 (2026-09-02): PO \"shall be\n * executed after the O action … and the OpenAction entry\"; PC \"shall be\n * executed before the C action\". Rootless trees are skipped (a\n * budget-degraded tree with no root has nothing to walk).\n */\n const planPageSteps = (\n event: 'open' | 'close' | 'visible' | 'invisible',\n pon: PageObjectNumber,\n pageActions: PdfPageActions | undefined,\n lifecycle: LifecycleAnnot[],\n ): Array<{ source: ActionSource; tree: PdfActionTree }> => {\n const pageSource: ActionSource = { kind: 'page', pon };\n const annotSteps = (key: 'pageOpen' | 'pageClose' | 'pageVisible' | 'pageInvisible') =>\n lifecycle\n .filter((a) => a.actions[key]?.root)\n .map((a) => ({\n source: { kind: 'annotation', annotation: a.ref, pon } as ActionSource,\n tree: a.actions[key]!,\n }));\n switch (event) {\n case 'open':\n return [\n ...(pageActions?.open?.root ? [{ source: pageSource, tree: pageActions.open }] : []),\n ...annotSteps('pageOpen'),\n ];\n case 'close':\n return [\n ...annotSteps('pageClose'),\n ...(pageActions?.close?.root ? [{ source: pageSource, tree: pageActions.close }] : []),\n ];\n case 'visible':\n return annotSteps('pageVisible');\n case 'invisible':\n return annotSteps('pageInvisible');\n }\n };\n\n /** Aggregate step statuses. A step failure never skips its siblings; this\n * only FOLDS what each step reported. */\n const foldSteps = (\n steps: ActionStepResult[],\n diagnostics: ActionDiagnostic[],\n ): ActionTriggerResult => {\n const statuses = steps.map((s) => s.result.status);\n const status: ActionTriggerResult['status'] =\n steps.length === 0\n ? 'inert'\n : statuses.every((s) => s === 'refused')\n ? 'refused'\n : statuses.every((s) => s === 'inert')\n ? 'inert'\n : statuses.every((s) => s === 'executed')\n ? 'executed'\n : 'partial';\n return { status, steps, diagnostics };\n };\n\n const runSteps = async (\n steps: Array<{ source: ActionSource; tree: PdfActionTree }>,\n origin: ActionOrigin,\n event: import('./types').ActionTriggerEvent,\n diagnostics: ActionDiagnostic[],\n ): Promise<ActionTriggerResult> => {\n const results: ActionStepResult[] = [];\n for (const step of steps) {\n const result = await runAndEmit(step.tree, { origin, source: step.source, event });\n results.push({ source: step.source, tree: step.tree, result });\n }\n return foldSteps(results, diagnostics);\n };\n\n /** Everything a trigger needs — reads included — INSIDE the queued op:\n * submission order is execution order. Never throws. */\n const resolveAndRun = async (trigger: ActionTrigger): Promise<ActionTriggerResult> => {\n const diagnostics: ActionDiagnostic[] = [];\n const diagnose = (diagnostic: ActionDiagnostic): void => {\n diagnostics.push(diagnostic);\n diagnosticHook.emit(diagnostic);\n };\n try {\n const doc = ctx.doc;\n if (!doc) return { status: 'inert', steps: [], diagnostics };\n if (!triggerEnabled(trigger)) {\n diagnose({\n code: 'trigger-disabled',\n message: `${trigger.scope}: trigger family disabled by config`,\n });\n return { status: 'inert', steps: [], diagnostics };\n }\n const origin = originOf(trigger);\n switch (trigger.scope) {\n case 'activate':\n case 'annotation': {\n const event = trigger.scope === 'activate' ? 'activate' : trigger.event;\n const { annotations } = await doc.page(trigger.pon).annotations.list();\n const annotation = annotations.find((candidate) => sameRef(candidate.ref, trigger.ref));\n // ISO Table 197 (verified 2026-09-02): \"the A entry, if present,\n // takes precedence over [the /AA U entry]\" — a shadowed U tree is\n // silently inert, exactly like an absent one.\n if (event === 'mouseUp' && annotation?.actions?.activate) {\n return { status: 'inert', steps: [], diagnostics };\n }\n const tree = annotation?.actions?.[event];\n if (!tree?.root && !tree?.incomplete) return { status: 'inert', steps: [], diagnostics };\n const source: ActionSource = trigger.source ?? {\n kind: 'annotation',\n annotation: trigger.ref,\n pon: trigger.pon,\n };\n return await runSteps([{ source, tree }], origin, eventOf(trigger), diagnostics);\n }\n case 'page': {\n const layout = ctx\n .document()\n ?.pages.find((page) => page.pageObjectNumber === trigger.pon);\n const lifecycle = await lifecycleTreesFor(trigger.pon);\n const steps = planPageSteps(trigger.event, trigger.pon, layout?.actions, lifecycle);\n return await runSteps(steps, origin, eventOf(trigger), diagnostics);\n }\n case 'document': {\n if (trigger.event !== 'open') {\n return await runDocumentEventOp(trigger.event, diagnostics, diagnose);\n }\n if (openFired) {\n diagnose({\n code: 'open-sequence-replayed',\n message: 'document open sequence already fired for this document',\n });\n return { status: 'inert', steps: [], diagnostics };\n }\n openFired = true;\n return await runOpenSequenceOp();\n }\n }\n } catch (error) {\n diagnose({\n code: 'trigger-failed',\n message: `trigger resolution failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n return { status: 'refused', steps: [], diagnostics };\n }\n };\n\n const dispatch = (trigger: ActionTrigger): Promise<ActionTriggerResult> => {\n // A user-origin trigger is user activity (latch + cascade reset) — noted\n // BEFORE taking the queue slot, so an armed open sequence runs first.\n if (originOf(trigger) === 'user') noteUserActivity();\n return enqueue(() => {\n jsNodesThisDispatch = 0; // D11: one aggregate per dispatch\n return resolveAndRun(trigger);\n });\n };\n\n // ── the lifecycle coordinator (document-open barrier + cascade budget) ──\n // Stage owns page truth (reports through reportPageState); this owns WHEN\n // page-lifecycle triggers fire: nothing emits before the §3.9 open\n // sequence has run (or been declared off/headless), and emission is a diff\n // against the last-emitted state — pre-open motion collapses to one open,\n // with no phantom close.\n const CASCADE_CAP = 8;\n let barrierOpen = false;\n let bufferedReport: PageStateReport | null = null;\n let lastEmitted: { currentPon: PageObjectNumber | null; visible: Set<PageObjectNumber> } = {\n currentPon: null,\n visible: new Set(),\n };\n let cascadeRounds = 0;\n let openFired = false;\n let sawUserActivity = false;\n\n const emitForReport = (report: PageStateReport): void => {\n if (report.cause === 'user') cascadeRounds = 0;\n const nextVisible = new Set(report.visiblePons);\n const changedCurrent = report.currentPon !== lastEmitted.currentPon;\n const leaving = [...lastEmitted.visible].filter((pon) => !nextVisible.has(pon));\n const entering = [...nextVisible].filter((pon) => !lastEmitted.visible.has(pon));\n if (!changedCurrent && leaving.length === 0 && entering.length === 0) return;\n const previousCurrent = lastEmitted.currentPon;\n // Track truth even when suppressed — the budget bounds EMISSION, not state.\n lastEmitted = { currentPon: report.currentPon, visible: nextVisible };\n if (report.cause === 'programmatic') {\n cascadeRounds += 1;\n if (cascadeRounds > CASCADE_CAP) {\n diagnosticHook.emit({\n code: 'cascade-budget',\n message: `page-lifecycle emission suppressed: ${cascadeRounds} consecutive programmatic rounds (cap ${CASCADE_CAP})`,\n });\n return;\n }\n }\n // Canonical order (cross-page order is unspecified by ISO; within a page\n // planPageSteps holds Table 197's PO-after-O / PC-before-C):\n // close(old) → invisible set → visible set → open(new).\n if (changedCurrent && previousCurrent !== null) {\n void dispatch({ scope: 'page', event: 'close', pon: previousCurrent });\n }\n for (const pon of leaving) void dispatch({ scope: 'page', event: 'invisible', pon });\n for (const pon of entering) void dispatch({ scope: 'page', event: 'visible', pon });\n if (changedCurrent && report.currentPon !== null) {\n void dispatch({ scope: 'page', event: 'open', pon: report.currentPon });\n }\n };\n\n const reportPageState = (report: PageStateReport): void => {\n if (!report.placed) return;\n if (report.cause === 'user') cascadeRounds = 0;\n if (!barrierOpen) {\n bufferedReport = report; // coalesce: only the LATEST pre-open state matters\n return;\n }\n emitForReport(report);\n };\n\n const releaseBarrier = (fireFallback: boolean): void => {\n barrierOpen = true;\n const report = bufferedReport;\n bufferedReport = null;\n try {\n if (report) {\n emitForReport(report);\n } else if (fireFallback && config.openSequence === 'headless') {\n // §3.9's initial page open falls back to the document's first page\n // ONLY in declared-headless mode (no stage will ever report). In\n // 'auto', the stage report owns the initial open — firing a\n // first-page /O before a restored view reports would be exactly the\n // phantom open the coordinator exists to prevent; a stage-less\n // 'auto' embedder drives page triggers itself or declares headless.\n const first = ctx.document()?.pages[0]?.pageObjectNumber;\n if (first !== undefined) {\n lastEmitted = { currentPon: first, visible: lastEmitted.visible };\n void dispatch({ scope: 'page', event: 'open', pon: first });\n }\n }\n } catch (error) {\n // The barrier is OPEN either way — feeds must never stay buffered.\n diagnosticHook.emit({\n code: 'trigger-failed',\n message: `barrier release failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n };\n\n /** The §3.9 sequence body — runs INSIDE the queue (via dispatch or the\n * latch's own enqueue; callers guarantee openFired was set). */\n const runOpenSequenceOp = async (): Promise<ActionTriggerResult> => {\n const diagnostics: ActionDiagnostic[] = [];\n const steps: ActionStepResult[] = [];\n const lifecycleCtx: ActionContext = {\n origin: 'lifecycle',\n source: { kind: 'document' },\n event: { scope: 'document', name: 'open' },\n };\n try {\n const snapshot = await readDocumentActions();\n if (snapshot?.openDestination) {\n // The initial view reuses the whole spine (stage's goto executor,\n // policy included) as a synthesized lifecycle goto.\n const tree: PdfActionTree = {\n root: {\n type: 'goto',\n subtype: 'GoTo',\n destination: snapshot.openDestination,\n next: [],\n },\n incomplete: false,\n warningFlags: 0,\n warnings: [],\n };\n steps.push({\n source: { kind: 'document' },\n tree,\n result: await runAndEmit(tree, lifecycleCtx),\n });\n }\n if (snapshot?.openAction?.root || snapshot?.openAction?.incomplete) {\n steps.push({\n source: { kind: 'document' },\n tree: snapshot.openAction,\n result: await runAndEmit(snapshot.openAction, lifecycleCtx),\n });\n }\n } catch (error) {\n const diagnostic: ActionDiagnostic = {\n code: 'trigger-failed',\n message: `open sequence failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n diagnostics.push(diagnostic);\n diagnosticHook.emit(diagnostic);\n } finally {\n // Release AFTER the document steps, on EVERY path; page-open emission\n // enqueues BEHIND this op (never awaited here — awaiting our own\n // queue self-deadlocks).\n releaseBarrier(true);\n }\n return foldSteps(steps, diagnostics);\n };\n\n // ── document lifecycle events (Phase 4: WC/WS/DS/WP/DP) ─────────────────\n\n /**\n * D1's open-ordering law: catalog `OpenAction` may never run AFTER a\n * WillSave/WillPrint/WillClose script. Before the first verb-shaped\n * document event, an armed-but-unfired open sequence runs inline (we are\n * already inside the queue; `runOpenSequenceOp` never enqueues). It does\n * NOT wait for the initial page `/O` — the guarantee is catalog-level.\n */\n const ensureOpenSequenceBeforeDocEvent = async (): Promise<void> => {\n if (openFired || config.openSequence === 'off') return;\n openFired = true;\n await runOpenSequenceOp();\n };\n\n /**\n * Run ONE catalog lifecycle tree inside the current queue operation —\n * shared by the dispatch path, `runDocumentVerb`, and the print wrapper.\n * Never throws: a read/resolution failure degrades to a diagnostic (a\n * broken script must not cancel the user's save/print — D2).\n */\n const runDocEventTreeSafe = async (\n event: Exclude<DocumentTriggerEvent, 'open'>,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<ActionStepResult | null> => {\n if (config.triggers?.document === false) return null;\n try {\n await ensureOpenSequenceBeforeDocEvent();\n const snapshot = await readDocumentActions();\n const tree = snapshot?.[DOC_EVENT_TREES[event]];\n if (!tree?.root && !tree?.incomplete) return null;\n const actionCtx: ActionContext = {\n origin: 'lifecycle',\n source: { kind: 'document' },\n event: { scope: 'document', name: event },\n };\n return { source: { kind: 'document' }, tree, result: await runAndEmit(tree, actionCtx) };\n } catch (error) {\n diagnose({\n code: 'trigger-failed',\n message: `${event}: ${error instanceof Error ? error.message : String(error)}`,\n });\n return null;\n }\n };\n\n /** The dispatch-path body for a verb-shaped document event. */\n const runDocumentEventOp = async (\n event: Exclude<DocumentTriggerEvent, 'open'>,\n diagnostics: ActionDiagnostic[],\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<ActionTriggerResult> => {\n const step = await runDocEventTreeSafe(event, diagnose);\n return foldSteps(step ? [step] : [], diagnostics);\n };\n\n /**\n * D3: BOTH adapter print invocations (the Named Print verb; script\n * `doc.print()` effects from the actions plane) go through here — WP →\n * `uiAdapter.print` exactly once → DP, latch reset in `finally`. While\n * the latch is held (including `runDocumentVerb('print')`'s body) a\n * nested request is suppressed with `reentrant-print`. An adapter throw\n * skips DP (the latch still resets) — named deviation: DP otherwise\n * fires when the adapter call RETURNS, since a browser cannot observe\n * dialog completion.\n */\n const firePrintThroughAdapter = async (\n uiContext: { origin: ActionOrigin; phase: 'boot' | 'user' } | undefined,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<{ status: ActionNodeStatus; detail?: string }> => {\n if (docPrintEventActive) {\n diagnose({\n code: 'reentrant-print',\n message:\n 'print request during a document print event — suppressed (one dialog per request)',\n });\n return { status: 'blocked', detail: 'reentrant print suppressed' };\n }\n if (!allowsPrint()) {\n diagnose({ code: 'blocked', message: 'print: doc.print is not allowed' });\n return { status: 'blocked', detail: 'doc.print is not allowed' };\n }\n if (!uiAdapter) {\n diagnose({ code: 'no-adapter', message: 'print: no UI adapter installed' });\n return { status: 'no-executor', detail: 'no UI adapter installed' };\n }\n docPrintEventActive = true;\n try {\n await runDocEventTreeSafe('will-print', diagnose);\n const adapter = uiAdapter;\n if (!adapter) return { status: 'no-executor', detail: 'UI adapter uninstalled mid-print' };\n if (uiContext) adapter.print(uiContext);\n else adapter.print();\n await runDocEventTreeSafe('did-print', diagnose);\n return { status: 'executed' };\n } finally {\n docPrintEventActive = false;\n }\n };\n\n const maybeFireOpenSequence = (): void => {\n if (openFired) return;\n if (config.openSequence === 'off') {\n // The sequence never runs, but feeds must not buffer forever.\n openFired = true;\n releaseBarrier(false);\n return;\n }\n if (!uiAdapter && config.openSequence !== 'headless' && !sawUserActivity) return;\n openFired = true;\n void enqueue(() => runOpenSequenceOp());\n };\n\n const noteUserActivity = (): void => {\n cascadeRounds = 0;\n if (!sawUserActivity) {\n sawUserActivity = true;\n maybeFireOpenSequence();\n }\n };\n\n // Arm the latch at bringup: fires immediately for 'headless', releases the\n // barrier for 'off', waits for an adapter or user activity for 'auto'.\n maybeFireOpenSequence();\n\n return {\n execute,\n canExecute,\n dispatch,\n // Sync twin: family enabled ∧ document present (per-tree truth stays\n // per-step in results — resolution is async and never previewed here).\n canDispatch: (trigger) => triggerEnabled(trigger) && ctx.doc !== null,\n setUiAdapter: (adapter): Unsubscribe => {\n uiAdapter = adapter;\n // An adapter arriving is the §3.9 latch's usual release.\n if (adapter) maybeFireOpenSequence();\n return () => {\n // Identity-safe: never wipe a successor installed after us.\n if (uiAdapter === adapter) uiAdapter = null;\n };\n },\n runDocumentVerb: <T>(verb: 'save' | 'print', operation: () => Promise<T> | T): Promise<T> =>\n enqueue(async () => {\n jsNodesThisDispatch = 0; // one D11 aggregate for the whole verb op\n const diagnose = (diagnostic: ActionDiagnostic): void => diagnosticHook.emit(diagnostic);\n const before = verb === 'save' ? ('will-save' as const) : ('will-print' as const);\n const after = verb === 'save' ? ('did-save' as const) : ('did-print' as const);\n const body = async (): Promise<T> => {\n // A before-event failure never cancels the user's verb (D2);\n // runDocEventTreeSafe already degrades to diagnostics.\n await runDocEventTreeSafe(before, diagnose);\n // `operation()` throwing skips the after-event and rethrows —\n // no DidSave for a failed save.\n const value = await operation();\n await runDocEventTreeSafe(after, diagnose);\n return value;\n };\n if (verb !== 'print') return body();\n // The print verb holds the D3 latch for its WHOLE body, so a\n // WillPrint/DidPrint script calling doc.print() is suppressed\n // instead of opening a second dialog.\n docPrintEventActive = true;\n try {\n return await body();\n } finally {\n docPrintEventActive = false;\n }\n }),\n prepareClose: (): Promise<ActionTriggerResult> =>\n dispatch({ scope: 'document', event: 'will-close' }),\n setSubmitHandler: (handler): Unsubscribe => {\n submitHandler = handler;\n // Deliberately NOT an open-latch release — that stays the UI\n // adapter's role.\n return () => {\n if (submitHandler === handler) submitHandler = null;\n };\n },\n onAction: actionHook.on,\n onDiagnostic: diagnosticHook.on,\n onScriptDiagnostic: scriptDiagnosticHook.on,\n onScriptError: scriptErrorHook.on,\n\n registerExecutor: (type, executor): Unsubscribe => {\n if (executors.has(type)) {\n diagnosticHook.emit({\n code: 'duplicate-executor',\n message: `executor for '${type}' replaced (last-wins)`,\n });\n }\n executors.set(type, executor);\n return () => {\n if (executors.get(type) === executor) executors.delete(type);\n };\n },\n registerAnnotCommitSink: (sink): Unsubscribe => {\n annotCommitSink = sink;\n return () => {\n if (annotCommitSink === sink) annotCommitSink = null;\n };\n },\n registerFormCommitSink: (sink): Unsubscribe => {\n formCommitSink = sink;\n return () => {\n if (formCommitSink === sink) formCommitSink = null;\n };\n },\n ...(scriptHost && realms\n ? {\n scriptRealm: {\n transaction: <T>(\n body: (txn: import('@embedpdf/core-acrojs').ScriptTransaction) => Promise<T>,\n ) => scriptHost.transaction(body),\n budget: realms.budget,\n },\n createDetachedScriptRealm: (target) => {\n const host = realms.realmFor(target);\n return {\n transaction: <T>(\n body: (txn: import('@embedpdf/core-acrojs').ScriptTransaction) => Promise<T>,\n ) => host.transaction(body),\n budget: realms.budget,\n dispose: () => host.dispose(),\n };\n },\n }\n : {}),\n surfaceScriptResult,\n surfaceScriptCommit,\n reportPageState,\n registerSubmitResolver: (resolver): Unsubscribe => {\n submitResolver = resolver;\n return () => {\n if (submitResolver === resolver) submitResolver = null;\n };\n },\n };\n}\n","import type { ActionsAction, ActionsState } from './types';\n\nexport const initialActionsState = (): ActionsState => ({ seq: 0 });\n\nexport function actionsReducer(state: ActionsState, action: ActionsAction): ActionsState {\n switch (action.type) {\n case 'ACTIONS_DISPATCHED':\n return { seq: state.seq + 1 };\n default:\n return state;\n }\n}\n","import { definePlugin } from '@embedpdf/core';\n\nimport { createActionsCapability } from './capability';\nimport { actionsReducer, initialActionsState } from './reducer';\nimport { ActionsToken } from './types';\nimport type { ActionsAction, ActionsCapability, ActionsPluginConfig, ActionsState } from './types';\n\n/**\n * The action engine: the DEPENDENCY ROOT of the action architecture. It\n * interprets extracted /A and /AA trees; it never detects triggers and never\n * imports another plugin's token — stage, annotation, link, and form\n * optionally depend on ActionsToken and register their executors and sinks\n * at init (the kernel's topological order guarantees this plugin initializes\n * first). JavaScript is one registered interpreter among many: Hide,\n * ResetForm, GoTo, and Named work with scripting off.\n */\nexport const actionsPlugin = (config?: ActionsPluginConfig) =>\n definePlugin<ActionsState, ActionsAction, ActionsCapability>({\n id: 'actions',\n token: ActionsToken,\n scope: 'document',\n initialState: initialActionsState,\n reduce: actionsReducer,\n capability: (ctx) => createAction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S,MAAM;IACnC,OAAO;KACL,cACE,SACG,KAAK,YAAY,IAAI;KAC1B,QAAQ,OAAO;KACf,eAAe,KAAK,QAAQ;IAC9B;GACF;EACF,IACA,CAAC;EACL;EACA;EACA;EACA,yBAAyB,aAA0B;GACjD,iBAAiB;GACjB,aAAa;IACX,IAAI,mBAAmB,UAAU,iBAAiB;GACpD;EACF;CACF;AACF;;;ACxmDA,MAAa,6BAA2C,EAAE,KAAK,EAAE;AAEjE,SAAgB,eAAe,OAAqB,QAAqC;CACvF,QAAQ,OAAO,MAAf;EACE,KAAK,sBACH,OAAO,EAAE,KAAK,MAAM,MAAM,EAAE;EAC9B,SACE,OAAO;CACX;AACF;;;;;;;;;;;;ACKA,MAAa,iBAAiB,WAC5B,aAA6D;CAC3D,IAAI;CACJ,OAAO;CACP,OAAO;CACP,cAAc;CACd,QAAQ;CACR,aAAa,QAAQ,wBAAwB,KAAK,MAAM;AAC1D,CAAC"}
1
+ {"version":3,"file":"index.js","names":["toPageRef","ActionsToken"],"sources":["../src/services/annotation-rows.ts","../src/dispatch/fold.ts","../src/dispatch/dispatcher.ts","../src/services/policy.ts","../src/submit/intent.ts","../src/dispatch/run.ts","../src/dispatch/triggers.ts","../src/lifecycle/document-events.ts","../src/lifecycle/open-sequence.ts","../src/lifecycle/page-lifecycle.ts","../src/scripting/world.ts","../src/scripting/executor.ts","../src/scripting/environment.ts","../src/scripting/realm.ts","../src/scripting/surface.ts","../src/services/authority.ts","../src/services/catalog.ts","../src/services/events.ts","../src/services/form.ts","../src/services/ports.ts","../src/services/print-latch.ts","../src/services/queue.ts","../src/services/index.ts","../src/submit/perform.ts","../src/controller.ts","../src/settings.ts","../src/actions.plugin.ts"],"sourcesContent":["/**\n * The annotations an action can live on, of both read families: a page's\n * annotations (`doc.annotations`, `doc.annotate.read`) and its widgets, which\n * come with the form (`ActionsForm`, `doc.forms.read`). Each family is read\n * only when the session may read it, so a fill-only session still finds its\n * widgets' actions.\n */\nimport {\n annotationKey,\n type Annotation,\n type AnnotationRef,\n type PageRef,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { ActionsContext } from './context';\nimport type { ActionsForm } from './form';\n\n/** Every annotation of a page the session may read: its annotations, then its widgets. */\nexport async function readPageAnnotations(\n ctx: ActionsContext,\n form: ActionsForm,\n page: PageRef,\n read: <T>(task: Promise<T>) => Promise<T> = (task) => task,\n): Promise<Annotation[]> {\n const [annotations, widgets] = await Promise.all([\n ctx.allows('doc.annotate.read')\n ? read(ctx.doc.page(page).annotations.list()).then((list) => list.annotations)\n : Promise.resolve([]),\n ctx.allows('doc.forms.read')\n ? form\n .read(read)\n .then((snapshot) =>\n snapshot.widgets.filter((widget) => widget.page.objectNumber === page.objectNumber),\n )\n : Promise.resolve([]),\n ]);\n return [...annotations, ...widgets];\n}\n\n/**\n * The annotation `ref` names, of either family, or `null` when the session\n * can't see it: the form's widgets first (most actions a viewer runs are a\n * field's), then the page's annotations.\n */\nexport async function readAnnotation(\n ctx: ActionsContext,\n form: ActionsForm,\n ref: AnnotationRef,\n read: <T>(task: Promise<T>) => Promise<T> = (task) => task,\n): Promise<Annotation | null> {\n const key = annotationKey(ref);\n const matches = (candidate: Annotation) => annotationKey(candidate.ref) === key;\n if (ctx.allows('doc.forms.read')) {\n const widget = (await form.read(read)).widgets.find(matches);\n if (widget) return widget;\n }\n if (!ctx.allows('doc.annotate.read')) return null;\n return (await read(ctx.doc.page(ref.page).annotations.list())).annotations.find(matches) ?? null;\n}\n","/** Aggregate step statuses. A step failure never skips its siblings; this\n * only folds what each step reported. Pure. */\nimport type { ActionDiagnostic, ActionStepResult, ActionTriggerResult } from '../contract';\n\nexport const foldSteps = (\n steps: ActionStepResult[],\n diagnostics: ActionDiagnostic[],\n): ActionTriggerResult => {\n const statuses = steps.map((step) => step.result.status);\n const status: ActionTriggerResult['status'] =\n steps.length === 0\n ? 'inert'\n : statuses.every((stepStatus) => stepStatus === 'refused')\n ? 'refused'\n : statuses.every((stepStatus) => stepStatus === 'inert')\n ? 'inert'\n : statuses.every((stepStatus) => stepStatus === 'executed')\n ? 'executed'\n : 'partial';\n return { status, steps, diagnostics };\n};\n","/**\n * The dispatcher: the one serialized queue every tree rides. `execute` runs\n * a resolved tree; `dispatch` resolves a trigger inside the queued operation\n * (submission order is execution order) and fans out through the lifecycle\n * areas. `runAndEmit` is the shared per-tree unit: run, then `onExecuted`.\n *\n * A caller's signal skips an operation that hasn't started, stops a\n * trigger's reads, and stops a tree before its next node. `execute` then\n * rejects `operation-cancelled`; `dispatch` never rejects, so it resolves\n * `cancelled`.\n */\nimport { isPluginError, PluginError, type OperationOptions } from '@embedpdf/core';\nimport { annotationKey, type PdfActionTree } from '@embedpdf/engine-core/runtime';\n\nimport { eventOf, triggerOriginOf } from '../contract';\nimport type {\n ActionContext,\n ActionDiagnostic,\n ActionDispatchResult,\n ActionOrigin,\n ActionsCapability,\n ActionSource,\n ActionStepResult,\n ActionTreeSource,\n ActionTrigger,\n ActionTriggerEvent,\n ActionTriggerResult,\n PdfNamedAction,\n} from '../contract';\nimport type { ActionsDocumentEvents } from '../lifecycle/document-events';\nimport type { ActionsOpenSequence } from '../lifecycle/open-sequence';\nimport type { ActionsContext, ActionsServices } from '../services';\nimport { readAnnotation } from '../services/annotation-rows';\nimport { foldSteps } from './fold';\nimport type { ActionsRunner } from './run';\nimport type { ActionsTriggers } from './triggers';\n\n/** The source a trigger reports for: what its diagnostics carry before a tree is found. */\nconst sourceOfTrigger = (trigger: ActionTrigger): ActionSource => {\n switch (trigger.scope) {\n case 'activate':\n case 'annotation':\n return trigger.source ?? { kind: 'annotation', annotation: trigger.ref, page: trigger.page };\n case 'page':\n return { kind: 'page', page: trigger.page };\n case 'document':\n return { kind: 'document' };\n }\n};\n\nconst cancelled = (operation: string, signal: AbortSignal | undefined) =>\n new PluginError('operation-cancelled', 'actions', `${operation} was cancelled`, {\n cause: signal?.reason,\n });\n\nexport function createDispatcher(\n ctx: ActionsContext,\n services: Pick<ActionsServices, 'events' | 'policy' | 'queue' | 'catalog' | 'authority' | 'form'>,\n { run }: ActionsRunner,\n { triggerEnabled, lifecycleAnnotationsOf, planPageSteps }: ActionsTriggers,\n openSequence: Pick<ActionsOpenSequence, 'noteUserActivity' | 'claim' | 'run'>,\n { runDocumentEventOp }: Pick<ActionsDocumentEvents, 'runDocumentEventOp'>,\n) {\n const { executed, reportDiagnostic } = services.events;\n const { decisionFor } = services.policy;\n const { allowsPrint } = services.authority;\n const { enqueue, budget } = services.queue;\n const { readDocumentActions, DOC_EVENT_TREES } = services.catalog;\n const { form } = services;\n const { noteUserActivity } = openSequence;\n\n /** Run one tree and announce it: the shared per-tree unit (queued by\n * `execute`; called inline per step by the queued trigger resolver). */\n const runAndEmit = async (\n tree: PdfActionTree,\n actionContext: ActionContext,\n signal?: AbortSignal,\n ): Promise<ActionDispatchResult> => {\n const result = await run(tree, actionContext, signal);\n executed.emit({ tree, result, source: actionContext.source });\n return result;\n };\n\n const execute = (\n tree: PdfActionTree,\n actionContext: ActionContext,\n options?: OperationOptions,\n ): Promise<ActionDispatchResult> => {\n const signal = options?.signal;\n // Before enqueueing: a real user gesture arms the open sequence (its\n // operation then lands ahead of this action in the queue) and resets the\n // cascade budget.\n if (actionContext.origin === 'user') noteUserActivity();\n return enqueue(async () => {\n budget.scriptNodes = 0; // one script budget per dispatch\n const result = await runAndEmit(tree, actionContext, signal);\n if (result.status === 'cancelled') throw cancelled('actions.execute', signal);\n return result;\n }, options);\n };\n\n const canExecute = (tree: PdfActionTree, actionContext: ActionContext): boolean => {\n if (tree.incomplete || !tree.root) return false;\n const decision = decisionFor(tree.root, actionContext.origin);\n return decision === 'allow' || decision === 'adapter';\n };\n\n const runSteps = async (\n steps: Array<{ source: ActionSource; tree: PdfActionTree }>,\n origin: ActionOrigin,\n event: ActionTriggerEvent,\n diagnostics: ActionDiagnostic[],\n signal: AbortSignal | undefined,\n ): Promise<ActionTriggerResult> => {\n const results: ActionStepResult[] = [];\n for (const step of steps) {\n if (signal?.aborted) break;\n const result = await runAndEmit(step.tree, { origin, source: step.source, event }, signal);\n results.push({ source: step.source, tree: step.tree, result });\n }\n if (signal?.aborted) return { status: 'cancelled', steps: results, diagnostics };\n return foldSteps(results, diagnostics);\n };\n\n /** Everything a trigger needs, reads included, inside the queued operation:\n * submission order is execution order. Never throws. */\n const resolveAndRun = async (\n trigger: ActionTrigger,\n signal: AbortSignal | undefined,\n ): Promise<ActionTriggerResult> => {\n const diagnostics: ActionDiagnostic[] = [];\n const diagnose = (diagnostic: ActionDiagnostic): void => {\n diagnostics.push(diagnostic);\n reportDiagnostic(diagnostic, { source: sourceOfTrigger(trigger) });\n };\n /** A read the caller's signal can stop. */\n const read = <T>(task: Promise<T>): Promise<T> => ctx.cancellable(signal, task);\n try {\n if (!triggerEnabled(trigger)) {\n diagnose({\n code: 'trigger-disabled',\n message: `${trigger.scope}: trigger family disabled by config`,\n });\n return { status: 'inert', steps: [], diagnostics };\n }\n const origin = triggerOriginOf(trigger);\n switch (trigger.scope) {\n case 'activate':\n case 'annotation': {\n const event = trigger.scope === 'activate' ? 'activate' : trigger.event;\n const annotation = await readAnnotation(ctx, form, trigger.ref, read);\n // ISO 32000-2 Table 197: \"the A entry, if present, takes precedence\n // over [the /AA U entry]\"; a shadowed U tree is silently inert,\n // exactly like an absent one.\n if (event === 'mouseUp' && annotation?.actions?.activate) {\n return { status: 'inert', steps: [], diagnostics };\n }\n const tree = annotation?.actions?.[event];\n if (!tree?.root && !tree?.incomplete) return { status: 'inert', steps: [], diagnostics };\n const source = sourceOfTrigger(trigger);\n return await runSteps([{ source, tree }], origin, eventOf(trigger), diagnostics, signal);\n }\n case 'page': {\n // A shared read other triggers may wait on too: never aborted, only not awaited further.\n const lifecycle = await lifecycleAnnotationsOf(trigger.page);\n const pageActions = ctx.getPage(trigger.page)?.actions;\n const steps = planPageSteps(trigger.event, trigger.page, pageActions, lifecycle);\n return await runSteps(steps, origin, eventOf(trigger), diagnostics, signal);\n }\n case 'document': {\n if (trigger.event !== 'open') {\n return await runDocumentEventOp(trigger.event, diagnostics, diagnose);\n }\n if (!openSequence.claim()) {\n diagnose({\n code: 'open-sequence-replayed',\n message: 'document open sequence already fired for this document',\n });\n return { status: 'inert', steps: [], diagnostics };\n }\n return await openSequence.run();\n }\n }\n } catch (error) {\n if (isPluginError(error, 'operation-cancelled') && signal?.aborted) {\n return { status: 'cancelled', steps: [], diagnostics };\n }\n diagnose({\n code: 'trigger-failed',\n message: `trigger resolution failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n return { status: 'refused', steps: [], diagnostics };\n }\n };\n\n const dispatch = (\n trigger: ActionTrigger,\n options?: OperationOptions,\n ): Promise<ActionTriggerResult> => {\n const signal = options?.signal;\n // A user-origin trigger is user activity (it arms the open sequence and\n // resets the cascade budget), noted before taking the queue slot, so an\n // armed open sequence runs first.\n if (triggerOriginOf(trigger) === 'user') noteUserActivity();\n return enqueue(() => {\n budget.scriptNodes = 0; // one script budget per dispatch\n return resolveAndRun(trigger, signal);\n }, options).catch(\n // Only a signal that fired while the trigger waited for its turn gets\n // here: resolveAndRun itself never throws.\n (): ActionTriggerResult => ({ status: 'cancelled', steps: [], diagnostics: [] }),\n );\n };\n\n /** The tree `executeNamed` runs, and its context: a click from your code unless `context` says otherwise. */\n const namedTree = (name: PdfNamedAction): PdfActionTree => ({\n root: { type: 'named', subtype: 'Named', name, next: [] },\n incomplete: false,\n warningFlags: 0,\n warnings: [],\n });\n const namedContext = (context?: Partial<ActionContext>): ActionContext => ({\n origin: 'user',\n source: { kind: 'api' },\n event: { scope: 'activate' },\n ...context,\n });\n\n const executeNamed = (\n name: PdfNamedAction,\n context?: Partial<ActionContext>,\n options?: OperationOptions,\n ): Promise<ActionDispatchResult> => execute(namedTree(name), namedContext(context), options);\n\n const canExecuteNamed = (name: PdfNamedAction, context?: Partial<ActionContext>): boolean =>\n canExecute(namedTree(name), namedContext(context)) && (name !== 'Print' || allowsPrint());\n\n /** The raw tree behind a source, read from the document, with no dispatch\n * rules applied (the /A-shadows-U rule lives in `resolveAndRun`). */\n const readActionTree = async (source: ActionTreeSource): Promise<PdfActionTree | null> => {\n switch (source.kind) {\n case 'annotation': {\n const annotation = await readAnnotation(ctx, form, source.annotation);\n const tree = annotation?.actions?.[source.event ?? 'activate'];\n return tree ?? null;\n }\n case 'field': {\n const { fields } = await form.read();\n const target = source.field;\n const field = fields.find((candidate) =>\n target.kind === 'objectNumber'\n ? candidate.ref.kind === 'objectNumber' &&\n candidate.ref.objectNumber === target.objectNumber\n : candidate.name === target.name,\n );\n return field?.actions?.[source.event] ?? null;\n }\n case 'page':\n return ctx.getPage(source.page)?.actions?.[source.event ?? 'open'] ?? null;\n case 'document': {\n const snapshot = await readDocumentActions();\n if (!snapshot) return null;\n const event = source.event ?? 'open';\n return (event === 'open' ? snapshot.openAction : snapshot[DOC_EVENT_TREES[event]]) ?? null;\n }\n }\n };\n\n return {\n runAndEmit,\n dispatch,\n api: {\n execute,\n canExecute,\n executeNamed,\n canExecuteNamed,\n getActionTree: (source, options) => ctx.cancellable(options?.signal, readActionTree(source)),\n dispatch,\n // The synchronous twin: the trigger family is enabled. Per-tree truth\n // stays per step in the results; resolution is async and never\n // previewed here.\n canDispatch: (trigger) => triggerEnabled(trigger),\n prepareClose: (options): Promise<ActionTriggerResult> =>\n dispatch({ scope: 'document', event: 'will-close' }, options),\n } satisfies Partial<ActionsCapability>,\n };\n}\nexport type ActionsDispatcher = ReturnType<typeof createDispatcher>;\n","/**\n * The policy matrix (type × origin → decision): the fixed `never` and\n * unsupported sets, and the one decision function over the `policy` setting.\n * The setting itself (its defaults and its merge) is the plugin's settings.\n */\nimport type { PdfActionNode, PdfActionType } from '@embedpdf/engine-core/runtime';\n\nimport type {\n ActionOrigin,\n ActionPolicy,\n ActionPolicyDecision,\n ActionPolicyRow,\n} from '../contract';\nimport type { ActionsContext } from './context';\n\n/** Never executable, not configurable — diagnostics only. */\nconst NEVER_TYPES: ReadonlySet<PdfActionType> = new Set([\n 'launch',\n 'goto-remote',\n 'goto-embedded',\n 'sound',\n 'movie',\n 'import-data',\n]);\n\n/** Recognized types with no interpreter: reported, never executed. */\nconst UNSUPPORTED_TYPES: ReadonlySet<PdfActionType> = new Set([\n 'rendition',\n 'thread',\n 'set-ocg-state',\n 'transition',\n 'goto-3d-view',\n 'unknown',\n]);\n\n/** Document-lifetime node types: engine mutations, committed in walk order. */\nexport const DOCUMENT_TYPES: ReadonlySet<PdfActionType> = new Set(['reset-form', 'javascript']);\n\nexport const isPrintVerb = (node: PdfActionNode): boolean =>\n node.type === 'named' && node.name === 'Print';\n\nexport function createPolicy(ctx: ActionsContext) {\n const settings = ctx.settings();\n /** The live policy: read at decision time, never captured. */\n const current = (): ActionPolicy => settings.get().policy;\n\n /** The decision for one node and origin; `'never'` and `'unsupported'` are fixed, not configurable. */\n const decisionFor = (\n node: PdfActionNode,\n origin: ActionOrigin,\n ): ActionPolicyDecision | 'never' | 'unsupported' => {\n if (NEVER_TYPES.has(node.type)) return 'never';\n if (UNSUPPORTED_TYPES.has(node.type)) return 'unsupported';\n const policy = current();\n if (isPrintVerb(node)) return policy.print[origin];\n const row = policy[node.type as keyof ActionPolicy] as ActionPolicyRow | undefined;\n return row ? row[origin] : 'unsupported';\n };\n\n return { decisionFor, current };\n}\nexport type ActionsPolicy = ReturnType<typeof createPolicy>;\n","/** The one normalized submit intent, from either source (an action node's\n * payload or a script `doc.submitForm()` effect), and the engine request\n * shape the document's home receives. Pure. */\nimport type { ScriptUiEffect } from '@embedpdf/core-acrojs';\nimport type {\n FormSubmissionRequest,\n IsoDateTime,\n SubmitFormPayload,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { ActionSubmitRequest, SubmitIntent } from '../contract';\n\nexport const intentOfPayload = (payload: SubmitFormPayload): SubmitIntent => ({\n url: payload.url,\n fields: payload.fields,\n exclude: payload.flags.exclude,\n includeNoValueFields: payload.flags.includeNoValueFields,\n format: payload.flags.format,\n method: payload.flags.method,\n flagsRaw: payload.flags.raw,\n ...(payload.charSet === undefined ? {} : { charSet: payload.charSet }),\n});\n\nexport const toFormSubmissionRequest = (\n request: ActionSubmitRequest,\n sentAt: IsoDateTime,\n): FormSubmissionRequest => ({\n entries: request.entries,\n intent: {\n url: request.url,\n format: request.format,\n method: request.method,\n flagsRaw: request.flagsRaw,\n ...(request.charSet === undefined ? {} : { charSet: request.charSet }),\n },\n origin: request.origin,\n sentAt,\n});\n\n/** Script `doc.submitForm(...)` → the one normalized intent. Script field\n * names are include-mode by definition (Acrobat's aFields). */\nexport const intentOfSubmitEffect = (\n effect: Extract<ScriptUiEffect, { kind: 'submitForm' }>,\n): SubmitIntent => {\n const format = effect.format ?? 'fdf';\n return {\n url: effect.url,\n fields: effect.fieldNames?.map((name) => ({ kind: 'name' as const, name })) ?? null,\n exclude: false,\n includeNoValueFields: effect.includeEmpty,\n format,\n method: effect.method ?? 'post',\n flagsRaw: 0,\n };\n};\n","/**\n * The tree walker: policy per node, document-lifetime work in walk order\n * (Hide through the owner sinks, executors for the rest), and navigation and\n * external effects deferred until every document node succeeded. A caller's\n * signal that fires stops the walk before its next node, and nothing\n * deferred fires.\n */\nimport type {\n FormFieldRef,\n PdfActionNode,\n PdfActionTree,\n PdfActionType,\n} from '@embedpdf/engine-core/runtime';\n\nimport type {\n ActionContext,\n ActionDiagnostic,\n ActionDispatchResult,\n ActionExecutorResult,\n ActionNodeResult,\n ActionNodeStatus,\n} from '../contract';\nimport type { AnnotCommitEntry } from '../host-contract';\nimport type { ActionsContext, ActionsServices } from '../services';\nimport { DOCUMENT_TYPES, isPrintVerb } from '../services/policy';\nimport { intentOfPayload } from '../submit/intent';\nimport type { ActionsSubmit } from '../submit/perform';\nimport type { ActionsDocumentEvents } from '../lifecycle/document-events';\n\nexport function createRunner(\n ctx: ActionsContext,\n services: Pick<ActionsServices, 'policy' | 'ports' | 'events' | 'form'>,\n { performSubmit }: ActionsSubmit,\n { firePrintThroughAdapter }: Pick<ActionsDocumentEvents, 'firePrintThroughAdapter'>,\n) {\n const { decisionFor } = services.policy;\n const ports = services.ports.slots;\n const { reportDiagnostic } = services.events;\n const { form } = services;\n\n async function run(\n tree: PdfActionTree,\n actionContext: ActionContext,\n signal?: AbortSignal,\n ): Promise<ActionDispatchResult> {\n const diagnostics: ActionDiagnostic[] = [];\n /** Record a diagnostic in the result and report it, with the action it concerns. */\n const diagnose = (diagnostic: ActionDiagnostic, action: PdfActionType | null): void => {\n diagnostics.push(diagnostic);\n reportDiagnostic(diagnostic, { action, source: actionContext.source });\n };\n\n // The law: never execute an incomplete tree — not even its root.\n if (tree.incomplete) {\n diagnose(\n { code: 'incomplete-tree', message: 'refused: the action tree is incomplete' },\n tree.root?.type ?? null,\n );\n return { status: 'refused', nodes: [], diagnostics };\n }\n if (!tree.root) return { status: 'inert', nodes: [], diagnostics };\n\n const nodes: ActionNodeResult[] = [];\n // Navigation and external effects are deferred thunks, fired only after\n // every document-lifetime node succeeded, in node order, so navigation\n // never yanks the user away from a failed write.\n const deferred: Array<{ result: ActionNodeResult; fire: () => Promise<void> | void }> = [];\n let documentFailed = false;\n let cancelled = false;\n\n const settle = (result: ActionNodeResult, outcome: ActionExecutorResult): void => {\n if (outcome.status === 'executed') result.status = 'executed';\n else if (outcome.status === 'inert') {\n result.status = 'inert';\n result.detail = outcome.reason;\n diagnose(\n { code: 'executor-inert', message: `${result.type}: ${outcome.reason}` },\n result.type,\n );\n } else {\n result.status = 'failed';\n result.detail = outcome.error;\n diagnose(\n { code: 'executor-failed', message: `${result.type}: ${outcome.error}` },\n result.type,\n );\n }\n };\n\n // A Hide action sets or clears the Hidden state (ISO 32000-2 §12.6.4.11):\n // a real mutation through the owning plane's commit sink, authority-gated\n // by the engine like every other write. Widgets are the forms plane's\n // visibility (the engine's field-level `setDisplay`, like Acrobat's\n // `field.display`; there is no per-widget annotation patch); plain\n // annotations are flag patches through the annotation sink.\n const interpretHide = async (\n node: Extract<PdfActionNode, { type: 'hide' }>,\n ): Promise<{ status: ActionNodeStatus; detail?: string }> => {\n const display = node.hide ? ('hidden' as const) : ('visible' as const);\n const diagnoseHide = (diagnostic: ActionDiagnostic): void => diagnose(diagnostic, 'hide');\n const fieldRefs: FormFieldRef[] = [];\n const annotEntries: AnnotCommitEntry[] = [];\n const names: string[] = [];\n const bareObjectNumbers: number[] = [];\n for (const target of node.targets) {\n if (target.kind === 'objectNumber') bareObjectNumbers.push(target.objectNumber);\n else names.push(target.name);\n }\n if (names.length || bareObjectNumbers.length) {\n const snapshot = await form.read();\n for (const name of names) {\n const field = snapshot.fields.find((candidate) => candidate.name === name);\n if (!field) {\n diagnoseHide({ code: 'unresolved-target', message: `hide: no field named '${name}'` });\n continue;\n }\n fieldRefs.push(field.ref);\n }\n for (const objectNumber of bareObjectNumbers) {\n // A bare object number may be a widget (its field's display) or a\n // plain annotation (its own flags): the forms snapshot decides.\n const owner = snapshot.fields.find((field) =>\n field.widgets.some((widget) => widget.objectNumber === objectNumber),\n );\n if (owner) {\n fieldRefs.push(owner.ref);\n } else {\n annotEntries.push({\n annotObjectNumber: objectNumber,\n patch: { flags: { hidden: node.hide } },\n });\n }\n }\n }\n let failedDetail: string | undefined;\n if (fieldRefs.length) {\n if (!ports.formCommitSink) {\n diagnoseHide({\n code: 'no-commit-sink',\n message: 'hide: no form commit sink registered (form plugin absent)',\n });\n return { status: 'no-executor' };\n }\n const result = await ports.formCommitSink(\n fieldRefs.map((ref) => ({ kind: 'setDisplay', ref, display })),\n );\n if (result.status === 'failed') {\n failedDetail = result.error ?? 'failed';\n diagnoseHide({ code: 'executor-failed', message: `hide: ${failedDetail}` });\n }\n }\n if (annotEntries.length && !failedDetail) {\n if (!ports.annotCommitSink) {\n diagnoseHide({\n code: 'no-commit-sink',\n message: 'hide: no annotation commit sink registered (annotation plugin absent)',\n });\n return { status: 'no-executor' };\n }\n const committed = await ports.annotCommitSink(annotEntries);\n const failed = committed.results.filter((entry) => entry.status === 'failed');\n for (const failure of failed) {\n diagnoseHide({\n code: 'executor-failed',\n message: `hide: annotation ${failure.annotObjectNumber}: ${failure.error ?? 'failed'}`,\n });\n }\n if (failed.length === committed.results.length && failed.length > 0) {\n failedDetail = failed[0]?.error;\n }\n }\n if (failedDetail) return { status: 'failed', detail: failedDetail };\n return { status: 'executed' };\n };\n\n const interpret = async (node: PdfActionNode, path: number[]): Promise<void> => {\n const result: ActionNodeResult = { path, type: node.type, status: 'blocked' };\n nodes.push(result);\n const decision = decisionFor(node, actionContext.origin);\n const diagnoseNode = (diagnostic: ActionDiagnostic): void => diagnose(diagnostic, node.type);\n\n if (decision === 'never' || decision === 'block' || decision === 'report') {\n result.status = 'blocked';\n // `block` refuses quietly; `report`, and a type that never runs, say so.\n if (decision !== 'block') {\n diagnoseNode({\n code: 'blocked',\n message: `${node.type}: ${decision === 'never' ? 'never executable' : `policy 'report' for origin '${actionContext.origin}'`}`,\n });\n }\n return;\n }\n if (decision === 'unsupported') {\n result.status = 'no-executor';\n return;\n }\n\n if (node.type === 'hide') {\n // A document mutation: an earlier document failure skips it, and its\n // own failure stops later document work and drops deferred effects.\n if (documentFailed) {\n result.status = 'skipped';\n return;\n }\n const outcome = await interpretHide(node);\n result.status = outcome.status;\n if (outcome.detail) result.detail = outcome.detail;\n if (outcome.status === 'failed') documentFailed = true;\n return;\n }\n\n if (DOCUMENT_TYPES.has(node.type)) {\n if (documentFailed) {\n result.status = 'skipped';\n return;\n }\n const executor = ports.executors.get(node.type);\n if (!executor) {\n result.status = node.type === 'javascript' ? 'inert' : 'no-executor';\n diagnoseNode({\n code: 'no-executor',\n message: `${node.type}: no executor registered${node.type === 'javascript' ? ' (scripting unavailable)' : ''}`,\n });\n return;\n }\n try {\n settle(result, await executor(node, actionContext));\n } catch (error) {\n settle(result, {\n status: 'failed',\n error: error instanceof Error ? error.message : String(error),\n });\n }\n if (result.status === 'failed') documentFailed = true;\n return;\n }\n\n if (node.type === 'submit-form') {\n if (!node.payload) {\n // A runtime that does not extract the submit payload: the node is\n // recognized but inert, and diagnosed.\n result.status = 'inert';\n result.detail = 'submit payload unavailable (older runtime extraction)';\n diagnoseNode({\n code: 'submit-payload-unavailable',\n message: 'submit-form: payload unavailable (older runtime extraction) — node inert',\n });\n return;\n }\n const payload = node.payload;\n // External like print and uri: deferred until every document-lifetime\n // node succeeded, so a submission never carries a half-failed form\n // state.\n result.status = 'skipped'; // provisional until fired\n deferred.push({\n result,\n fire: async () => {\n const outcome = await performSubmit(\n intentOfPayload(payload),\n actionContext,\n diagnoseNode,\n );\n result.status = outcome.status;\n if (outcome.detail) result.detail = outcome.detail;\n },\n });\n return;\n }\n\n if (isPrintVerb(node) || node.type === 'uri') {\n // External: adapter-routed, deferred.\n result.status = 'skipped'; // provisional until fired\n deferred.push({\n result,\n fire: async () => {\n if (node.type === 'uri') {\n if (!ports.uiAdapter) {\n result.status = 'no-executor';\n diagnoseNode({\n code: 'no-adapter',\n message: `${node.type}: no UI adapter installed`,\n });\n return;\n }\n ports.uiAdapter.openUri(node.uri, {\n isMap: node.isMap,\n origin: actionContext.origin,\n });\n result.status = 'executed';\n return;\n }\n // The Print verb: /WP → the adapter (exactly once) → /DP, under\n // the print latch. Authority, adapter and reentrancy verdicts come\n // back as the node's status.\n const outcome = await firePrintThroughAdapter(undefined, diagnoseNode);\n result.status = outcome.status;\n if (outcome.detail) result.detail = outcome.detail;\n },\n });\n return;\n }\n\n // goto + named page verbs: navigation, executor-routed, deferred.\n result.status = 'skipped'; // provisional until fired\n deferred.push({\n result,\n fire: async () => {\n const executor = ports.executors.get(node.type);\n if (!executor) {\n result.status = 'no-executor';\n diagnoseNode({ code: 'no-executor', message: `${node.type}: no executor registered` });\n return;\n }\n try {\n settle(result, await executor(node, actionContext));\n } catch (error) {\n settle(result, {\n status: 'failed',\n error: error instanceof Error ? error.message : String(error),\n });\n }\n },\n });\n };\n\n const walk = async (node: PdfActionNode, path: number[]): Promise<void> => {\n if (signal?.aborted) {\n cancelled = true;\n return;\n }\n await interpret(node, path);\n for (let index = 0; index < node.next.length && !cancelled; index++) {\n await walk(node.next[index], [...path, index]);\n }\n };\n await walk(tree.root, []);\n\n if (!documentFailed && !cancelled) {\n for (const entry of deferred) await entry.fire();\n }\n if (cancelled) return { status: 'cancelled', nodes, diagnostics };\n\n const anyExecuted = nodes.some((node) => node.status === 'executed');\n const anyFailedOrSkipped = nodes.some(\n (node) => node.status === 'failed' || node.status === 'skipped',\n );\n const status: ActionDispatchResult['status'] = anyExecuted\n ? anyFailedOrSkipped\n ? 'partial'\n : 'executed'\n : anyFailedOrSkipped\n ? 'partial'\n : 'inert';\n return { status, nodes, diagnostics };\n }\n\n return { run };\n}\nexport type ActionsRunner = ReturnType<typeof createRunner>;\n","/**\n * Trigger resolution helpers: the `triggers` setting, the per-page cache of annotations bearing page-lifecycle trees (the fan-out's\n * read amplifier) and ISO 32000-2 Table 197's page-step order.\n */\nimport type {\n AnnotationRef,\n DocumentEvent,\n PageObjectNumber,\n PageRef,\n PdfActionTree,\n PdfAnnotationActions,\n PdfPageActions,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { ActionSource, ActionTrigger } from '../contract';\nimport type { ActionsContext, ActionsServices } from '../services';\nimport { readPageAnnotations } from '../services/annotation-rows';\n\n/** An annotation that carries at least one page-lifecycle tree (/PO, /PC, /PV, /PI), as read. */\ninterface LifecycleAnnotation {\n readonly ref: AnnotationRef;\n readonly actions: PdfAnnotationActions;\n}\n\n/**\n * The pages whose annotations an event changes: those pages, every page\n * (`'all'`: a redaction, a skipped stretch of the stream, new document\n * bytes), or none.\n */\nconst annotationPagesOf = (event: DocumentEvent): readonly PageRef[] | 'all' | null => {\n switch (event.type) {\n case 'annotations.created':\n case 'annotations.updated':\n case 'annotations.deleted':\n case 'annotations.reordered':\n case 'annotations.flattened':\n case 'forms.widgetsReordered':\n return [event.page];\n // A form write can add, move or remove widgets, which carry page actions too.\n case 'forms.created':\n case 'forms.deleted':\n case 'forms.widgetAdded':\n case 'forms.widgetRemoved':\n case 'forms.widgetDeleted':\n case 'forms.widgetRestored':\n case 'forms.widgetUpdated':\n case 'forms.restored':\n case 'forms.repaired':\n return 'all';\n case 'pages.flattened':\n return event.pages;\n case 'redaction.applied':\n case 'stream.desynced':\n case 'document.versioned':\n return 'all';\n default:\n return null;\n }\n};\n\nexport function createTriggers(\n ctx: ActionsContext,\n { settings, form }: Pick<ActionsServices, 'settings' | 'form'>,\n) {\n const triggerEnabled = (trigger: ActionTrigger): boolean => {\n const { triggers } = settings.get();\n switch (trigger.scope) {\n case 'activate':\n return true; // the click door is never gated\n case 'annotation':\n return triggers.annotation;\n case 'page':\n return triggers.page;\n case 'document':\n return triggers.document;\n }\n };\n\n // Per page, the pending or settled read of its lifecycle-bearing\n // annotations. Reads start only inside the queued operation that needs\n // them, so a trigger sees every change made by the operations queued\n // before it. Holding the promise lets concurrent readers share one read,\n // and dropping it on invalidation means a read that was in flight when its\n // page changed is never reused afterwards.\n const lifecycleReads = new Map<PageObjectNumber, Promise<readonly LifecycleAnnotation[]>>();\n\n const lifecycleAnnotationsOf = (page: PageRef): Promise<readonly LifecycleAnnotation[]> => {\n const key = page.objectNumber;\n const cached = lifecycleReads.get(key);\n if (cached) return cached;\n const read = readPageAnnotations(ctx, form, page).then((annotations) =>\n annotations\n .filter(\n (annotation) =>\n annotation.actions &&\n (annotation.actions.pageOpen?.root ||\n annotation.actions.pageClose?.root ||\n annotation.actions.pageVisible?.root ||\n annotation.actions.pageInvisible?.root),\n )\n .map((annotation) => ({ ref: annotation.ref, actions: annotation.actions! })),\n );\n lifecycleReads.set(key, read);\n // A failed read is not kept: the next trigger for the page reads again.\n read.catch(() => {\n if (lifecycleReads.get(key) === read) lifecycleReads.delete(key);\n });\n return read;\n };\n\n /** Forget the pages a confirmed document event changed. */\n const invalidate = (event: DocumentEvent): void => {\n const pages = annotationPagesOf(event);\n if (pages === 'all') lifecycleReads.clear();\n else if (pages) for (const page of pages) lifecycleReads.delete(page.objectNumber);\n };\n\n /**\n * ISO 32000-2 Table 197 order: /PO \"shall be executed after the O action …\n * and the OpenAction entry\"; /PC \"shall be executed before the C action\".\n * Rootless trees are skipped (a budget-degraded tree with no root has\n * nothing to walk).\n */\n const planPageSteps = (\n event: 'open' | 'close' | 'visible' | 'invisible',\n page: PageRef,\n pageActions: PdfPageActions | undefined,\n lifecycle: readonly LifecycleAnnotation[],\n ): Array<{ source: ActionSource; tree: PdfActionTree }> => {\n const pageSource: ActionSource = { kind: 'page', page };\n const annotationSteps = (key: 'pageOpen' | 'pageClose' | 'pageVisible' | 'pageInvisible') =>\n lifecycle\n .filter((annotation) => annotation.actions[key]?.root)\n .map((annotation) => ({\n source: { kind: 'annotation', annotation: annotation.ref, page } as ActionSource,\n tree: annotation.actions[key]!,\n }));\n switch (event) {\n case 'open':\n return [\n ...(pageActions?.open?.root ? [{ source: pageSource, tree: pageActions.open }] : []),\n ...annotationSteps('pageOpen'),\n ];\n case 'close':\n return [\n ...annotationSteps('pageClose'),\n ...(pageActions?.close?.root ? [{ source: pageSource, tree: pageActions.close }] : []),\n ];\n case 'visible':\n return annotationSteps('pageVisible');\n case 'invisible':\n return annotationSteps('pageInvisible');\n }\n };\n\n return { triggerEnabled, lifecycleAnnotationsOf, invalidate, planPageSteps };\n}\nexport type ActionsTriggers = ReturnType<typeof createTriggers>;\n","/**\n * The verb-shaped document events (/WC, /WS, /DS, /WP, /DP) and the print\n * door: one catalog lifecycle tree per event, run inside the current queue\n * operation and never throwing (a broken script must not cancel the user's\n * save or print), and the adapter print wrapped /WP → print → /DP under the\n * print latch.\n */\nimport { PluginError, type OperationOptions } from '@embedpdf/core';\n\nimport type {\n ActionContext,\n ActionDiagnostic,\n ActionNodeStatus,\n ActionOrigin,\n ActionsCapability,\n ActionStepResult,\n ActionTriggerResult,\n DocumentTriggerEvent,\n} from '../contract';\nimport type { DispatchCore } from '../dispatch/core';\nimport { foldSteps } from '../dispatch/fold';\nimport type { ActionsServices } from '../services';\nimport type { ActionsOpenSequence } from './open-sequence';\n\nexport function createDocumentEvents(\n services: Pick<\n ActionsServices,\n 'events' | 'catalog' | 'queue' | 'ports' | 'authority' | 'printLatch' | 'settings'\n >,\n {\n ensureOpenSequenceBeforeDocEvent,\n }: Pick<ActionsOpenSequence, 'ensureOpenSequenceBeforeDocEvent'>,\n { runAndEmit }: DispatchCore,\n) {\n const { reportDiagnostic } = services.events;\n const { readDocumentActions, DOC_EVENT_TREES } = services.catalog;\n const { enqueue, budget } = services.queue;\n const ports = services.ports.slots;\n const { allowsPrint } = services.authority;\n const printLatch = services.printLatch;\n\n /**\n * Run one catalog lifecycle tree inside the current queue operation, shared\n * by the dispatch path, `runDocumentVerb` and the print wrapper. Never\n * throws: a read or resolution failure degrades to a diagnostic, because a\n * broken script must not cancel the user's save or print.\n */\n const runDocEventTreeSafe = async (\n event: Exclude<DocumentTriggerEvent, 'open'>,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<ActionStepResult | null> => {\n if (!services.settings.get().triggers.document) return null;\n try {\n await ensureOpenSequenceBeforeDocEvent();\n const snapshot = await readDocumentActions();\n const tree = snapshot?.[DOC_EVENT_TREES[event]];\n if (!tree?.root && !tree?.incomplete) return null;\n const actionContext: ActionContext = {\n origin: 'lifecycle',\n source: { kind: 'document' },\n event: { scope: 'document', name: event },\n };\n return { source: { kind: 'document' }, tree, result: await runAndEmit(tree, actionContext) };\n } catch (error) {\n diagnose({\n code: 'trigger-failed',\n message: `${event}: ${error instanceof Error ? error.message : String(error)}`,\n });\n return null;\n }\n };\n\n /** The dispatch-path body for a verb-shaped document event. */\n const runDocumentEventOp = async (\n event: Exclude<DocumentTriggerEvent, 'open'>,\n diagnostics: ActionDiagnostic[],\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<ActionTriggerResult> => {\n const step = await runDocEventTreeSafe(event, diagnose);\n return foldSteps(step ? [step] : [], diagnostics);\n };\n\n /**\n * Both adapter print paths (the Named Print verb, and script `doc.print()`\n * effects from the actions plane) go through here: /WP →\n * `ports.uiAdapter.print` exactly once → /DP, with the latch reset in\n * `finally`. While the latch is held (including `runDocumentVerb('print')`'s\n * body) a nested request is suppressed with `reentrant-print`. An adapter\n * throw skips /DP (the latch still resets). /DP fires when the adapter call\n * returns, since a browser cannot observe dialog completion.\n */\n const firePrintThroughAdapter = async (\n uiContext: { origin: ActionOrigin; phase: 'boot' | 'user' } | undefined,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<{ status: ActionNodeStatus; detail?: string }> => {\n if (printLatch.active) {\n diagnose({\n code: 'reentrant-print',\n message:\n 'print request during a document print event — suppressed (one dialog per request)',\n });\n return { status: 'blocked', detail: 'reentrant print suppressed' };\n }\n if (!allowsPrint()) {\n diagnose({ code: 'blocked', message: 'print: doc.print is not allowed' });\n return { status: 'blocked', detail: 'doc.print is not allowed' };\n }\n if (!ports.uiAdapter) {\n diagnose({ code: 'no-adapter', message: 'print: no UI adapter installed' });\n return { status: 'no-executor', detail: 'no UI adapter installed' };\n }\n printLatch.active = true;\n try {\n await runDocEventTreeSafe('will-print', diagnose);\n const adapter = ports.uiAdapter;\n if (!adapter) return { status: 'no-executor', detail: 'UI adapter uninstalled mid-print' };\n if (uiContext) adapter.print(uiContext);\n else adapter.print();\n await runDocEventTreeSafe('did-print', diagnose);\n return { status: 'executed' };\n } finally {\n printLatch.active = false;\n }\n };\n\n return {\n runDocumentEventOp,\n firePrintThroughAdapter,\n api: {\n runDocumentVerb: <T>(\n verb: 'save' | 'print',\n operation: () => Promise<T> | T,\n options?: OperationOptions,\n ): Promise<T> =>\n enqueue(async () => {\n budget.scriptNodes = 0; // one script budget for the whole verb operation\n const diagnose = (diagnostic: ActionDiagnostic): void =>\n reportDiagnostic(diagnostic, { source: { kind: 'document' } });\n const before = verb === 'save' ? ('will-save' as const) : ('will-print' as const);\n const after = verb === 'save' ? ('did-save' as const) : ('did-print' as const);\n const body = async (): Promise<T> => {\n // A before-event failure never cancels the user's verb;\n // runDocEventTreeSafe already degrades to diagnostics.\n await runDocEventTreeSafe(before, diagnose);\n // The caller can still cancel here; once the operation started,\n // it finishes, and so does its after-event.\n if (options?.signal?.aborted) {\n throw new PluginError('operation-cancelled', 'actions', `${verb} was cancelled`, {\n cause: options.signal.reason,\n });\n }\n // `operation()` throwing skips the after-event and rethrows: no\n // /DS for a failed save.\n const value = await operation();\n await runDocEventTreeSafe(after, diagnose);\n return value;\n };\n if (verb !== 'print') return body();\n // The print verb holds the print latch for its whole body, so a /WP\n // or /DP script calling doc.print() is suppressed instead of\n // opening a second dialog.\n printLatch.active = true;\n try {\n return await body();\n } finally {\n printLatch.active = false;\n }\n }, options),\n } satisfies Partial<ActionsCapability>,\n };\n}\nexport type ActionsDocumentEvents = ReturnType<typeof createDocumentEvents>;\n","/**\n * The document-open sequence and its latch. The sequence runs the open\n * destination (as a lifecycle GoTo), then the catalog /OpenAction, and only\n * then releases the page-lifecycle barrier, so the first page /O fires after\n * both. It fires once: at the earliest of a UI adapter installing or the\n * first user-origin dispatch (`'auto'`), at bringup (`'headless'`), or never\n * (`'off'`, which still releases the barrier). Unless it is off, it runs\n * before the first verb-shaped document event (/WS, /WP, /WC, …).\n */\nimport type { Unsubscribe } from '@embedpdf/core';\nimport type { PdfActionTree } from '@embedpdf/engine-core/runtime';\n\nimport type {\n ActionContext,\n ActionDiagnostic,\n ActionsCapability,\n ActionStepResult,\n ActionTriggerResult,\n} from '../contract';\nimport type { DispatchCore } from '../dispatch/core';\nimport { foldSteps } from '../dispatch/fold';\nimport type { ActionsServices } from '../services';\nimport type { ActionsPageLifecycle } from './page-lifecycle';\n\nexport function createOpenSequence(\n services: Pick<ActionsServices, 'events' | 'catalog' | 'queue' | 'ports' | 'settings'>,\n { releaseBarrier, resetCascade }: Pick<ActionsPageLifecycle, 'releaseBarrier' | 'resetCascade'>,\n { runAndEmit }: DispatchCore,\n) {\n const { reportDiagnostic, openSequenceCompleted } = services.events;\n /** The `openSequence` setting, read when it decides: it applies until the sequence has run. */\n const mode = () => services.settings.get().openSequence;\n const { readDocumentActions } = services.catalog;\n const { enqueue } = services.queue;\n const ports = services.ports.slots;\n let openFired = false;\n let sawUserActivity = false;\n\n /** The sequence body. Runs inside the queue (through dispatch or the\n * latch's own enqueue); callers guarantee `openFired` was set. */\n const runOpenSequenceOp = async (): Promise<ActionTriggerResult> => {\n const diagnostics: ActionDiagnostic[] = [];\n const steps: ActionStepResult[] = [];\n const openContext: ActionContext = {\n origin: 'lifecycle',\n source: { kind: 'document' },\n event: { scope: 'document', name: 'open' },\n };\n try {\n const snapshot = await readDocumentActions();\n if (snapshot?.openDestination) {\n // The initial view reuses the whole spine (stage's goto executor,\n // policy included) as a synthesized lifecycle goto.\n const tree: PdfActionTree = {\n root: {\n type: 'goto',\n subtype: 'GoTo',\n destination: snapshot.openDestination,\n next: [],\n },\n incomplete: false,\n warningFlags: 0,\n warnings: [],\n };\n steps.push({\n source: { kind: 'document' },\n tree,\n result: await runAndEmit(tree, openContext),\n });\n }\n if (snapshot?.openAction?.root || snapshot?.openAction?.incomplete) {\n steps.push({\n source: { kind: 'document' },\n tree: snapshot.openAction,\n result: await runAndEmit(snapshot.openAction, openContext),\n });\n }\n } catch (error) {\n const diagnostic: ActionDiagnostic = {\n code: 'trigger-failed',\n message: `open sequence failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n diagnostics.push(diagnostic);\n reportDiagnostic(diagnostic, { source: { kind: 'document' } });\n } finally {\n // Release after the document steps, on every path; page-open emission\n // enqueues behind this operation (never awaited here: awaiting our own\n // queue would deadlock).\n releaseBarrier(true);\n }\n const result = foldSteps(steps, diagnostics);\n openSequenceCompleted.emit({ result });\n return result;\n };\n\n /**\n * The catalog /OpenAction never runs after a /WS, /WP or /WC script: before\n * the first verb-shaped document event, an armed but unfired open sequence\n * runs inline (the caller is already inside the queue; `runOpenSequenceOp`\n * never enqueues). It does not wait for the initial page /O: the guarantee\n * is catalog-level.\n */\n const ensureOpenSequenceBeforeDocEvent = async (): Promise<void> => {\n if (openFired || mode() === 'off') return;\n openFired = true;\n await runOpenSequenceOp();\n };\n\n const maybeFireOpenSequence = (): void => {\n if (openFired) return;\n if (mode() === 'off') {\n // The sequence never runs, but feeds must not buffer forever.\n openFired = true;\n releaseBarrier(false);\n return;\n }\n if (!ports.uiAdapter && mode() !== 'headless' && !sawUserActivity) return;\n openFired = true;\n void enqueue(() => runOpenSequenceOp());\n };\n\n const noteUserActivity = (): void => {\n resetCascade();\n if (!sawUserActivity) {\n sawUserActivity = true;\n maybeFireOpenSequence();\n }\n };\n\n /** Claim the one-shot open for a dispatched document-open trigger: false\n * when it already fired (the caller reports a replay). */\n const claim = (): boolean => {\n if (openFired) return false;\n openFired = true;\n return true;\n };\n\n return {\n run: runOpenSequenceOp,\n ensureOpenSequenceBeforeDocEvent,\n noteUserActivity,\n claim,\n /** Arm the latch at bringup: fires immediately for 'headless', releases\n * the barrier for 'off', waits for an adapter or user activity for 'auto'. */\n arm: maybeFireOpenSequence,\n api: {\n setUiAdapter: (adapter): Unsubscribe => {\n ports.uiAdapter = adapter;\n // An adapter arriving is the usual trigger of the open sequence.\n if (adapter) maybeFireOpenSequence();\n return () => {\n // Identity-safe: never wipe a successor installed after us.\n if (ports.uiAdapter === adapter) ports.uiAdapter = null;\n };\n },\n } satisfies Partial<ActionsCapability>,\n };\n}\nexport type ActionsOpenSequence = ReturnType<typeof createOpenSequence>;\n","/**\n * The lifecycle coordinator's page half: the document-open barrier and the\n * cascade budget. The stage owns page truth (it reports through\n * `reportPageState`); this owns when page-lifecycle triggers fire: nothing\n * emits before the document-open sequence has run (or was declared off or\n * headless), and emission is a diff against the last-emitted state, so\n * pre-open motion collapses to one open with no phantom close.\n */\nimport { toPageRef } from '@embedpdf/core';\nimport type { PageObjectNumber } from '@embedpdf/engine-core/runtime';\n\nimport type { DispatchCore } from '../dispatch/core';\nimport type { ActionsHostCapability, PageStateReport } from '../host-contract';\nimport type { ActionsContext, ActionsServices } from '../services';\n\n/** Consecutive programmatic rounds after which page-lifecycle emission is suppressed. */\nconst CASCADE_LIMIT = 8;\n\nexport function createPageLifecycle(\n ctx: ActionsContext,\n { events, settings }: Pick<ActionsServices, 'events' | 'settings'>,\n { dispatch }: DispatchCore,\n) {\n const { reportDiagnostic } = events;\n let barrierOpen = false;\n let bufferedReport: PageStateReport | null = null;\n let lastEmitted: {\n current: PageObjectNumber | null;\n visible: Set<PageObjectNumber>;\n } = {\n current: null,\n visible: new Set(),\n };\n let cascadeRounds = 0;\n\n const emitForReport = (report: PageStateReport): void => {\n if (report.cause === 'user') cascadeRounds = 0;\n const current = report.currentPage === null ? null : report.currentPage.objectNumber;\n const nextVisible = new Set(report.visiblePages.map((page) => page.objectNumber));\n const changedCurrent = current !== lastEmitted.current;\n const leaving = [...lastEmitted.visible].filter(\n (pageObjectNumber) => !nextVisible.has(pageObjectNumber),\n );\n const entering = [...nextVisible].filter(\n (pageObjectNumber) => !lastEmitted.visible.has(pageObjectNumber),\n );\n if (!changedCurrent && leaving.length === 0 && entering.length === 0) return;\n const previousCurrent = lastEmitted.current;\n // Track truth even when suppressed: the budget bounds emission, not state.\n lastEmitted = { current, visible: nextVisible };\n if (report.cause === 'programmatic') {\n cascadeRounds += 1;\n if (cascadeRounds > CASCADE_LIMIT) {\n reportDiagnostic({\n code: 'cascade-budget',\n message: `page-lifecycle emission suppressed: ${cascadeRounds} consecutive programmatic rounds (cap ${CASCADE_LIMIT})`,\n });\n return;\n }\n }\n // Canonical order (ISO leaves the cross-page order unspecified; within a\n // page, planPageSteps holds Table 197's /PO-after-/O and /PC-before-/C):\n // close(previous) → invisible set → visible set → open(current).\n if (changedCurrent && previousCurrent !== null) {\n void dispatch({ scope: 'page', event: 'close', page: toPageRef(previousCurrent) });\n }\n for (const pageObjectNumber of leaving) {\n void dispatch({ scope: 'page', event: 'invisible', page: toPageRef(pageObjectNumber) });\n }\n for (const pageObjectNumber of entering) {\n void dispatch({ scope: 'page', event: 'visible', page: toPageRef(pageObjectNumber) });\n }\n if (changedCurrent && current !== null) {\n void dispatch({ scope: 'page', event: 'open', page: toPageRef(current) });\n }\n };\n\n const reportPageState = (report: PageStateReport): void => {\n if (!report.placed) return;\n if (report.cause === 'user') cascadeRounds = 0;\n if (!barrierOpen) {\n bufferedReport = report; // coalesce: only the latest pre-open state matters\n return;\n }\n emitForReport(report);\n };\n\n const releaseBarrier = (fireFallback: boolean): void => {\n barrierOpen = true;\n const report = bufferedReport;\n bufferedReport = null;\n try {\n if (report) {\n emitForReport(report);\n } else if (fireFallback && settings.get().openSequence === 'headless') {\n // The initial page open falls back to the document's first page only\n // in declared-headless mode (no stage will ever report). In 'auto',\n // the stage report owns the initial open: firing a first-page /O\n // before a restored view reports would be exactly the phantom open\n // the coordinator exists to prevent; a stage-less 'auto' embedder\n // drives page triggers itself or declares headless.\n const first = ctx.document()?.pages[0]?.ref.objectNumber;\n if (first !== undefined) {\n lastEmitted = { current: first, visible: lastEmitted.visible };\n void dispatch({ scope: 'page', event: 'open', page: toPageRef(first) });\n }\n }\n } catch (error) {\n // The barrier is open either way: feeds must never stay buffered.\n reportDiagnostic({\n code: 'trigger-failed',\n message: `barrier release failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n };\n\n return {\n releaseBarrier,\n /** A user gesture resets the programmatic-cascade counter. */\n resetCascade: (): void => {\n cascadeRounds = 0;\n },\n api: { reportPageState } satisfies Partial<ActionsHostCapability>,\n };\n}\nexport type ActionsPageLifecycle = ReturnType<typeof createPageLifecycle>;\n","/**\n * Script world building (a page-scoped prefetch: the form as the user sees it\n * plus the annotations of the page the action runs on) and the event bridge between\n * two standards: the /AA keys are ISO 32000-2 Table 200; the event names\n * live in the JavaScript API layer (ISO 21757-1, Acrobat).\n */\nimport { scriptFieldsFromSnapshot } from '@embedpdf/core-acrojs';\nimport type {\n ScriptAnnotInput,\n ScriptColorArray,\n ScriptEventInput,\n ScriptWorldInput,\n} from '@embedpdf/core-acrojs';\nimport { pdfRectOf, rgbOf, toPageRef } from '@embedpdf/engine-core/runtime';\nimport type { FormSnapshot, PageObjectNumber } from '@embedpdf/engine-core/runtime';\n\nimport type { ActionContext } from '../contract';\nimport type { ActionsContext, ActionsServices } from '../services';\n\nexport function createScriptWorld(ctx: ActionsContext, { form }: Pick<ActionsServices, 'form'>) {\n // Acrobat's JavaScript keeps colors as color arrays, so they convert here, at its edge.\n const engineColorToArray = (color: string | null | undefined): ScriptColorArray => {\n if (!color) return ['T'];\n const { r, g, b } = rgbOf(color);\n return ['RGB', r / 255, g / 255, b / 255];\n };\n\n const scriptWorldFor = async (\n pageObjectNumber: PageObjectNumber,\n ): Promise<{ snapshot: FormSnapshot; world: Omit<ScriptWorldInput, 'event'> }> => {\n const page = toPageRef(pageObjectNumber);\n const snapshot = await form.read();\n const layout = ctx.getPage(page);\n const pageIndex = Math.max(0, layout?.index ?? -1);\n const { annotations } = await ctx.doc.page(page).annotations.list();\n const annots: ScriptAnnotInput[] = annotations\n // Script-addressable = everything except links and widgets (they are\n // Link and Field objects in Acrobat and separate planes here).\n .filter(\n (annotation) => annotation.subtype !== 'link' && !annotation.subtype.startsWith('widget'),\n )\n .map((annotation) => {\n // Acrobat's JavaScript keeps an annotation's rect in the file's\n // numbers, [x_ll, y_ll, x_ur, y_ur], so it converts here, at its edge.\n const inFile = layout ? pdfRectOf(annotation.rect, layout.pdfCropBox) : null;\n const styled = annotation as unknown as {\n color?: string;\n interiorColor?: string | null;\n opacity?: number;\n strokeWidth?: number;\n borderStyle?: string;\n dashArray?: number[];\n };\n return {\n ref: annotation.ref,\n name: annotation.nm ?? '',\n subtype: annotation.subtype,\n page: pageIndex,\n rect: (inFile\n ? [inFile.left, inFile.bottom, inFile.right, inFile.top]\n : [0, 0, 0, 0]) as [number, number, number, number],\n contents: annotation.contents ?? '',\n author: annotation.author ?? '',\n subject: annotation.subject ?? '',\n strokeColor: engineColorToArray(styled.color),\n fillColor: engineColorToArray(styled.interiorColor),\n opacity: styled.opacity ?? 1,\n width: styled.strokeWidth ?? 1,\n borderStyle: styled.borderStyle === 'dashed' ? ('D' as const) : ('S' as const),\n dash: styled.dashArray ?? [],\n hidden: annotation.hidden,\n print: annotation.print,\n readOnly: annotation.readOnly,\n locked: annotation.locked,\n noView: annotation.noView,\n toggleNoView: annotation.toggleNoView,\n opaqueBody: annotation.subtype === 'stamp',\n };\n });\n return {\n snapshot,\n world: {\n fields: scriptFieldsFromSnapshot(snapshot),\n annots,\n annotPages: [pageIndex],\n annotsCoverDocument: (ctx.document()?.pageCount ?? 0) <= 1,\n },\n };\n };\n\n const ANNOTATION_EVENT_NAMES: Record<string, string> = {\n cursorEnter: 'Mouse Enter',\n cursorExit: 'Mouse Exit',\n mouseDown: 'Mouse Down',\n mouseUp: 'Mouse Up',\n focus: 'Focus',\n blur: 'Blur',\n };\n const PAGE_EVENT_NAMES: Record<string, string> = {\n open: 'Open',\n close: 'Close',\n // /PV and /PI have no Acrobat event name: these two are an EmbedPDF extension.\n visible: 'Visible',\n invisible: 'Invisible',\n };\n // The /AA keys are ISO 32000-2 Table 200; the event names live in the\n // JavaScript API layer (ISO 21757-1, Acrobat).\n const DOC_EVENT_NAMES: Record<string, string> = {\n open: 'Open',\n 'will-save': 'WillSave',\n 'did-save': 'DidSave',\n 'will-print': 'WillPrint',\n 'did-print': 'DidPrint',\n 'will-close': 'WillClose',\n };\n\n const scriptEventFor = (\n actionContext: ActionContext,\n snapshot: FormSnapshot,\n ): ScriptEventInput => {\n const provenance = actionContext.event;\n const type =\n provenance.scope === 'page'\n ? 'Page'\n : provenance.scope === 'document'\n ? 'Doc'\n : actionContext.source.kind === 'widget'\n ? 'Field'\n : actionContext.source.kind === 'link'\n ? 'Link'\n : 'Annot'; // EmbedPDF extension — Acrobat has no plain-annot type\n const name =\n provenance.scope === 'activate'\n ? 'Mouse Up'\n : provenance.scope === 'annotation'\n ? (ANNOTATION_EVENT_NAMES[provenance.name] ?? 'Mouse Up')\n : provenance.scope === 'page'\n ? (PAGE_EVENT_NAMES[provenance.name] ?? 'Open')\n : (DOC_EVENT_NAMES[provenance.name] ?? 'Open');\n const targetRef =\n actionContext.source.kind === 'widget' ? actionContext.source.field : undefined;\n const targetField = targetRef\n ? snapshot.fields.find((field) =>\n targetRef.kind === 'objectNumber' && field.ref.kind === 'objectNumber'\n ? field.ref.objectNumber === targetRef.objectNumber\n : targetRef.kind === 'fqn' && field.name === targetRef.name,\n )\n : undefined;\n return {\n kind: 'widget-activate',\n type,\n name,\n ...(targetRef ? { target: targetRef, source: targetRef } : {}),\n ...(targetField && targetField.valueEntry.kind === 'scalar'\n ? { value: targetField.valueEntry.value }\n : {}),\n };\n };\n\n return { scriptWorldFor, scriptEventFor };\n}\n","/**\n * The `javascript` executor: one node is one host transaction with prefetch →\n * boot (once) → run → commit → surface inside the boundary. Print and submit\n * effects are external: replayed after the transaction releases, still inside\n * the queued dispatch operation.\n */\nimport type { ScriptOutput, ScriptUiEffect } from '@embedpdf/core-acrojs';\n\nimport type {\n ActionDiagnostic,\n ActionNodeStatus,\n ActionOrigin,\n ActionsScriptEnvironment,\n} from '../contract';\nimport type { AnnotCommitEntry } from '../host-contract';\nimport type { ActionsContext, ActionsServices } from '../services';\nimport { intentOfSubmitEffect } from '../submit/intent';\nimport type { ActionsSubmit } from '../submit/perform';\nimport type { ActionsRealm } from './realm';\nimport type { ActionsScriptSurface } from './surface';\nimport { createScriptWorld } from './world';\n\ntype FirePrint = (\n uiContext: { origin: ActionOrigin; phase: 'boot' | 'user' } | undefined,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n) => Promise<{ status: ActionNodeStatus; detail?: string }>;\n\n/** The default cap on JavaScript nodes one dispatch may run. */\nconst DEFAULT_SCRIPT_NODES_PER_DISPATCH = 16;\n\nexport function registerScriptExecutor(\n ctx: ActionsContext,\n services: Pick<ActionsServices, 'events' | 'ports' | 'queue' | 'form'>,\n environment: ActionsScriptEnvironment,\n { scriptHost }: Pick<ActionsRealm, 'scriptHost'>,\n { performSubmit }: ActionsSubmit,\n { surfaceScriptResult }: Pick<ActionsScriptSurface, 'surfaceScriptResult'>,\n documentEvents: { firePrintThroughAdapter: FirePrint },\n): void {\n const { reportDiagnostic } = services.events;\n const ports = services.ports.slots;\n const { budget } = services.queue;\n const { firePrintThroughAdapter } = documentEvents;\n const { scriptWorldFor, scriptEventFor } = createScriptWorld(ctx, services);\n\n /** Commit one run's document effects through the owner sinks in the\n * declared order (form first, then annotations); the first failure skips\n * the rest across both streams. Returns the failure summary, if any. */\n const commitScriptOutput = async (\n output: ScriptOutput,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<string | null> => {\n let failure: string | null = null;\n if (output.formEffects.length > 0) {\n if (!ports.formCommitSink) {\n diagnose({\n code: 'no-commit-sink',\n message: `script form effects dropped: no form commit sink registered (${output.formEffects.length})`,\n });\n } else {\n const result = await ports.formCommitSink(output.formEffects);\n if (result.status === 'failed') failure = `form effects: ${result.error ?? 'failed'}`;\n }\n }\n if (output.annotEffects.length > 0) {\n if (failure) {\n diagnose({\n code: 'executor-failed',\n message: `script annot effects skipped after form failure (${output.annotEffects.length})`,\n });\n } else if (!ports.annotCommitSink) {\n diagnose({\n code: 'no-commit-sink',\n message: `script annot effects dropped: no annotation commit sink registered (${output.annotEffects.length})`,\n });\n } else {\n const entries: AnnotCommitEntry[] = output.annotEffects.map((effect) => ({\n annotObjectNumber: effect.ref.kind === 'objectNumber' ? effect.ref.objectNumber : -1,\n ...(effect.ref.kind === 'objectNumber' ? { page: effect.ref.page } : {}),\n patch: effect.patch,\n }));\n const result = await ports.annotCommitSink(entries);\n const firstFailure = result.results.find((entry) => entry.status === 'failed');\n if (firstFailure)\n failure = `annotation ${firstFailure.annotObjectNumber}: ${firstFailure.error ?? 'failed'}`;\n }\n }\n if (failure) diagnose({ code: 'executor-failed', message: `script commit: ${failure}` });\n return failure;\n };\n\n if (!scriptHost) return;\n const nodeLimit = environment.maxScriptNodesPerDispatch ?? DEFAULT_SCRIPT_NODES_PER_DISPATCH;\n ports.executors.set('javascript', async (node, actionContext) => {\n if (node.type !== 'javascript') return { status: 'inert', reason: 'not a JS node' };\n if (budget.scriptNodes >= nodeLimit) {\n return {\n status: 'inert',\n reason: `dispatch script budget exhausted (${nodeLimit} JS nodes)`,\n };\n }\n budget.scriptNodes += 1;\n const source = actionContext.source;\n const firstPage = ctx.document()?.pages[0]?.ref.objectNumber;\n const pageObjectNumber =\n source.kind === 'widget' || source.kind === 'page'\n ? source.page.objectNumber\n : source.kind === 'link' || source.kind === 'annotation'\n ? (source.page?.objectNumber ?? firstPage)\n : firstPage;\n if (pageObjectNumber === undefined) {\n return { status: 'inert', reason: 'no page to anchor the world on' };\n }\n const diagnose = (diagnostic: ActionDiagnostic): void =>\n reportDiagnostic(diagnostic, { action: 'javascript', source });\n // Print and submit effects are external: the /WP and /DP wrap runs\n // action trees (which may need their own host transactions) and the\n // submit dataset must be resolved from post-commit truth, so both run\n // after the transaction releases, still inside this queued operation.\n const pendingExternal: Array<{\n effect: Extract<ScriptUiEffect, { kind: 'print' | 'submitForm' }>;\n phase: 'boot' | 'user';\n }> = [];\n const splitExternal = (output: ScriptOutput, phase: 'boot' | 'user'): ScriptUiEffect[] =>\n output.uiEffects.filter((effect) => {\n if (effect.kind === 'print' || effect.kind === 'submitForm') {\n pendingExternal.push({ effect, phase });\n return false;\n }\n return true;\n });\n const outcome = await scriptHost.transaction<\n { status: 'executed' } | { status: 'failed'; error: string }\n >(async (transaction) => {\n let built = await scriptWorldFor(pageObjectNumber);\n const boot = await transaction.boot({\n ...built.world,\n event: { kind: 'name-tree-boot', type: 'Doc', name: 'Open' },\n });\n if (boot) {\n // Boot effects belong to this first transaction; a boot fault only\n // degrades, never blocks. Refetch the world afterwards so the run\n // sees post-boot truth.\n await commitScriptOutput(boot, diagnose);\n surfaceScriptResult({\n uiEffects: splitExternal(boot, 'boot'),\n diagnostics: boot.diagnostics,\n ...(boot.error ? { error: boot.error } : {}),\n origin: actionContext.origin,\n phase: 'boot',\n realm: 'document',\n source,\n });\n if (boot.formEffects.length || boot.annotEffects.length) {\n built = await scriptWorldFor(pageObjectNumber);\n }\n }\n const output = await transaction.run(node.script, {\n ...built.world,\n event: scriptEventFor(actionContext, built.snapshot),\n });\n surfaceScriptResult({\n uiEffects: splitExternal(output, 'user'),\n diagnostics: output.diagnostics,\n ...(output.error ? { error: output.error } : {}),\n origin: actionContext.origin,\n phase: 'user',\n realm: 'document',\n source,\n });\n if (output.error) return { status: 'failed', error: output.error.message };\n const failure = await commitScriptOutput(output, diagnose);\n return failure ? { status: 'failed', error: failure } : { status: 'executed' };\n });\n for (const entry of pendingExternal) {\n if (entry.effect.kind === 'print') {\n await firePrintThroughAdapter(\n { origin: actionContext.origin, phase: entry.phase },\n diagnose,\n );\n } else {\n await performSubmit(intentOfSubmitEffect(entry.effect), actionContext, diagnose);\n }\n }\n return outcome;\n });\n}\n","import {\n createScriptHost,\n DEFAULT_SCRIPT_BUDGET,\n resolveScriptIdentity,\n seedFrom,\n type ScriptBudget,\n type ScriptHost,\n} from '@embedpdf/core-acrojs';\nimport type { DocumentHandle } from '@embedpdf/engine-core/runtime';\n\nimport type { ActionsScriptEnvironment, ActionsScriptIdentity } from '../contract';\nimport type { ScriptRealmTarget } from '../host-contract';\n\n/**\n * The scripting environment, the session-level half of the JavaScript\n * switch: sandbox factory, identity, clock, timezone, seed and budget. Policy\n * (`enabled`) decides whether one exists; realms are minted from it.\n *\n * One environment mints any number of realms: the owning document's own\n * host, and detached realms for documents that are not the viewer document\n * (a stamp asset, a template). Every realm gets a fresh sandbox from the\n * factory: the same policy and environment, isolated globals.\n *\n * Identity closes over the owning document: who the user is, is a session\n * fact resolved from the owner's claims plus the `javascript.identity`\n * setting as it is at each run, never from a detached document's\n * (authority-less) handle.\n */\nexport interface ScriptRealmFactory {\n realmFor(target: ScriptRealmTarget): ScriptHost;\n /** The embedder's budget (or the default): the per-run budget every minted\n * realm enforces, and the transaction aggregate consumers apply. */\n readonly budget: ScriptBudget;\n}\n\nexport function createScriptRealmFactory(\n environment: ActionsScriptEnvironment,\n identity: () => ActionsScriptIdentity | undefined,\n identityDoc: DocumentHandle,\n): ScriptRealmFactory {\n const sandboxFactory =\n environment.sandboxFactory ??\n (() =>\n import('@embedpdf/core-js-sandbox').then(({ createQuickJsSandbox }) =>\n createQuickJsSandbox(),\n ));\n const budget = environment.budget ?? DEFAULT_SCRIPT_BUDGET;\n return {\n budget,\n realmFor: (target) =>\n createScriptHost({\n sandboxFactory,\n document: () => {\n const documentInfo = target.document();\n return {\n id: target.doc.id,\n fileName: environment.fileName?.() ?? documentInfo?.name ?? 'document.pdf',\n pageCount: documentInfo?.pageCount ?? 0,\n pageNumber: 0,\n };\n },\n identity: () => resolveScriptIdentity(identityDoc, identity()),\n environment: (sequence) => {\n const nowMs = environment.now?.() ?? Date.now();\n return {\n nowMs,\n utcOffsetMinutes:\n environment.utcOffsetMinutes?.() ?? -new Date(nowMs).getTimezoneOffset(),\n randomSeed: environment.randomSeed?.() ?? seedFrom(target.doc.id, sequence),\n };\n },\n bootSources: target.bootSources,\n budget,\n }),\n };\n}\n","/**\n * The one ScriptHost per document. The `javascript.enabled` setting, as it is\n * when the document opens, decides whether a realm factory exists; the\n * factory carries the session environment and mints this document's own\n * realm here, and detached realms on demand (host lens): one environment, any\n * number of isolated realms.\n */\nimport { javaScriptProgramFromActionTree, type ScriptTransaction } from '@embedpdf/core-acrojs';\n\nimport type { ActionsScriptEnvironment } from '../contract';\nimport type { ActionsHostCapability } from '../host-contract';\nimport type { ActionsContext, ActionsServices } from '../services';\nimport { createScriptRealmFactory } from './environment';\n\nexport function createRealm(\n ctx: ActionsContext,\n { catalog, settings }: Pick<ActionsServices, 'catalog' | 'settings'>,\n environment: ActionsScriptEnvironment,\n) {\n const { readDocumentActions } = catalog;\n const realms = settings.get().javascript.enabled\n ? createScriptRealmFactory(\n environment,\n () => settings.get().javascript.identity ?? undefined,\n ctx.doc,\n )\n : null;\n const scriptHost = realms\n ? realms.realmFor({\n doc: ctx.doc,\n document: () => ctx.document(),\n bootSources: async () => {\n const snapshot = await readDocumentActions();\n return (snapshot?.nameTreeScripts ?? []).map(({ action }) =>\n javaScriptProgramFromActionTree(action),\n );\n },\n })\n : null;\n if (scriptHost) ctx.cleanup(() => scriptHost.dispose());\n\n return {\n scriptHost,\n api: {\n isScriptingEnabled: () => scriptHost !== null,\n ...(scriptHost && realms\n ? {\n scriptRealm: {\n transaction: <T>(body: (transaction: ScriptTransaction) => Promise<T>) =>\n scriptHost.transaction(body),\n budget: realms.budget,\n },\n createDetachedScriptRealm: (target) => {\n const host = realms.realmFor(target);\n return {\n transaction: <T>(body: (transaction: ScriptTransaction) => Promise<T>) =>\n host.transaction(body),\n budget: realms.budget,\n dispose: () => host.dispose(),\n };\n },\n }\n : {}),\n } satisfies Partial<ActionsHostCapability>,\n };\n}\nexport type ActionsRealm = ReturnType<typeof createRealm>;\n","/**\n * The surface door: the one UI and diagnostic port for script results. Print\n * and submitForm effects from the actions plane never reach it (the\n * JavaScript executor extracts them and routes them through\n * `firePrintThroughAdapter` and `performSubmit` after the transaction, since\n * the /WP and /DP wrap and the post-commit dataset must run outside the host\n * transaction). Such effects here come from the form pipeline's K/V/C/F path.\n */\nimport type { ActionOrigin, ActionSource } from '../contract';\nimport type {\n ActionsHostCapability,\n ScriptCommitSurface,\n ScriptRealmKind,\n ScriptSurfaceResult,\n} from '../host-contract';\nimport type { ActionsServices } from '../services';\nimport { intentOfSubmitEffect } from '../submit/intent';\nimport type { ActionsSubmit } from '../submit/perform';\n\nexport function createScriptSurface(\n services: Pick<ActionsServices, 'events' | 'ports' | 'authority' | 'printLatch'>,\n { performSubmit }: ActionsSubmit,\n) {\n const { reportDiagnostic, scriptDiagnosticReported, scriptFailed } = services.events;\n const ports = services.ports.slots;\n const { allowsPrint } = services.authority;\n const printLatch = services.printLatch;\n\n const surfaceScriptResult = (result: ScriptSurfaceResult): void => {\n const uiContext = { origin: result.origin, phase: result.phase };\n const source = result.source ?? null;\n for (const effect of result.uiEffects) {\n // A detached realm has no document surface: the document it scripted\n // is not displayed, and this door's print, goto and submit act on this\n // document. Only alerts have a valid target (the user); everything\n // else is suppressed observably, never routed to the wrong document.\n if (result.realm === 'detached' && effect.kind !== 'alert') {\n scriptDiagnosticReported.emit({\n code: 'ui-effect-suppressed',\n message: `script ${effect.kind} request from a detached realm suppressed: no document surface`,\n });\n continue;\n }\n if (effect.kind === 'submitForm') {\n // A form-pipeline scripted submit: the same door, not awaited (the\n // form queue must not wait on submit sinks). Policy, sinks and\n // diagnostics all live inside performSubmit.\n void performSubmit(\n intentOfSubmitEffect(effect),\n {\n origin: result.origin,\n source: result.source ?? { kind: 'api' },\n event: { scope: 'activate' },\n },\n (diagnostic) => reportDiagnostic(diagnostic, { action: 'javascript', source }),\n );\n continue;\n }\n // Permission, not preference: a print request without doc.print\n // authority reaches no adapter; not overridable, and observable.\n if (effect.kind === 'print' && !allowsPrint()) {\n scriptDiagnosticReported.emit({\n code: 'ui-effect-suppressed',\n message: 'script print request withheld: doc.print is not allowed',\n });\n continue;\n }\n // The print latch: a /WP or /DP script (or anything running while a\n // print wrapper is active) printing again is suppressed, so there is\n // one dialog per outer request.\n if (effect.kind === 'print' && printLatch.active) {\n scriptDiagnosticReported.emit({\n code: 'ui-effect-suppressed',\n message: 'script print request during a document print event — suppressed (reentrant)',\n });\n continue;\n }\n if (!ports.uiAdapter) {\n reportDiagnostic(\n { code: 'no-adapter', message: `script ${effect.kind}: no UI adapter installed` },\n { action: 'javascript', source },\n );\n continue;\n }\n if (effect.kind === 'alert') {\n ports.uiAdapter.alert?.(effect.message, {\n ...uiContext,\n icon: effect.icon,\n ...(effect.title !== undefined ? { title: effect.title } : {}),\n });\n } else if (effect.kind === 'gotoPage') {\n ports.uiAdapter.gotoPage?.(effect.page, uiContext);\n } else {\n ports.uiAdapter.print(uiContext);\n }\n }\n for (const diagnostic of result.diagnostics) scriptDiagnosticReported.emit(diagnostic);\n if (result.error) scriptFailed.emit({ error: result.error, source });\n };\n\n /** A K/V/C/F commit surfaces as up to two results: the boot phase (only\n * when it produced effects) and the user phase (always — it carries the\n * diagnostics and the error). */\n const surfaceScriptCommit = (\n commit: ScriptCommitSurface,\n context: { origin: ActionOrigin; realm: ScriptRealmKind; source?: ActionSource },\n ): void => {\n const phases: Array<'boot' | 'user'> = ['boot', 'user'];\n for (const phase of phases) {\n const uiEffects = commit.uiEffects.filter((effect) => effect.phase === phase);\n if (uiEffects.length === 0 && phase === 'boot') continue;\n surfaceScriptResult({\n uiEffects,\n diagnostics: phase === 'user' ? commit.diagnostics : [],\n ...(phase === 'user' && commit.error ? { error: commit.error } : {}),\n origin: context.origin,\n phase,\n realm: context.realm,\n ...(context.source ? { source: context.source } : {}),\n });\n }\n };\n\n return {\n surfaceScriptResult,\n api: { surfaceScriptResult, surfaceScriptCommit } satisfies Partial<ActionsHostCapability>,\n };\n}\nexport type ActionsScriptSurface = ReturnType<typeof createScriptSurface>;\n","/** Session authority the action plane enforces itself (permission, not preference). */\nimport type { ActionsContext } from './context';\n\nexport function createAuthority(ctx: ActionsContext) {\n const allowsPrint = (): boolean => ctx.allows('doc.print');\n return { allowsPrint };\n}\n","/**\n * The one catalog-actions read. The catalog /AA is immutable in a session (no\n * writer exists in the stack), so the open sequence, the boot sources and the\n * five document events share one memoized read; a rejected read is evicted,\n * so a transient failure cannot poison every later lifecycle event.\n */\nimport type { DocumentActionsSnapshot } from '@embedpdf/engine-core/runtime';\n\nimport type { ActionsContext } from './context';\n\n/** The ISO 32000-2 Table 200 key for each verb-shaped document trigger event. */\nconst DOC_EVENT_TREES = {\n 'will-save': 'willSave',\n 'did-save': 'didSave',\n 'will-print': 'willPrint',\n 'did-print': 'didPrint',\n 'will-close': 'willClose',\n} as const;\n\nexport function createCatalog(ctx: ActionsContext) {\n let snapshotRead: Promise<DocumentActionsSnapshot | null> | null = null;\n const readDocumentActions = (): Promise<DocumentActionsSnapshot | null> => {\n if (!snapshotRead) {\n const service = ctx.doc.actions;\n const read: Promise<DocumentActionsSnapshot | null> = service\n ? Promise.resolve(service.get())\n : Promise.resolve(null);\n const memoized: Promise<DocumentActionsSnapshot | null> = read.catch((error: unknown) => {\n if (snapshotRead === memoized) snapshotRead = null;\n throw error;\n });\n snapshotRead = memoized;\n }\n return snapshotRead;\n };\n return { readDocumentActions, DOC_EVENT_TREES };\n}\nexport type ActionsCatalog = ReturnType<typeof createCatalog>;\n","/** The plugin's events, disposed with it, and the one way a diagnostic is reported. */\nimport type { PdfActionType } from '@embedpdf/engine-core/runtime';\n\nimport type {\n ActionDiagnostic,\n ActionDiagnosticReportedEvent,\n ActionExecutedEvent,\n ActionSource,\n OpenSequenceCompletedEvent,\n ScriptDiagnosticReportedEvent,\n ScriptFailedEvent,\n} from '../contract';\nimport type { ActionsContext } from './context';\n\n/** Which action a diagnostic is about, and what started it, when one is concerned. */\nexport interface DiagnosticPlace {\n readonly action?: PdfActionType | null;\n readonly source?: ActionSource | null;\n}\n\nexport function createEvents(ctx: ActionsContext) {\n const executed = ctx.events.source<ActionExecutedEvent>();\n const diagnosticReported = ctx.events.source<ActionDiagnosticReportedEvent>();\n return {\n executed,\n diagnosticReported,\n scriptDiagnosticReported: ctx.events.source<ScriptDiagnosticReportedEvent>(),\n scriptFailed: ctx.events.source<ScriptFailedEvent>(),\n openSequenceCompleted: ctx.events.source<OpenSequenceCompletedEvent>(),\n /** Fire `onDiagnosticReported` with the action and source it concerns (`null` for none). */\n reportDiagnostic(diagnostic: ActionDiagnostic, place: DiagnosticPlace = {}): void {\n diagnosticReported.emit({\n code: diagnostic.code,\n action: place.action ?? null,\n source: place.source ?? null,\n });\n },\n };\n}\nexport type ActionsEvents = ReturnType<typeof createEvents>;\n","/**\n * The form, as scripts and dispatch read it: the form plugin's view, its fields with this\n * session's pending fills, when it registered one (`registerFormReader`); the engine's\n * otherwise.\n */\nimport type { FormSnapshot } from '@embedpdf/engine-core/runtime';\n\nimport type { ActionsContext } from './context';\nimport type { ActionPorts } from './ports';\n\nexport interface ActionsForm {\n /** The form now. `read` wraps an engine read, so the caller's signal can stop it. */\n read(read?: <T>(task: Promise<T>) => Promise<T>): Promise<FormSnapshot>;\n}\n\nexport function createForm(ctx: ActionsContext, ports: ActionPorts): ActionsForm {\n return {\n read: (read = (task) => task) => {\n const shown = ports.formReader?.();\n return shown ? Promise.resolve(shown) : read(ctx.doc.forms.list());\n },\n };\n}\n","/**\n * The registration slots: every port a sibling or the embedder installs. One\n * owner: the slots live here; areas read them at call time (never captured),\n * and every disposer is identity-safe (it clears a slot only while the\n * registrant is still current). Executors are last-wins. No capability read\n * exposes a slot, so installing one wakes no reader.\n */\nimport type { Unsubscribe } from '@embedpdf/core';\nimport type { PdfActionType } from '@embedpdf/engine-core/runtime';\n\nimport type { ActionExecutor, ActionSubmitHandler, ActionUiAdapter } from '../contract';\nimport type {\n ActionsHostCapability,\n AnnotCommitSink,\n FormCommitSink,\n FormReader,\n SubmitResolver,\n} from '../host-contract';\nimport type { ActionsEvents } from './events';\n\nexport interface ActionPorts {\n readonly executors: Map<PdfActionType, ActionExecutor>;\n annotCommitSink: AnnotCommitSink | null;\n formCommitSink: FormCommitSink | null;\n /** The form plugin's form, as the user sees it. */\n formReader: FormReader | null;\n uiAdapter: ActionUiAdapter | null;\n /** Sink 1 of the submit chain (consent = installation). */\n submitHandler: ActionSubmitHandler | null;\n /** The form plugin's dataset resolver: the one door every submit resolves through. */\n submitResolver: SubmitResolver | null;\n}\n\nexport function createPorts({ reportDiagnostic }: Pick<ActionsEvents, 'reportDiagnostic'>) {\n const ports: ActionPorts = {\n executors: new Map(),\n annotCommitSink: null,\n formCommitSink: null,\n formReader: null,\n uiAdapter: null,\n submitHandler: null,\n submitResolver: null,\n };\n const api = {\n registerExecutor: (type, executor): Unsubscribe => {\n if (ports.executors.has(type)) {\n reportDiagnostic(\n { code: 'duplicate-executor', message: `executor for '${type}' replaced (last-wins)` },\n { action: type },\n );\n }\n ports.executors.set(type, executor);\n return () => {\n if (ports.executors.get(type) === executor) ports.executors.delete(type);\n };\n },\n registerAnnotCommitSink: (sink): Unsubscribe => {\n ports.annotCommitSink = sink;\n return () => {\n if (ports.annotCommitSink === sink) ports.annotCommitSink = null;\n };\n },\n registerFormCommitSink: (sink): Unsubscribe => {\n ports.formCommitSink = sink;\n return () => {\n if (ports.formCommitSink === sink) ports.formCommitSink = null;\n };\n },\n registerFormReader: (reader): Unsubscribe => {\n ports.formReader = reader;\n return () => {\n if (ports.formReader === reader) ports.formReader = null;\n };\n },\n setSubmitHandler: (handler): Unsubscribe => {\n ports.submitHandler = handler;\n // Not an open-sequence release: that stays the UI adapter's role.\n return () => {\n if (ports.submitHandler === handler) ports.submitHandler = null;\n };\n },\n registerSubmitResolver: (resolver): Unsubscribe => {\n ports.submitResolver = resolver;\n return () => {\n if (ports.submitResolver === resolver) ports.submitResolver = null;\n };\n },\n } satisfies Partial<ActionsHostCapability>;\n return { slots: ports, api };\n}\n","/**\n * The document-print latch: while a print wrapper is active\n * (`firePrintThroughAdapter`, `runDocumentVerb('print')`), a nested print\n * request is suppressed (`reentrant-print`), so the adapter opens exactly one\n * dialog per outer request. Read by the script surface, held by the\n * document-events area.\n */\nexport interface PrintLatch {\n active: boolean;\n}\n\nexport const createPrintLatch = (): PrintLatch => ({ active: false });\n","/**\n * The one serial queue every dispatch, verb and open sequence rides, plus the\n * per-operation script budget: the JavaScript nodes run in the current queue\n * operation, reset at every operation boundary and read by the executor, so a\n * /Next chain shares one deterministic cap.\n */\nimport type { ActionsContext } from './context';\n\nexport function createQueue(ctx: ActionsContext) {\n const enqueue = ctx.serialQueue('actions');\n const budget = { scriptNodes: 0 };\n return { enqueue, budget };\n}\nexport type ActionsQueue = ReturnType<typeof createQueue>;\n","/**\n * Plugin-private services every area is built on: the settings, the events,\n * the policy decision, the registration ports, the serial queue, the catalog\n * read, the form, session authority and the print latch.\n */\nimport type { Settings } from '@embedpdf/core';\n\nimport type { ActionsSettings } from '../contract';\nimport { createAuthority } from './authority';\nimport { createCatalog, type ActionsCatalog } from './catalog';\nimport type { ActionsContext } from './context';\nimport { createEvents, type ActionsEvents } from './events';\nimport { createForm, type ActionsForm } from './form';\nimport { createPolicy, type ActionsPolicy } from './policy';\nimport { createPorts } from './ports';\nimport { createPrintLatch, type PrintLatch } from './print-latch';\nimport { createQueue, type ActionsQueue } from './queue';\n\nexport type { ActionsContext } from './context';\n\nexport interface ActionsServices {\n /** The plugin's settings: read `get()` where a setting is used, so a change applies at once. */\n readonly settings: Settings<ActionsSettings>;\n readonly events: ActionsEvents;\n readonly policy: ActionsPolicy;\n readonly ports: ReturnType<typeof createPorts>;\n readonly queue: ActionsQueue;\n readonly catalog: ActionsCatalog;\n /** The form scripts and dispatch read: the form plugin's view, else the engine's. */\n readonly form: ActionsForm;\n readonly authority: ReturnType<typeof createAuthority>;\n readonly printLatch: PrintLatch;\n}\n\nexport function createServices(ctx: ActionsContext): ActionsServices {\n const events = createEvents(ctx);\n const ports = createPorts(events);\n return {\n settings: ctx.settings(),\n events,\n policy: createPolicy(ctx),\n ports,\n queue: createQueue(ctx),\n catalog: createCatalog(ctx),\n form: createForm(ctx, ports.slots),\n authority: createAuthority(ctx),\n printLatch: createPrintLatch(),\n };\n}\n","/**\n * The submit pipeline: one intent, one resolver, one sink chain. Both submit\n * sources (a SubmitForm node, a script `doc.submitForm()`) land in\n * `performSubmit` after policy. Never a network call from this plugin.\n */\nimport type {\n ActionContext,\n ActionDiagnostic,\n ActionNodeStatus,\n ActionsScriptEnvironment,\n ActionSubmitRequest,\n SubmitIntent,\n} from '../contract';\nimport type { ActionsContext, ActionsServices } from '../services';\nimport { toFormSubmissionRequest } from './intent';\n\nexport function createSubmit(\n ctx: ActionsContext,\n services: Pick<ActionsServices, 'policy' | 'ports' | 'events'>,\n environment: ActionsScriptEnvironment,\n) {\n const policy = services.policy;\n const ports = services.ports.slots;\n const { reportDiagnostic } = services.events;\n const nowMs = (): number => environment.now?.() ?? Date.now();\n\n /**\n * The one submit door. Sink order: the embedder handler (explicit beats\n * ambient; its promise is not awaited) → the document's home\n * (`doc.forms.submit`, engine-asserted and awaited: a real operation with a\n * real receipt) → blocked with `no-submit-sink`.\n */\n const performSubmit = async (\n intent: SubmitIntent,\n actionContext: ActionContext,\n diagnose: (diagnostic: ActionDiagnostic) => void,\n ): Promise<{ status: ActionNodeStatus; detail?: string }> => {\n const decision = policy.current()['submit-form'][actionContext.origin];\n if (decision !== 'adapter' && decision !== 'allow') {\n // `block` refuses quietly; `report` says so.\n if (decision === 'report') {\n diagnose({\n code: 'blocked',\n message: `submit-form: policy 'report' for origin '${actionContext.origin}'`,\n });\n }\n return { status: 'blocked' };\n }\n if (!ports.submitResolver) {\n diagnose({\n code: 'no-submit-resolver',\n message: 'submit-form: no dataset resolver registered (form plugin missing?)',\n });\n return { status: 'blocked', detail: 'no dataset resolver' };\n }\n let request: ActionSubmitRequest;\n try {\n request = await ports.submitResolver(intent, actionContext, diagnose);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n diagnose({ code: 'executor-failed', message: `submit-form: dataset resolution: ${detail}` });\n return { status: 'failed', detail };\n }\n const forms = ctx.doc.forms;\n const homeSubmit =\n typeof forms.submit === 'function'\n ? () =>\n Promise.resolve(\n forms.submit!(toFormSubmissionRequest(request, new Date(nowMs()).toISOString())),\n )\n : null;\n if (ports.submitHandler) {\n try {\n const outcome = ports.submitHandler(request, { submitToDocumentHome: homeSubmit });\n if (outcome && typeof (outcome as Promise<void>).then === 'function') {\n // Not awaited, by contract: `executed` means \"handed to the\n // embedder\"; a later rejection is a diagnostic, never a rewrite of\n // the node result.\n void (outcome as Promise<void>).catch((error: unknown) => {\n reportDiagnostic(\n {\n code: 'executor-failed',\n message: `submit handler rejected (detached): ${\n error instanceof Error ? error.message : String(error)\n }`,\n },\n { action: 'submit-form', source: actionContext.source },\n );\n });\n }\n return { status: 'executed' };\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n diagnose({ code: 'executor-failed', message: `submit handler threw: ${detail}` });\n return { status: 'failed', detail };\n }\n }\n if (homeSubmit) {\n try {\n await homeSubmit();\n return { status: 'executed' };\n } catch (error) {\n // The engine's refusal (authority, transport) surfaces on the node:\n // enforcement lives at the home's boundary, this only reports it.\n const detail = error instanceof Error ? error.message : String(error);\n diagnose({ code: 'executor-failed', message: `document home refused submit: ${detail}` });\n return { status: 'failed', detail };\n }\n }\n diagnose({\n code: 'no-submit-sink',\n message: 'submit-form: no handler installed and the document has no submit-capable home',\n });\n return { status: 'blocked', detail: 'no submit sink' };\n };\n\n return { performSubmit };\n}\nexport type ActionsSubmit = ReturnType<typeof createSubmit>;\n","/**\n * The actions controller: the composition root. It builds the plugin's\n * services once, wires each area with the services it declares, and\n * assembles the host capability from the areas' API slices. No behavior\n * lives here: every verb and read has a home in `submit/`, `scripting/`,\n * `dispatch/` or `lifecycle/`. The plugin keeps no session state: its rules\n * are its settings, and its live data (ports, queue, latches) are resources\n * of the areas.\n */\nimport { composeApi } from '@embedpdf/core';\n\nimport type { ActionsConfig } from './contract';\nimport type { DispatchCore } from './dispatch/core';\nimport { createDispatcher } from './dispatch/dispatcher';\nimport { createRunner } from './dispatch/run';\nimport { createTriggers } from './dispatch/triggers';\nimport type { ActionsHostCapability } from './host-contract';\nimport { createDocumentEvents } from './lifecycle/document-events';\nimport { createOpenSequence } from './lifecycle/open-sequence';\nimport { createPageLifecycle } from './lifecycle/page-lifecycle';\nimport { registerScriptExecutor } from './scripting/executor';\nimport { createRealm } from './scripting/realm';\nimport { createScriptSurface } from './scripting/surface';\nimport { createServices, type ActionsContext } from './services';\nimport { createSubmit } from './submit/perform';\n\n/**\n * `config` is what the app registered; the settings in it reach the\n * controller through `ctx.settings()`, and only the script environment is\n * read from it here.\n */\nexport function createActionsController(ctx: ActionsContext, config: ActionsConfig = {}) {\n const services = createServices(ctx);\n const { events, ports, settings } = services;\n\n // The lifecycle areas dispatch and run trees through the dispatcher that\n // is assembled last, bound late and explicitly (see `dispatch/core.ts`).\n const core: DispatchCore = {\n dispatch: (trigger) => dispatcher.dispatch(trigger),\n runAndEmit: (tree, actionContext) => dispatcher.runAndEmit(tree, actionContext),\n };\n\n const environment = config.javascript ?? {};\n const submit = createSubmit(ctx, services, environment);\n const realm = createRealm(ctx, services, environment);\n const surface = createScriptSurface(services, submit);\n const pageLifecycle = createPageLifecycle(ctx, services, core);\n const openSequence = createOpenSequence(services, pageLifecycle, core);\n const documentEvents = createDocumentEvents(services, openSequence, core);\n const triggers = createTriggers(ctx, services);\n const runner = createRunner(ctx, services, submit, documentEvents);\n const dispatcher = createDispatcher(\n ctx,\n services,\n runner,\n triggers,\n openSequence,\n documentEvents,\n );\n registerScriptExecutor(ctx, services, environment, realm, submit, surface, documentEvents);\n\n const api: ActionsHostCapability = composeApi('actions', [\n settings.api,\n ports.api,\n realm.api,\n surface.api,\n pageLifecycle.api,\n openSequence.api,\n documentEvents.api,\n dispatcher.api,\n {\n onExecuted: events.executed.on,\n onDiagnosticReported: events.diagnosticReported.on,\n onScriptDiagnosticReported: events.scriptDiagnosticReported.on,\n onScriptFailed: events.scriptFailed.on,\n onOpenSequenceCompleted: events.openSequenceCompleted.on,\n },\n ]);\n\n return {\n api,\n connect() {\n // Confirmed document events of every origin invalidate the per-page\n // lifecycle-annotation cache.\n ctx.listen(ctx.doc.events, (event) => triggers.invalidate(event));\n // Fires the open sequence at once for 'headless', releases the page\n // barrier for 'off', and waits for an adapter or user activity for 'auto'.\n openSequence.arm();\n // The document's save actions (/WS, /DS) run around every download of its file, so\n // what WillSave changes is in the bytes.\n ctx.aroundDownload((read) => documentEvents.api.runDocumentVerb('save', read));\n },\n };\n}\n","/** The settings in what the app registered with `actionsPlugin(config)`. */\nimport type { DeepPartial } from '@embedpdf/core';\n\nimport type { ActionsConfig, ActionsSettings } from './contract';\n\n/** `config` without the script environment, which is no setting: what the settings register. */\nexport function registeredSettings(\n config: ActionsConfig | undefined,\n): DeepPartial<ActionsSettings> | undefined {\n if (!config) return undefined;\n const { javascript } = config;\n return {\n policy: config.policy,\n triggers: config.triggers,\n openSequence: config.openSequence,\n javascript: javascript && { enabled: javascript.enabled, identity: javascript.identity },\n };\n}\n","import { definePlugin } from '@embedpdf/core';\n\nimport { ACTIONS_DEFAULTS, type ActionsConfig } from './contract';\nimport { createActionsController } from './controller';\nimport { ActionsToken } from './host-contract';\nimport { registeredSettings } from './settings';\n\n/**\n * The action engine, the dependency root of the action architecture. It\n * interprets extracted /A and /AA trees; it never detects triggers and never\n * imports another plugin's token: the stage, annotation, link and form\n * plugins optionally depend on it and register their executors and sinks\n * when they connect (the kernel's dependency order creates this plugin\n * first). JavaScript is one registered interpreter among many: Hide,\n * ResetForm, GoTo and Named work with scripting off. Document-scoped and\n * stateless; its settings are what the app registered over\n * {@link ACTIONS_DEFAULTS}.\n */\nexport const actionsPlugin = (config?: ActionsConfig) =>\n definePlugin({\n id: 'actions',\n token: ActionsToken,\n scope: 'document',\n settings: { defaults: ACTIONS_DEFAULTS, registered: registeredSettings(config) },\n create: (ctx) => createActionsController(ctx, config),\n });\n"],"mappings":";;;;;;;;;;;;;;AAkBA,eAAsB,oBACpB,KACA,MACA,MACA,QAA6C,SAAS,MAC/B;CACvB,MAAM,CAAC,aAAa,WAAW,MAAM,QAAQ,IAAI,CAC/C,IAAI,OAAO,mBAAmB,IAC1B,KAAK,IAAI,IAAI,KAAK,IAAI,CAAC,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,MAAM,SAAS,KAAK,WAAW,IAC3E,QAAQ,QAAQ,CAAC,CAAC,GACtB,IAAI,OAAO,gBAAgB,IACvB,KACG,KAAK,IAAI,CAAC,CACV,MAAM,aACL,SAAS,QAAQ,QAAQ,WAAW,OAAO,KAAK,iBAAiB,KAAK,YAAY,CACpF,IACF,QAAQ,QAAQ,CAAC,CAAC,CACxB,CAAC;CACD,OAAO,CAAC,GAAG,aAAa,GAAG,OAAO;AACpC;;;;;;AAOA,eAAsB,eACpB,KACA,MACA,KACA,QAA6C,SAAS,MAC1B;CAC5B,MAAM,MAAM,cAAc,GAAG;CAC7B,MAAM,WAAW,cAA0B,cAAc,UAAU,GAAG,MAAM;CAC5E,IAAI,IAAI,OAAO,gBAAgB,GAAG;EAChC,MAAM,UAAU,MAAM,K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