@folijs/core 0.6.0 → 1.0.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.
Files changed (190) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/README.md +1 -1
  3. package/dist/document.d.ts +0 -7
  4. package/dist/document.d.ts.map +1 -1
  5. package/dist/document.js +5 -1
  6. package/dist/document.js.map +1 -1
  7. package/dist/index.d.ts +4 -4
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +8 -4
  10. package/dist/index.js.map +1 -1
  11. package/dist/internal.d.ts +5 -0
  12. package/dist/internal.d.ts.map +1 -0
  13. package/dist/internal.js +7 -0
  14. package/dist/internal.js.map +1 -0
  15. package/dist/model/attrs.d.ts +0 -10
  16. package/dist/model/attrs.d.ts.map +1 -1
  17. package/dist/model/attrs.js +10 -2
  18. package/dist/model/attrs.js.map +1 -1
  19. package/dist/model/content.d.ts +1 -1
  20. package/dist/model/content.d.ts.map +1 -1
  21. package/dist/model/content.js +1 -1
  22. package/dist/model/content.js.map +1 -1
  23. package/dist/model/errors.d.ts +0 -2
  24. package/dist/model/errors.d.ts.map +1 -1
  25. package/dist/model/errors.js +4 -1
  26. package/dist/model/errors.js.map +1 -1
  27. package/dist/model/fragment.d.ts +1 -1
  28. package/dist/model/fragment.d.ts.map +1 -1
  29. package/dist/model/fragment.js +3 -1
  30. package/dist/model/fragment.js.map +1 -1
  31. package/dist/model/mark.d.ts +1 -1
  32. package/dist/model/mark.d.ts.map +1 -1
  33. package/dist/model/mark.js +1 -1
  34. package/dist/model/mark.js.map +1 -1
  35. package/dist/model/node.d.ts +4 -4
  36. package/dist/model/node.d.ts.map +1 -1
  37. package/dist/model/node.js +8 -4
  38. package/dist/model/node.js.map +1 -1
  39. package/dist/model/schema.d.ts +8 -8
  40. package/dist/model/schema.d.ts.map +1 -1
  41. package/dist/model/schema.js +4 -3
  42. package/dist/model/schema.js.map +1 -1
  43. package/dist/schema.d.ts +0 -11
  44. package/dist/schema.d.ts.map +1 -1
  45. package/dist/schema.js +2 -0
  46. package/dist/schema.js.map +1 -1
  47. package/dist/state/attempt.d.ts +1 -3
  48. package/dist/state/attempt.d.ts.map +1 -1
  49. package/dist/state/comments.d.ts +1 -7
  50. package/dist/state/comments.d.ts.map +1 -1
  51. package/dist/state/comments.js +1 -0
  52. package/dist/state/comments.js.map +1 -1
  53. package/dist/state/controls.d.ts +1 -19
  54. package/dist/state/controls.d.ts.map +1 -1
  55. package/dist/state/controls.js +21 -7
  56. package/dist/state/controls.js.map +1 -1
  57. package/dist/state/editor.d.ts +107 -72
  58. package/dist/state/editor.d.ts.map +1 -1
  59. package/dist/state/editor.js +121 -61
  60. package/dist/state/editor.js.map +1 -1
  61. package/dist/state/fields.d.ts +1 -12
  62. package/dist/state/fields.d.ts.map +1 -1
  63. package/dist/state/fields.js +16 -4
  64. package/dist/state/fields.js.map +1 -1
  65. package/dist/state/fieldupdate.d.ts +1 -47
  66. package/dist/state/fieldupdate.d.ts.map +1 -1
  67. package/dist/state/fieldupdate.js +1 -0
  68. package/dist/state/fieldupdate.js.map +1 -1
  69. package/dist/state/find.d.ts +1 -3
  70. package/dist/state/find.d.ts.map +1 -1
  71. package/dist/state/find.js +10 -2
  72. package/dist/state/find.js.map +1 -1
  73. package/dist/state/history.d.ts +1 -10
  74. package/dist/state/history.d.ts.map +1 -1
  75. package/dist/state/history.js +1 -0
  76. package/dist/state/history.js.map +1 -1
  77. package/dist/state/index.d.ts +4 -4
  78. package/dist/state/index.d.ts.map +1 -1
  79. package/dist/state/index.js +4 -4
  80. package/dist/state/index.js.map +1 -1
  81. package/dist/state/lists.d.ts +3 -3
  82. package/dist/state/lists.d.ts.map +1 -1
  83. package/dist/state/lists.js.map +1 -1
  84. package/dist/state/mark.d.ts +1 -17
  85. package/dist/state/mark.d.ts.map +1 -1
  86. package/dist/state/mark.js +2 -0
  87. package/dist/state/mark.js.map +1 -1
  88. package/dist/state/notes.d.ts +2 -12
  89. package/dist/state/notes.d.ts.map +1 -1
  90. package/dist/state/notes.js +10 -3
  91. package/dist/state/notes.js.map +1 -1
  92. package/dist/state/review.d.ts +1 -6
  93. package/dist/state/review.d.ts.map +1 -1
  94. package/dist/state/review.js +1 -0
  95. package/dist/state/review.js.map +1 -1
  96. package/dist/state/sections.d.ts +1 -11
  97. package/dist/state/sections.d.ts.map +1 -1
  98. package/dist/state/sections.js +10 -3
  99. package/dist/state/sections.js.map +1 -1
  100. package/dist/state/state.d.ts +13 -9
  101. package/dist/state/state.d.ts.map +1 -1
  102. package/dist/state/state.js +5 -2
  103. package/dist/state/state.js.map +1 -1
  104. package/dist/state/stories.d.ts +1 -40
  105. package/dist/state/stories.d.ts.map +1 -1
  106. package/dist/state/stories.js +18 -2
  107. package/dist/state/stories.js.map +1 -1
  108. package/dist/state/tables.d.ts +1 -36
  109. package/dist/state/tables.d.ts.map +1 -1
  110. package/dist/state/tables.js +23 -5
  111. package/dist/state/tables.js.map +1 -1
  112. package/dist/state/track.d.ts +1 -29
  113. package/dist/state/track.d.ts.map +1 -1
  114. package/dist/state/track.js +9 -2
  115. package/dist/state/track.js.map +1 -1
  116. package/dist/state/word.d.ts +8 -78
  117. package/dist/state/word.d.ts.map +1 -1
  118. package/dist/state/word.js +95 -28
  119. package/dist/state/word.js.map +1 -1
  120. package/dist/state/wordclip.d.ts +3 -1
  121. package/dist/state/wordclip.d.ts.map +1 -1
  122. package/dist/state/wordclip.js +67 -8
  123. package/dist/state/wordclip.js.map +1 -1
  124. package/dist/state/wordformat.d.ts +1 -86
  125. package/dist/state/wordformat.d.ts.map +1 -1
  126. package/dist/state/wordformat.js +54 -11
  127. package/dist/state/wordformat.js.map +1 -1
  128. package/dist/transform/stepmap.d.ts +0 -2
  129. package/dist/transform/stepmap.d.ts.map +1 -1
  130. package/dist/v3/check.d.ts +0 -25
  131. package/dist/v3/check.d.ts.map +1 -1
  132. package/dist/v3/check.js +35 -7
  133. package/dist/v3/check.js.map +1 -1
  134. package/dist/v3/document.d.ts +8 -6
  135. package/dist/v3/document.d.ts.map +1 -1
  136. package/dist/v3/document.js +28 -16
  137. package/dist/v3/document.js.map +1 -1
  138. package/dist/v3/extensions.d.ts +43 -0
  139. package/dist/v3/extensions.d.ts.map +1 -0
  140. package/dist/v3/extensions.js +154 -0
  141. package/dist/v3/extensions.js.map +1 -0
  142. package/dist/v3/index.d.ts +2 -1
  143. package/dist/v3/index.d.ts.map +1 -1
  144. package/dist/v3/index.js +2 -1
  145. package/dist/v3/index.js.map +1 -1
  146. package/dist/v3/resolve.d.ts.map +1 -1
  147. package/dist/v3/resolve.js +6 -0
  148. package/dist/v3/resolve.js.map +1 -1
  149. package/dist/v3/schema.d.ts +5 -18
  150. package/dist/v3/schema.d.ts.map +1 -1
  151. package/dist/v3/schema.js +79 -5
  152. package/dist/v3/schema.js.map +1 -1
  153. package/package.json +5 -1
  154. package/src/document.ts +5 -1
  155. package/src/index.ts +330 -4
  156. package/src/internal.ts +50 -0
  157. package/src/model/attrs.ts +10 -2
  158. package/src/model/content.ts +1 -1
  159. package/src/model/errors.ts +4 -1
  160. package/src/model/fragment.ts +2 -1
  161. package/src/model/mark.ts +1 -1
  162. package/src/model/node.ts +6 -4
  163. package/src/model/schema.ts +9 -3
  164. package/src/schema.ts +2 -0
  165. package/src/state/comments.ts +1 -0
  166. package/src/state/controls.ts +25 -9
  167. package/src/state/editor.ts +251 -130
  168. package/src/state/fields.ts +16 -4
  169. package/src/state/fieldupdate.ts +1 -0
  170. package/src/state/find.ts +12 -4
  171. package/src/state/history.ts +2 -0
  172. package/src/state/index.ts +5 -4
  173. package/src/state/lists.ts +2 -2
  174. package/src/state/mark.ts +2 -0
  175. package/src/state/notes.ts +27 -17
  176. package/src/state/review.ts +1 -0
  177. package/src/state/sections.ts +10 -3
  178. package/src/state/state.ts +16 -3
  179. package/src/state/stories.ts +32 -5
  180. package/src/state/tables.ts +27 -6
  181. package/src/state/track.ts +9 -2
  182. package/src/state/word.ts +105 -32
  183. package/src/state/wordclip.ts +76 -8
  184. package/src/state/wordformat.ts +55 -11
  185. package/src/v3/check.ts +35 -7
  186. package/src/v3/document.ts +39 -16
  187. package/src/v3/extensions.ts +201 -0
  188. package/src/v3/index.ts +9 -0
  189. package/src/v3/resolve.ts +5 -0
  190. package/src/v3/schema.ts +83 -5
package/src/v3/check.ts CHANGED
@@ -7,12 +7,15 @@
7
7
 
8
8
  export type Check = (value: unknown) => string | undefined;
9
9
 
10
+ /** @internal */
10
11
  export function isRecord(value: unknown): value is Record<string, unknown> {
11
12
  return typeof value === "object" && value !== null && !Array.isArray(value);
12
13
  }
13
14
 
15
+ /** @internal */
14
16
  export const bool: Check = (v) => (typeof v === "boolean" ? undefined : "must be true or false");
15
17
 
18
+ /** @internal */
16
19
  export const int =
17
20
  (min: number, max: number): Check =>
18
21
  (v) =>
@@ -20,7 +23,10 @@ export const int =
20
23
  ? undefined
21
24
  : `must be an integer from ${min} to ${max}`;
22
25
 
23
- /** A string of at most `max` characters, empty allowed (Word's ST_String: authors, initials). */
26
+ /**
27
+ * A string of at most `max` characters, empty allowed (Word's ST_String: authors, initials).
28
+ * @internal
29
+ */
24
30
  export const str =
25
31
  (max = 255): Check =>
26
32
  (v) =>
@@ -28,7 +34,10 @@ export const str =
28
34
  ? undefined
29
35
  : `must be a string of at most ${max} characters`;
30
36
 
31
- /** A non-empty string: ids and names things are referenced by. */
37
+ /**
38
+ * A non-empty string: ids and names things are referenced by.
39
+ * @internal
40
+ */
32
41
  export const text =
33
42
  (max = 255): Check =>
34
43
  (v) =>
@@ -36,35 +45,51 @@ export const text =
36
45
  ? undefined
37
46
  : `must be a non-empty string of at most ${max} characters`;
38
47
 
48
+ /** @internal */
39
49
  export const oneOf =
40
50
  (values: readonly string[]): Check =>
41
51
  (v) =>
42
52
  values.includes(v as string) ? undefined : `must be one of ${values.join(", ")}`;
43
53
 
44
- /** A token of one of Word's long enumerations (border styles, number formats…). */
54
+ /**
55
+ * A token of one of Word's long enumerations (border styles, number formats…).
56
+ * @internal
57
+ */
45
58
  export const token: Check = (v) =>
46
59
  typeof v === "string" && /^[A-Za-z][A-Za-z0-9-]{0,63}$/.test(v)
47
60
  ? undefined
48
61
  : "must be a Word token";
49
62
 
50
- /** `RRGGBB` (any case, as Word writes it) or `auto`. */
63
+ /**
64
+ * `RRGGBB` (any case, as Word writes it) or `auto`.
65
+ * @internal
66
+ */
51
67
  export const color: Check = (v) =>
52
68
  typeof v === "string" && /^([0-9A-Fa-f]{6}|auto)$/.test(v) ? undefined : "must be RRGGBB or auto";
53
69
 
54
- /** An ISO 8601 date-time, as Word stores revision and comment dates. */
70
+ /**
71
+ * An ISO 8601 date-time, as Word stores revision and comment dates.
72
+ * @internal
73
+ */
55
74
  export const date: Check = (v) =>
56
75
  typeof v === "string" &&
57
76
  /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?$/.test(v)
58
77
  ? undefined
59
78
  : "must be an ISO 8601 date-time";
60
79
 
61
- /** Verbatim XML kept for export: never parsed by the engine. */
80
+ /**
81
+ * Verbatim XML kept for export: never parsed by the engine.
82
+ * @internal
83
+ */
62
84
  export const xml: Check = (v) =>
63
85
  typeof v === "string" && v.length > 0 && v.length <= 16_777_216
64
86
  ? undefined
65
87
  : "must be an XML string";
66
88
 
67
- /** An element's own attributes Foli does not model, by qualified name (`w14:paraId`). */
89
+ /**
90
+ * An element's own attributes Foli does not model, by qualified name (`w14:paraId`).
91
+ * @internal
92
+ */
68
93
  export const attributes: Check = (v) => {
69
94
  if (!isRecord(v)) return "must be an object";
70
95
  const entries = Object.entries(v);
@@ -78,11 +103,13 @@ export const attributes: Check = (v) => {
78
103
  return undefined;
79
104
  };
80
105
 
106
+ /** @internal */
81
107
  export const nullable =
82
108
  (check: Check): Check =>
83
109
  (v) =>
84
110
  v === null ? undefined : check(v);
85
111
 
112
+ /** @internal */
86
113
  export const listOf =
87
114
  (check: Check, max = 100_000): Check =>
88
115
  (v) => {
@@ -98,6 +125,7 @@ export const listOf =
98
125
  /**
99
126
  * An object with only the given keys, each optional unless listed in `required`. Unless
100
127
  * `allowEmpty`, at least one key is present (an empty object means "not set": use null).
128
+ * @internal
101
129
  */
102
130
  export const shape =
103
131
  (
@@ -1,5 +1,11 @@
1
1
  import { DEFAULT_SETTINGS, parseDocumentV2 } from "../document.js";
2
- import { FoliDocumentError, type MarkJSON, type Node, type NodeJSON } from "../model/index.js";
2
+ import {
3
+ FoliDocumentError,
4
+ type MarkJSON,
5
+ type Node,
6
+ type NodeJSON,
7
+ type Schema,
8
+ } from "../model/index.js";
3
9
  import {
4
10
  bool,
5
11
  type Check,
@@ -15,6 +21,13 @@ import {
15
21
  token,
16
22
  xml,
17
23
  } from "./check.js";
24
+ import {
25
+ type ContentOptions,
26
+ type ParseOptions,
27
+ resolveCustom,
28
+ schemaWith,
29
+ writeCustom,
30
+ } from "./extensions.js";
18
31
  import { migrateToV3 } from "./migrate.js";
19
32
  import {
20
33
  checkCellProperties,
@@ -24,7 +37,6 @@ import {
24
37
  checkTableProperties,
25
38
  checkParagraphProperties as paragraphProperties,
26
39
  checkRunProperties as runProperties,
27
- schema,
28
40
  } from "./schema.js";
29
41
 
30
42
  /**
@@ -456,23 +468,26 @@ export function createDocument(
456
468
  * and 2 are validated as such and migrated (`migrateToV3`). Throws FoliDocumentError instead
457
469
  * of dropping anything.
458
470
  *
471
+ * Custom types (ADR-0008) are validated by `options.extensions`; a namespaced type none of them
472
+ * declares is kept as it is, its attributes checked only as plain JSON (a foreign node or mark).
473
+ *
459
474
  * What Word opens is accepted: duplicate ids (the first wins), a numbering instance or a reply
460
475
  * whose target is missing, references to styles that do not exist. Rejected is only what the
461
476
  * engine cannot work with: wrong types, out-of-range values, and cycles (a style based on
462
477
  * itself, comments replying to each other) that would never end when followed.
463
478
  */
464
- export function parseDocument(input: unknown): FoliDocument {
479
+ export function parseDocument(input: unknown, options: ParseOptions = {}): FoliDocument {
465
480
  if (!isRecord(input)) throw new FoliDocumentError("Document must be an object");
466
481
  const version = input.schemaVersion;
467
482
  if (version === 1 || version === 2) {
468
- return parseDocument(migrateToV5(migrateToV4(migrateToV3(parseDocumentV2(input)))));
483
+ return parseDocument(migrateToV5(migrateToV4(migrateToV3(parseDocumentV2(input)))), options);
469
484
  }
470
485
  if (version === 3 || version === 4) {
471
486
  if (version === 3 && Object.hasOwn(input, "resources"))
472
487
  fail("resources", "unknown key (schema 4 and later)");
473
488
  for (const key of V5_KEYS)
474
489
  if (Object.hasOwn(input, key)) fail(key, "unknown key (schema 5 and later)");
475
- const doc = parseDocument({ ...input, schemaVersion: SCHEMA_VERSION });
490
+ const doc = parseDocument({ ...input, schemaVersion: SCHEMA_VERSION }, options);
476
491
  // What a later schema added is not in a document that says it is of an earlier one.
477
492
  const later = laterSection(doc.section);
478
493
  if (later) fail("section", `${later} is of schema 5 (the document says schema ${version})`);
@@ -544,11 +559,12 @@ export function parseDocument(input: unknown): FoliDocument {
544
559
  (c) => `comment ${c.id} replies to itself`,
545
560
  );
546
561
 
547
- const content = parseContent(input.content);
562
+ const schema = schemaWith(options.extensions);
563
+ const content = parseContent(input.content, { schema });
548
564
  const stories = Object.entries((input.stories ?? {}) as Record<string, StoryJSON>).map(
549
565
  ([id, story]) => {
550
566
  const path = `stories[${JSON.stringify(id)}].content`;
551
- const tree = parseContent(story.content, path);
567
+ const tree = parseContent(story.content, { path, schema });
552
568
  storyRules(tree, story.kind, path);
553
569
  return [id, { ...structuredClone({ ...story, content: null }), content: copied(tree) }];
554
570
  },
@@ -583,7 +599,7 @@ export function parseDocument(input: unknown): FoliDocument {
583
599
  ...(envelope.theme === undefined ? {} : { theme: envelope.theme }),
584
600
  comments: comments.map((c, i) => ({
585
601
  ...structuredClone({ ...c, content: [] }),
586
- content: blocks(c.content, `comments[${i}].content`).map((block) => {
602
+ content: blocks(c.content, `comments[${i}].content`, schema).map((block) => {
587
603
  block.descendants((node) => {
588
604
  if (node.type.name === "noteReference")
589
605
  fail(`comments[${i}].content`, "a comment cannot hold a note reference");
@@ -600,18 +616,21 @@ export function parseDocument(input: unknown): FoliDocument {
600
616
  };
601
617
  }
602
618
 
603
- /** A node's JSON sharing nothing with the input its attributes came from. */
604
- const copied = (node: Node): NodeJSON => structuredClone(node.toJSON());
619
+ /** A node's JSON sharing nothing with the input its attributes came from, foreign types written back. */
620
+ const copied = (node: Node): NodeJSON => writeCustom(structuredClone(node.toJSON()));
605
621
 
606
622
  /**
607
623
  * Parses untrusted schema v4 content into a `doc` node, with Word's rules the content
608
624
  * expressions do not say (`fragment`: content to paste, which a table may end): a table is never
609
625
  * followed by a table (Word would merge them; tables in different content controls stay apart)
610
626
  * nor ends the document, and a paragraph in a cell ends no section and holds no page or column
611
- * break.
627
+ * break. With `extensions` their types are read as themselves; a namespaced type they do not
628
+ * declare becomes a foreign node or mark.
612
629
  */
613
- export function parseContent(value: unknown, path = "content", fragment = false): Node {
614
- const doc = schema.nodeFromJSON(value, path);
630
+ export function parseContent(value: unknown, options: ContentOptions = {}): Node {
631
+ const { path = "content", fragment = false } = options;
632
+ const schema = options.schema ?? schemaWith(options.extensions);
633
+ const doc = schema.nodeFromJSON(resolveCustom(value, schema), path);
615
634
  if (doc.type !== schema.topNodeType) fail(path, 'root node must be of type "doc"');
616
635
  if (doc.marks.length) fail(`${path}.marks`, "doc cannot have marks");
617
636
  wordRules(doc, path, false, fragment);
@@ -649,7 +668,10 @@ function wordRules(parent: Node, path: string, inCell: boolean, fragment = false
649
668
  });
650
669
  }
651
670
 
652
- /** What a story may not hold (ADR-0007): import keeps such content opaque instead. */
671
+ /**
672
+ * What a story may not hold (ADR-0007): import keeps such content opaque instead.
673
+ * @internal
674
+ */
653
675
  export function storyRules(tree: Node, kind: StoryJSON["kind"], path: string): void {
654
676
  tree.descendants((node) => {
655
677
  const name = node.type.name;
@@ -764,8 +786,8 @@ function noCycles<T>(
764
786
  });
765
787
  }
766
788
 
767
- function blocks(content: NodeJSON[], path: string): Node[] {
768
- const doc = parseContent({ type: "doc", content }, path);
789
+ function blocks(content: NodeJSON[], path: string, schema: Schema): Node[] {
790
+ const doc = parseContent({ type: "doc", content }, { path, schema });
769
791
  const list: Node[] = [];
770
792
  doc.forEach((block) => {
771
793
  list.push(block);
@@ -820,6 +842,7 @@ function protocolOf(url: string): string {
820
842
  /** Pictures only: `image/png`, `image/svg+xml`… */
821
843
  const IMAGE_TYPE = /^image\/[A-Za-z0-9][\w.+-]{0,126}$/;
822
844
 
845
+ /** @internal */
823
846
  export const checkResource: Check = (v) => {
824
847
  const error = shape(
825
848
  {
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Custom nodes and marks (ADR-0008): extensions add namespaced inline or block leaves and marks
3
+ * to the Word schema. A namespaced type the schema does not have is never dropped: it is read as
4
+ * a foreign node or mark holding its type and attributes, and written back as it was.
5
+ */
6
+ import type { Attrs, MarkJSON, MarkSpec, NodeJSON, NodeSpec } from "../model/index.js";
7
+ import { Schema } from "../model/index.js";
8
+ import type { Plugin } from "../state/state.js";
9
+ import { isRecord } from "./check.js";
10
+ import { CUSTOM_TYPE, schema as wordSchema } from "./schema.js";
11
+
12
+ /** A custom node type: an inline leaf (`inline: true`) or a block leaf. */
13
+ export interface ExtensionNodeSpec extends Omit<NodeSpec, "content" | "text"> {
14
+ /** The text it stands for in plain text, find, the clipboard and `.docx`. */
15
+ text: (attrs: Attrs) => string;
16
+ }
17
+
18
+ /**
19
+ * What an app adds to the editor: custom node and mark types, named `<namespace>:<name>`
20
+ * (lowercase letters, digits and `-`), and plugins. Given to `createEditor` and `parseDocument`.
21
+ */
22
+ export interface Extension {
23
+ name: string;
24
+ nodes?: Readonly<Record<string, ExtensionNodeSpec>>;
25
+ marks?: Readonly<Record<string, MarkSpec>>;
26
+ plugins?: readonly Plugin[];
27
+ }
28
+
29
+ /** Options of `parseDocument`. */
30
+ export interface ParseOptions {
31
+ /** The custom types the document may hold as themselves; others are kept as foreign. */
32
+ extensions?: readonly Extension[];
33
+ }
34
+
35
+ /** Options of `parseContent`. */
36
+ export interface ContentOptions extends ParseOptions {
37
+ /** Where the content is, for error messages (default `content`). */
38
+ path?: string;
39
+ /** Content to paste, which a table may end. */
40
+ fragment?: boolean;
41
+ /**
42
+ * The schema to parse with (an editor's `state.schema`), in place of `extensions`.
43
+ * @internal
44
+ */
45
+ schema?: Schema;
46
+ }
47
+
48
+ /** Schemas by extension list: an array given again gets the same schema (do not mutate it). */
49
+ const schemas = new WeakMap<readonly Extension[], Schema>();
50
+
51
+ /**
52
+ * The Word schema with `extensions`' types (the Word schema itself when there are none). Throws
53
+ * a `RangeError` on a name that is not namespaced or is taken twice, or a node that is not a leaf.
54
+ * @internal
55
+ */
56
+ export function schemaWith(extensions: readonly Extension[] | undefined): Schema {
57
+ if (!extensions?.length) return wordSchema;
58
+ const known = schemas.get(extensions);
59
+ if (known) return known;
60
+ const nodes: Record<string, NodeSpec> = { ...wordSchema.spec.nodes };
61
+ const marks: Record<string, MarkSpec> = { ...wordSchema.spec.marks };
62
+ const add = (into: Record<string, unknown>, name: string, from: string) => {
63
+ if (!CUSTOM_TYPE.test(name))
64
+ throw new RangeError(`${from}: ${name} is not a namespaced type (<namespace>:<name>)`);
65
+ if (Object.hasOwn(nodes, name) || Object.hasOwn(marks, name))
66
+ throw new RangeError(`${from}: ${name} is declared twice`);
67
+ return into;
68
+ };
69
+ for (const extension of extensions) {
70
+ for (const [name, spec] of Object.entries(extension.nodes ?? {})) {
71
+ const group = spec.inline ? "inline" : "block";
72
+ if ((spec as NodeSpec).content || (spec.group !== undefined && spec.group !== group))
73
+ throw new RangeError(`${extension.name}: ${name} must be a leaf in the ${group} group`);
74
+ if (typeof spec.text !== "function")
75
+ throw new RangeError(`${extension.name}: ${name} needs text(attrs)`);
76
+ add(nodes, name, extension.name)[name] = { ...spec, group };
77
+ }
78
+ for (const [name, spec] of Object.entries(extension.marks ?? {}))
79
+ add(marks, name, extension.name)[name] = spec;
80
+ }
81
+ const schema = new Schema({ nodes, marks });
82
+ schemas.set(extensions, schema);
83
+ return schema;
84
+ }
85
+
86
+ /** What a foreign node's JSON carries in memory: the text its `.docx` control showed. */
87
+ const FOREIGN_TEXT = Symbol.for("foli.foreignText");
88
+
89
+ /**
90
+ * The text a custom node's JSON carries in memory (read from a `.docx` control), if any.
91
+ */
92
+ export const foreignTextOf = (json: NodeJSON): string | undefined =>
93
+ (json as { [FOREIGN_TEXT]?: string })[FOREIGN_TEXT];
94
+
95
+ /**
96
+ * `json` carrying `text` in memory: never saved (`JSON.stringify` and copies leave it out).
97
+ */
98
+ export function withForeignText<T extends NodeJSON>(json: T, text: string): T {
99
+ Object.defineProperty(json, FOREIGN_TEXT, { value: text, configurable: true });
100
+ return json;
101
+ }
102
+
103
+ const FOREIGN = new Set(["foreignInline", "foreignBlock"]);
104
+ /** The deepest JSON walked; deeper input is left to the schema, which refuses it. */
105
+ const MAX_DEPTH = 302;
106
+
107
+ function resolveMarks(marks: unknown, schema: Schema): unknown {
108
+ if (!Array.isArray(marks)) return marks;
109
+ let out: unknown[] | undefined;
110
+ marks.forEach((mark, i) => {
111
+ let next = mark;
112
+ if (isRecord(mark) && typeof mark.type === "string") {
113
+ const attrs = isRecord(mark.attrs) ? mark.attrs : undefined;
114
+ if (CUSTOM_TYPE.test(mark.type) && !schema.marks[mark.type])
115
+ next = { type: "foreign", attrs: { type: mark.type, attrs: mark.attrs ?? null } };
116
+ else if (
117
+ mark.type === "foreign" &&
118
+ typeof attrs?.type === "string" &&
119
+ CUSTOM_TYPE.test(attrs.type) &&
120
+ schema.marks[attrs.type]
121
+ )
122
+ next = { type: attrs.type, ...(isRecord(attrs.attrs) ? { attrs: attrs.attrs } : {}) };
123
+ }
124
+ if (next === mark) return;
125
+ out ??= marks.slice();
126
+ out[i] = next;
127
+ });
128
+ return out ?? marks;
129
+ }
130
+
131
+ /**
132
+ * Untrusted content JSON with custom types `schema` lacks as foreign nodes and marks, and foreign
133
+ * ones whose type it has as themselves. Returns `value` itself when nothing changes; never
134
+ * changes it.
135
+ * @internal
136
+ */
137
+ export function resolveCustom(value: unknown, schema: Schema, inline = false, depth = 0): unknown {
138
+ if (!isRecord(value) || depth > MAX_DEPTH) return value;
139
+ const type = value.type;
140
+ const marks = resolveMarks(value.marks, schema);
141
+ if (typeof type === "string" && CUSTOM_TYPE.test(type) && !schema.nodes[type]) {
142
+ const text = foreignTextOf(value as unknown as NodeJSON);
143
+ return {
144
+ type: inline ? "foreignInline" : "foreignBlock",
145
+ attrs: { type, attrs: value.attrs ?? null, ...(text === undefined ? {} : { text }) },
146
+ ...(marks === undefined ? {} : { marks }),
147
+ };
148
+ }
149
+ if (typeof type === "string" && FOREIGN.has(type) && isRecord(value.attrs)) {
150
+ const custom = value.attrs.type;
151
+ if (typeof custom === "string" && CUSTOM_TYPE.test(custom) && schema.nodes[custom]) {
152
+ const attrs = value.attrs.attrs;
153
+ return {
154
+ type: custom,
155
+ ...(isRecord(attrs) ? { attrs } : {}),
156
+ ...(marks === undefined ? {} : { marks }),
157
+ };
158
+ }
159
+ }
160
+ let content = value.content;
161
+ if (Array.isArray(content)) {
162
+ const items: unknown[] = content;
163
+ const parent = typeof type === "string" ? schema.nodes[type] : undefined;
164
+ const inner = parent ? parent.inlineContent : false;
165
+ let out: unknown[] | undefined;
166
+ items.forEach((child, i) => {
167
+ const next = resolveCustom(child, schema, inner, depth + 1);
168
+ if (next === child) return;
169
+ out ??= items.slice();
170
+ out[i] = next;
171
+ });
172
+ content = out ?? items;
173
+ }
174
+ return content === value.content && marks === value.marks ? value : { ...value, content, marks };
175
+ }
176
+
177
+ /** A foreign mark's JSON as the custom mark it stands for. */
178
+ const markOut = (mark: MarkJSON): MarkJSON =>
179
+ mark.type === "foreign" && mark.attrs
180
+ ? {
181
+ type: String(mark.attrs.type),
182
+ ...(isRecord(mark.attrs.attrs) ? { attrs: mark.attrs.attrs } : {}),
183
+ }
184
+ : mark;
185
+
186
+ /**
187
+ * Content JSON with foreign nodes and marks written back as the custom types they stand for (a
188
+ * foreign node's text carried in memory: `foreignTextOf`). Changes `json` in place.
189
+ * @internal
190
+ */
191
+ export function writeCustom(json: NodeJSON): NodeJSON {
192
+ if (json.marks?.some((m) => m.type === "foreign")) json.marks = json.marks.map(markOut);
193
+ if (FOREIGN.has(json.type) && json.attrs) {
194
+ const { type, attrs, text } = json.attrs as { type: string; attrs?: unknown; text?: unknown };
195
+ const out: NodeJSON = { type, ...(isRecord(attrs) ? { attrs } : {}) };
196
+ if (json.marks) out.marks = json.marks;
197
+ return typeof text === "string" ? withForeignText(out, text) : out;
198
+ }
199
+ if (json.content) json.content = json.content.map(writeCustom);
200
+ return json;
201
+ }
package/src/v3/index.ts CHANGED
@@ -31,6 +31,14 @@ export {
31
31
  type ThemeJSON,
32
32
  type WordSettingsJSON,
33
33
  } from "./document.js";
34
+ export {
35
+ type ContentOptions,
36
+ type Extension,
37
+ type ExtensionNodeSpec,
38
+ foreignTextOf,
39
+ type ParseOptions,
40
+ withForeignText,
41
+ } from "./extensions.js";
34
42
  export { migrateToV3 } from "./migrate.js";
35
43
  export {
36
44
  type CellFormat,
@@ -44,6 +52,7 @@ export {
44
52
  tableConditions,
45
53
  } from "./resolve.js";
46
54
  export {
55
+ CUSTOM_TYPE,
47
56
  checkSection,
48
57
  HIGHLIGHT_COLORS,
49
58
  JUSTIFICATIONS,
package/src/v3/resolve.ts CHANGED
@@ -866,6 +866,11 @@ export class Resolver {
866
866
  const counters = new Map<number, (number | undefined)[]>();
867
867
  const overridden = new Set<string>();
868
868
  return paragraphs.map((attrs) => {
869
+ // Not numbered (most paragraphs): no number without resolving the whole paragraph, which
870
+ // the view does for every block on every change (12.11). As `#resolve` merges numbering.
871
+ const numbering = (attrs as ParagraphPropertiesJSON).numbering;
872
+ const style = (attrs as ParagraphPropertiesJSON).style ?? undefined;
873
+ if (!(numbering?.id ?? this.#paragraphStyle(style).paragraph.numbering?.id)) return null;
869
874
  const { run, level: found } = this.#resolve(attrs);
870
875
  if (!found) return null;
871
876
  const { instance, abstract, index, level } = found;
package/src/v3/schema.ts CHANGED
@@ -61,7 +61,9 @@ export const JUSTIFICATIONS = [
61
61
  ] as const;
62
62
  export type Justification = (typeof JUSTIFICATIONS)[number];
63
63
 
64
+ /** @internal */
64
65
  export const LINE_RULES = ["auto", "exact", "atLeast"] as const;
66
+ /** @internal */
65
67
  export const TAB_KINDS = [
66
68
  "left",
67
69
  "center",
@@ -73,7 +75,9 @@ export const TAB_KINDS = [
73
75
  "start",
74
76
  "end",
75
77
  ] as const;
78
+ /** @internal */
76
79
  export const TAB_LEADERS = ["none", "dot", "hyphen", "underscore", "heavy", "middleDot"] as const;
80
+ /** @internal */
77
81
  export const SECTION_TYPES = [
78
82
  "nextPage",
79
83
  "continuous",
@@ -81,6 +85,7 @@ export const SECTION_TYPES = [
81
85
  "oddPage",
82
86
  "nextColumn",
83
87
  ] as const;
88
+ /** @internal */
84
89
  export const VERTICAL_ALIGNS = ["baseline", "superscript", "subscript"] as const;
85
90
  /** Word's highlight colors (ST_HighlightColor); any other color is shading. */
86
91
  export const HIGHLIGHT_COLORS = [
@@ -102,6 +107,7 @@ export const HIGHLIGHT_COLORS = [
102
107
  "lightGray",
103
108
  "none",
104
109
  ] as const;
110
+ /** @internal */
105
111
  export const THEME_FONTS = [
106
112
  "majorAscii",
107
113
  "majorHAnsi",
@@ -136,7 +142,10 @@ const ID = int(0, 2_147_483_647);
136
142
  const revisionFields = { id: ID, author: str(), date: nullable(date) };
137
143
  const revision = shape(revisionFields, ["id", "author"]);
138
144
 
139
- /** How notes are placed and numbered (`w:footnotePr`, `w:endnotePr`), for a document or section. */
145
+ /**
146
+ * How notes are placed and numbered (`w:footnotePr`, `w:endnotePr`), for a document or section.
147
+ * @internal
148
+ */
140
149
  export const checkNoteProperties: Check = shape({
141
150
  position: oneOf(["pageBottom", "beneathText", "sectEnd", "docEnd"]),
142
151
  format: token,
@@ -294,9 +303,14 @@ const propertiesCheck =
294
303
  return undefined;
295
304
  };
296
305
 
297
- /** Table, row and cell properties as a table style or a row's exceptions give them. */
306
+ /**
307
+ * Table, row and cell properties as a table style or a row's exceptions give them.
308
+ * @internal
309
+ */
298
310
  export const checkTableProperties: Check = propertiesCheck(tableProperties);
311
+ /** @internal */
299
312
  export const checkRowProperties: Check = propertiesCheck(rowProperties);
313
+ /** @internal */
300
314
  export const checkCellProperties: Check = propertiesCheck(cellProperties);
301
315
 
302
316
  /** EMU (English Metric Units: 914 400 per inch), as DrawingML measures pictures. */
@@ -341,7 +355,10 @@ export const RUN_PROPERTY_MARKS = [
341
355
  "characterSpacing",
342
356
  ];
343
357
 
344
- /** Run properties given as marks JSON (a style's, a paragraph mark's, a recorded change's previous). */
358
+ /**
359
+ * Run properties given as marks JSON (a style's, a paragraph mark's, a recorded change's previous).
360
+ * @internal
361
+ */
345
362
  export const checkRunProperties: Check = (v) => {
346
363
  if (!Array.isArray(v)) return "must be an array of marks";
347
364
  for (const mark of v) {
@@ -416,10 +433,16 @@ const paragraphProperties: Record<string, AttributeSpec> = {
416
433
  ext: nullableAttr(xml),
417
434
  };
418
435
 
419
- /** The names of the paragraph properties (`w:pPr`) among a paragraph's attributes. */
436
+ /**
437
+ * The names of the paragraph properties (`w:pPr`) among a paragraph's attributes.
438
+ * @internal
439
+ */
420
440
  export const PARAGRAPH_PROPERTY_KEYS: readonly string[] = Object.keys(paragraphProperties);
421
441
 
422
- /** Paragraph properties as a style, a numbering level, the defaults or a recorded change give them. */
442
+ /**
443
+ * Paragraph properties as a style, a numbering level, the defaults or a recorded change give them.
444
+ * @internal
445
+ */
423
446
  export const checkParagraphProperties: Check = (v) => {
424
447
  if (!isRecord(v)) return "must be an object";
425
448
  for (const [key, value] of Object.entries(v)) {
@@ -479,6 +502,53 @@ const themeFont = markAttr(nullable(oneOf(THEME_FONTS)), null);
479
502
  const hexByte = (v: unknown) =>
480
503
  typeof v === "string" && /^[0-9A-Fa-f]{2}$/.test(v) ? undefined : "must be a hex byte";
481
504
 
505
+ /**
506
+ * The name of a custom node or mark type (ADR-0008): `<namespace>:<name>`, lowercase letters,
507
+ * digits and `-`. Word's types never have a colon.
508
+ */
509
+ export const CUSTOM_TYPE = /^[a-z0-9-]+:[a-z0-9-]+$/;
510
+
511
+ /** The largest custom attributes a foreign node or mark holds, as JSON text. */
512
+ const MAX_FOREIGN_ATTRS = 65_536;
513
+
514
+ /** Plain JSON (no `undefined`, functions, non-finite numbers or cycles), nested at most 32 deep. */
515
+ function plainJSON(value: unknown, depth = 0): boolean {
516
+ if (depth > 32) return false;
517
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
518
+ if (typeof value === "number") return Number.isFinite(value);
519
+ if (Array.isArray(value)) return value.every((v) => plainJSON(v, depth + 1));
520
+ return (
521
+ isRecord(value) &&
522
+ Object.getPrototypeOf(value) === Object.prototype &&
523
+ Object.values(value).every((v) => plainJSON(v, depth + 1))
524
+ );
525
+ }
526
+
527
+ /** A foreign type's attributes: a plain JSON object, size-limited. */
528
+ const foreignAttrs: Check = (v) => {
529
+ if (!isRecord(v) || !plainJSON(v)) return "must be a plain JSON object";
530
+ return JSON.stringify(v).length <= MAX_FOREIGN_ATTRS
531
+ ? undefined
532
+ : `must be at most ${MAX_FOREIGN_ATTRS} characters as JSON`;
533
+ };
534
+
535
+ /**
536
+ * What a foreign node or mark holds: the custom type and attributes it was read as. `text` is
537
+ * a foreign node's text as a `.docx` control showed it: in memory only, never saved.
538
+ */
539
+ const foreign = {
540
+ type: {
541
+ validate: (v: unknown) =>
542
+ typeof v === "string" && CUSTOM_TYPE.test(v) ? undefined : "must be a namespaced type",
543
+ },
544
+ attrs: nullableAttr(foreignAttrs),
545
+ };
546
+ const foreignNode = {
547
+ attrs: { ...foreign, text: nullableAttr(str(65_535)) },
548
+ text: (attrs: Record<string, unknown>) =>
549
+ typeof attrs.text === "string" ? attrs.text : `[${String(attrs.type)}]`,
550
+ };
551
+
482
552
  export const schema = new Schema({
483
553
  nodes: {
484
554
  doc: { content: "block+" },
@@ -666,6 +736,12 @@ export const schema = new Schema({
666
736
  run: { default: false, validate: bool },
667
737
  },
668
738
  },
739
+ /**
740
+ * A custom node whose extension is not loaded (ADR-0008): kept whole, written back as the
741
+ * type and attributes it was read as. Only in memory: never saved under this name.
742
+ */
743
+ foreignInline: { group: "inline", inline: true, ...foreignNode },
744
+ foreignBlock: { group: "block", ...foreignNode },
669
745
  },
670
746
  marks: {
671
747
  // Order: the canonical order of mark sets, and of nesting when rendered (outermost first).
@@ -747,5 +823,7 @@ export const schema = new Schema({
747
823
  },
748
824
  /** The `w:rPr` these marks were read from, verbatim (see the module comment). */
749
825
  runExt: { attrs: { xml: markAttr(xml) } },
826
+ /** A custom mark whose extension is not loaded, as `foreignInline` is a node. Several combine. */
827
+ foreign: { attrs: foreign, excludes: "", inclusive: false },
750
828
  },
751
829
  });