@hussmartinez/pdf-sdk 0.1.0 → 0.3.0

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.
@@ -1,4 +1,4 @@
1
- import { SdkError, checkFile, coreLimits, createWorkerClient, defineLimits, defineMessages, isSdkError, plural, sdkCoreMessages, withProcessingTime } from "@hussmartinez/sdk-core";
1
+ import { SdkError, applyCommands, checkFile, coreLimits, createAssetsResolver, createErrorHelpers, createHistory, createStore, createWorkerClient, defineLimits, defineMessages, isSdkError, plural, sdkCoreMessages, withProcessingTime } from "@hussmartinez/sdk-core";
2
2
  // src/core/errors/pdf-error.ts
3
3
  var PdfError = class extends SdkError {
4
4
  name = "PdfError";
@@ -7,24 +7,13 @@ function isPdfError(value, code) {
7
7
  return isSdkError(value, code) && value.name === "PdfError";
8
8
  }
9
9
  // src/core/errors/abort.ts
10
- function asPdfError(reason, message = "PDF processing failed.") {
11
- if (reason instanceof PdfError) return reason;
12
- if (isSdkError(reason)) return new PdfError(reason.code, reason.message, {
13
- ...reason.details === void 0 ? {} : { details: reason.details },
14
- cause: reason
15
- });
16
- return new PdfError("PROCESSING_FAILED", message, { cause: reason });
17
- }
18
- function abortError(signal) {
19
- const { reason } = signal;
20
- if (reason instanceof PdfError) return reason;
21
- if (isSdkError(reason)) return asPdfError(reason);
22
- const timedOut = reason instanceof DOMException && reason.name === "TimeoutError";
23
- return new PdfError(timedOut ? "TIMEOUT" : "ABORTED", timedOut ? "The operation timed out." : "The operation was cancelled.", { cause: reason });
24
- }
25
- function throwIfAborted(signal) {
26
- if (signal?.aborted) throw abortError(signal);
27
- }
10
+ var helpers = /* @__PURE__ */ createErrorHelpers(PdfError, {
11
+ fallbackCode: "PROCESSING_FAILED",
12
+ fallbackMessage: "PDF processing failed."
13
+ });
14
+ var asPdfError = helpers.adapt;
15
+ var abortError = helpers.abortError;
16
+ var throwIfAborted = helpers.throwIfAborted;
28
17
  // src/core/errors/pdf-limits.ts
29
18
  var pdfLimitDefinitions = {
30
19
  ...coreLimits,
@@ -87,12 +76,6 @@ function linkDestination(url) {
87
76
  }
88
77
  // src/core/ports/pdf-engine.ts
89
78
  var PDF_MAX_CANVAS_PIXELS = 16777216;
90
- // src/adapters/assets-url.ts
91
- function assetsBase(assetsUrl) {
92
- if (assetsUrl === void 0) return void 0;
93
- const base = new URL(String(assetsUrl), globalThis.location?.href).href;
94
- return base.endsWith("/") ? base : `${base}/`;
95
- }
96
79
  // src/adapters/pdfjs/binary-data.ts
97
80
  var NO_NETWORK_URL = "hm-pdf-no-network:/";
98
81
  function decodeBase64(base64) {
@@ -200,6 +183,20 @@ function settle(host, promise, options) {
200
183
  });
201
184
  });
202
185
  }
186
+ var VERSION_MISMATCH = /The API version "([^"]+)" does not match the Worker version "([^"]+)"/;
187
+ function workerVersionMismatch(error, base) {
188
+ for (let reason = error; reason instanceof Error; reason = reason.cause) {
189
+ const match = VERSION_MISMATCH.exec(reason.message);
190
+ if (match) return new PdfError("WORKER_START_FAILED", "The PDF render worker is another version.", {
191
+ details: {
192
+ asset: base === void 0 ? null : `${base}build/pdf.worker.min.mjs`,
193
+ expected: match[1] ?? null,
194
+ actual: match[2] ?? null
195
+ },
196
+ cause: error
197
+ });
198
+ }
199
+ }
203
200
  function takeBytes(source, transfer) {
204
201
  if (transfer) {
205
202
  const view = source instanceof Uint8Array ? source : new Uint8Array(source);
@@ -213,12 +210,14 @@ function normalizeRotation(rotation) {
213
210
  var clamp = (value) => Math.min(1, Math.max(0, value));
214
211
  var PdfJsEngine = class {
215
212
  #options;
213
+ #asset;
216
214
  #runtime;
217
215
  #host;
218
216
  #documents = /* @__PURE__ */ new Set();
219
217
  #destroyed = false;
220
218
  constructor(options) {
221
219
  this.#options = options;
220
+ this.#asset = options.assetsUrl === void 0 ? void 0 : createAssetsResolver(options.assetsUrl);
222
221
  }
223
222
  async open(source, options = {}) {
224
223
  if (this.#destroyed) throw new PdfError("WORKER_TERMINATED", "The PDF engine was destroyed.");
@@ -259,6 +258,11 @@ var PdfJsEngine = class {
259
258
  return document;
260
259
  } catch (error) {
261
260
  task.destroy().catch(() => {});
261
+ const mismatch = workerVersionMismatch(error, base);
262
+ if (mismatch) {
263
+ host.fail(mismatch);
264
+ throw mismatch;
265
+ }
262
266
  throw error;
263
267
  }
264
268
  }
@@ -285,8 +289,7 @@ var PdfJsEngine = class {
285
289
  return this.#host;
286
290
  }
287
291
  #assetsBase() {
288
- const base = assetsBase(this.#options.assetsUrl);
289
- return base === void 0 ? void 0 : `${base}pdfjs/`;
292
+ return this.#asset?.("pdfjs/");
290
293
  }
291
294
  #cancel(task, host) {
292
295
  const timer = setTimeout(() => host.fail(new PdfError("WORKER_TERMINATED", "The worker was stopped to cancel an operation.")), CANCEL_TIMEOUT);
@@ -458,20 +461,23 @@ var PdfJsDocument = class {
458
461
  };
459
462
  // src/adapters/qpdf/qpdf-processor.ts
460
463
  function createPdfProcessor(options = {}) {
461
- const base = assetsBase(options.assetsUrl);
464
+ const asset = options.assetsUrl === void 0 ? void 0 : createAssetsResolver(options.assetsUrl);
465
+ const workerPath = "processing/processing.worker.js";
462
466
  let client;
463
467
  let destroyed = false;
464
468
  const start = () => {
465
469
  client ??= createWorkerClient({
466
470
  createWorker: () => {
467
- if (base) return new Worker(`${base}processing/processing.worker.js`, {
471
+ if (asset) return new Worker(asset(workerPath), {
468
472
  type: "module",
469
473
  name: "hm-pdf-processing"
470
474
  });
471
475
  if (!inlineWorker) throw new PdfError("WORKER_START_FAILED", "The processing worker hasn't loaded.");
472
476
  return inlineWorker();
473
477
  },
474
- errorClasses: { PdfError }
478
+ errorClasses: { PdfError },
479
+ packageVersion: "0.3.0",
480
+ ...asset ? { workerAsset: asset(workerPath) } : {}
475
481
  });
476
482
  return client;
477
483
  };
@@ -479,7 +485,7 @@ function createPdfProcessor(options = {}) {
479
485
  return {
480
486
  async build(job, options = {}) {
481
487
  if (destroyed) throw new PdfError("WORKER_TERMINATED", "The PDF processor was destroyed.");
482
- if (!base) inlineWorker ??= (await import("../lazy/processing-worker-CxoVSxEZ.js")).createInlineWorker;
488
+ if (!asset) inlineWorker ??= (await import("../lazy/processing-worker-Dy5JQHXJ.js")).createInlineWorker;
483
489
  let outcome;
484
490
  try {
485
491
  outcome = await start().call("build", job, {
@@ -500,21 +506,180 @@ function createPdfProcessor(options = {}) {
500
506
  }
501
507
  };
502
508
  }
503
- // src/core/model/plan.ts
504
- var EMPTY_PLAN = Object.freeze({
505
- pages: Object.freeze([]),
506
- formValues: Object.freeze({})
507
- });
509
+ // src/core/model/portable.ts
510
+ var PDF_POSITION_GRID = 1e6;
511
+ var PDF_MAX_ID_LENGTH = 128;
512
+ var PDF_MAX_FIELD_NAME_LENGTH = 1e3;
513
+ var PDF_MAX_TEXT_LENGTH = 1e4;
514
+ var PDF_MAX_STROKE_POINTS = 1e4;
515
+ function toGrid(fraction) {
516
+ return Math.round(fraction * PDF_POSITION_GRID) / PDF_POSITION_GRID;
517
+ }
518
+ function longerThan(text, max) {
519
+ if (text.length <= max) return false;
520
+ let count = 0;
521
+ for (const _ of text) {
522
+ count += 1;
523
+ if (count > max) return true;
524
+ }
525
+ return false;
526
+ }
508
527
  // src/core/operations/commands.ts
528
+ var Invalid = class extends Error {
529
+ reason;
530
+ constructor(reason, message) {
531
+ super(message);
532
+ this.reason = reason;
533
+ }
534
+ };
535
+ function invalid(reason, message) {
536
+ throw new Invalid(reason, message);
537
+ }
538
+ function malformed(message) {
539
+ return invalid("malformed-command", message);
540
+ }
541
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
542
+ function fields(value, required, what, optional = []) {
543
+ for (const name of Object.keys(value)) if (!required.includes(name) && !optional.includes(name)) malformed(`${what} has no field "${name}"`);
544
+ for (const name of required) if (!Object.hasOwn(value, name)) malformed(`${what} needs "${name}"`);
545
+ }
546
+ var isIndex = (value) => Number.isSafeInteger(value) && value >= 0;
547
+ function checkId(value, what) {
548
+ if (typeof value !== "string" || value === "" || longerThan(value, 128)) malformed(`${what} is text of 1 to 128 code points`);
549
+ return value;
550
+ }
551
+ function checkKeys(value, what) {
552
+ if (!Array.isArray(value) || value.length === 0) malformed(`${what} is a list of page keys`);
553
+ return value.map((key) => checkId(key, "a page key"));
554
+ }
555
+ function checkFraction(value, what) {
556
+ if (typeof value !== "number" || !Number.isFinite(value)) malformed(`${what} is a number`);
557
+ if (value < 0 || value > 1) invalid("outside-page", `${what} is from 0 to 1`);
558
+ return toGrid(value);
559
+ }
560
+ function checkSize(value, what) {
561
+ if (typeof value !== "number" || !Number.isFinite(value)) malformed(`${what} is a number`);
562
+ const size = toGrid(value);
563
+ if (!(size > 0 && size <= 1)) invalid("invalid-size", `${what} is more than 0 and at most 1`);
564
+ return size;
565
+ }
566
+ function checkPoint(value, what) {
567
+ if (!isRecord(value)) malformed(`${what} is an object`);
568
+ fields(value, ["x", "y"], what);
569
+ return {
570
+ x: checkFraction(value.x, `${what}.x`),
571
+ y: checkFraction(value.y, `${what}.y`)
572
+ };
573
+ }
574
+ var COLOR = /^#[0-9a-f]{6}$/;
575
+ function checkColor(value) {
576
+ if (typeof value !== "string") malformed("a colour is text");
577
+ if (!COLOR.test(value)) invalid("invalid-color", "a colour is #rrggbb, in lowercase");
578
+ return value;
579
+ }
580
+ function checkText(value, what) {
581
+ if (typeof value !== "string") malformed(`${what} is text`);
582
+ if (longerThan(value, 1e4)) invalid("text-too-long", `${what} has more than ${PDF_MAX_TEXT_LENGTH} code points`);
583
+ return value;
584
+ }
585
+ function checkAnnotation(value) {
586
+ if (!isRecord(value)) malformed("an annotation is an object");
587
+ const { type } = value;
588
+ if (type === "signature") invalid("unsupported-annotation", "signature annotations can't be edited yet");
589
+ if (type === "pen" || type === "highlight") {
590
+ const stroke = value;
591
+ fields(stroke, [
592
+ "id",
593
+ "type",
594
+ "points",
595
+ "color",
596
+ "width"
597
+ ], "a stroke");
598
+ if (!Array.isArray(stroke.points)) malformed("a stroke's points are a list");
599
+ if (stroke.points.length === 0 || stroke.points.length > 1e4) invalid("too-many-points", `a stroke has 1 to ${PDF_MAX_STROKE_POINTS} points`);
600
+ return {
601
+ id: checkId(stroke.id, "an annotation id"),
602
+ type,
603
+ points: stroke.points.map((point) => checkPoint(point, "a point")),
604
+ color: checkColor(stroke.color),
605
+ width: checkSize(stroke.width, "a stroke's width")
606
+ };
607
+ }
608
+ if (type === "text") {
609
+ const note = value;
610
+ fields(note, [
611
+ "id",
612
+ "type",
613
+ "at",
614
+ "text",
615
+ "size",
616
+ "color"
617
+ ], "a text note");
618
+ return {
619
+ id: checkId(note.id, "an annotation id"),
620
+ type,
621
+ at: checkPoint(note.at, "a text note's position"),
622
+ text: checkText(note.text, "a text note"),
623
+ size: checkSize(note.size, "a text size"),
624
+ color: checkColor(note.color)
625
+ };
626
+ }
627
+ return malformed("an annotation is a pen, highlight or text annotation");
628
+ }
629
+ function checkPageOf(source, pageIndex, pageCount) {
630
+ const count = pageCount(source);
631
+ if (count === void 0) invalid("unknown-source", `the session has no source ${source}`);
632
+ if (pageIndex >= count) invalid("page-out-of-range", `source ${source} has no page index ${pageIndex}`);
633
+ }
634
+ var ROTATIONS = [
635
+ 0,
636
+ 90,
637
+ 180,
638
+ 270
639
+ ];
640
+ var ANGLES = [
641
+ -360,
642
+ -270,
643
+ -180,
644
+ -90,
645
+ 0,
646
+ 90,
647
+ 180,
648
+ 270,
649
+ 360
650
+ ];
651
+ function checkPage(value, pageCount) {
652
+ if (!isRecord(value)) malformed("a page is an object");
653
+ fields(value, [
654
+ "key",
655
+ "source",
656
+ "pageIndex",
657
+ "rotation",
658
+ "annotations"
659
+ ], "a page");
660
+ const key = checkId(value.key, "a page key");
661
+ const source = checkId(value.source, "a source id");
662
+ if (!isIndex(value.pageIndex)) malformed("a page index is a whole number from 0");
663
+ if (!ROTATIONS.includes(value.rotation)) invalid("invalid-rotation", "a page's rotation is 0, 90, 180 or 270");
664
+ if (!Array.isArray(value.annotations)) malformed("a page's annotations are a list");
665
+ checkPageOf(source, value.pageIndex, pageCount);
666
+ const annotations = value.annotations.map(checkAnnotation);
667
+ if (new Set(annotations.map(({ id }) => id)).size !== annotations.length) invalid("duplicate-annotation", `page ${key} has two annotations with one id`);
668
+ return {
669
+ key,
670
+ source,
671
+ pageIndex: value.pageIndex,
672
+ rotation: value.rotation,
673
+ annotations
674
+ };
675
+ }
509
676
  function positions(plan, keys) {
510
- if (keys.length === 0) throw new TypeError("A command needs at least one page.");
511
677
  const wanted = new Set(keys);
512
- if (wanted.size !== keys.length) throw new TypeError("A page appears twice in the command.");
678
+ if (wanted.size !== keys.length) invalid("duplicate-page", "a page appears twice");
513
679
  const found = plan.pages.flatMap((page, index) => wanted.has(page.key) ? [index] : []);
514
680
  if (found.length !== wanted.size) {
515
681
  const known = new Set(plan.pages.map((page) => page.key));
516
- const missing = keys.filter((key) => !known.has(key));
517
- throw new TypeError(`The plan has no page ${missing.join(", ")}.`);
682
+ invalid("unknown-page", `the plan has no page ${keys.filter((key) => !known.has(key)).join(", ")}`);
518
683
  }
519
684
  return found;
520
685
  }
@@ -524,35 +689,82 @@ function withPages(plan, pages) {
524
689
  formValues: plan.formValues
525
690
  };
526
691
  }
527
- function updatePage(plan, key, update) {
528
- const [index] = positions(plan, [key]);
529
- const pages = [...plan.pages];
530
- pages[index] = update(plan.pages[index]);
531
- return withPages(plan, pages);
692
+ function withKey(record, key, value) {
693
+ const entries = Object.entries(record).filter(([name]) => name !== key);
694
+ if (value !== void 0) entries.push([key, value]);
695
+ return Object.fromEntries(entries);
532
696
  }
533
- function applyCommand(plan, command) {
697
+ var COMMAND_FIELDS = {
698
+ "pdf.rotatePages": [[
699
+ "type",
700
+ "pages",
701
+ "angle"
702
+ ], []],
703
+ "pdf.deletePages": [["type", "pages"], []],
704
+ "pdf.restorePages": [["type", "entries"], []],
705
+ "pdf.movePages": [[
706
+ "type",
707
+ "pages",
708
+ "to"
709
+ ], []],
710
+ "pdf.reorderPages": [["type", "order"], []],
711
+ "pdf.insertPages": [[
712
+ "type",
713
+ "source",
714
+ "pageIndexes",
715
+ "at",
716
+ "keys"
717
+ ], []],
718
+ "pdf.setFieldValue": [[
719
+ "type",
720
+ "source",
721
+ "field",
722
+ "value"
723
+ ], []],
724
+ "pdf.addAnnotation": [[
725
+ "type",
726
+ "page",
727
+ "annotation"
728
+ ], ["index"]],
729
+ "pdf.removeAnnotation": [[
730
+ "type",
731
+ "page",
732
+ "id"
733
+ ], []]
734
+ };
735
+ function apply(plan, input, pageCount) {
736
+ if (!isRecord(input)) malformed("a command is an object");
737
+ const { type } = input;
738
+ if (typeof type !== "string") malformed("a command's type is text");
739
+ if (!Object.hasOwn(COMMAND_FIELDS, type)) invalid("unknown-command", `"${type}" isn't a command`);
740
+ const command = input;
741
+ const [required, optional] = COMMAND_FIELDS[command.type];
742
+ fields(command, required, command.type, optional);
534
743
  switch (command.type) {
535
744
  case "pdf.rotatePages": {
536
- const at = new Set(positions(plan, command.pages));
537
- addRotation(0, command.angle);
745
+ const pages = checkKeys(command.pages, "pages");
746
+ const { angle } = command;
747
+ if (typeof angle !== "number") malformed("an angle is a number");
748
+ if (!ANGLES.includes(angle)) invalid("invalid-rotation", "an angle is a multiple of 90 degrees, from -360 to 360");
749
+ const at = new Set(positions(plan, pages));
538
750
  return {
539
- plan: withPages(plan, plan.pages.map((page, index) => at.has(index) ? {
751
+ state: withPages(plan, plan.pages.map((page, index) => at.has(index) ? {
540
752
  ...page,
541
- rotation: addRotation(page.rotation, command.angle)
753
+ rotation: addRotation(page.rotation, angle)
542
754
  } : page)),
543
755
  inverse: {
544
756
  type: "pdf.rotatePages",
545
- pages: command.pages,
546
- angle: -command.angle
757
+ pages,
758
+ angle: 0 - angle
547
759
  }
548
760
  };
549
761
  }
550
762
  case "pdf.deletePages": {
551
- const at = positions(plan, command.pages);
552
- if (at.length === plan.pages.length) throw new RangeError("A document needs at least one page.");
763
+ const at = positions(plan, checkKeys(command.pages, "pages"));
764
+ if (at.length === plan.pages.length) invalid("last-page", "a document keeps one page");
553
765
  const removed = new Set(at);
554
766
  return {
555
- plan: withPages(plan, plan.pages.filter((_, index) => !removed.has(index))),
767
+ state: withPages(plan, plan.pages.filter((_, index) => !removed.has(index))),
556
768
  inverse: {
557
769
  type: "pdf.restorePages",
558
770
  entries: at.map((index) => ({
@@ -563,19 +775,24 @@ function applyCommand(plan, command) {
563
775
  };
564
776
  }
565
777
  case "pdf.restorePages": {
778
+ if (!Array.isArray(command.entries) || command.entries.length === 0) malformed("entries is a list of pages and their positions");
566
779
  const known = new Set(plan.pages.map((page) => page.key));
567
780
  const pages = [...plan.pages];
568
781
  let previous = -1;
569
- for (const { index, page } of command.entries) {
570
- if (known.has(page.key)) throw new TypeError(`The plan already has page ${page.key}.`);
571
- if (!Number.isInteger(index) || index <= previous || index > pages.length) throw new RangeError(`Page ${page.key} can't be restored at position ${index}.`);
782
+ for (const entry of command.entries) {
783
+ if (!isRecord(entry)) malformed("an entry is an object");
784
+ fields(entry, ["index", "page"], "an entry");
785
+ const page = checkPage(entry.page, pageCount);
786
+ const { index } = entry;
787
+ if (!isIndex(index)) malformed("an entry's index is a whole number from 0");
788
+ if (known.has(page.key)) invalid("duplicate-key", `the plan already has page ${page.key}`);
789
+ if (index <= previous || index > pages.length) invalid("invalid-position", `page ${page.key} can't be restored at ${index}`);
572
790
  pages.splice(index, 0, page);
573
791
  known.add(page.key);
574
792
  previous = index;
575
793
  }
576
- if (command.entries.length === 0) throw new TypeError("A command needs at least one page.");
577
794
  return {
578
- plan: withPages(plan, pages),
795
+ state: withPages(plan, pages),
579
796
  inverse: {
580
797
  type: "pdf.deletePages",
581
798
  pages: command.entries.map(({ page }) => page.key)
@@ -583,12 +800,14 @@ function applyCommand(plan, command) {
583
800
  };
584
801
  }
585
802
  case "pdf.movePages": {
586
- const moved = new Set(positions(plan, command.pages));
803
+ const keys = checkKeys(command.pages, "pages");
804
+ if (!isIndex(command.to)) malformed("to is a whole number from 0");
805
+ const moved = new Set(positions(plan, keys));
587
806
  const block = plan.pages.filter((_, index) => moved.has(index));
588
807
  const rest = plan.pages.filter((_, index) => !moved.has(index));
589
- if (!Number.isInteger(command.to) || command.to < 0 || command.to > rest.length) throw new RangeError(`Pages can't be moved to position ${command.to}.`);
808
+ if (command.to > rest.length) invalid("invalid-position", `pages can't be moved to ${command.to}`);
590
809
  return {
591
- plan: withPages(plan, [
810
+ state: withPages(plan, [
592
811
  ...rest.slice(0, command.to),
593
812
  ...block,
594
813
  ...rest.slice(command.to)
@@ -600,10 +819,11 @@ function applyCommand(plan, command) {
600
819
  };
601
820
  }
602
821
  case "pdf.reorderPages": {
822
+ const order = checkKeys(command.order, "order");
603
823
  const byKey = new Map(plan.pages.map((page) => [page.key, page]));
604
- if (command.order.length !== plan.pages.length || new Set(command.order).size !== command.order.length || command.order.some((key) => !byKey.has(key))) throw new TypeError("A new order must list every page of the plan exactly once.");
824
+ if (order.length !== plan.pages.length || new Set(order).size !== order.length || order.some((key) => !byKey.has(key))) invalid("invalid-order", "a new order lists every page of the plan exactly once");
605
825
  return {
606
- plan: withPages(plan, command.order.map((key) => byKey.get(key))),
826
+ state: withPages(plan, order.map((key) => byKey.get(key))),
607
827
  inverse: {
608
828
  type: "pdf.reorderPages",
609
829
  order: plan.pages.map((page) => page.key)
@@ -611,20 +831,25 @@ function applyCommand(plan, command) {
611
831
  };
612
832
  }
613
833
  case "pdf.insertPages": {
614
- const { pageIndexes, keys, at } = command;
615
- if (pageIndexes.length === 0 || keys.length !== pageIndexes.length) throw new TypeError("An insert needs one key for each of at least one page.");
616
- if (!Number.isInteger(at) || at < 0 || at > plan.pages.length) throw new RangeError(`Pages can't be inserted at position ${at}.`);
834
+ const source = checkId(command.source, "a source id");
835
+ const { pageIndexes, at } = command;
836
+ if (!Array.isArray(pageIndexes) || pageIndexes.length === 0 || !pageIndexes.every(isIndex)) malformed("pageIndexes is a list of whole numbers from 0");
837
+ const keys = checkKeys(command.keys, "keys");
838
+ if (!isIndex(at)) malformed("at is a whole number from 0");
839
+ if (keys.length !== pageIndexes.length) invalid("invalid-keys", "an insert needs one key per page");
617
840
  const known = new Set(plan.pages.map((page) => page.key));
618
- if (new Set(keys).size !== keys.length || keys.some((key) => known.has(key))) throw new TypeError("Inserted pages need keys the plan doesn't have.");
841
+ if (new Set(keys).size !== keys.length || keys.some((key) => known.has(key))) invalid("duplicate-key", "inserted pages need new keys, each once");
842
+ if (at > plan.pages.length) invalid("invalid-position", `pages can't be inserted at ${at}`);
843
+ for (const pageIndex of pageIndexes) checkPageOf(source, pageIndex, pageCount);
619
844
  const inserted = pageIndexes.map((pageIndex, index) => ({
620
845
  key: keys[index],
621
- source: command.source,
846
+ source,
622
847
  pageIndex,
623
848
  rotation: 0,
624
849
  annotations: []
625
850
  }));
626
851
  return {
627
- plan: withPages(plan, [
852
+ state: withPages(plan, [
628
853
  ...plan.pages.slice(0, at),
629
854
  ...inserted,
630
855
  ...plan.pages.slice(at)
@@ -636,19 +861,18 @@ function applyCommand(plan, command) {
636
861
  };
637
862
  }
638
863
  case "pdf.setFieldValue": {
639
- const { source, field, value } = command;
640
- const current = plan.formValues[source] ?? {};
864
+ const source = checkId(command.source, "a source id");
865
+ const { field, value } = command;
866
+ if (typeof field !== "string" || field === "") malformed("a field's name is text");
867
+ if (longerThan(field, 1e3)) invalid("field-name-too-long", `a field's name has at most ${PDF_MAX_FIELD_NAME_LENGTH} code points`);
868
+ if (value !== null && typeof value !== "boolean") checkText(value, "a field's value");
869
+ if (pageCount(source) === void 0) invalid("unknown-source", `the session has no source ${source}`);
870
+ const current = Object.hasOwn(plan.formValues, source) ? plan.formValues[source] : {};
641
871
  const previous = Object.hasOwn(current, field) ? current[field] : null;
642
- const next = { ...current };
643
- if (value === null) delete next[field];
644
- else next[field] = value;
645
- const formValues = {
646
- ...plan.formValues,
647
- [source]: next
648
- };
649
- if (Object.keys(next).length === 0) delete formValues[source];
872
+ const next = withKey(current, field, value ?? void 0);
873
+ const formValues = withKey(plan.formValues, source, Object.keys(next).length === 0 ? void 0 : next);
650
874
  return {
651
- plan: {
875
+ state: {
652
876
  pages: plan.pages,
653
877
  formValues
654
878
  },
@@ -661,130 +885,76 @@ function applyCommand(plan, command) {
661
885
  };
662
886
  }
663
887
  case "pdf.addAnnotation": {
664
- const { annotation } = command;
888
+ const key = checkId(command.page, "a page key");
889
+ const annotation = checkAnnotation(command.annotation);
890
+ if (command.index !== void 0 && !isIndex(command.index)) malformed("an annotation's index is a whole number from 0");
891
+ const [at] = positions(plan, [key]);
892
+ const page = plan.pages[at];
893
+ if (page.annotations.some((existing) => existing.id === annotation.id)) invalid("duplicate-annotation", `page ${key} already has annotation ${annotation.id}`);
894
+ const index = command.index ?? page.annotations.length;
895
+ if (index > page.annotations.length) invalid("invalid-position", `the annotation can't go at ${index}`);
896
+ const annotations = [...page.annotations];
897
+ annotations.splice(index, 0, annotation);
898
+ const pages = [...plan.pages];
899
+ pages[at] = {
900
+ ...page,
901
+ annotations
902
+ };
665
903
  return {
666
- plan: updatePage(plan, command.page, (page) => {
667
- if (page.annotations.some((existing) => existing.id === annotation.id)) throw new TypeError(`Page ${page.key} already has annotation ${annotation.id}.`);
668
- const index = command.index ?? page.annotations.length;
669
- if (!Number.isInteger(index) || index < 0 || index > page.annotations.length) throw new RangeError(`The annotation can't go at position ${index}.`);
670
- const annotations = [...page.annotations];
671
- annotations.splice(index, 0, annotation);
672
- return {
673
- ...page,
674
- annotations
675
- };
676
- }),
904
+ state: withPages(plan, pages),
677
905
  inverse: {
678
906
  type: "pdf.removeAnnotation",
679
- page: command.page,
907
+ page: key,
680
908
  id: annotation.id
681
909
  }
682
910
  };
683
911
  }
684
912
  case "pdf.removeAnnotation": {
685
- let removed;
686
- const next = updatePage(plan, command.page, (page) => {
687
- const index = page.annotations.findIndex((annotation) => annotation.id === command.id);
688
- if (index < 0) throw new TypeError(`Page ${page.key} has no annotation ${command.id}.`);
689
- removed = {
690
- annotation: page.annotations[index],
691
- index
692
- };
693
- return {
694
- ...page,
695
- annotations: page.annotations.filter((_, at) => at !== index)
696
- };
697
- });
698
- const { annotation, index } = removed;
913
+ const key = checkId(command.page, "a page key");
914
+ const id = checkId(command.id, "an annotation id");
915
+ const [at] = positions(plan, [key]);
916
+ const page = plan.pages[at];
917
+ const index = page.annotations.findIndex((annotation) => annotation.id === id);
918
+ if (index < 0) invalid("unknown-annotation", `page ${key} has no annotation ${id}`);
919
+ const pages = [...plan.pages];
920
+ pages[at] = {
921
+ ...page,
922
+ annotations: page.annotations.filter((_, place) => place !== index)
923
+ };
699
924
  return {
700
- plan: next,
925
+ state: withPages(plan, pages),
701
926
  inverse: {
702
927
  type: "pdf.addAnnotation",
703
- page: command.page,
704
- annotation,
928
+ page: key,
929
+ annotation: page.annotations[index],
705
930
  index
706
931
  }
707
932
  };
708
933
  }
709
- default: throw new TypeError(`Unknown command ${command.type}.`);
710
934
  }
711
935
  }
712
- function applyCommands(plan, commands) {
713
- let current = plan;
714
- const inverses = [];
715
- for (const command of commands) {
716
- const applied = applyCommand(current, command);
717
- current = applied.plan;
718
- inverses.unshift(applied.inverse);
719
- }
720
- return {
721
- plan: current,
722
- inverses
936
+ function createPdfReducer(pageCount) {
937
+ return (plan, command) => {
938
+ try {
939
+ return apply(plan, command, pageCount);
940
+ } catch (error) {
941
+ if (!(error instanceof Invalid)) throw error;
942
+ throw new PdfError("INVALID_COMMAND", `Invalid command: ${error.message}.`, { details: { reason: error.reason } });
943
+ }
723
944
  };
724
945
  }
725
- // src/core/session/history.ts
726
- var History = class {
727
- #past = [];
728
- #future = [];
729
- #trimmed = false;
730
- get canUndo() {
731
- return this.#past.length > 0;
732
- }
733
- get canRedo() {
734
- return this.#future.length > 0;
735
- }
736
- get trimmed() {
737
- return this.#trimmed;
738
- }
739
- get steps() {
740
- return [...this.#past, ...this.#future];
741
- }
742
- get dropOrder() {
743
- return [...this.#future, ...this.#past];
744
- }
745
- push(step) {
746
- this.#past.push(step);
747
- this.#future = [];
748
- }
749
- undo() {
750
- const step = this.#past.pop();
751
- if (step) this.#future.push(step);
752
- return step;
753
- }
754
- redo() {
755
- const step = this.#future.pop();
756
- if (step) this.#past.push(step);
757
- return step;
758
- }
759
- restore(direction) {
760
- if (direction === "undo") {
761
- const step = this.#future.pop();
762
- if (step) this.#past.push(step);
763
- } else {
764
- const step = this.#past.pop();
765
- if (step) this.#future.push(step);
766
- }
767
- }
768
- drop(count) {
769
- if (count <= 0) return;
770
- const fromFuture = Math.min(count, this.#future.length);
771
- this.#future.splice(0, fromFuture);
772
- this.#past.splice(0, count - fromFuture);
773
- this.#trimmed = true;
774
- }
775
- clear() {
776
- this.#past = [];
777
- this.#future = [];
778
- this.#trimmed = false;
779
- }
780
- };
946
+ // src/core/model/plan.ts
947
+ var EMPTY_PLAN = Object.freeze({
948
+ pages: Object.freeze([]),
949
+ formValues: Object.freeze({})
950
+ });
781
951
  // src/core/session/session.ts
782
952
  function createPdfSession(options) {
783
953
  const { engine } = options;
784
954
  const policy = pdfLimits.resolve(options.filePolicy);
785
- const history = new History();
786
- const listeners = /* @__PURE__ */ new Set();
955
+ const history = createHistory();
787
956
  const sources = /* @__PURE__ */ new Map();
957
+ const reduce = createPdfReducer((id) => sources.get(id)?.pageCount);
788
958
  let plan = EMPTY_PLAN;
789
959
  let status = "empty";
790
960
  let error;
@@ -821,7 +991,7 @@ function createPdfSession(options) {
821
991
  if ([...referenced(history.steps.filter((entry) => kept.has(entry)))].reduce((sum, id) => sum + (sources.get(id)?.byteLength ?? 0), 0) + extra <= maximum) return count;
822
992
  }
823
993
  }
824
- let snapshot = makeSnapshot();
994
+ const store = createStore(makeSnapshot());
825
995
  function sessionWarnings() {
826
996
  const bytes = heldBytes();
827
997
  const sessionWarning = bytes > 0 && bytes >= policy.limits.maxSessionSize.warning ? [{
@@ -857,8 +1027,7 @@ function createPdfSession(options) {
857
1027
  if (currentPage !== void 0 && !keys.has(currentPage)) currentPage = plan.pages[0]?.key;
858
1028
  if (currentPage === void 0 && plan.pages.length > 0) currentPage = plan.pages[0]?.key;
859
1029
  if (navigation && !keys.has(navigation.page)) navigation = void 0;
860
- snapshot = makeSnapshot();
861
- for (const listener of [...listeners]) listener();
1030
+ store.set(makeSnapshot());
862
1031
  }
863
1032
  function emit(event) {
864
1033
  try {
@@ -931,8 +1100,8 @@ function createPdfSession(options) {
931
1100
  };
932
1101
  }
933
1102
  function step(commands) {
934
- const result = applyCommands(plan, commands);
935
- plan = result.plan;
1103
+ const result = applyCommands(reduce, plan, commands);
1104
+ plan = result.state;
936
1105
  history.push({
937
1106
  commands,
938
1107
  inverses: result.inverses
@@ -940,11 +1109,8 @@ function createPdfSession(options) {
940
1109
  collect();
941
1110
  }
942
1111
  return {
943
- getSnapshot: () => snapshot,
944
- subscribe(listener) {
945
- listeners.add(listener);
946
- return () => listeners.delete(listener);
947
- },
1112
+ getSnapshot: store.getSnapshot,
1113
+ subscribe: store.subscribe,
948
1114
  async open(file, callOptions = {}) {
949
1115
  status = "opening";
950
1116
  error = void 0;
@@ -1031,7 +1197,7 @@ function createPdfSession(options) {
1031
1197
  throw reason;
1032
1198
  }
1033
1199
  } catch (reason) {
1034
- if (reason instanceof TypeError || reason instanceof RangeError) throw reason;
1200
+ if (reason instanceof TypeError || reason instanceof RangeError || isPdfError(reason, "INVALID_COMMAND")) throw reason;
1035
1201
  const failure = asPdfError(reason, "The PDF couldn't be inserted.");
1036
1202
  error = failure;
1037
1203
  changed();
@@ -1057,7 +1223,7 @@ function createPdfSession(options) {
1057
1223
  const entry = history.undo();
1058
1224
  if (!entry) return;
1059
1225
  try {
1060
- plan = applyCommands(plan, entry.inverses).plan;
1226
+ plan = applyCommands(reduce, plan, entry.inverses).state;
1061
1227
  } catch (reason) {
1062
1228
  history.restore("undo");
1063
1229
  throw reason;
@@ -1069,7 +1235,7 @@ function createPdfSession(options) {
1069
1235
  const entry = history.redo();
1070
1236
  if (!entry) return;
1071
1237
  try {
1072
- plan = applyCommands(plan, entry.commands).plan;
1238
+ plan = applyCommands(reduce, plan, entry.commands).state;
1073
1239
  } catch (reason) {
1074
1240
  history.restore("redo");
1075
1241
  throw reason;
@@ -1212,6 +1378,9 @@ var pdfMessages = /* @__PURE__ */ defineMessages({
1212
1378
  "errors.TOO_MANY_PAGES": "This document has {actual, number} pages, which is over the {maximum, number}-page limit.",
1213
1379
  "errors.SESSION_TOO_LARGE": "The open documents would use {actual, fileSize}, which is over the {maximum, fileSize} limit. Close a document, or clear the undo history, and try again.",
1214
1380
  "errors.IMAGE_TOO_LARGE": "Some images are too large to show. They're kept unchanged in the document.",
1381
+ "errors.INVALID_COMMAND": "This edit couldn't be made. Please try again.",
1382
+ "errors.INVALID_DOCUMENT": "This project is damaged, or it isn't a PDF project.",
1383
+ "errors.UNSUPPORTED_FORMAT": "This project was saved by a newer version, or by another app. Update the app, and try again.",
1215
1384
  "warnings.maxPages": /* @__PURE__ */ plural("actual", {
1216
1385
  one: "This document has {actual} page. Large documents may be slow.",
1217
1386
  other: "This document has {actual} pages. Large documents may be slow."
@@ -1237,8 +1406,24 @@ var pdfMessages = /* @__PURE__ */ defineMessages({
1237
1406
  one: "Opened a PDF with {count} page.",
1238
1407
  other: "Opened a PDF with {count} pages."
1239
1408
  }),
1240
- "editor.closed": "The PDF was closed."
1409
+ "editor.closed": "The PDF was closed.",
1410
+ "editor.undone": "Undone.",
1411
+ "editor.redone": "Redone.",
1412
+ "editor.rotated": /* @__PURE__ */ plural("count", {
1413
+ one: "Rotated {count} page.",
1414
+ other: "Rotated {count} pages."
1415
+ }),
1416
+ "toolbar.label": "PDF tools",
1417
+ "toolbar.groups.file": "File",
1418
+ "toolbar.groups.history": "History",
1419
+ "toolbar.groups.pages": "Pages",
1420
+ "toolbar.groups.other": "More tools",
1421
+ "tools.open": "Open a PDF",
1422
+ "tools.undo": "Undo",
1423
+ "tools.redo": "Redo",
1424
+ "tools.rotate-left": "Rotate left",
1425
+ "tools.rotate-right": "Rotate right"
1241
1426
  });
1242
- export { PDF_MAX_CANVAS_PIXELS as a, addRotation as c, PdfError as d, isPdfError as f, createPdfJsEngine as i, pdfLimitDefinitions as l, createPdfSession as n, linkDestination as o, createPdfProcessor as r, safeLinkUrl as s, pdfMessages as t, pdfLimits as u };
1427
+ export { PdfError as C, pdfLimits as S, PDF_MAX_CANVAS_PIXELS as _, checkId as a, addRotation as b, isRecord as c, PDF_MAX_STROKE_POINTS as d, PDF_MAX_TEXT_LENGTH as f, createPdfJsEngine as g, createPdfProcessor as h, checkAnnotation as i, PDF_MAX_FIELD_NAME_LENGTH as l, longerThan as m, createPdfSession as n, fields as o, PDF_POSITION_GRID as p, Invalid as r, invalid as s, pdfMessages as t, PDF_MAX_ID_LENGTH as u, linkDestination as v, isPdfError as w, pdfLimitDefinitions as x, safeLinkUrl as y };
1243
1428
 
1244
- //# sourceMappingURL=en-B0u26URn.js.map
1429
+ //# sourceMappingURL=en-CQX26xju.js.map