@embedpdf/plugin-form 3.0.0-next.10 → 3.0.0-next.11

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.
package/dist/index.js CHANGED
@@ -1,9 +1,104 @@
1
- import { createCapabilityToken, definePlugin } from "@embedpdf/core";
2
- import { AnnotationToken, MIN_DRAG, resolveClickPlacement, widgetAppearanceFromProps } from "@embedpdf/plugin-annotation";
3
- import { AnnotationToken as AnnotationToken$1 } from "@embedpdf/plugin-annotation/internal";
4
- import { InteractionToken, samplePointOn } from "@embedpdf/plugin-interaction";
1
+ import { FormScriptingController, createFormScriptingController } from "./scripting.js";
2
+ import { t as FormToken$1 } from "./types-DkQmmcTG.js";
3
+ import { FormToken } from "./contract.js";
4
+ import { createSerialQueue, definePlugin } from "@embedpdf/core";
5
+ import { ActionsToken, createHoverPump } from "@embedpdf/plugin-actions/contract";
6
+ import { ActionsToken as ActionsToken$1 } from "@embedpdf/plugin-actions/contract/host";
7
+ import { AnnotationToken } from "@embedpdf/plugin-annotation/contract";
8
+ import { AnnotationToken as AnnotationToken$1 } from "@embedpdf/plugin-annotation/contract/host";
9
+ import { InteractionToken, samplePointOn } from "@embedpdf/plugin-interaction/contract";
5
10
  import { PermissionDenied } from "@embedpdf/engine-core/runtime";
6
- import { DEFAULT_SCRIPT_BUDGET, javaScriptProgramFromActionTree, scriptFieldsFromSnapshot } from "@embedpdf/core-acrojs";
11
+ import { MIN_DRAG, resolveClickPlacement, widgetAppearanceFromProps } from "@embedpdf/plugin-annotation/authoring";
12
+ //#region src/field-selection.ts
13
+ /**
14
+ * ISO field selection, written ONCE for ResetForm (Tables 241/242) and
15
+ * SubmitForm (Tables 239/240): a NAME target selects the field AND its
16
+ * descendants (FQN dot-prefix — `parent` selects `parent.c1`, the rule the
17
+ * old exact-match resolution violated); an objectNumber target selects that
18
+ * field dictionary. Include mode keeps the selection; exclude mode keeps
19
+ * the complement (a name excludes its subtree the same way it includes
20
+ * it). `targets === null` (the key ABSENT) selects everything and the flag
21
+ * is ignored; `[]` + include selects NOTHING while `[]` + exclude selects
22
+ * everything — presence and emptiness are different states.
23
+ *
24
+ * `listed` reports whether a field was ADDRESSED by the target list
25
+ * (directly or through its subtree) — the "explicitly listed" predicate the
26
+ * submit honesty diagnostics key on.
27
+ */
28
+ const resolveFieldSelection = (all, targets, exclude) => {
29
+ if (targets === null) return {
30
+ selected: [...all],
31
+ listed: () => false
32
+ };
33
+ const names = targets.filter((t) => t.kind === "name").map((t) => t.name);
34
+ const objectNumbers = new Set(targets.filter((t) => t.kind === "objectNumber").map((t) => t.objectNumber));
35
+ const listed = (field) => field.ref.kind === "objectNumber" && objectNumbers.has(field.ref.fieldObjectNumber) || names.some((name) => field.name === name || field.name.startsWith(`${name}.`));
36
+ return {
37
+ selected: exclude ? all.filter((f) => !listed(f)) : all.filter(listed),
38
+ listed
39
+ };
40
+ };
41
+ /**
42
+ * Build the resolved submission dataset from a live field list (Tables
43
+ * 239/240 semantics; pure — the capability supplies a FRESH engine read so
44
+ * no model-lag class exists):
45
+ *
46
+ * - the unconditional **NoExport veto** — even an explicit include cannot
47
+ * override it (diagnosed when explicitly listed, so the veto is
48
+ * observable, silent when swept in implicitly);
49
+ * - **push-buttons and signatures** never contribute entries in v1 —
50
+ * ISO's explicit-pushbutton-`/AP`-in-FDF rule is unrepresentable in the
51
+ * current DTO, so an EXPLICITLY listed one is diagnosed
52
+ * (`submit-entry-unsupported`), never silently dropped;
53
+ * - an **unsupported `/V` shape** is always diagnosed (silent omission
54
+ * would be data loss);
55
+ * - a valueless field becomes a NAME-ONLY entry (`value: null`) only under
56
+ * IncludeNoValueFields, else it is skipped (the ISO default);
57
+ * - values are entry-faithful: scalar → string, array (multi-select list
58
+ * box) → string[]; the submitted name is the fully qualified name.
59
+ */
60
+ const buildSubmitEntries = (fields, intent, diagnose) => {
61
+ const { selected, listed } = resolveFieldSelection(fields, intent.fields, intent.exclude);
62
+ const explicitInclude = intent.fields !== null && !intent.exclude;
63
+ const entries = [];
64
+ for (const field of selected) {
65
+ const explicit = explicitInclude && listed(field);
66
+ if (field.family === "pushbutton" || field.family === "signature") {
67
+ if (explicit) diagnose({
68
+ code: "submit-entry-unsupported",
69
+ message: `submit: '${field.name}' (${field.family}) has no representable submission value in v1 — skipped`
70
+ });
71
+ continue;
72
+ }
73
+ if (field.flags.noExport) {
74
+ if (explicit) diagnose({
75
+ code: "submit-entry-unsupported",
76
+ message: `submit: '${field.name}' carries the NoExport flag — the veto is unconditional (ISO 12.7.6.2), skipped`
77
+ });
78
+ continue;
79
+ }
80
+ const entry = field.valueEntry;
81
+ if (entry.kind === "scalar") entries.push({
82
+ name: field.name,
83
+ value: entry.value
84
+ });
85
+ else if (entry.kind === "array") entries.push({
86
+ name: field.name,
87
+ value: entry.values
88
+ });
89
+ else if (entry.kind === "none") {
90
+ if (intent.includeNoValueFields) entries.push({
91
+ name: field.name,
92
+ value: null
93
+ });
94
+ } else diagnose({
95
+ code: "submit-entry-unsupported",
96
+ message: `submit: '${field.name}' has an unsupported /V shape — skipped (would otherwise be silent data loss)`
97
+ });
98
+ }
99
+ return entries;
100
+ };
101
+ //#endregion
7
102
  //#region src/core/model.ts
8
103
  const fieldKeyOf = (field) => field.fieldObjectNumber > 0 ? `obj:${field.fieldObjectNumber}` : `fqn:${field.name}`;
9
104
  const initialModel = () => ({
@@ -217,507 +312,8 @@ function fillItemForWidget(model, annotObjectNumber) {
217
312
  }
218
313
  //#endregion
219
314
  //#region src/mutationQueue.ts
220
- /** Small promise-tail queue: failures never poison later mutations. */
221
- function createSerialMutationQueue() {
222
- let tail = Promise.resolve();
223
- return (operation) => {
224
- const result = tail.then(operation, operation);
225
- tail = result.then(() => void 0, () => void 0);
226
- return result;
227
- };
228
- }
229
- //#endregion
230
- //#region src/scripting.ts
231
- const refKey = (ref) => ref.kind === "objectNumber" ? `obj:${ref.fieldObjectNumber}` : `fqn:${ref.name}`;
232
- const sameRef = (left, right) => refKey(left) === refKey(right);
233
- const cloneValue = (value) => Array.isArray(value) ? [...value] : value;
234
- const sameValue = (left, right) => Array.isArray(left) && Array.isArray(right) ? left.length === right.length && left.every((value, index) => value === right[index]) : left === right;
235
- function cloneFields(fields) {
236
- return fields.map((field) => ({
237
- ...field,
238
- ref: { ...field.ref },
239
- value: cloneValue(field.value),
240
- defaultValue: cloneValue(field.defaultValue),
241
- ...field.options ? { options: field.options.map((option) => ({ ...option })) } : {}
242
- }));
243
- }
244
- function fieldByRef(fields, ref) {
245
- return fields.find((field) => sameRef(field.ref, ref));
246
- }
247
- function snapshotField(snapshot, ref) {
248
- return snapshot.fields.find((field) => sameRef(field.ref, ref));
249
- }
250
- function scriptValueFromFormValue(field, value) {
251
- if (field.family === "text" && value.type === "text") return value.value;
252
- if ((field.family === "checkbox" || field.family === "radio") && value.type === "toggle") return value.state ?? "Off";
253
- if (field.family === "combobox" && value.type === "choice") return value.values[0] ?? "";
254
- if (field.family === "listbox" && value.type === "choice") return [...value.values];
255
- throw new Error(`Form value type '${value.type}' does not match field family '${field.family}'`);
256
- }
257
- function formValueFromScriptValue(field) {
258
- switch (field.family) {
259
- case "text": return {
260
- type: "text",
261
- value: String(field.value ?? "")
262
- };
263
- case "checkbox":
264
- case "radio": return {
265
- type: "toggle",
266
- state: field.value === null || field.value === void 0 || String(field.value) === "Off" ? null : String(field.value)
267
- };
268
- case "combobox": return {
269
- type: "choice",
270
- values: Array.isArray(field.value) ? field.value.slice(0, 1) : [String(field.value ?? "")]
271
- };
272
- case "listbox": return {
273
- type: "choice",
274
- values: Array.isArray(field.value) ? [...field.value] : [String(field.value ?? "")]
275
- };
276
- default: return null;
277
- }
278
- }
279
- function applyEffects(overlay, effects) {
280
- for (const effect of effects) {
281
- if (effect.kind === "reset") {
282
- for (const ref of effect.refs) {
283
- const field = fieldByRef(overlay.fields, ref);
284
- if (!field) continue;
285
- field.value = cloneValue(field.defaultValue);
286
- overlay.resetKeys.add(refKey(ref));
287
- }
288
- continue;
289
- }
290
- const field = fieldByRef(overlay.fields, effect.ref);
291
- if (!field) continue;
292
- const key = refKey(effect.ref);
293
- if (effect.kind === "setValue") {
294
- field.value = scriptValueFromFormValue(field, effect.value);
295
- overlay.resetKeys.delete(key);
296
- } else if (effect.kind === "setDisplay") field.display = effect.display;
297
- else overlay.appearances.set(key, {
298
- ref: effect.ref,
299
- text: effect.text
300
- });
301
- }
302
- }
303
- function canonicalEffects(overlay) {
304
- const effects = [];
305
- const resets = [];
306
- for (const field of overlay.fields) {
307
- const original = fieldByRef(overlay.original, field.ref);
308
- if (!original) continue;
309
- if (!sameValue(original.value, field.value)) {
310
- const key = refKey(field.ref);
311
- if (overlay.resetKeys.has(key) && sameValue(field.value, field.defaultValue)) resets.push(field.ref);
312
- else {
313
- const value = formValueFromScriptValue(field);
314
- if (value) effects.push({
315
- kind: "setValue",
316
- ref: field.ref,
317
- value
318
- });
319
- }
320
- }
321
- if (original.display !== field.display) effects.push({
322
- kind: "setDisplay",
323
- ref: field.ref,
324
- display: field.display
325
- });
326
- }
327
- if (resets.length > 0) effects.unshift({
328
- kind: "reset",
329
- refs: resets
330
- });
331
- effects.push(...Array.from(overlay.appearances.values(), ({ ref, text }) => ({
332
- kind: "setAppearanceText",
333
- ref,
334
- text
335
- })));
336
- return effects;
337
- }
338
- function scriptError(message) {
339
- return {
340
- kind: "invalid-output",
341
- message
342
- };
343
- }
344
- function utf8Length(value) {
345
- let length = 0;
346
- for (let index = 0; index < value.length; index += 1) {
347
- const code = value.charCodeAt(index);
348
- if (code < 128) length += 1;
349
- else if (code < 2048) length += 2;
350
- else if (code >= 55296 && code <= 56319 && index + 1 < value.length) {
351
- length += 4;
352
- index += 1;
353
- } else length += 3;
354
- }
355
- return length;
356
- }
357
- function seedFrom(documentId, sequence) {
358
- let hash = 2166136261;
359
- for (const char of `${documentId}:${sequence}`) {
360
- hash ^= char.charCodeAt(0);
361
- hash = Math.imul(hash, 16777619);
362
- }
363
- return hash >>> 0;
364
- }
365
- function resolvedIdentity(doc, config) {
366
- const claims = doc.security.identity;
367
- const supplied = typeof config.identity === "function" ? config.identity() : config.identity ?? {};
368
- return {
369
- name: supplied.name ?? claims?.display_name ?? claims?.user_id ?? "",
370
- loginName: supplied.loginName ?? claims?.user_id ?? "",
371
- corporation: supplied.corporation ?? claims?.group_id ?? "",
372
- email: supplied.email ?? ""
373
- };
374
- }
375
- function pageNumberFor(meta, field) {
376
- const pon = field.widgets.find((widget) => widget.pageObjectNumber > 0)?.pageObjectNumber;
377
- if (!meta || pon === void 0) return 0;
378
- const index = meta.pages.findIndex((page) => page.pageObjectNumber === pon);
379
- return Math.max(0, index);
380
- }
381
- function statusFromEffects(result) {
382
- if (result.results.some(({ status }) => status === "failed" || status === "skipped")) return "failed";
383
- if (result.results.some(({ status }) => status === "rejected")) return "failed";
384
- return result.results.some(({ status }) => status === "applied") ? "applied" : "unchanged";
385
- }
386
- var FormScriptingController = class {
387
- constructor(options) {
388
- this.options = options;
389
- this.sandboxPromise = null;
390
- this.booted = false;
391
- this.disposed = false;
392
- this.sequence = 0;
393
- }
394
- dispose() {
395
- if (this.disposed) return;
396
- this.disposed = true;
397
- this.sandboxPromise?.then((sandbox) => sandbox.dispose()).catch(() => void 0);
398
- }
399
- async commit(snapshot, ref, proposed) {
400
- return this.transact(snapshot, ref, proposed);
401
- }
402
- /** Execute one originating widget's activation action (`/A`, including `/Next`). */
403
- async activate(snapshot, ref, action) {
404
- return this.transact(snapshot, ref, void 0, action);
405
- }
406
- /** Run lazy document boot plus the `/CO` chain without a user field change. */
407
- async recalculate(snapshot) {
408
- const target = snapshot.calculationOrder.find((ref) => ref !== null && snapshotField(snapshot, ref) !== void 0) ?? snapshot.fields[0]?.ref;
409
- if (!target) return {
410
- status: "unchanged",
411
- scripted: true,
412
- effectsResult: null,
413
- uiEffects: [],
414
- diagnostics: []
415
- };
416
- return this.transact(snapshot, target);
417
- }
418
- async transact(snapshot, ref, proposed, activation) {
419
- if (this.disposed) throw new Error("Form scripting controller is disposed");
420
- const target = snapshotField(snapshot, ref);
421
- if (!target) return this.failed([], [], scriptError(`Form field '${refKey(ref)}' no longer exists`));
422
- const original = scriptFieldsFromSnapshot(snapshot);
423
- const overlay = {
424
- original,
425
- fields: cloneFields(original),
426
- resetKeys: /* @__PURE__ */ new Set(),
427
- appearances: /* @__PURE__ */ new Map()
428
- };
429
- const targetInput = fieldByRef(overlay.fields, ref);
430
- if (!targetInput) return this.failed([], [], scriptError(`Form field '${refKey(ref)}' has no script view`));
431
- const hasProposedValue = proposed !== void 0;
432
- let proposedValue = cloneValue(targetInput.value);
433
- if (proposed) try {
434
- proposedValue = scriptValueFromFormValue(targetInput, proposed);
435
- } catch (error) {
436
- return this.failed([], [], scriptError(error instanceof Error ? error.message : String(error)));
437
- }
438
- const uiEffects = [];
439
- const diagnostics = [];
440
- const meta = this.options.document();
441
- const nowMs = this.options.config.now?.() ?? Date.now();
442
- const inputBase = {
443
- document: {
444
- id: this.options.doc.id,
445
- fileName: this.options.config.fileName?.() ?? meta?.name ?? this.options.doc.id,
446
- pageCount: meta?.pageCount ?? 0,
447
- pageNumber: pageNumberFor(meta, target)
448
- },
449
- identity: resolvedIdentity(this.options.doc, this.options.config),
450
- environment: {
451
- nowMs,
452
- utcOffsetMinutes: this.options.config.utcOffsetMinutes?.() ?? -new Date(nowMs).getTimezoneOffset(),
453
- randomSeed: this.options.config.randomSeed?.() ?? seedFrom(this.options.doc.id, this.sequence++)
454
- }
455
- };
456
- const budget = this.options.config.budget ?? DEFAULT_SCRIPT_BUDGET;
457
- let executionMs = 0;
458
- let aggregateOutputSize = 0;
459
- const consume = (output, phase) => {
460
- aggregateOutputSize += utf8Length(JSON.stringify(output));
461
- uiEffects.push(...output.uiEffects.map((effect) => ({
462
- ...effect,
463
- phase
464
- })));
465
- diagnostics.push(...output.diagnostics);
466
- if (aggregateOutputSize > budget.maxOutputBytes) return {
467
- kind: "budget",
468
- message: `Form script transaction output exceeded ${budget.maxOutputBytes} bytes`
469
- };
470
- return output.error ?? null;
471
- };
472
- const remainingBudget = () => {
473
- const remaining = budget.maxExecutionMs - executionMs;
474
- return remaining <= 0 ? null : {
475
- ...budget,
476
- maxExecutionMs: remaining
477
- };
478
- };
479
- const run = async (kind, source, input) => {
480
- const remaining = remainingBudget();
481
- if (!remaining) return { error: {
482
- kind: "budget",
483
- message: "Form script transaction timed out"
484
- } };
485
- let output;
486
- try {
487
- const sandbox = await this.sandbox();
488
- const startedAt = Date.now();
489
- output = kind === "boot" ? sandbox.boot(source, input, remaining) : sandbox.run(source, input, remaining);
490
- executionMs += Date.now() - startedAt;
491
- } catch (error) {
492
- return { error: scriptError(error instanceof Error ? error.message : String(error)) };
493
- }
494
- const error = consume(output, kind === "boot" ? "boot" : "user");
495
- return error ? { error } : { output };
496
- };
497
- if (!this.booted) {
498
- this.booted = true;
499
- let sources = [];
500
- let bootError = null;
501
- try {
502
- sources = (this.options.doc.actions ? await this.options.doc.actions.read() : null)?.nameTreeScripts.map(({ action }) => javaScriptProgramFromActionTree(action)) ?? [];
503
- } catch (error) {
504
- bootError = scriptError(error instanceof Error ? error.message : String(error));
505
- }
506
- if (!bootError && sources.length > 0) {
507
- const boot = await run("boot", sources, {
508
- ...inputBase,
509
- fields: overlay.fields,
510
- event: { kind: "name-tree-boot" }
511
- });
512
- if (boot.error) bootError = boot.error;
513
- else applyEffects(overlay, boot.output.formEffects);
514
- }
515
- if (bootError) diagnostics.push({
516
- code: "script-error",
517
- message: `Document boot script failed (continuing without it): ${bootError.message}`
518
- });
519
- }
520
- const bootEffects = canonicalEffects(overlay);
521
- if (activation) {
522
- let program;
523
- try {
524
- program = javaScriptProgramFromActionTree(activation);
525
- } catch (error) {
526
- return this.failed(uiEffects, diagnostics, scriptError(error instanceof Error ? error.message : String(error)));
527
- }
528
- if (program) {
529
- const activated = await run("run", program, {
530
- ...inputBase,
531
- fields: overlay.fields,
532
- event: {
533
- kind: "widget-activate",
534
- target: ref,
535
- source: ref,
536
- value: targetInput.value
537
- }
538
- });
539
- if (activated.error) return this.failed(uiEffects, diagnostics, activated.error);
540
- applyEffects(overlay, activated.output.formEffects);
541
- }
542
- }
543
- if (!activation && hasProposedValue && target.actions?.keystroke && target.family === "text") {
544
- let program;
545
- try {
546
- program = javaScriptProgramFromActionTree(target.actions.keystroke);
547
- } catch (error) {
548
- return this.failed(uiEffects, diagnostics, scriptError(error instanceof Error ? error.message : String(error)));
549
- }
550
- if (program) {
551
- const oldValue = String(targetInput.value ?? "");
552
- const key = await run("run", program, {
553
- ...inputBase,
554
- fields: overlay.fields,
555
- event: {
556
- kind: "field-keystroke",
557
- target: ref,
558
- source: ref,
559
- value: oldValue,
560
- change: String(proposedValue ?? ""),
561
- selStart: 0,
562
- selEnd: oldValue.length,
563
- willCommit: true
564
- }
565
- });
566
- if (key.error) return this.failed(uiEffects, diagnostics, key.error);
567
- if (!key.output.event.rc) return this.finishRejected(bootEffects, uiEffects, diagnostics);
568
- applyEffects(overlay, key.output.formEffects);
569
- const event = key.output.event;
570
- const base = String(event.value ?? "");
571
- proposedValue = base.slice(0, event.selStart) + event.change + base.slice(Math.max(event.selStart, event.selEnd));
572
- }
573
- }
574
- if (!activation && hasProposedValue) {
575
- targetInput.value = cloneValue(proposedValue);
576
- overlay.resetKeys.delete(refKey(ref));
577
- }
578
- if (!activation && hasProposedValue && target.actions?.validate) {
579
- let program;
580
- try {
581
- program = javaScriptProgramFromActionTree(target.actions.validate);
582
- } catch (error) {
583
- return this.failed(uiEffects, diagnostics, scriptError(error instanceof Error ? error.message : String(error)));
584
- }
585
- if (program) {
586
- const validation = await run("run", program, {
587
- ...inputBase,
588
- fields: overlay.fields,
589
- event: {
590
- kind: "field-validate",
591
- target: ref,
592
- source: ref,
593
- value: proposedValue,
594
- willCommit: true
595
- }
596
- });
597
- if (validation.error) return this.failed(uiEffects, diagnostics, validation.error);
598
- if (!validation.output.event.rc) return this.finishRejected(bootEffects, uiEffects, diagnostics);
599
- targetInput.value = cloneValue(validation.output.event.value);
600
- applyEffects(overlay, validation.output.formEffects);
601
- }
602
- }
603
- const formatRefs = !activation && hasProposedValue ? [ref] : [];
604
- for (const calculationRef of activation ? [] : snapshot.calculationOrder) {
605
- if (!calculationRef) continue;
606
- const calculated = snapshotField(snapshot, calculationRef);
607
- const tree = calculated?.actions?.calculate;
608
- if (!calculated || !tree) continue;
609
- let program;
610
- try {
611
- program = javaScriptProgramFromActionTree(tree);
612
- } catch (error) {
613
- return this.failed(uiEffects, diagnostics, scriptError(error instanceof Error ? error.message : String(error)));
614
- }
615
- const calculatedInput = fieldByRef(overlay.fields, calculationRef);
616
- if (program && calculatedInput) {
617
- const calculation = await run("run", program, {
618
- ...inputBase,
619
- fields: overlay.fields,
620
- event: {
621
- kind: "field-calculate",
622
- target: calculationRef,
623
- ...hasProposedValue ? { source: ref } : {},
624
- value: calculatedInput.value
625
- }
626
- });
627
- if (calculation.error) return this.failed(uiEffects, diagnostics, calculation.error);
628
- applyEffects(overlay, calculation.output.formEffects);
629
- }
630
- if (!formatRefs.some((candidate) => sameRef(candidate, calculationRef))) formatRefs.push(calculationRef);
631
- }
632
- for (const formatRef of formatRefs) {
633
- const field = snapshotField(snapshot, formatRef);
634
- const tree = field?.actions?.format;
635
- const overlayField = fieldByRef(overlay.fields, formatRef);
636
- if (!field || !tree || !overlayField) continue;
637
- let program;
638
- try {
639
- program = javaScriptProgramFromActionTree(tree);
640
- } catch (error) {
641
- return this.failed(uiEffects, diagnostics, scriptError(error instanceof Error ? error.message : String(error)));
642
- }
643
- if (!program) continue;
644
- const format = await run("run", program, {
645
- ...inputBase,
646
- fields: overlay.fields,
647
- event: {
648
- kind: "field-format",
649
- target: formatRef,
650
- ...hasProposedValue ? { source: ref } : {},
651
- value: overlayField.value
652
- }
653
- });
654
- if (format.error) return this.failed(uiEffects, diagnostics, format.error);
655
- applyEffects(overlay, format.output.formEffects);
656
- }
657
- const effects = canonicalEffects(overlay);
658
- if (effects.length + uiEffects.length > budget.maxEffects) return this.failed(uiEffects, diagnostics, {
659
- kind: "budget",
660
- message: `Form script transaction exceeded ${budget.maxEffects} effects`
661
- });
662
- if (effects.length === 0) return {
663
- status: "unchanged",
664
- scripted: true,
665
- effectsResult: null,
666
- uiEffects,
667
- diagnostics
668
- };
669
- if (!this.options.doc.forms.applyEffects) return this.failed(uiEffects, diagnostics, scriptError("This engine does not support batched form effects"));
670
- const effectsResult = await this.options.doc.forms.applyEffects(effects);
671
- const status = statusFromEffects(effectsResult);
672
- return {
673
- status,
674
- scripted: true,
675
- effectsResult,
676
- uiEffects,
677
- diagnostics,
678
- ...status === "failed" ? { error: scriptError("One or more native form effects failed") } : {}
679
- };
680
- }
681
- async sandbox() {
682
- this.sandboxPromise ?? (this.sandboxPromise = this.options.sandboxFactory().then((sandbox) => {
683
- if (this.disposed) sandbox.dispose();
684
- return sandbox;
685
- }));
686
- return this.sandboxPromise;
687
- }
688
- failed(uiEffects, diagnostics, error) {
689
- return {
690
- status: "failed",
691
- scripted: true,
692
- effectsResult: null,
693
- uiEffects,
694
- diagnostics,
695
- error
696
- };
697
- }
698
- async finishRejected(bootEffects, uiEffects, diagnostics) {
699
- if (bootEffects.length === 0) return {
700
- status: "rejected",
701
- scripted: true,
702
- effectsResult: null,
703
- uiEffects,
704
- diagnostics
705
- };
706
- if (!this.options.doc.forms.applyEffects) return this.failed(uiEffects, diagnostics, scriptError("Batched form effects are unavailable"));
707
- const effectsResult = await this.options.doc.forms.applyEffects(bootEffects);
708
- if (statusFromEffects(effectsResult) === "failed") return this.failed(uiEffects, diagnostics, scriptError("A name-tree boot effect failed"));
709
- return {
710
- status: "rejected",
711
- scripted: true,
712
- effectsResult,
713
- uiEffects,
714
- diagnostics
715
- };
716
- }
717
- };
718
- function createFormScriptingController(options) {
719
- return new FormScriptingController(options);
720
- }
315
+ /** The core serial queue under its historical form-plugin name. */
316
+ const createSerialMutationQueue = createSerialQueue;
721
317
  //#endregion
722
318
  //#region src/capability.ts
723
319
  /** PDF user-space rect (y-up) → content-space box (y-down, crop-relative). */
@@ -757,29 +353,29 @@ function createFormCapability(ctx, options = {}) {
757
353
  };
758
354
  };
759
355
  const enqueueMutation = createSerialMutationQueue();
760
- const scripting = options.scripting?.enabled && ctx.doc ? createFormScriptingController({
356
+ const actionsHost = ctx.tryGet(ActionsToken$1);
357
+ const scriptPort = actionsHost?.scriptTransaction?.bind(actionsHost) ?? null;
358
+ const scripting = scriptPort && ctx.doc ? createFormScriptingController({
761
359
  doc: ctx.doc,
762
360
  document: () => ctx.document(),
763
- config: options.scripting,
764
- sandboxFactory: options.scripting.sandboxFactory ?? (() => import("@embedpdf/core-js-sandbox").then(({ createQuickJsSandbox }) => createQuickJsSandbox()))
361
+ transaction: scriptPort
765
362
  }) : null;
766
363
  if (scripting) ctx.cleanup(() => scripting.dispose());
767
- let uiEffectProvider = null;
768
- const surfaceScriptingResult = (result) => {
769
- const observe = (callback) => {
770
- if (!callback) return;
771
- try {
772
- callback();
773
- } catch (error) {
774
- globalThis.console?.error("[form] scripting observer failed:", error);
775
- }
776
- };
777
- for (const effect of result.uiEffects) {
778
- observe(options.scripting?.onUiEffect ? () => options.scripting.onUiEffect(effect) : void 0);
779
- observe(uiEffectProvider ? () => uiEffectProvider(effect) : void 0);
364
+ /** Every script surface (UI effects, diagnostics, errors) flows through
365
+ * the actions plugin's ONE port — origin/phase attached (D9). */
366
+ const surfaceViaActions = (result, origin) => {
367
+ if (!actionsHost) return;
368
+ for (const phase of ["boot", "user"]) {
369
+ const uiEffects = result.uiEffects.filter((effect) => effect.phase === phase);
370
+ if (uiEffects.length === 0 && phase === "boot") continue;
371
+ actionsHost.surfaceScriptResult({
372
+ uiEffects,
373
+ diagnostics: phase === "user" ? result.diagnostics : [],
374
+ ...phase === "user" && result.error ? { error: result.error } : {},
375
+ origin,
376
+ phase
377
+ });
780
378
  }
781
- for (const diagnostic of result.diagnostics) observe(options.scripting?.onDiagnostic ? () => options.scripting.onDiagnostic(diagnostic) : void 0);
782
- if (result.error) observe(options.scripting?.onError ? () => options.scripting.onError(result.error) : void 0);
783
379
  };
784
380
  const can = (cap) => ctx.doc?.security.allows(cap) ?? false;
785
381
  let refreshPromise = null;
@@ -860,8 +456,8 @@ function createFormCapability(ctx, options = {}) {
860
456
  const doc = ctx.doc;
861
457
  if (!doc) throw new Error("no document");
862
458
  if (scripting) {
863
- const result = await scripting.commit(await doc.forms.list(), ref, value);
864
- surfaceScriptingResult(result);
459
+ const result = await scripting.commit(ref, value);
460
+ surfaceViaActions(result, "user");
865
461
  if (result.effectsResult !== null) await refresh(true);
866
462
  return result;
867
463
  }
@@ -913,8 +509,7 @@ function createFormCapability(ctx, options = {}) {
913
509
  return annotation?.subtype === "widget" ? annotation.actions?.activate ?? null : null;
914
510
  };
915
511
  const activateWidgetNow = async (key, annotationRef) => {
916
- const doc = ctx.doc;
917
- if (!doc) throw new Error("no document");
512
+ if (!ctx.doc) throw new Error("no document");
918
513
  if (!scripting) return {
919
514
  status: "unchanged",
920
515
  scripted: false,
@@ -930,11 +525,118 @@ function createFormCapability(ctx, options = {}) {
930
525
  uiEffects: [],
931
526
  diagnostics: []
932
527
  };
933
- const result = await scripting.activate(await doc.forms.list(), refKeyOf(key), action);
934
- surfaceScriptingResult(result);
528
+ const result = await scripting.activate(refKeyOf(key), action);
529
+ surfaceViaActions(result, "user");
935
530
  if (result.effectsResult !== null) await refresh(true);
936
531
  return result;
937
532
  };
533
+ const NOT_SCRIPTED = {
534
+ status: "unchanged",
535
+ scripted: false,
536
+ effectsResult: null,
537
+ uiEffects: [],
538
+ diagnostics: []
539
+ };
540
+ /**
541
+ * The shared reset core: one effects batch → refresh → V/C/F
542
+ * recalculation when the transaction port is present. Ridden by BOTH
543
+ * doors — the /ResetForm executor and the public `reset(key)` — so the
544
+ * two can never diverge again (the "reset() asymmetry" fix). `origin` is
545
+ * PRESERVED through recalculation surfacing: a lifecycle/hover ResetForm
546
+ * can no longer launder its alerts into user origin.
547
+ */
548
+ const applyResetBatch = async (refs, origin) => {
549
+ const doc = ctx.doc;
550
+ if (!doc) throw new Error("no document");
551
+ if (!doc.forms.applyEffects) {
552
+ const result = {
553
+ ...NOT_SCRIPTED,
554
+ diagnostics: [{
555
+ code: "unsupported-api",
556
+ message: "this engine has no form-effects batch door"
557
+ }]
558
+ };
559
+ surfaceViaActions(result, origin);
560
+ return result;
561
+ }
562
+ if (refs.length === 0) return NOT_SCRIPTED;
563
+ const effectsResult = await doc.forms.applyEffects([{
564
+ kind: "reset",
565
+ refs
566
+ }]);
567
+ const resetFailed = effectsResult.results.some((entry) => entry.status === "failed" || entry.status === "rejected");
568
+ await refresh(true);
569
+ if (resetFailed) return {
570
+ status: "failed",
571
+ scripted: false,
572
+ effectsResult,
573
+ uiEffects: [],
574
+ diagnostics: []
575
+ };
576
+ let recalc = null;
577
+ if (scripting) {
578
+ recalc = await scripting.recalculate();
579
+ surfaceViaActions(recalc, origin);
580
+ if (recalc.effectsResult !== null) await refresh(true);
581
+ }
582
+ return {
583
+ status: "applied",
584
+ scripted: recalc !== null,
585
+ effectsResult,
586
+ uiEffects: recalc?.uiEffects ?? [],
587
+ diagnostics: recalc?.diagnostics ?? [],
588
+ ...recalc?.error ? { error: recalc.error } : {}
589
+ };
590
+ };
591
+ const resetFormAction = (targets, exclude, origin = "user") => enqueueMutation(async () => {
592
+ const doc = ctx.doc;
593
+ if (!doc) throw new Error("no document");
594
+ const { selected } = resolveFieldSelection((await doc.forms.list()).fields, targets, exclude);
595
+ const resettable = selected.filter((f) => f.family !== "pushbutton" && f.family !== "signature");
596
+ return applyResetBatch(resettable.map((f) => f.ref), origin);
597
+ });
598
+ /**
599
+ * The submit dataset resolver (Phase 4, D7): a FRESH engine read — never
600
+ * the cached model, so no staleness class exists — then the pure ISO
601
+ * builder. Selection/veto/value semantics live in `field-selection.ts`;
602
+ * this door only supplies the live fields and assembles the request.
603
+ */
604
+ const resolveSubmitDataset = async (intent, actionCtx, diagnose) => {
605
+ const doc = ctx.doc;
606
+ if (!doc) throw new Error("no document");
607
+ const snapshot = await doc.forms.list();
608
+ return {
609
+ url: intent.url,
610
+ method: intent.method,
611
+ format: intent.format,
612
+ flagsRaw: intent.flagsRaw,
613
+ ...intent.charSet === void 0 ? {} : { charSet: intent.charSet },
614
+ entries: buildSubmitEntries(snapshot.fields, intent, diagnose),
615
+ origin: actionCtx.origin,
616
+ event: actionCtx.event
617
+ };
618
+ };
619
+ const widgetSource = (key, annotationRef) => ({
620
+ kind: "widget",
621
+ field: refKeyOf(key),
622
+ annotation: annotationRef,
623
+ pon: annotationRef.pageObjectNumber
624
+ });
625
+ /** One shared hover pump (Exit→Enter as one ordered pair; intermediates
626
+ * skipped), created on first use against the resolved actions capability. */
627
+ let widgetPump = null;
628
+ const widgetHoverPump = (actions) => {
629
+ widgetPump ?? (widgetPump = createHoverPump(actions.dispatch));
630
+ return widgetPump;
631
+ };
632
+ const widgetHoverFlags = (annotationRef) => {
633
+ const loaded = annotationHost?.get(annotationRef);
634
+ if (loaded?.subtype !== "widget") return null;
635
+ return {
636
+ enter: Boolean(loaded.actions?.cursorEnter?.root),
637
+ exit: Boolean(loaded.actions?.cursorExit?.root)
638
+ };
639
+ };
938
640
  const nudgeAnnotations = (pons) => {
939
641
  if (!annotationHost) return;
940
642
  for (const pon of new Set(pons)) annotationHost.reloadPage(pon);
@@ -1088,12 +790,27 @@ function createFormCapability(ctx, options = {}) {
1088
790
  key
1089
791
  });
1090
792
  try {
1091
- const result = await doc.forms.reset(refKeyOf(key));
1092
- apply({
1093
- t: "writeDone",
1094
- key,
1095
- field: result.field
1096
- });
793
+ if (doc.forms.applyEffects) {
794
+ const result = await applyResetBatch([refKeyOf(key)], "user");
795
+ if (result.status === "failed") throw new Error(result.effectsResult?.results.find((entry) => entry.status === "failed" || entry.status === "rejected")?.error?.message ?? "reset failed");
796
+ const field = fieldByKey(model(), key);
797
+ if (field) apply({
798
+ t: "writeDone",
799
+ key,
800
+ field
801
+ });
802
+ else apply({
803
+ t: "writeFailed",
804
+ key
805
+ });
806
+ } else {
807
+ const result = await doc.forms.reset(refKeyOf(key));
808
+ apply({
809
+ t: "writeDone",
810
+ key,
811
+ field: result.field
812
+ });
813
+ }
1097
814
  } catch (err) {
1098
815
  apply({
1099
816
  t: "writeFailed",
@@ -1104,9 +821,96 @@ function createFormCapability(ctx, options = {}) {
1104
821
  });
1105
822
  },
1106
823
  commitValue: (ref, value) => enqueueMutation(() => commitValueNow(ref, value)),
1107
- activateWidget: (key, annotationRef) => enqueueMutation(() => activateWidgetNow(key, annotationRef)),
1108
- setUiEffectProvider: (provider) => {
1109
- uiEffectProvider = provider;
824
+ activateWidget: async (key, annotationRef) => {
825
+ const actions = ctx.tryGet(ActionsToken);
826
+ if (actions) {
827
+ const result = await actions.dispatch({
828
+ scope: "activate",
829
+ ref: annotationRef,
830
+ pon: annotationRef.pageObjectNumber,
831
+ source: widgetSource(key, annotationRef)
832
+ });
833
+ if (!(result.status === "inert" && result.steps.length === 0 && result.diagnostics.length === 0)) return {
834
+ kind: "dispatched",
835
+ result
836
+ };
837
+ }
838
+ return {
839
+ kind: "form",
840
+ result: await enqueueMutation(() => activateWidgetNow(key, annotationRef))
841
+ };
842
+ },
843
+ notifyWidgetEvent: (key, annotationRef, event) => {
844
+ const actions = ctx.tryGet(ActionsToken);
845
+ if (!actions) return;
846
+ const source = widgetSource(key, annotationRef);
847
+ if (event === "cursorEnter" || event === "cursorExit") {
848
+ if (event === "cursorExit") {
849
+ widgetHoverPump(actions).hover(null);
850
+ return;
851
+ }
852
+ const flags = widgetHoverFlags(annotationRef);
853
+ if (flags && !flags.enter && !flags.exit) return;
854
+ widgetHoverPump(actions).hover({
855
+ ref: annotationRef,
856
+ pon: annotationRef.pageObjectNumber,
857
+ source,
858
+ ...flags ? { events: flags } : {}
859
+ });
860
+ return;
861
+ }
862
+ actions.dispatch({
863
+ scope: "annotation",
864
+ event,
865
+ ref: annotationRef,
866
+ pon: annotationRef.pageObjectNumber,
867
+ source
868
+ });
869
+ },
870
+ resetFormAction,
871
+ resolveSubmitDataset,
872
+ commitScriptFormEffects: async (effects) => {
873
+ const doc = ctx.doc;
874
+ if (!doc?.forms.applyEffects) return {
875
+ results: effects.map((_, index) => ({
876
+ index,
877
+ status: "failed",
878
+ fields: [],
879
+ changedWidgets: [],
880
+ error: {
881
+ code: "NotSupported",
882
+ message: "no form-effects batch door"
883
+ }
884
+ })),
885
+ changedWidgets: [],
886
+ meta: null
887
+ };
888
+ let result;
889
+ try {
890
+ result = await doc.forms.applyEffects(effects);
891
+ } catch (error) {
892
+ const message = error instanceof Error ? error.message : String(error);
893
+ return {
894
+ results: effects.map((_, index) => ({
895
+ index,
896
+ status: "failed",
897
+ fields: [],
898
+ changedWidgets: [],
899
+ error: {
900
+ code: "Refused",
901
+ message
902
+ }
903
+ })),
904
+ changedWidgets: [],
905
+ meta: null
906
+ };
907
+ }
908
+ await refresh(true);
909
+ if (annotationHost) {
910
+ const pons = new Set(result.changedWidgets.map((widget) => widget.pageObjectNumber).filter((pon) => pon > 0));
911
+ for (const pon of pons) await annotationHost.reloadPage(pon);
912
+ }
913
+ return result;
1110
914
  },
1111
915
  setValue: (ref, value) => enqueueMutation(async () => {
1112
916
  const doc = ctx.doc;
@@ -1365,9 +1169,6 @@ const initialFormState = () => ({ model: initialModel() });
1365
1169
  /** Dumb store: the pure core computes the next model; the shell dispatches it. */
1366
1170
  const formReducer = (state, action) => action.type === "SET_MODEL" ? { model: action.model } : state;
1367
1171
  //#endregion
1368
- //#region src/types.ts
1369
- const FormToken = createCapabilityToken("form");
1370
- //#endregion
1371
1172
  //#region src/form.plugin.ts
1372
1173
  /**
1373
1174
  * The form plugin: the FIELD plane. Document-scoped; requires the
@@ -1382,17 +1183,17 @@ const FormToken = createCapabilityToken("form");
1382
1183
  */
1383
1184
  const formPlugin = (options = {}) => definePlugin({
1384
1185
  id: "form",
1385
- token: FormToken,
1186
+ token: FormToken$1,
1386
1187
  scope: "document",
1387
1188
  requires: [InteractionToken],
1388
- optional: [AnnotationToken],
1189
+ optional: [AnnotationToken, ActionsToken],
1389
1190
  initialState: initialFormState,
1390
1191
  reduce: formReducer,
1391
1192
  capability: (ctx) => createFormCapability(ctx, options),
1392
1193
  effects: registerFormEffects,
1393
1194
  init: (ctx) => {
1394
1195
  const interaction = ctx.get(InteractionToken);
1395
- const form = ctx.get(FormToken);
1196
+ const form = ctx.get(FormToken$1);
1396
1197
  interaction.registerTool({
1397
1198
  id: "form-fill",
1398
1199
  cursor: "default",
@@ -1423,6 +1224,49 @@ const formPlugin = (options = {}) => definePlugin({
1423
1224
  matches: (a) => a.subtype.startsWith("widget"),
1424
1225
  engaged: () => interaction.activeTool()?.enables.has("form-fill") ?? false
1425
1226
  });
1227
+ const actions = ctx.tryGet(ActionsToken$1);
1228
+ if (actions) {
1229
+ ctx.cleanup(actions.registerFormCommitSink((effects) => {
1230
+ const formHost = ctx.tryGet(FormToken$1);
1231
+ if (!formHost) return Promise.resolve({
1232
+ results: effects.map((_, index) => ({
1233
+ index,
1234
+ status: "failed",
1235
+ fields: [],
1236
+ changedWidgets: []
1237
+ })),
1238
+ changedWidgets: [],
1239
+ meta: null
1240
+ });
1241
+ return formHost.commitScriptFormEffects(effects);
1242
+ }));
1243
+ ctx.cleanup(actions.registerSubmitResolver((intent, actionCtx, diagnose) => {
1244
+ const formHost = ctx.tryGet(FormToken$1);
1245
+ if (!formHost) throw new Error("form plugin unavailable");
1246
+ return formHost.resolveSubmitDataset(intent, actionCtx, diagnose);
1247
+ }));
1248
+ ctx.cleanup(actions.registerExecutor("reset-form", async (node, actionCtx) => {
1249
+ if (node.type !== "reset-form") return {
1250
+ status: "inert",
1251
+ reason: "not a reset-form node"
1252
+ };
1253
+ const formHost = ctx.tryGet(FormToken$1);
1254
+ if (!formHost) return {
1255
+ status: "inert",
1256
+ reason: "form plugin unavailable"
1257
+ };
1258
+ const result = await formHost.resetFormAction(node.fields, node.exclude, actionCtx.origin);
1259
+ if (result.status === "failed") return {
1260
+ status: "failed",
1261
+ error: result.error?.message ?? "reset failed"
1262
+ };
1263
+ if (result.effectsResult === null) return {
1264
+ status: "inert",
1265
+ reason: result.diagnostics[0]?.message ?? "reset-form resolved no fields"
1266
+ };
1267
+ return { status: "executed" };
1268
+ }));
1269
+ }
1426
1270
  }
1427
1271
  });
1428
1272
  //#endregion