@hussmartinez/pdf-sdk 0.2.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, createErrorHelpers, createWorkerClient, defineLimits, defineMessages, isSdkError, plural, resolveAssetsBase, 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";
@@ -210,14 +210,14 @@ function normalizeRotation(rotation) {
210
210
  var clamp = (value) => Math.min(1, Math.max(0, value));
211
211
  var PdfJsEngine = class {
212
212
  #options;
213
- #pdfJsBase;
213
+ #asset;
214
214
  #runtime;
215
215
  #host;
216
216
  #documents = /* @__PURE__ */ new Set();
217
217
  #destroyed = false;
218
218
  constructor(options) {
219
219
  this.#options = options;
220
- this.#pdfJsBase = options.assetsUrl === void 0 ? void 0 : `${resolveAssetsBase(options.assetsUrl)}pdfjs/`;
220
+ this.#asset = options.assetsUrl === void 0 ? void 0 : createAssetsResolver(options.assetsUrl);
221
221
  }
222
222
  async open(source, options = {}) {
223
223
  if (this.#destroyed) throw new PdfError("WORKER_TERMINATED", "The PDF engine was destroyed.");
@@ -289,7 +289,7 @@ var PdfJsEngine = class {
289
289
  return this.#host;
290
290
  }
291
291
  #assetsBase() {
292
- return this.#pdfJsBase;
292
+ return this.#asset?.("pdfjs/");
293
293
  }
294
294
  #cancel(task, host) {
295
295
  const timer = setTimeout(() => host.fail(new PdfError("WORKER_TERMINATED", "The worker was stopped to cancel an operation.")), CANCEL_TIMEOUT);
@@ -461,13 +461,14 @@ var PdfJsDocument = class {
461
461
  };
462
462
  // src/adapters/qpdf/qpdf-processor.ts
463
463
  function createPdfProcessor(options = {}) {
464
- const base = options.assetsUrl === void 0 ? void 0 : resolveAssetsBase(options.assetsUrl);
464
+ const asset = options.assetsUrl === void 0 ? void 0 : createAssetsResolver(options.assetsUrl);
465
+ const workerPath = "processing/processing.worker.js";
465
466
  let client;
466
467
  let destroyed = false;
467
468
  const start = () => {
468
469
  client ??= createWorkerClient({
469
470
  createWorker: () => {
470
- if (base) return new Worker(`${base}processing/processing.worker.js`, {
471
+ if (asset) return new Worker(asset(workerPath), {
471
472
  type: "module",
472
473
  name: "hm-pdf-processing"
473
474
  });
@@ -475,8 +476,8 @@ function createPdfProcessor(options = {}) {
475
476
  return inlineWorker();
476
477
  },
477
478
  errorClasses: { PdfError },
478
- packageVersion: "0.2.0",
479
- ...base ? { workerAsset: `${base}processing/processing.worker.js` } : {}
479
+ packageVersion: "0.3.0",
480
+ ...asset ? { workerAsset: asset(workerPath) } : {}
480
481
  });
481
482
  return client;
482
483
  };
@@ -484,7 +485,7 @@ function createPdfProcessor(options = {}) {
484
485
  return {
485
486
  async build(job, options = {}) {
486
487
  if (destroyed) throw new PdfError("WORKER_TERMINATED", "The PDF processor was destroyed.");
487
- if (!base) inlineWorker ??= (await import("../lazy/processing-worker-DU8GEYFs.js")).createInlineWorker;
488
+ if (!asset) inlineWorker ??= (await import("../lazy/processing-worker-Dy5JQHXJ.js")).createInlineWorker;
488
489
  let outcome;
489
490
  try {
490
491
  outcome = await start().call("build", job, {
@@ -505,21 +506,180 @@ function createPdfProcessor(options = {}) {
505
506
  }
506
507
  };
507
508
  }
508
- // src/core/model/plan.ts
509
- var EMPTY_PLAN = Object.freeze({
510
- pages: Object.freeze([]),
511
- formValues: Object.freeze({})
512
- });
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
+ }
513
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
+ }
514
676
  function positions(plan, keys) {
515
- if (keys.length === 0) throw new TypeError("A command needs at least one page.");
516
677
  const wanted = new Set(keys);
517
- 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");
518
679
  const found = plan.pages.flatMap((page, index) => wanted.has(page.key) ? [index] : []);
519
680
  if (found.length !== wanted.size) {
520
681
  const known = new Set(plan.pages.map((page) => page.key));
521
- const missing = keys.filter((key) => !known.has(key));
522
- 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(", ")}`);
523
683
  }
524
684
  return found;
525
685
  }
@@ -529,35 +689,82 @@ function withPages(plan, pages) {
529
689
  formValues: plan.formValues
530
690
  };
531
691
  }
532
- function updatePage(plan, key, update) {
533
- const [index] = positions(plan, [key]);
534
- const pages = [...plan.pages];
535
- pages[index] = update(plan.pages[index]);
536
- 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);
537
696
  }
538
- 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);
539
743
  switch (command.type) {
540
744
  case "pdf.rotatePages": {
541
- const at = new Set(positions(plan, command.pages));
542
- 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));
543
750
  return {
544
- plan: withPages(plan, plan.pages.map((page, index) => at.has(index) ? {
751
+ state: withPages(plan, plan.pages.map((page, index) => at.has(index) ? {
545
752
  ...page,
546
- rotation: addRotation(page.rotation, command.angle)
753
+ rotation: addRotation(page.rotation, angle)
547
754
  } : page)),
548
755
  inverse: {
549
756
  type: "pdf.rotatePages",
550
- pages: command.pages,
551
- angle: -command.angle
757
+ pages,
758
+ angle: 0 - angle
552
759
  }
553
760
  };
554
761
  }
555
762
  case "pdf.deletePages": {
556
- const at = positions(plan, command.pages);
557
- 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");
558
765
  const removed = new Set(at);
559
766
  return {
560
- plan: withPages(plan, plan.pages.filter((_, index) => !removed.has(index))),
767
+ state: withPages(plan, plan.pages.filter((_, index) => !removed.has(index))),
561
768
  inverse: {
562
769
  type: "pdf.restorePages",
563
770
  entries: at.map((index) => ({
@@ -568,19 +775,24 @@ function applyCommand(plan, command) {
568
775
  };
569
776
  }
570
777
  case "pdf.restorePages": {
778
+ if (!Array.isArray(command.entries) || command.entries.length === 0) malformed("entries is a list of pages and their positions");
571
779
  const known = new Set(plan.pages.map((page) => page.key));
572
780
  const pages = [...plan.pages];
573
781
  let previous = -1;
574
- for (const { index, page } of command.entries) {
575
- if (known.has(page.key)) throw new TypeError(`The plan already has page ${page.key}.`);
576
- 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}`);
577
790
  pages.splice(index, 0, page);
578
791
  known.add(page.key);
579
792
  previous = index;
580
793
  }
581
- if (command.entries.length === 0) throw new TypeError("A command needs at least one page.");
582
794
  return {
583
- plan: withPages(plan, pages),
795
+ state: withPages(plan, pages),
584
796
  inverse: {
585
797
  type: "pdf.deletePages",
586
798
  pages: command.entries.map(({ page }) => page.key)
@@ -588,12 +800,14 @@ function applyCommand(plan, command) {
588
800
  };
589
801
  }
590
802
  case "pdf.movePages": {
591
- 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));
592
806
  const block = plan.pages.filter((_, index) => moved.has(index));
593
807
  const rest = plan.pages.filter((_, index) => !moved.has(index));
594
- 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}`);
595
809
  return {
596
- plan: withPages(plan, [
810
+ state: withPages(plan, [
597
811
  ...rest.slice(0, command.to),
598
812
  ...block,
599
813
  ...rest.slice(command.to)
@@ -605,10 +819,11 @@ function applyCommand(plan, command) {
605
819
  };
606
820
  }
607
821
  case "pdf.reorderPages": {
822
+ const order = checkKeys(command.order, "order");
608
823
  const byKey = new Map(plan.pages.map((page) => [page.key, page]));
609
- 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");
610
825
  return {
611
- plan: withPages(plan, command.order.map((key) => byKey.get(key))),
826
+ state: withPages(plan, order.map((key) => byKey.get(key))),
612
827
  inverse: {
613
828
  type: "pdf.reorderPages",
614
829
  order: plan.pages.map((page) => page.key)
@@ -616,20 +831,25 @@ function applyCommand(plan, command) {
616
831
  };
617
832
  }
618
833
  case "pdf.insertPages": {
619
- const { pageIndexes, keys, at } = command;
620
- if (pageIndexes.length === 0 || keys.length !== pageIndexes.length) throw new TypeError("An insert needs one key for each of at least one page.");
621
- 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");
622
840
  const known = new Set(plan.pages.map((page) => page.key));
623
- 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);
624
844
  const inserted = pageIndexes.map((pageIndex, index) => ({
625
845
  key: keys[index],
626
- source: command.source,
846
+ source,
627
847
  pageIndex,
628
848
  rotation: 0,
629
849
  annotations: []
630
850
  }));
631
851
  return {
632
- plan: withPages(plan, [
852
+ state: withPages(plan, [
633
853
  ...plan.pages.slice(0, at),
634
854
  ...inserted,
635
855
  ...plan.pages.slice(at)
@@ -641,19 +861,18 @@ function applyCommand(plan, command) {
641
861
  };
642
862
  }
643
863
  case "pdf.setFieldValue": {
644
- const { source, field, value } = command;
645
- 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] : {};
646
871
  const previous = Object.hasOwn(current, field) ? current[field] : null;
647
- const next = { ...current };
648
- if (value === null) delete next[field];
649
- else next[field] = value;
650
- const formValues = {
651
- ...plan.formValues,
652
- [source]: next
653
- };
654
- 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);
655
874
  return {
656
- plan: {
875
+ state: {
657
876
  pages: plan.pages,
658
877
  formValues
659
878
  },
@@ -666,130 +885,76 @@ function applyCommand(plan, command) {
666
885
  };
667
886
  }
668
887
  case "pdf.addAnnotation": {
669
- 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
+ };
670
903
  return {
671
- plan: updatePage(plan, command.page, (page) => {
672
- if (page.annotations.some((existing) => existing.id === annotation.id)) throw new TypeError(`Page ${page.key} already has annotation ${annotation.id}.`);
673
- const index = command.index ?? page.annotations.length;
674
- if (!Number.isInteger(index) || index < 0 || index > page.annotations.length) throw new RangeError(`The annotation can't go at position ${index}.`);
675
- const annotations = [...page.annotations];
676
- annotations.splice(index, 0, annotation);
677
- return {
678
- ...page,
679
- annotations
680
- };
681
- }),
904
+ state: withPages(plan, pages),
682
905
  inverse: {
683
906
  type: "pdf.removeAnnotation",
684
- page: command.page,
907
+ page: key,
685
908
  id: annotation.id
686
909
  }
687
910
  };
688
911
  }
689
912
  case "pdf.removeAnnotation": {
690
- let removed;
691
- const next = updatePage(plan, command.page, (page) => {
692
- const index = page.annotations.findIndex((annotation) => annotation.id === command.id);
693
- if (index < 0) throw new TypeError(`Page ${page.key} has no annotation ${command.id}.`);
694
- removed = {
695
- annotation: page.annotations[index],
696
- index
697
- };
698
- return {
699
- ...page,
700
- annotations: page.annotations.filter((_, at) => at !== index)
701
- };
702
- });
703
- 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
+ };
704
924
  return {
705
- plan: next,
925
+ state: withPages(plan, pages),
706
926
  inverse: {
707
927
  type: "pdf.addAnnotation",
708
- page: command.page,
709
- annotation,
928
+ page: key,
929
+ annotation: page.annotations[index],
710
930
  index
711
931
  }
712
932
  };
713
933
  }
714
- default: throw new TypeError(`Unknown command ${command.type}.`);
715
934
  }
716
935
  }
717
- function applyCommands(plan, commands) {
718
- let current = plan;
719
- const inverses = [];
720
- for (const command of commands) {
721
- const applied = applyCommand(current, command);
722
- current = applied.plan;
723
- inverses.unshift(applied.inverse);
724
- }
725
- return {
726
- plan: current,
727
- 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
+ }
728
944
  };
729
945
  }
730
- // src/core/session/history.ts
731
- var History = class {
732
- #past = [];
733
- #future = [];
734
- #trimmed = false;
735
- get canUndo() {
736
- return this.#past.length > 0;
737
- }
738
- get canRedo() {
739
- return this.#future.length > 0;
740
- }
741
- get trimmed() {
742
- return this.#trimmed;
743
- }
744
- get steps() {
745
- return [...this.#past, ...this.#future];
746
- }
747
- get dropOrder() {
748
- return [...this.#future, ...this.#past];
749
- }
750
- push(step) {
751
- this.#past.push(step);
752
- this.#future = [];
753
- }
754
- undo() {
755
- const step = this.#past.pop();
756
- if (step) this.#future.push(step);
757
- return step;
758
- }
759
- redo() {
760
- const step = this.#future.pop();
761
- if (step) this.#past.push(step);
762
- return step;
763
- }
764
- restore(direction) {
765
- if (direction === "undo") {
766
- const step = this.#future.pop();
767
- if (step) this.#past.push(step);
768
- } else {
769
- const step = this.#past.pop();
770
- if (step) this.#future.push(step);
771
- }
772
- }
773
- drop(count) {
774
- if (count <= 0) return;
775
- const fromFuture = Math.min(count, this.#future.length);
776
- this.#future.splice(0, fromFuture);
777
- this.#past.splice(0, count - fromFuture);
778
- this.#trimmed = true;
779
- }
780
- clear() {
781
- this.#past = [];
782
- this.#future = [];
783
- this.#trimmed = false;
784
- }
785
- };
946
+ // src/core/model/plan.ts
947
+ var EMPTY_PLAN = Object.freeze({
948
+ pages: Object.freeze([]),
949
+ formValues: Object.freeze({})
950
+ });
786
951
  // src/core/session/session.ts
787
952
  function createPdfSession(options) {
788
953
  const { engine } = options;
789
954
  const policy = pdfLimits.resolve(options.filePolicy);
790
- const history = new History();
791
- const listeners = /* @__PURE__ */ new Set();
955
+ const history = createHistory();
792
956
  const sources = /* @__PURE__ */ new Map();
957
+ const reduce = createPdfReducer((id) => sources.get(id)?.pageCount);
793
958
  let plan = EMPTY_PLAN;
794
959
  let status = "empty";
795
960
  let error;
@@ -826,7 +991,7 @@ function createPdfSession(options) {
826
991
  if ([...referenced(history.steps.filter((entry) => kept.has(entry)))].reduce((sum, id) => sum + (sources.get(id)?.byteLength ?? 0), 0) + extra <= maximum) return count;
827
992
  }
828
993
  }
829
- let snapshot = makeSnapshot();
994
+ const store = createStore(makeSnapshot());
830
995
  function sessionWarnings() {
831
996
  const bytes = heldBytes();
832
997
  const sessionWarning = bytes > 0 && bytes >= policy.limits.maxSessionSize.warning ? [{
@@ -862,8 +1027,7 @@ function createPdfSession(options) {
862
1027
  if (currentPage !== void 0 && !keys.has(currentPage)) currentPage = plan.pages[0]?.key;
863
1028
  if (currentPage === void 0 && plan.pages.length > 0) currentPage = plan.pages[0]?.key;
864
1029
  if (navigation && !keys.has(navigation.page)) navigation = void 0;
865
- snapshot = makeSnapshot();
866
- for (const listener of [...listeners]) listener();
1030
+ store.set(makeSnapshot());
867
1031
  }
868
1032
  function emit(event) {
869
1033
  try {
@@ -936,8 +1100,8 @@ function createPdfSession(options) {
936
1100
  };
937
1101
  }
938
1102
  function step(commands) {
939
- const result = applyCommands(plan, commands);
940
- plan = result.plan;
1103
+ const result = applyCommands(reduce, plan, commands);
1104
+ plan = result.state;
941
1105
  history.push({
942
1106
  commands,
943
1107
  inverses: result.inverses
@@ -945,11 +1109,8 @@ function createPdfSession(options) {
945
1109
  collect();
946
1110
  }
947
1111
  return {
948
- getSnapshot: () => snapshot,
949
- subscribe(listener) {
950
- listeners.add(listener);
951
- return () => listeners.delete(listener);
952
- },
1112
+ getSnapshot: store.getSnapshot,
1113
+ subscribe: store.subscribe,
953
1114
  async open(file, callOptions = {}) {
954
1115
  status = "opening";
955
1116
  error = void 0;
@@ -1036,7 +1197,7 @@ function createPdfSession(options) {
1036
1197
  throw reason;
1037
1198
  }
1038
1199
  } catch (reason) {
1039
- if (reason instanceof TypeError || reason instanceof RangeError) throw reason;
1200
+ if (reason instanceof TypeError || reason instanceof RangeError || isPdfError(reason, "INVALID_COMMAND")) throw reason;
1040
1201
  const failure = asPdfError(reason, "The PDF couldn't be inserted.");
1041
1202
  error = failure;
1042
1203
  changed();
@@ -1062,7 +1223,7 @@ function createPdfSession(options) {
1062
1223
  const entry = history.undo();
1063
1224
  if (!entry) return;
1064
1225
  try {
1065
- plan = applyCommands(plan, entry.inverses).plan;
1226
+ plan = applyCommands(reduce, plan, entry.inverses).state;
1066
1227
  } catch (reason) {
1067
1228
  history.restore("undo");
1068
1229
  throw reason;
@@ -1074,7 +1235,7 @@ function createPdfSession(options) {
1074
1235
  const entry = history.redo();
1075
1236
  if (!entry) return;
1076
1237
  try {
1077
- plan = applyCommands(plan, entry.commands).plan;
1238
+ plan = applyCommands(reduce, plan, entry.commands).state;
1078
1239
  } catch (reason) {
1079
1240
  history.restore("redo");
1080
1241
  throw reason;
@@ -1217,6 +1378,9 @@ var pdfMessages = /* @__PURE__ */ defineMessages({
1217
1378
  "errors.TOO_MANY_PAGES": "This document has {actual, number} pages, which is over the {maximum, number}-page limit.",
1218
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.",
1219
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.",
1220
1384
  "warnings.maxPages": /* @__PURE__ */ plural("actual", {
1221
1385
  one: "This document has {actual} page. Large documents may be slow.",
1222
1386
  other: "This document has {actual} pages. Large documents may be slow."
@@ -1260,6 +1424,6 @@ var pdfMessages = /* @__PURE__ */ defineMessages({
1260
1424
  "tools.rotate-left": "Rotate left",
1261
1425
  "tools.rotate-right": "Rotate right"
1262
1426
  });
1263
- 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 };
1264
1428
 
1265
- //# sourceMappingURL=en-BYB_GHqG.js.map
1429
+ //# sourceMappingURL=en-CQX26xju.js.map