@folijs/core 0.5.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 (202) hide show
  1. package/CHANGELOG.md +187 -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/commands.d.ts +2 -0
  50. package/dist/state/commands.d.ts.map +1 -1
  51. package/dist/state/commands.js +38 -6
  52. package/dist/state/commands.js.map +1 -1
  53. package/dist/state/comments.d.ts +1 -7
  54. package/dist/state/comments.d.ts.map +1 -1
  55. package/dist/state/comments.js +13 -3
  56. package/dist/state/comments.js.map +1 -1
  57. package/dist/state/controls.d.ts +110 -0
  58. package/dist/state/controls.d.ts.map +1 -0
  59. package/dist/state/controls.js +1473 -0
  60. package/dist/state/controls.js.map +1 -0
  61. package/dist/state/editor.d.ts +188 -68
  62. package/dist/state/editor.d.ts.map +1 -1
  63. package/dist/state/editor.js +265 -79
  64. package/dist/state/editor.js.map +1 -1
  65. package/dist/state/fields.d.ts +68 -0
  66. package/dist/state/fields.d.ts.map +1 -0
  67. package/dist/state/fields.js +410 -0
  68. package/dist/state/fields.js.map +1 -0
  69. package/dist/state/fieldupdate.d.ts +132 -0
  70. package/dist/state/fieldupdate.d.ts.map +1 -0
  71. package/dist/state/fieldupdate.js +1575 -0
  72. package/dist/state/fieldupdate.js.map +1 -0
  73. package/dist/state/find.d.ts +66 -0
  74. package/dist/state/find.d.ts.map +1 -0
  75. package/dist/state/find.js +405 -0
  76. package/dist/state/find.js.map +1 -0
  77. package/dist/state/history.d.ts +2 -0
  78. package/dist/state/history.d.ts.map +1 -1
  79. package/dist/state/history.js +44 -7
  80. package/dist/state/history.js.map +1 -1
  81. package/dist/state/index.d.ts +13 -6
  82. package/dist/state/index.d.ts.map +1 -1
  83. package/dist/state/index.js +12 -5
  84. package/dist/state/index.js.map +1 -1
  85. package/dist/state/lists.d.ts +3 -3
  86. package/dist/state/lists.d.ts.map +1 -1
  87. package/dist/state/lists.js.map +1 -1
  88. package/dist/state/mark.d.ts +1 -17
  89. package/dist/state/mark.d.ts.map +1 -1
  90. package/dist/state/mark.js +10 -1
  91. package/dist/state/mark.js.map +1 -1
  92. package/dist/state/navigation.d.ts +70 -0
  93. package/dist/state/navigation.d.ts.map +1 -0
  94. package/dist/state/navigation.js +226 -0
  95. package/dist/state/navigation.js.map +1 -0
  96. package/dist/state/notes.d.ts +84 -0
  97. package/dist/state/notes.d.ts.map +1 -0
  98. package/dist/state/notes.js +451 -0
  99. package/dist/state/notes.js.map +1 -0
  100. package/dist/state/review.d.ts +8 -4
  101. package/dist/state/review.d.ts.map +1 -1
  102. package/dist/state/review.js +134 -18
  103. package/dist/state/review.js.map +1 -1
  104. package/dist/state/sections.d.ts +91 -0
  105. package/dist/state/sections.d.ts.map +1 -0
  106. package/dist/state/sections.js +479 -0
  107. package/dist/state/sections.js.map +1 -0
  108. package/dist/state/state.d.ts +13 -7
  109. package/dist/state/state.d.ts.map +1 -1
  110. package/dist/state/state.js +9 -2
  111. package/dist/state/state.js.map +1 -1
  112. package/dist/state/stories.d.ts +2 -0
  113. package/dist/state/stories.d.ts.map +1 -0
  114. package/dist/state/stories.js +259 -0
  115. package/dist/state/stories.js.map +1 -0
  116. package/dist/state/tables.d.ts +1 -36
  117. package/dist/state/tables.d.ts.map +1 -1
  118. package/dist/state/tables.js +25 -6
  119. package/dist/state/tables.js.map +1 -1
  120. package/dist/state/track.d.ts +1 -6
  121. package/dist/state/track.d.ts.map +1 -1
  122. package/dist/state/track.js +65 -9
  123. package/dist/state/track.js.map +1 -1
  124. package/dist/state/word.d.ts +47 -55
  125. package/dist/state/word.d.ts.map +1 -1
  126. package/dist/state/word.js +306 -19
  127. package/dist/state/word.js.map +1 -1
  128. package/dist/state/wordclip.d.ts +17 -6
  129. package/dist/state/wordclip.d.ts.map +1 -1
  130. package/dist/state/wordclip.js +254 -17
  131. package/dist/state/wordclip.js.map +1 -1
  132. package/dist/state/wordformat.d.ts +1 -86
  133. package/dist/state/wordformat.d.ts.map +1 -1
  134. package/dist/state/wordformat.js +114 -12
  135. package/dist/state/wordformat.js.map +1 -1
  136. package/dist/transform/stepmap.d.ts +0 -2
  137. package/dist/transform/stepmap.d.ts.map +1 -1
  138. package/dist/v3/check.d.ts +0 -25
  139. package/dist/v3/check.d.ts.map +1 -1
  140. package/dist/v3/check.js +35 -7
  141. package/dist/v3/check.js.map +1 -1
  142. package/dist/v3/document.d.ts +135 -10
  143. package/dist/v3/document.d.ts.map +1 -1
  144. package/dist/v3/document.js +192 -38
  145. package/dist/v3/document.js.map +1 -1
  146. package/dist/v3/extensions.d.ts +43 -0
  147. package/dist/v3/extensions.d.ts.map +1 -0
  148. package/dist/v3/extensions.js +154 -0
  149. package/dist/v3/extensions.js.map +1 -0
  150. package/dist/v3/index.d.ts +3 -2
  151. package/dist/v3/index.d.ts.map +1 -1
  152. package/dist/v3/index.js +3 -2
  153. package/dist/v3/index.js.map +1 -1
  154. package/dist/v3/resolve.d.ts +9 -3
  155. package/dist/v3/resolve.d.ts.map +1 -1
  156. package/dist/v3/resolve.js +28 -4
  157. package/dist/v3/resolve.js.map +1 -1
  158. package/dist/v3/schema.d.ts +5 -16
  159. package/dist/v3/schema.d.ts.map +1 -1
  160. package/dist/v3/schema.js +167 -7
  161. package/dist/v3/schema.js.map +1 -1
  162. package/package.json +5 -1
  163. package/src/document.ts +5 -1
  164. package/src/index.ts +330 -4
  165. package/src/internal.ts +50 -0
  166. package/src/model/attrs.ts +10 -2
  167. package/src/model/content.ts +1 -1
  168. package/src/model/errors.ts +4 -1
  169. package/src/model/fragment.ts +2 -1
  170. package/src/model/mark.ts +1 -1
  171. package/src/model/node.ts +6 -4
  172. package/src/model/schema.ts +9 -3
  173. package/src/schema.ts +2 -0
  174. package/src/state/commands.ts +41 -4
  175. package/src/state/comments.ts +12 -3
  176. package/src/state/controls.ts +1612 -0
  177. package/src/state/editor.ts +508 -143
  178. package/src/state/fields.ts +444 -0
  179. package/src/state/fieldupdate.ts +1771 -0
  180. package/src/state/find.ts +518 -0
  181. package/src/state/history.ts +53 -7
  182. package/src/state/index.ts +125 -1
  183. package/src/state/lists.ts +2 -2
  184. package/src/state/mark.ts +10 -1
  185. package/src/state/navigation.ts +305 -0
  186. package/src/state/notes.ts +529 -0
  187. package/src/state/numeric-pictures.word.json +172 -0
  188. package/src/state/review.ts +172 -19
  189. package/src/state/sections.ts +578 -0
  190. package/src/state/state.ts +21 -3
  191. package/src/state/stories.ts +312 -0
  192. package/src/state/tables.ts +29 -7
  193. package/src/state/track.ts +72 -10
  194. package/src/state/word.ts +360 -24
  195. package/src/state/wordclip.ts +282 -32
  196. package/src/state/wordformat.ts +116 -12
  197. package/src/v3/check.ts +35 -7
  198. package/src/v3/document.ts +358 -50
  199. package/src/v3/extensions.ts +201 -0
  200. package/src/v3/index.ts +16 -0
  201. package/src/v3/resolve.ts +38 -9
  202. package/src/v3/schema.ts +174 -7
@@ -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,19 +21,29 @@ 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,
34
+ checkNoteProperties,
21
35
  checkRowProperties,
22
36
  checkSection,
23
37
  checkTableProperties,
24
38
  checkParagraphProperties as paragraphProperties,
25
39
  checkRunProperties as runProperties,
26
- schema,
27
40
  } from "./schema.js";
28
41
 
29
- /** The schema version of documents in the Word model (ADR-0005; v4 adds tables and pictures, ADR-0006). */
30
- export const SCHEMA_VERSION = 4;
42
+ /**
43
+ * The schema version of documents in the Word model (ADR-0005; v4 adds tables and pictures,
44
+ * ADR-0006; v5 stories, fields, content controls and notes, ADR-0007).
45
+ */
46
+ export const SCHEMA_VERSION = 5;
31
47
 
32
48
  /** Page setup of a section, in twips (1/1440 inch). Missing parts take Word's defaults. */
33
49
  export interface SectionJSON {
@@ -46,10 +62,32 @@ export interface SectionJSON {
46
62
  /** Relationship ids of the header and footer parts (their content stays in the package until Phase 11). */
47
63
  headers?: { default?: string; first?: string; even?: string };
48
64
  footers?: { default?: string; first?: string; even?: string };
65
+ /** `w:cols` (v5). `widths` when the columns are not of equal width. */
66
+ columns?: {
67
+ count?: number;
68
+ space?: number;
69
+ equalWidth?: boolean;
70
+ separator?: boolean;
71
+ widths?: { width: number; space?: number }[];
72
+ };
73
+ /** `w:pgNumType` (v5). */
74
+ pageNumbers?: { start?: number; format?: string };
75
+ footnotes?: NotePropertiesJSON;
76
+ endnotes?: NotePropertiesJSON;
77
+ /** `w:sectPrChange`: who changed the page setup while tracking, and what it was. */
78
+ change?: { id: number; author: string; date?: string | null; previous: SectionJSON };
49
79
  /** The `w:sectPr` this was read from, verbatim. */
50
80
  ext?: string;
51
81
  }
52
82
 
83
+ /** How notes are placed and numbered (`w:footnotePr`, `w:endnotePr`). */
84
+ export interface NotePropertiesJSON {
85
+ position?: "pageBottom" | "beneathText" | "sectEnd" | "docEnd";
86
+ format?: string;
87
+ start?: number;
88
+ restart?: "continuous" | "eachSect" | "eachPage";
89
+ }
90
+
53
91
  export interface BorderJSON {
54
92
  style: string;
55
93
  size?: number;
@@ -278,6 +316,74 @@ export interface CommentJSON {
278
316
  ext?: string;
279
317
  }
280
318
 
319
+ /**
320
+ * Content outside the body (schema v5, ADR-0007). `noteType` is a note's `w:type`: the separators
321
+ * and the continuation notice have no reference and are not numbered.
322
+ */
323
+ export interface StoryJSON {
324
+ kind: "header" | "footer" | "footnote" | "endnote";
325
+ noteType?: "normal" | "separator" | "continuationSeparator" | "continuationNotice";
326
+ /** A `doc` of blocks. */
327
+ content: NodeJSON;
328
+ /** What the part keeps of the story's own element, verbatim. */
329
+ ext?: string;
330
+ }
331
+
332
+ /** A content control's properties (`w:sdtPr`, schema v5), by the id its nodes refer to. */
333
+ export interface ControlJSON {
334
+ kind:
335
+ | "text"
336
+ | "richText"
337
+ | "dropDown"
338
+ | "comboBox"
339
+ | "date"
340
+ | "checkbox"
341
+ | "picture"
342
+ | "repeating"
343
+ | "repeatingItem"
344
+ | "other";
345
+ tag?: string;
346
+ alias?: string;
347
+ lock?: "sdtLocked" | "contentLocked" | "sdtContentLocked" | "unlocked";
348
+ items?: { value: string; display?: string }[];
349
+ dateFormat?: string;
350
+ /** `w:date/@w:fullDate`: the date picked, as Word writes it (`2026-03-03T00:00:00Z`). */
351
+ date?: string;
352
+ checked?: boolean;
353
+ /** A check box's glyphs (`w14:checkedState`, `w14:uncheckedState`): hex code and font. */
354
+ checkedState?: { value: string; font?: string };
355
+ uncheckedState?: { value: string; font?: string };
356
+ /** `w:text/@w:multiLine`: a plain text control that takes line breaks. */
357
+ multiLine?: boolean;
358
+ /** `w:sdtPr/w:rPr` as marks: how text put in place of the placeholder looks. */
359
+ format?: MarkJSON[];
360
+ /** `w15:doNotAllowInsertDeleteSection`: a repeating section's items are fixed. */
361
+ noInsertDelete?: boolean;
362
+ /** Deleted whole while tracking (in the editor: not written): accepting removes the control. */
363
+ deleted?: boolean;
364
+ /**
365
+ * `showing`: the content is the placeholder. `docPart`: the glossary entry it comes from.
366
+ * `text`: that entry's text, what emptying the control brings back.
367
+ */
368
+ placeholder?: { showing?: boolean; docPart?: string; text?: string };
369
+ /** `w:dataBinding`: kept, not evaluated. */
370
+ binding?: { xpath?: string; storeItemId?: string; prefixMappings?: string };
371
+ /** `w:sdtPr` and `w:sdtEndPr`, verbatim. */
372
+ ext?: string;
373
+ }
374
+
375
+ /** What `word/settings.xml` says about pages and notes (schema v5). */
376
+ export interface WordSettingsJSON {
377
+ /**
378
+ * `w:compat/w:doNotUseHTMLParagraphAutoSpacing`: the space after a paragraph and the space
379
+ * before the next add up (without it Word takes the larger, in every compatibility mode).
380
+ */
381
+ doNotUseHTMLParagraphAutoSpacing?: boolean;
382
+ evenAndOddHeaders?: boolean;
383
+ footnotes?: NotePropertiesJSON;
384
+ endnotes?: NotePropertiesJSON;
385
+ }
386
+
281
387
  /** A document in the Word model: the content tree and what Word keeps beside it. */
282
388
  export interface FoliDocument {
283
389
  schemaVersion: typeof SCHEMA_VERSION;
@@ -296,21 +402,37 @@ export interface FoliDocument {
296
402
  comments: CommentJSON[];
297
403
  /** The pictures' bytes, by the key `picture` nodes give (none when missing). */
298
404
  resources?: Record<string, ResourceJSON>;
405
+ /** Headers, footers and notes, by id (a header's or footer's is its relationship id). */
406
+ stories?: Record<string, StoryJSON>;
407
+ /** Content controls' properties, by the id their nodes refer to. */
408
+ controls?: Record<string, ControlJSON>;
409
+ settings?: WordSettingsJSON;
299
410
  content: NodeJSON;
300
411
  }
301
412
 
413
+ /** A document of schema v4 (no stories, fields or content controls in the model). */
414
+ export type FoliDocumentV4 = Omit<
415
+ FoliDocument,
416
+ "schemaVersion" | "stories" | "controls" | "settings"
417
+ > & { schemaVersion: 4 };
418
+
302
419
  /** A document of schema v3 (no tables or pictures in the model), as `migrateToV3` gives it. */
303
- export type FoliDocumentV3 = Omit<FoliDocument, "schemaVersion" | "resources"> & {
420
+ export type FoliDocumentV3 = Omit<FoliDocumentV4, "schemaVersion" | "resources"> & {
304
421
  schemaVersion: 3;
305
422
  };
306
423
 
307
424
  /** Schema v3 → v4: the version only (a table kept opaque stays so until imported again). */
308
- export function migrateToV4(doc: FoliDocumentV3): FoliDocument {
425
+ export function migrateToV4(doc: FoliDocumentV3): FoliDocumentV4 {
426
+ return { ...doc, schemaVersion: 4 };
427
+ }
428
+
429
+ /** Schema v4 → v5: the version only (what is opaque stays so until imported again). */
430
+ export function migrateToV5(doc: FoliDocumentV4): FoliDocument {
309
431
  return { ...doc, schemaVersion: SCHEMA_VERSION };
310
432
  }
311
433
 
312
434
  /**
313
- * A new document: `content` (schema v4; default: one empty paragraph) on A4 with 25.4 mm
435
+ * A new document: `content` (schema v5; default: one empty paragraph) on A4 with 25.4 mm
314
436
  * margins, with the styles and list definitions the editor's commands use (Normal, Heading 1–6,
315
437
  * List Paragraph, Hyperlink; bullets and numbers) and 11 pt Georgia, 1.5 lines: the look a
316
438
  * migrated 0.2.0 document has. `section` (in twips: `mmToTwips`) is merged over that page:
@@ -322,8 +444,10 @@ export function createDocument(
322
444
  section?: SectionJSON,
323
445
  ): FoliDocument {
324
446
  const empty = { type: "doc", content: [] } as const satisfies NodeJSON;
325
- const blank = migrateToV4(
326
- migrateToV3({ schemaVersion: 2, settings: DEFAULT_SETTINGS, content: empty as never }),
447
+ const blank = migrateToV5(
448
+ migrateToV4(
449
+ migrateToV3({ schemaVersion: 2, settings: DEFAULT_SETTINGS, content: empty as never }),
450
+ ),
327
451
  );
328
452
  const base = blank.section;
329
453
  return {
@@ -344,34 +468,47 @@ export function createDocument(
344
468
  * and 2 are validated as such and migrated (`migrateToV3`). Throws FoliDocumentError instead
345
469
  * of dropping anything.
346
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
+ *
347
474
  * What Word opens is accepted: duplicate ids (the first wins), a numbering instance or a reply
348
475
  * whose target is missing, references to styles that do not exist. Rejected is only what the
349
476
  * engine cannot work with: wrong types, out-of-range values, and cycles (a style based on
350
477
  * itself, comments replying to each other) that would never end when followed.
351
478
  */
352
- export function parseDocument(input: unknown): FoliDocument {
479
+ export function parseDocument(input: unknown, options: ParseOptions = {}): FoliDocument {
353
480
  if (!isRecord(input)) throw new FoliDocumentError("Document must be an object");
354
481
  const version = input.schemaVersion;
355
482
  if (version === 1 || version === 2) {
356
- return parseDocument(migrateToV4(migrateToV3(parseDocumentV2(input))));
483
+ return parseDocument(migrateToV5(migrateToV4(migrateToV3(parseDocumentV2(input)))), options);
357
484
  }
358
- if (version === 3) {
359
- if (Object.hasOwn(input, "resources")) fail("resources", "unknown key (schema 4 and later)");
360
- const doc = parseDocument({ ...input, schemaVersion: SCHEMA_VERSION });
361
- // Tables and pictures are schema 4's: a schema 3 document holding one is not one.
485
+ if (version === 3 || version === 4) {
486
+ if (version === 3 && Object.hasOwn(input, "resources"))
487
+ fail("resources", "unknown key (schema 4 and later)");
488
+ for (const key of V5_KEYS)
489
+ if (Object.hasOwn(input, key)) fail(key, "unknown key (schema 5 and later)");
490
+ const doc = parseDocument({ ...input, schemaVersion: SCHEMA_VERSION }, options);
491
+ // What a later schema added is not in a document that says it is of an earlier one.
492
+ const later = laterSection(doc.section);
493
+ if (later) fail("section", `${later} is of schema 5 (the document says schema ${version})`);
362
494
  for (const [path, content] of [
363
495
  ["content", doc.content],
364
496
  ...doc.comments.map((c, i) => [`comments[${i}].content`, { content: c.content }] as const),
365
497
  ] as const) {
366
- const found = nodeOfV4(content);
367
- if (found) fail(path, `${found} is a schema 4 node (the document says schema 3)`);
498
+ const found = laterNode(content, version);
499
+ if (found)
500
+ fail(
501
+ path,
502
+ `${found.name} is a schema ${found.schema} node (the document says schema ${version})`,
503
+ );
368
504
  }
369
- doc.styles.forEach((style, i) => {
370
- for (const key of ["table", "row", "cell", "conditions"]) {
371
- if (Object.hasOwn(style, key))
372
- fail(`styles[${i}]`, `unknown key ${key} (schema 4 and later)`);
373
- }
374
- });
505
+ if (version === 3)
506
+ doc.styles.forEach((style, i) => {
507
+ for (const key of ["table", "row", "cell", "conditions"]) {
508
+ if (Object.hasOwn(style, key))
509
+ fail(`styles[${i}]`, `unknown key ${key} (schema 4 and later)`);
510
+ }
511
+ });
375
512
  return doc;
376
513
  }
377
514
  if (version !== SCHEMA_VERSION) {
@@ -402,6 +539,9 @@ export function parseDocument(input: unknown): FoliDocument {
402
539
  if (input.theme !== undefined) check("theme", input.theme, checkTheme);
403
540
  check("comments", input.comments, listOf(checkComment));
404
541
  if (input.resources !== undefined) check("resources", input.resources, checkResources);
542
+ if (input.stories !== undefined) check("stories", input.stories, checkStories);
543
+ if (input.controls !== undefined) check("controls", input.controls, checkControls);
544
+ if (input.settings !== undefined) check("settings", input.settings, checkSettings);
405
545
  const styles = input.styles as StyleJSON[];
406
546
  const comments = input.comments as CommentJSON[];
407
547
  noCycles(
@@ -419,7 +559,16 @@ export function parseDocument(input: unknown): FoliDocument {
419
559
  (c) => `comment ${c.id} replies to itself`,
420
560
  );
421
561
 
422
- const content = parseContent(input.content);
562
+ const schema = schemaWith(options.extensions);
563
+ const content = parseContent(input.content, { schema });
564
+ const stories = Object.entries((input.stories ?? {}) as Record<string, StoryJSON>).map(
565
+ ([id, story]) => {
566
+ const path = `stories[${JSON.stringify(id)}].content`;
567
+ const tree = parseContent(story.content, { path, schema });
568
+ storyRules(tree, story.kind, path);
569
+ return [id, { ...structuredClone({ ...story, content: null }), content: copied(tree) }];
570
+ },
571
+ );
423
572
  // A copy: the validated document must not change when the caller's input does.
424
573
  const envelope = structuredClone({
425
574
  section: input.section,
@@ -428,7 +577,19 @@ export function parseDocument(input: unknown): FoliDocument {
428
577
  numbering: input.numbering,
429
578
  theme: input.theme,
430
579
  resources: input.resources,
431
- }) as Pick<FoliDocument, "section" | "defaults" | "styles" | "numbering" | "theme" | "resources">;
580
+ controls: input.controls,
581
+ settings: input.settings,
582
+ }) as Pick<
583
+ FoliDocument,
584
+ | "section"
585
+ | "defaults"
586
+ | "styles"
587
+ | "numbering"
588
+ | "theme"
589
+ | "resources"
590
+ | "controls"
591
+ | "settings"
592
+ >;
432
593
  return {
433
594
  schemaVersion: SCHEMA_VERSION,
434
595
  section: envelope.section,
@@ -438,21 +599,38 @@ export function parseDocument(input: unknown): FoliDocument {
438
599
  ...(envelope.theme === undefined ? {} : { theme: envelope.theme }),
439
600
  comments: comments.map((c, i) => ({
440
601
  ...structuredClone({ ...c, content: [] }),
441
- content: blocks(c.content, `comments[${i}].content`).map((block) => block.toJSON()),
602
+ content: blocks(c.content, `comments[${i}].content`, schema).map((block) => {
603
+ block.descendants((node) => {
604
+ if (node.type.name === "noteReference")
605
+ fail(`comments[${i}].content`, "a comment cannot hold a note reference");
606
+ return true;
607
+ });
608
+ return copied(block);
609
+ }),
442
610
  })),
443
611
  ...(envelope.resources === undefined ? {} : { resources: envelope.resources }),
444
- content: content.toJSON(),
612
+ ...(input.stories === undefined ? {} : { stories: Object.fromEntries(stories) }),
613
+ ...(envelope.controls === undefined ? {} : { controls: envelope.controls }),
614
+ ...(envelope.settings === undefined ? {} : { settings: envelope.settings }),
615
+ content: copied(content),
445
616
  };
446
617
  }
447
618
 
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()));
621
+
448
622
  /**
449
623
  * Parses untrusted schema v4 content into a `doc` node, with Word's rules the content
450
624
  * expressions do not say (`fragment`: content to paste, which a table may end): a table is never
451
- * followed by a table (Word would merge them) nor ends
452
- * the document, and a paragraph in a cell ends no section and holds no page or column break.
625
+ * followed by a table (Word would merge them; tables in different content controls stay apart)
626
+ * nor ends the document, and a paragraph in a cell ends no section and holds no page or column
627
+ * break. With `extensions` their types are read as themselves; a namespaced type they do not
628
+ * declare becomes a foreign node or mark.
453
629
  */
454
- export function parseContent(value: unknown, path = "content", fragment = false): Node {
455
- 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);
456
634
  if (doc.type !== schema.topNodeType) fail(path, 'root node must be of type "doc"');
457
635
  if (doc.marks.length) fail(`${path}.marks`, "doc cannot have marks");
458
636
  wordRules(doc, path, false, fragment);
@@ -464,7 +642,10 @@ function wordRules(parent: Node, path: string, inCell: boolean, fragment = false
464
642
  const at = `${path}.content[${index}]`;
465
643
  if (node.type.name === "table") {
466
644
  const next = parent.maybeChild(index + 1);
467
- if (next?.type.name === "table") {
645
+ if (
646
+ next?.type.name === "table" &&
647
+ JSON.stringify(next.attrs.controls) === JSON.stringify(node.attrs.controls)
648
+ ) {
468
649
  fail(at, "a table cannot follow a table (Word would merge them): a paragraph goes between");
469
650
  }
470
651
  if (!next && parent.type.name === "doc" && !fragment) {
@@ -487,15 +668,65 @@ function wordRules(parent: Node, path: string, inCell: boolean, fragment = false
487
668
  });
488
669
  }
489
670
 
671
+ /**
672
+ * What a story may not hold (ADR-0007): import keeps such content opaque instead.
673
+ * @internal
674
+ */
675
+ export function storyRules(tree: Node, kind: StoryJSON["kind"], path: string): void {
676
+ tree.descendants((node) => {
677
+ const name = node.type.name;
678
+ if (node.attrs.section) fail(path, "a story cannot end a section");
679
+ if (name === "noteReference") fail(path, "a story cannot hold a note reference");
680
+ if (COMMENT_NODES.has(name)) fail(path, `a ${kind} cannot hold comments`);
681
+ if (
682
+ (kind === "footnote" || kind === "endnote") &&
683
+ (name === "pageBreak" || name === "columnBreak")
684
+ )
685
+ fail(path, `a note cannot hold a ${name}`);
686
+ return true;
687
+ });
688
+ }
689
+
690
+ const COMMENT_NODES = new Set(["commentStart", "commentEnd", "commentReference"]);
691
+
490
692
  const V4_NODES = new Set(["table", "tableRow", "tableCell", "picture"]);
693
+ const V5_NODES = new Set([
694
+ "fieldStart",
695
+ "fieldCode",
696
+ "fieldSeparator",
697
+ "fieldEnd",
698
+ "controlStart",
699
+ "controlEnd",
700
+ "noteReference",
701
+ "noteMark",
702
+ ]);
703
+ const V5_KEYS = ["stories", "controls", "settings"];
704
+ const V5_SECTION_KEYS = ["columns", "pageNumbers", "footnotes", "endnotes"];
705
+
706
+ /** The first part of a section that schema 5 added, if any. */
707
+ function laterSection(section: unknown): string | undefined {
708
+ return isRecord(section) ? V5_SECTION_KEYS.find((key) => Object.hasOwn(section, key)) : undefined;
709
+ }
491
710
 
492
- /** The first schema 4 node type in validated content JSON, if any. */
493
- function nodeOfV4(content: NodeJSON | { content: NodeJSON[] }): string | undefined {
711
+ /**
712
+ * The first thing in validated content JSON that a schema after `version` added, if any: a node
713
+ * type, a block's `controls`, a part of a section.
714
+ */
715
+ function laterNode(
716
+ content: NodeJSON | { content: NodeJSON[] },
717
+ version: number,
718
+ ): { name: string; schema: number } | undefined {
494
719
  const stack: unknown[] = [content];
495
720
  while (stack.length) {
496
721
  const node = stack.pop();
497
722
  if (!isRecord(node)) continue;
498
- if (V4_NODES.has(node.type as string)) return node.type as string;
723
+ const name = node.type as string;
724
+ if (version < 4 && V4_NODES.has(name)) return { name, schema: 4 };
725
+ if (V5_NODES.has(name)) return { name, schema: 5 };
726
+ const attrs = isRecord(node.attrs) ? node.attrs : {};
727
+ if (attrs.controls) return { name: "controls", schema: 5 };
728
+ const part = laterSection(attrs.section);
729
+ if (part) return { name: part, schema: 5 };
499
730
  if (Array.isArray(node.content)) for (const child of node.content) stack.push(child);
500
731
  }
501
732
  return undefined;
@@ -510,6 +741,9 @@ const ENVELOPE_KEYS = [
510
741
  "theme",
511
742
  "comments",
512
743
  "resources",
744
+ "stories",
745
+ "controls",
746
+ "settings",
513
747
  "content",
514
748
  ];
515
749
 
@@ -552,8 +786,8 @@ function noCycles<T>(
552
786
  });
553
787
  }
554
788
 
555
- function blocks(content: NodeJSON[], path: string): Node[] {
556
- 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 });
557
791
  const list: Node[] = [];
558
792
  doc.forEach((block) => {
559
793
  list.push(block);
@@ -608,6 +842,7 @@ function protocolOf(url: string): string {
608
842
  /** Pictures only: `image/png`, `image/svg+xml`… */
609
843
  const IMAGE_TYPE = /^image\/[A-Za-z0-9][\w.+-]{0,126}$/;
610
844
 
845
+ /** @internal */
611
846
  export const checkResource: Check = (v) => {
612
847
  const error = shape(
613
848
  {
@@ -636,19 +871,92 @@ export const checkResource: Check = (v) => {
636
871
  : undefined;
637
872
  };
638
873
 
639
- const checkResources: Check = (v) => {
640
- if (!isRecord(v)) return "must be an object";
641
- const entries = Object.entries(v);
642
- if (entries.length > 100_000) return "must have at most 100000 resources";
643
- for (const [key, value] of entries) {
644
- // An own `__proto__` key would read as the prototype wherever a missing key is looked up.
645
- const keyError = key === "__proto__" ? "is not a resource key" : text()(key);
646
- if (keyError) return `${key.slice(0, 64)} ${keyError}`;
647
- const error = checkResource(value);
648
- if (error) return `${key} ${error}`;
649
- }
650
- return undefined;
651
- };
874
+ /** An object keyed by ids, every value passing `check`. */
875
+ const recordOf =
876
+ (check: Check, what: string): Check =>
877
+ (v) => {
878
+ if (!isRecord(v)) return "must be an object";
879
+ const entries = Object.entries(v);
880
+ if (entries.length > 100_000) return `must have at most 100000 ${what}s`;
881
+ for (const [key, value] of entries) {
882
+ // An own `__proto__` key would read as the prototype wherever a missing key is looked up.
883
+ const keyError = key === "__proto__" ? `is not a ${what} key` : text()(key);
884
+ if (keyError) return `${key.slice(0, 64)} ${keyError}`;
885
+ const error = check(value);
886
+ if (error) return `${key} ${error}`;
887
+ }
888
+ return undefined;
889
+ };
890
+
891
+ const checkResources = recordOf(checkResource, "resource");
892
+
893
+ const NOTE_KINDS = ["footnote", "endnote"];
894
+ /** The tree is checked by `parseContent` afterwards, with its path. */
895
+ const checkStory: Check = (v) =>
896
+ shape(
897
+ {
898
+ kind: oneOf(["header", "footer", ...NOTE_KINDS]),
899
+ noteType: oneOf(["normal", "separator", "continuationSeparator", "continuationNotice"]),
900
+ content: (c) => (isRecord(c) ? undefined : "must be an object"),
901
+ ext: xml,
902
+ },
903
+ ["kind", "content"],
904
+ )(v) ??
905
+ (isRecord(v) && v.noteType !== undefined && !NOTE_KINDS.includes(v.kind as string)
906
+ ? "noteType is for notes"
907
+ : undefined);
908
+ const checkStories = recordOf(checkStory, "story");
909
+
910
+ /** A content control's properties. */
911
+ export const checkControl: Check = shape(
912
+ {
913
+ kind: oneOf([
914
+ "text",
915
+ "richText",
916
+ "dropDown",
917
+ "comboBox",
918
+ "date",
919
+ "checkbox",
920
+ "picture",
921
+ "repeating",
922
+ "repeatingItem",
923
+ "other",
924
+ ]),
925
+ tag: str(),
926
+ alias: str(),
927
+ lock: oneOf(["sdtLocked", "contentLocked", "sdtContentLocked", "unlocked"]),
928
+ items: listOf(shape({ value: str(), display: str() }, ["value"])),
929
+ dateFormat: str(),
930
+ date: str(),
931
+ checked: bool,
932
+ checkedState: shape({ value: str(), font: str() }, ["value"]),
933
+ uncheckedState: shape({ value: str(), font: str() }, ["value"]),
934
+ multiLine: bool,
935
+ format: runProperties,
936
+ noInsertDelete: bool,
937
+ deleted: bool,
938
+ placeholder: shape({ showing: bool, docPart: str(), text: str(65_535) }, [], true),
939
+ binding: shape(
940
+ { xpath: str(65_535), storeItemId: str(), prefixMappings: str(65_535) },
941
+ [],
942
+ true,
943
+ ),
944
+ ext: xml,
945
+ },
946
+ ["kind"],
947
+ );
948
+ const checkControls = recordOf(checkControl, "control");
949
+
950
+ const checkSettings: Check = shape(
951
+ {
952
+ doNotUseHTMLParagraphAutoSpacing: bool,
953
+ evenAndOddHeaders: bool,
954
+ footnotes: checkNoteProperties,
955
+ endnotes: checkNoteProperties,
956
+ },
957
+ [],
958
+ true,
959
+ );
652
960
 
653
961
  const checkLevel: Check = shape(
654
962
  {