@hussmartinez/pdf-sdk 0.2.0 → 0.4.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.4.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-DIP9ck2l.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,90 @@ 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
+ });
951
+ var CONTROL = /\p{Cc}/gu;
952
+ var BIDI = /[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/gu;
953
+ var REFUSED = /[<>:"|?*]/gu;
954
+ function cleanFileName(raw) {
955
+ if (typeof raw !== "string") return void 0;
956
+ let name = raw.replace(CONTROL, "").replace(BIDI, "");
957
+ name = name.slice(Math.max(name.lastIndexOf("/"), name.lastIndexOf("\\")) + 1);
958
+ name = name.replace(REFUSED, "").normalize("NFC");
959
+ name = name.replace(/^[\s.]+/u, "").trimEnd();
960
+ const points = Array.from(name);
961
+ if (points.length > 128) name = points.slice(0, 128).join("").trimEnd();
962
+ return name === "" ? void 0 : name;
963
+ }
786
964
  // src/core/session/session.ts
787
965
  function createPdfSession(options) {
788
966
  const { engine } = options;
789
967
  const policy = pdfLimits.resolve(options.filePolicy);
790
- const history = new History();
791
- const listeners = /* @__PURE__ */ new Set();
968
+ const history = createHistory();
969
+ const views = /* @__PURE__ */ new WeakMap();
792
970
  const sources = /* @__PURE__ */ new Map();
971
+ const reduce = createPdfReducer((id) => sources.get(id)?.pageCount);
793
972
  let plan = EMPTY_PLAN;
794
973
  let status = "empty";
795
974
  let error;
@@ -826,7 +1005,7 @@ function createPdfSession(options) {
826
1005
  if ([...referenced(history.steps.filter((entry) => kept.has(entry)))].reduce((sum, id) => sum + (sources.get(id)?.byteLength ?? 0), 0) + extra <= maximum) return count;
827
1006
  }
828
1007
  }
829
- let snapshot = makeSnapshot();
1008
+ const store = createStore(makeSnapshot());
830
1009
  function sessionWarnings() {
831
1010
  const bytes = heldBytes();
832
1011
  const sessionWarning = bytes > 0 && bytes >= policy.limits.maxSessionSize.warning ? [{
@@ -839,10 +1018,11 @@ function createPdfSession(options) {
839
1018
  return Object.freeze({
840
1019
  status,
841
1020
  plan,
842
- sources: Object.freeze([...sources.values()].map(({ id, pageCount, byteLength }) => Object.freeze({
1021
+ sources: Object.freeze([...sources.values()].map(({ id, pageCount, byteLength, name }) => Object.freeze({
843
1022
  id,
844
1023
  pageCount,
845
- byteLength
1024
+ byteLength,
1025
+ ...name === void 0 ? {} : { name }
846
1026
  }))),
847
1027
  canUndo: history.canUndo,
848
1028
  canRedo: history.canRedo,
@@ -862,15 +1042,16 @@ function createPdfSession(options) {
862
1042
  if (currentPage !== void 0 && !keys.has(currentPage)) currentPage = plan.pages[0]?.key;
863
1043
  if (currentPage === void 0 && plan.pages.length > 0) currentPage = plan.pages[0]?.key;
864
1044
  if (navigation && !keys.has(navigation.page)) navigation = void 0;
865
- snapshot = makeSnapshot();
866
- for (const listener of [...listeners]) listener();
1045
+ store.set(makeSnapshot());
867
1046
  }
868
1047
  function emit(event) {
869
1048
  try {
870
1049
  options.onEvent?.(event);
871
1050
  } catch {}
872
1051
  }
873
- async function load(file, signal) {
1052
+ async function load(file, signal, given) {
1053
+ const fileName = typeof File !== "undefined" && file instanceof File ? file.name : void 0;
1054
+ const name = cleanFileName(given ?? fileName);
874
1055
  const found = [];
875
1056
  const warnAt = (limit, actual) => {
876
1057
  if (policy.check(limit, actual) === "warning") found.push({
@@ -902,6 +1083,7 @@ function createPdfSession(options) {
902
1083
  id: `s${nextSource}`,
903
1084
  pageCount: document.pageCount,
904
1085
  byteLength: bytes.byteLength,
1086
+ ...name === void 0 ? {} : { name },
905
1087
  bytes,
906
1088
  document
907
1089
  };
@@ -935,28 +1117,45 @@ function createPdfSession(options) {
935
1117
  source
936
1118
  };
937
1119
  }
1120
+ function view() {
1121
+ return {
1122
+ selection,
1123
+ currentPage
1124
+ };
1125
+ }
1126
+ function restore(saved) {
1127
+ const keys = new Set(plan.pages.map((page) => page.key));
1128
+ selection = saved.selection.filter((key) => keys.has(key));
1129
+ if (saved.currentPage !== void 0 && keys.has(saved.currentPage)) {
1130
+ currentPage = saved.currentPage;
1131
+ navigation = {
1132
+ page: saved.currentPage,
1133
+ sequence: (navigation?.sequence ?? 0) + 1
1134
+ };
1135
+ }
1136
+ }
938
1137
  function step(commands) {
939
- const result = applyCommands(plan, commands);
940
- plan = result.plan;
1138
+ const before = view();
1139
+ const result = applyCommands(reduce, plan, commands);
1140
+ plan = result.state;
941
1141
  history.push({
942
1142
  commands,
943
1143
  inverses: result.inverses
944
1144
  });
1145
+ const stored = history.steps.at(-1);
1146
+ if (stored) views.set(stored, { before });
945
1147
  collect();
946
1148
  }
947
1149
  return {
948
- getSnapshot: () => snapshot,
949
- subscribe(listener) {
950
- listeners.add(listener);
951
- return () => listeners.delete(listener);
952
- },
1150
+ getSnapshot: store.getSnapshot,
1151
+ subscribe: store.subscribe,
953
1152
  async open(file, callOptions = {}) {
954
1153
  status = "opening";
955
1154
  error = void 0;
956
1155
  try {
957
1156
  const source = await track(callOptions.signal, true, async (signal) => {
958
1157
  policy.check("maxSessionSize", file instanceof Blob ? file.size : file.byteLength);
959
- return load(file, signal);
1158
+ return load(file, signal, callOptions.name);
960
1159
  });
961
1160
  await release();
962
1161
  sources.set(source.id, source);
@@ -1000,7 +1199,7 @@ function createPdfSession(options) {
1000
1199
  try {
1001
1200
  const source = await track(insertOptions.signal, false, async (signal) => {
1002
1201
  policy.check("maxFiles", sources.size + 1);
1003
- return load(file, signal);
1202
+ return load(file, signal, insertOptions.name);
1004
1203
  });
1005
1204
  try {
1006
1205
  const pageIndexes = insertOptions.pageIndexes ?? Array.from({ length: source.pageCount }, (_, index) => index);
@@ -1036,7 +1235,7 @@ function createPdfSession(options) {
1036
1235
  throw reason;
1037
1236
  }
1038
1237
  } catch (reason) {
1039
- if (reason instanceof TypeError || reason instanceof RangeError) throw reason;
1238
+ if (reason instanceof TypeError || reason instanceof RangeError || isPdfError(reason, "INVALID_COMMAND")) throw reason;
1040
1239
  const failure = asPdfError(reason, "The PDF couldn't be inserted.");
1041
1240
  error = failure;
1042
1241
  changed();
@@ -1061,12 +1260,18 @@ function createPdfSession(options) {
1061
1260
  undo() {
1062
1261
  const entry = history.undo();
1063
1262
  if (!entry) return;
1263
+ const now = view();
1064
1264
  try {
1065
- plan = applyCommands(plan, entry.inverses).plan;
1265
+ plan = applyCommands(reduce, plan, entry.inverses).state;
1066
1266
  } catch (reason) {
1067
1267
  history.restore("undo");
1068
1268
  throw reason;
1069
1269
  }
1270
+ const record = views.get(entry);
1271
+ if (record) {
1272
+ record.after = now;
1273
+ restore(record.before);
1274
+ }
1070
1275
  changed();
1071
1276
  emit({ type: "undo" });
1072
1277
  },
@@ -1074,11 +1279,13 @@ function createPdfSession(options) {
1074
1279
  const entry = history.redo();
1075
1280
  if (!entry) return;
1076
1281
  try {
1077
- plan = applyCommands(plan, entry.commands).plan;
1282
+ plan = applyCommands(reduce, plan, entry.commands).state;
1078
1283
  } catch (reason) {
1079
1284
  history.restore("redo");
1080
1285
  throw reason;
1081
1286
  }
1287
+ const after = views.get(entry)?.after;
1288
+ if (after) restore(after);
1082
1289
  changed();
1083
1290
  emit({ type: "redo" });
1084
1291
  },
@@ -1217,49 +1424,16 @@ var pdfMessages = /* @__PURE__ */ defineMessages({
1217
1424
  "errors.TOO_MANY_PAGES": "This document has {actual, number} pages, which is over the {maximum, number}-page limit.",
1218
1425
  "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
1426
  "errors.IMAGE_TOO_LARGE": "Some images are too large to show. They're kept unchanged in the document.",
1427
+ "errors.INVALID_COMMAND": "This edit couldn't be made. Please try again.",
1428
+ "errors.INVALID_DOCUMENT": "This project is damaged, or it isn't a PDF project.",
1429
+ "errors.UNSUPPORTED_FORMAT": "This project was saved by a newer version, or by another app. Update the app, and try again.",
1220
1430
  "warnings.maxPages": /* @__PURE__ */ plural("actual", {
1221
1431
  one: "This document has {actual} page. Large documents may be slow.",
1222
1432
  other: "This document has {actual} pages. Large documents may be slow."
1223
1433
  }),
1224
1434
  "warnings.maxSessionSize": "The open documents use {actual, fileSize}. Clearing the undo history frees memory.",
1225
- "warnings.maxImagePixels": "Some images are very large and may be slow to show.",
1226
- "viewer.label": "Document",
1227
- "viewer.empty": "No document is open.",
1228
- "viewer.page": "Page {page} of {count}",
1229
- "viewer.webLink": "Link to {destination}, opens in a new tab",
1230
- "viewer.emailLink": "Email {destination}",
1231
- "thumbnails.label": "Pages",
1232
- "thumbnails.page": "Page {page} of {count}",
1233
- "thumbnails.number": "{page}",
1234
- "editor.label": "PDF editor",
1235
- "editor.start.title": "Open a PDF to get started",
1236
- "editor.start.retryTitle": "Try another PDF",
1237
- "editor.start.choose": "Choose a PDF",
1238
- "editor.start.retry": "Choose another PDF",
1239
- "editor.start.hint": "Or drop one here. Your file stays on this device and is never uploaded.",
1240
- "editor.opening": "Opening the PDF…",
1241
- "editor.opened": /* @__PURE__ */ plural("count", {
1242
- one: "Opened a PDF with {count} page.",
1243
- other: "Opened a PDF with {count} pages."
1244
- }),
1245
- "editor.closed": "The PDF was closed.",
1246
- "editor.undone": "Undone.",
1247
- "editor.redone": "Redone.",
1248
- "editor.rotated": /* @__PURE__ */ plural("count", {
1249
- one: "Rotated {count} page.",
1250
- other: "Rotated {count} pages."
1251
- }),
1252
- "toolbar.label": "PDF tools",
1253
- "toolbar.groups.file": "File",
1254
- "toolbar.groups.history": "History",
1255
- "toolbar.groups.pages": "Pages",
1256
- "toolbar.groups.other": "More tools",
1257
- "tools.open": "Open a PDF",
1258
- "tools.undo": "Undo",
1259
- "tools.redo": "Redo",
1260
- "tools.rotate-left": "Rotate left",
1261
- "tools.rotate-right": "Rotate right"
1435
+ "warnings.maxImagePixels": "Some images are very large and may be slow to show."
1262
1436
  });
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 };
1437
+ export { pdfLimits as C, pdfLimitDefinitions as S, isPdfError as T, createPdfJsEngine as _, checkAnnotation as a, safeLinkUrl as b, invalid as c, PDF_MAX_ID_LENGTH as d, PDF_MAX_STROKE_POINTS as f, createPdfProcessor as g, longerThan as h, Invalid as i, isRecord as l, PDF_POSITION_GRID as m, createPdfSession as n, checkId as o, PDF_MAX_TEXT_LENGTH as p, cleanFileName as r, fields as s, pdfMessages as t, PDF_MAX_FIELD_NAME_LENGTH as u, PDF_MAX_CANVAS_PIXELS as v, PdfError as w, addRotation as x, linkDestination as y };
1264
1438
 
1265
- //# sourceMappingURL=en-BYB_GHqG.js.map
1439
+ //# sourceMappingURL=en-DKR-ngAZ.js.map