@agentshouse/mdmodel 0.1.0-c3208a08ee314 → 0.1.0-c36da0b08f3db

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 (136) hide show
  1. package/API.md +282 -254
  2. package/README.md +21 -22
  3. package/dist/blocks.d.ts.map +1 -1
  4. package/dist/blocks.js +35 -20
  5. package/dist/definition.d.ts +17 -1
  6. package/dist/definition.d.ts.map +1 -1
  7. package/dist/definition.js +326 -46
  8. package/dist/divide.d.ts.map +1 -1
  9. package/dist/divide.js +27 -17
  10. package/dist/document.d.ts +7 -3
  11. package/dist/document.d.ts.map +1 -1
  12. package/dist/document.js +350 -176
  13. package/dist/event.d.ts +78 -0
  14. package/dist/event.d.ts.map +1 -0
  15. package/dist/event.js +230 -0
  16. package/dist/facts.d.ts +15 -0
  17. package/dist/facts.d.ts.map +1 -0
  18. package/dist/facts.js +38 -0
  19. package/dist/index.d.ts +26 -9
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +15 -6
  22. package/dist/kinds.d.ts +19 -0
  23. package/dist/kinds.d.ts.map +1 -0
  24. package/dist/kinds.js +161 -0
  25. package/dist/links.d.ts +3 -0
  26. package/dist/links.d.ts.map +1 -1
  27. package/dist/links.js +108 -51
  28. package/dist/paths.d.ts +10 -1
  29. package/dist/paths.d.ts.map +1 -1
  30. package/dist/paths.js +118 -12
  31. package/dist/pattern.d.ts +10 -0
  32. package/dist/pattern.d.ts.map +1 -0
  33. package/dist/pattern.js +355 -0
  34. package/dist/project.d.ts +1 -0
  35. package/dist/project.d.ts.map +1 -1
  36. package/dist/project.js +38 -15
  37. package/dist/query/language.d.ts +254 -0
  38. package/dist/query/language.d.ts.map +1 -0
  39. package/dist/query/language.js +620 -0
  40. package/dist/query/match.d.ts +14 -0
  41. package/dist/query/match.d.ts.map +1 -0
  42. package/dist/query/match.js +147 -0
  43. package/dist/query/rows.d.ts +32 -0
  44. package/dist/query/rows.d.ts.map +1 -0
  45. package/dist/query/rows.js +161 -0
  46. package/dist/query/sql.d.ts +39 -0
  47. package/dist/query/sql.d.ts.map +1 -0
  48. package/dist/query/sql.js +284 -0
  49. package/dist/references.d.ts +2 -2
  50. package/dist/references.d.ts.map +1 -1
  51. package/dist/references.js +6 -1
  52. package/dist/reserved.d.ts +5 -0
  53. package/dist/reserved.d.ts.map +1 -0
  54. package/dist/reserved.js +20 -0
  55. package/dist/schema.d.ts +1 -0
  56. package/dist/schema.d.ts.map +1 -1
  57. package/dist/schema.js +55 -4
  58. package/dist/types.d.ts +61 -2
  59. package/dist/types.d.ts.map +1 -1
  60. package/dist/validate.d.ts +32 -2
  61. package/dist/validate.d.ts.map +1 -1
  62. package/dist/validate.js +438 -120
  63. package/dist/yaml.d.ts.map +1 -1
  64. package/dist/yaml.js +36 -3
  65. package/fixtures/README.md +26 -6
  66. package/fixtures/cases/conditional-section/context.json +1 -0
  67. package/fixtures/cases/conditional-section/expected.json +6 -0
  68. package/fixtures/cases/conditional-section/library/questions/hosting.md +9 -0
  69. package/fixtures/cases/conditional-section/library/questions/payments.md +12 -0
  70. package/fixtures/cases/conditional-section/schema.yaml +14 -0
  71. package/fixtures/cases/cross-room-link/context.json +1 -0
  72. package/fixtures/cases/cross-room-link/expected.json +1 -0
  73. package/fixtures/cases/cross-room-link/library/clients/acme.md +6 -0
  74. package/fixtures/cases/cross-room-link/schema.yaml +3 -0
  75. package/fixtures/cases/cross-room-reference/context.json +1 -0
  76. package/fixtures/cases/cross-room-reference/expected.json +1 -0
  77. package/fixtures/cases/cross-room-reference/library/clients/acme.md +9 -0
  78. package/fixtures/cases/cross-room-reference/schema.yaml +9 -0
  79. package/fixtures/cases/link-into-a-reserved-name/context.json +1 -0
  80. package/fixtures/cases/link-into-a-reserved-name/expected.json +5 -0
  81. package/fixtures/cases/link-into-a-reserved-name/library/notes/a.md +6 -0
  82. package/fixtures/cases/link-into-a-reserved-name/schema.yaml +3 -0
  83. package/fixtures/cases/link-into-a-reserved-name-from-an-untyped-document/context.json +1 -0
  84. package/fixtures/cases/link-into-a-reserved-name-from-an-untyped-document/expected.json +5 -0
  85. package/fixtures/cases/link-into-a-reserved-name-from-an-untyped-document/library/notes/b.md +5 -0
  86. package/fixtures/cases/member-on-an-untyped-document/context.json +1 -0
  87. package/fixtures/cases/member-on-an-untyped-document/expected.json +6 -0
  88. package/fixtures/cases/member-on-an-untyped-document/library/note.md +4 -0
  89. package/fixtures/cases/member-on-another-type/context.json +1 -0
  90. package/fixtures/cases/member-on-another-type/expected.json +6 -0
  91. package/fixtures/cases/member-on-another-type/library/note.md +4 -0
  92. package/fixtures/cases/member-on-another-type/schema.yaml +7 -0
  93. package/fixtures/cases/reference-into-a-reserved-name/context.json +1 -0
  94. package/fixtures/cases/reference-into-a-reserved-name/expected.json +6 -0
  95. package/fixtures/cases/reference-into-a-reserved-name/library/notes/a.md +4 -0
  96. package/fixtures/cases/reference-into-a-reserved-name/library/settings/brief.md +1 -0
  97. package/fixtures/cases/reference-into-a-reserved-name/schema.yaml +3 -0
  98. package/fixtures/cases/room-md-declares-a-type/context.json +1 -0
  99. package/fixtures/cases/room-md-declares-a-type/expected.json +6 -0
  100. package/fixtures/cases/room-md-declares-a-type/library/ROOM.md +5 -0
  101. package/fixtures/cases/typed-path-names-another-type/context.json +11 -0
  102. package/fixtures/cases/typed-path-names-another-type/expected.json +6 -0
  103. package/fixtures/cases/typed-path-names-another-type/library/settings/prefs/one.md +3 -0
  104. package/fixtures/cases/typed-path-names-another-type/schema.yaml +6 -0
  105. package/fixtures/cases/typed-path-names-its-type/context.json +11 -0
  106. package/fixtures/cases/typed-path-names-its-type/expected.json +3 -0
  107. package/fixtures/cases/typed-path-names-its-type/library/settings/prefs/deeper/two.md +1 -0
  108. package/fixtures/cases/typed-path-names-its-type/library/settings/prefs/one.md +4 -0
  109. package/fixtures/cases/typed-path-names-its-type/schema.yaml +6 -0
  110. package/fixtures/cases/typed-path-names-no-type/context.json +11 -0
  111. package/fixtures/cases/typed-path-names-no-type/expected.json +6 -0
  112. package/fixtures/cases/typed-path-names-no-type/library/settings/prefs/one.md +1 -0
  113. package/fixtures/cases/typed-path-names-no-type/schema.yaml +6 -0
  114. package/fixtures/cases/unnamed-typed-path-checks-its-fields/context.json +11 -0
  115. package/fixtures/cases/unnamed-typed-path-checks-its-fields/expected.json +6 -0
  116. package/fixtures/cases/unnamed-typed-path-checks-its-fields/library/rooms/team/tasks/plan.md +4 -0
  117. package/fixtures/cases/unnamed-typed-path-checks-its-fields/schema.yaml +5 -0
  118. package/fixtures/cases/unnamed-typed-path-names-a-type/context.json +11 -0
  119. package/fixtures/cases/unnamed-typed-path-names-a-type/expected.json +6 -0
  120. package/fixtures/cases/unnamed-typed-path-names-a-type/library/rooms/team/tasks/plan.md +6 -0
  121. package/fixtures/cases/unnamed-typed-path-names-a-type/schema.yaml +5 -0
  122. package/fixtures/cases/unnamed-typed-path-reads-its-type/context.json +11 -0
  123. package/fixtures/cases/unnamed-typed-path-reads-its-type/expected.json +3 -0
  124. package/fixtures/cases/unnamed-typed-path-reads-its-type/library/rooms/team/plan.md +1 -0
  125. package/fixtures/cases/unnamed-typed-path-reads-its-type/library/rooms/team/tasks/plan.md +5 -0
  126. package/fixtures/cases/unnamed-typed-path-reads-its-type/schema.yaml +5 -0
  127. package/fixtures/cases/unnamed-typed-path-without-a-body/context.json +11 -0
  128. package/fixtures/cases/unnamed-typed-path-without-a-body/expected.json +5 -0
  129. package/fixtures/cases/unnamed-typed-path-without-a-body/library/rooms/team/tasks/plan.md +5 -0
  130. package/fixtures/cases/unnamed-typed-path-without-a-body/schema.yaml +5 -0
  131. package/fixtures/division.json +26 -26
  132. package/fixtures/queries.json +964 -0
  133. package/package.json +10 -3
  134. package/dist/condition.d.ts +0 -150
  135. package/dist/condition.d.ts.map +0 -1
  136. package/dist/condition.js +0 -497
@@ -1,13 +1,17 @@
1
1
  import { type Definition } from './definition.js';
2
- import type { ApplyResult, BodyResult, Change, Document, Link, ParseResult } from './types.js';
2
+ import { type LinkInventory } from './links.js';
3
+ import type { ApplyResult, BodyResult, FrontmatterResult, Change, Document, Link, ParseResult, UnlinkedBody } from './types.js';
3
4
  import { type YamlMap } from './yaml.js';
5
+ export declare function inventoryOf(document: Document): LinkInventory;
6
+ export declare function parseFrontmatter(content: string, file?: string): FrontmatterResult;
4
7
  export declare function parse(content: string, file?: string): ParseResult;
5
- export declare function relativize(document: Document, file: string, handle: string, definition?: Definition): ApplyResult;
8
+ export declare function relativize(document: Document, file: string, handle: string, definition?: Definition, kept?: ReadonlySet<string>): ApplyResult;
6
9
  export declare function relativizeBody(body: string, file: string, handle: string): BodyResult;
7
10
  export declare function relinkBody(body: string, file: string, moves: ReadonlyMap<string, string>): BodyResult;
11
+ export declare function unlinkBody(body: string, hrefs: ReadonlySet<string>): UnlinkedBody;
8
12
  export declare function links(document: Document, file: string): readonly Link[];
9
13
  export declare function bodyLinks(body: string, file: string): readonly Link[];
10
- export declare function apply(document: Document, change: Change): ApplyResult;
14
+ export declare function apply(document: Document, changes: readonly Change[]): ApplyResult;
11
15
  export declare function serialize(document: Document): string;
12
16
  export declare function frontmatter(document: Document): YamlMap | null;
13
17
  //# sourceMappingURL=document.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"document.d.ts","sourceRoot":"","sources":["../src/document.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgC,KAAK,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAMhF,OAAO,KAAK,EACV,WAAW,EACX,UAAU,EACV,MAAM,EACN,QAAQ,EACR,IAAI,EACJ,WAAW,EAEZ,MAAM,YAAY,CAAC;AACpB,OAAO,EAaL,KAAK,OAAO,EAEb,MAAM,WAAW,CAAC;AAwCnB,wBAAgB,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,SAAK,GAAG,WAAW,CAkD7D;AA+KD,wBAAgB,UAAU,CACxB,QAAQ,EAAE,QAAQ,EAClB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,UAAU,CAAC,EAAE,UAAU,GACtB,WAAW,CAYb;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,UAAU,CAOrF;AAED,wBAAgB,UAAU,CACxB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,GACjC,UAAU,CAeZ;AAeD,wBAAgB,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE,CAEvE;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE,CAErE;AAED,wBAAgB,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,WAAW,CAOrE;AAED,wBAAgB,SAAS,CAAC,QAAQ,EAAE,QAAQ,GAAG,MAAM,CAEpD;AAED,wBAAgB,WAAW,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,GAAG,IAAI,CAE9D"}
1
+ {"version":3,"file":"document.d.ts","sourceRoot":"","sources":["../src/document.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgC,KAAK,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAChF,OAAO,EAKL,KAAK,aAAa,EACnB,MAAM,YAAY,CAAC;AAcpB,OAAO,KAAK,EACV,WAAW,EACX,UAAU,EACV,iBAAiB,EACjB,MAAM,EACN,QAAQ,EACR,IAAI,EACJ,WAAW,EAEX,YAAY,EACb,MAAM,YAAY,CAAC;AACpB,OAAO,EAcL,KAAK,OAAO,EAEb,MAAM,WAAW,CAAC;AAgBnB,wBAAgB,WAAW,CAAC,QAAQ,EAAE,QAAQ,GAAG,aAAa,CAM7D;AAgED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,SAAK,GAAG,iBAAiB,CAW9E;AAED,wBAAgB,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,SAAK,GAAG,WAAW,CAgB7D;AAmED,wBAAgB,UAAU,CACxB,QAAQ,EAAE,QAAQ,EAClB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,UAAU,CAAC,EAAE,UAAU,EACvB,IAAI,GAAE,WAAW,CAAC,MAAM,CAAa,GACpC,WAAW,CAuBb;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,UAAU,CAUrF;AAED,wBAAgB,UAAU,CACxB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,GACjC,UAAU,CAkBZ;AAED,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,YAAY,CAqBjF;AAeD,wBAAgB,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE,CAEvE;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE,CAErE;AA4LD,wBAAgB,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,WAAW,CA4CjF;AAED,wBAAgB,SAAS,CAAC,QAAQ,EAAE,QAAQ,GAAG,MAAM,CAEpD;AAED,wBAAgB,WAAW,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,GAAG,IAAI,CAE9D"}
package/dist/document.js CHANGED
@@ -1,24 +1,35 @@
1
1
  import { ARRAY_INDEX, pointerSegments } from './definition.js';
2
- import { hrefOccurrences } from './links.js';
3
- import { relative, retarget, SHELL_ROOMS, shellTarget, target } from './paths.js';
2
+ import { destinations, hrefOccurrences, linkInventory, } from './links.js';
3
+ import { destinationPath, relative, retarget, roomPath, roomTarget, SHELL_ROOMS, shellTarget, target, } from './paths.js';
4
4
  import { references } from './references.js';
5
5
  import { headingSpans, sectionsRecord } from './sections.js';
6
6
  import { refusal } from './refuse.js';
7
7
  import { bodyStartAfterYaml, bodyStartOf, equalValue, extractFrontmatter, frontmatterValue, jsValue, lineEnding, mapEntry, parseYamlMapping, serializeJs, serializeKey, YamlError, } from './yaml.js';
8
- const internals = new WeakMap();
8
+ const HELD = Symbol('held');
9
+ function heldOf(document) {
10
+ return document[HELD];
11
+ }
12
+ export function inventoryOf(document) {
13
+ const held = heldOf(document);
14
+ if (held?.inventory !== undefined)
15
+ return held.inventory;
16
+ const inventory = linkInventory(document.content.slice(bodyStartOf(document.content)));
17
+ if (held !== undefined)
18
+ held.inventory = inventory;
19
+ return inventory;
20
+ }
9
21
  function refuse(file, rule, location) {
10
22
  return location === undefined ? refusal(file, rule) : refusal(file, rule, { location });
11
23
  }
12
24
  function freezeDocument(content, type, fields, preamble, sections, internal) {
13
- const document = Object.freeze({
25
+ const held = { internal, inventory: undefined };
26
+ return Object.freeze(Object.defineProperty({
14
27
  content,
15
28
  type,
16
29
  fields: Object.freeze(fields),
17
30
  preamble,
18
31
  sections: Object.freeze(sections),
19
- });
20
- internals.set(document, internal);
21
- return document;
32
+ }, HELD, { value: held }));
22
33
  }
23
34
  function declaredType(fields) {
24
35
  const value = fields.type;
@@ -28,19 +39,10 @@ function declaredType(fields) {
28
39
  return undefined;
29
40
  return value;
30
41
  }
31
- export function parse(content, file = '') {
42
+ function opened(content, file) {
32
43
  const fence = extractFrontmatter(content);
33
- if (fence.kind === 'none') {
34
- const spans = headingSpans(content, 0);
35
- return {
36
- ok: true,
37
- document: freezeDocument(content, undefined, {}, content.slice(0, spans[0]?.headingStart), sectionsRecord(spans, content), {
38
- root: null,
39
- yamlEnd: 0,
40
- bodyStart: 0,
41
- }),
42
- };
43
- }
44
+ if (fence.kind === 'none')
45
+ return { ok: true, root: null, fields: {}, yamlEnd: 0 };
44
46
  if (fence.kind === 'unclosed')
45
47
  return { ok: false, refusal: refuse(file, 'frontmatter-fence') };
46
48
  try {
@@ -49,17 +51,7 @@ export function parse(content, file = '') {
49
51
  if (fields === null || typeof fields !== 'object' || Array.isArray(fields)) {
50
52
  return { ok: false, refusal: refuse(file, 'frontmatter-fence') };
51
53
  }
52
- const bodyStart = bodyStartAfterYaml(content, fence.yamlEnd);
53
- const spans = headingSpans(content, bodyStart);
54
- const record = fields;
55
- return {
56
- ok: true,
57
- document: freezeDocument(content, declaredType(record), record, content.slice(bodyStart, spans[0]?.headingStart), sectionsRecord(spans, content), {
58
- root,
59
- yamlEnd: fence.yamlEnd,
60
- bodyStart,
61
- }),
62
- };
54
+ return { ok: true, root, fields: fields, yamlEnd: fence.yamlEnd };
63
55
  }
64
56
  catch (error) {
65
57
  if (error instanceof YamlError)
@@ -67,71 +59,29 @@ export function parse(content, file = '') {
67
59
  throw error;
68
60
  }
69
61
  }
70
- function splice(content, start, end, insert) {
71
- return content.slice(0, start) + insert + content.slice(end);
72
- }
73
- function applyField(document, name, value, prior) {
74
- const internal = internals.get(document);
75
- if (internal === undefined || internal.root === null) {
76
- return { outcome: 'refuse', refusal: refuse('', 'frontmatter-fence', name) };
77
- }
78
- if (!equalValue(document.fields[name], prior)) {
79
- return { outcome: 'stale', document };
80
- }
81
- if (!frontmatterValue(value)) {
82
- return { outcome: 'refuse', refusal: refuse('', 'frontmatter-fence', name) };
83
- }
84
- let nextContent;
85
- const existing = mapEntry(internal.root, name);
86
- if (existing !== undefined) {
87
- const held = existing.value;
88
- const inline = held.start > existing.after &&
89
- !/[\r\n]/.test(document.content.slice(existing.after, held.start));
90
- nextContent = inline
91
- ? splice(document.content, held.start, held.end, serializeJs(value))
92
- : splice(document.content, existing.after, held.end, ` ${serializeJs(value)}`);
93
- }
94
- else if (document.content[internal.root.start] === '{') {
95
- nextContent = splice(document.content, internal.root.end - 1, internal.root.end - 1, `${internal.root.entries.length === 0 ? '' : ', '}${serializeKey(name)}: ${serializeJs(value)}`);
96
- }
97
- else {
98
- const nl = lineEnding(document.content);
99
- const lineStart = document.content.lastIndexOf('\n', internal.root.start - 1) + 1;
100
- const indent = document.content.slice(lineStart, internal.root.start);
101
- const line = `${indent}${serializeKey(name)}: ${serializeJs(value)}${nl}`;
102
- const before = document.content.slice(0, internal.yamlEnd);
103
- const prefix = before.endsWith('\n') || before.endsWith('\r\n') ? '' : nl;
104
- nextContent = splice(document.content, internal.yamlEnd, internal.yamlEnd, `${prefix}${line}`);
105
- }
106
- const parsed = parse(nextContent);
107
- if (!parsed.ok)
108
- return { outcome: 'refuse', refusal: parsed.refusal };
109
- return { outcome: 'applied', document: parsed.document };
110
- }
111
- function applySection(document, name, value, prior) {
112
- const internal = internals.get(document);
113
- if (internal === undefined)
114
- return { outcome: 'refuse', refusal: refuse('', 'required-section', name) };
115
- const spans = headingSpans(document.content, internal.bodyStart);
116
- const span = spans.find((item) => item.name === name);
117
- if (span === undefined)
118
- return { outcome: 'refuse', refusal: refuse('', 'required-section', name) };
119
- const current = document.content.slice(span.bodyStart, span.bodyEnd);
120
- if (current !== prior)
121
- return { outcome: 'stale', document };
122
- const parsed = parse(splice(document.content, span.bodyStart, span.bodyEnd, value));
123
- if (!parsed.ok)
124
- return { outcome: 'refuse', refusal: parsed.refusal };
125
- return { outcome: 'applied', document: parsed.document };
62
+ export function parseFrontmatter(content, file = '') {
63
+ const read = opened(content, file);
64
+ if (!read.ok)
65
+ return read;
66
+ return {
67
+ ok: true,
68
+ frontmatter: Object.freeze({
69
+ content,
70
+ type: declaredType(read.fields),
71
+ fields: Object.freeze(read.fields),
72
+ }),
73
+ };
126
74
  }
127
- function applyPreamble(document, value, prior) {
128
- if (document.preamble !== prior)
129
- return { outcome: 'stale', document };
130
- const start = bodyStartOf(document.content);
131
- const parsed = parse(splice(document.content, start, start + document.preamble.length, value));
132
- if (!parsed.ok)
133
- return { outcome: 'refuse', refusal: parsed.refusal };
134
- return { outcome: 'applied', document: parsed.document };
75
+ export function parse(content, file = '') {
76
+ const read = opened(content, file);
77
+ if (!read.ok)
78
+ return read;
79
+ const bodyStart = read.root === null ? 0 : bodyStartAfterYaml(content, read.yamlEnd);
80
+ const spans = headingSpans(content, bodyStart);
81
+ return {
82
+ ok: true,
83
+ document: freezeDocument(content, declaredType(read.fields), read.fields, content.slice(bodyStart, spans[0]?.headingStart), sectionsRecord(spans, content), { root: read.root, yamlEnd: read.yamlEnd, bodyStart }),
84
+ };
135
85
  }
136
86
  function fitsBare(to) {
137
87
  if (to === '' || to.startsWith('<'))
@@ -160,58 +110,34 @@ function destinationText(to, bracketed) {
160
110
  return `<${to}>`;
161
111
  return null;
162
112
  }
163
- function relinked(content, bodyStart, href, to) {
164
- const written = retarget(href, to);
165
- let rewritten = '';
166
- let cursor = 0;
167
- for (const match of hrefOccurrences(content.slice(bodyStart))) {
168
- if (match.href !== href)
169
- continue;
170
- const text = destinationText(written, match.bracketed);
171
- if (text === null)
172
- return refuse('', 'unwritable-link', written);
173
- rewritten += content.slice(cursor, bodyStart + match.start);
174
- rewritten += text;
175
- cursor = bodyStart + match.end;
176
- }
177
- return rewritten + content.slice(cursor);
178
- }
179
- function shellRelinked(content, bodyStart, file, handle) {
180
- const hrefs = new Set(hrefOccurrences(content.slice(bodyStart)).map(({ href }) => href));
181
- let held = content;
182
- for (const href of hrefs) {
113
+ function shellRelinked(body, file, handle) {
114
+ const occurrences = hrefOccurrences(body);
115
+ const written = new Map();
116
+ for (const href of new Set(occurrences.map((occurrence) => occurrence.href))) {
183
117
  const path = shellTarget(href, handle);
184
118
  if (path === null)
185
119
  continue;
186
- const text = relinked(held, bodyStart, href, relative(file, path));
187
- if (typeof text !== 'string')
188
- return text;
189
- held = text;
120
+ const to = retarget(href, relative(file, path));
121
+ if (destinationText(to, false) === null)
122
+ return refuse('', 'unwritable-link', to);
123
+ written.set(href, to);
190
124
  }
191
- return held;
192
- }
193
- function reparsed(document, content) {
194
- if (typeof content !== 'string')
195
- return { outcome: 'refuse', refusal: content };
196
- if (content === document.content)
197
- return { outcome: 'applied', document };
198
- const parsed = parse(content);
199
- if (!parsed.ok)
200
- return { outcome: 'refuse', refusal: parsed.refusal };
201
- return { outcome: 'applied', document: parsed.document };
202
- }
203
- function applyLink(document, href, to) {
204
- const content = document.content;
205
- const bodyStart = bodyStartOf(content);
206
- if (!hrefOccurrences(content.slice(bodyStart)).some((occurrence) => occurrence.href === href))
207
- return { outcome: 'stale', document };
208
- return reparsed(document, relinked(content, bodyStart, href, to));
125
+ let rewritten = '';
126
+ let cursor = 0;
127
+ for (const match of occurrences) {
128
+ const to = written.get(match.href);
129
+ if (to === undefined)
130
+ continue;
131
+ rewritten += body.slice(cursor, match.start) + destinationText(to, match.bracketed);
132
+ cursor = match.end;
133
+ }
134
+ return rewritten + body.slice(cursor);
209
135
  }
210
- function nodeAt(root, pointer) {
136
+ function nodeAt(root, pointer, entryOf = mapEntry) {
211
137
  let node = root;
212
138
  for (const key of pointerSegments(pointer)) {
213
139
  if (node?.kind === 'map')
214
- node = mapEntry(node, key)?.value;
140
+ node = entryOf(node, key)?.value;
215
141
  else if (node?.kind === 'seq' && ARRAY_INDEX.test(key))
216
142
  node = node.items[Number(key)];
217
143
  else
@@ -226,37 +152,36 @@ function scalarText(source, value) {
226
152
  return JSON.stringify(value);
227
153
  return serializeJs(value);
228
154
  }
229
- function applyReference(document, pointer, value, prior) {
230
- const root = internals.get(document)?.root;
231
- const node = root === null || root === undefined ? undefined : nodeAt(root, pointer);
232
- if (node?.kind !== 'scalar' || node.value !== prior)
233
- return { outcome: 'stale', document };
234
- const text = scalarText(document.content[node.start], value);
235
- const parsed = parse(splice(document.content, node.start, node.end, text));
236
- if (!parsed.ok)
237
- return { outcome: 'refuse', refusal: parsed.refusal };
238
- return { outcome: 'applied', document: parsed.document };
239
- }
240
- export function relativize(document, file, handle, definition) {
241
- let held = document;
155
+ export function relativize(document, file, handle, definition, kept = new Set()) {
156
+ const relativized = (href) => {
157
+ const path = shellTarget(href, handle);
158
+ return path === null || kept.has(`${SHELL_ROOMS}${handle}/${path}`) ? null : path;
159
+ };
160
+ const changes = [];
242
161
  for (const { pointer, value } of definition === undefined
243
162
  ? []
244
163
  : references(document, definition)) {
245
- const path = shellTarget(value, handle);
246
- if (path === null)
247
- continue;
248
- const result = applyReference(held, pointer, retarget(value, relative(file, path)), value);
249
- if (result.outcome !== 'applied')
250
- return result;
251
- held = result.document;
164
+ const path = relativized(value);
165
+ if (path !== null)
166
+ changes.push({
167
+ kind: 'reference',
168
+ pointer,
169
+ value: retarget(value, relative(file, path)),
170
+ prior: value,
171
+ });
172
+ }
173
+ for (const href of new Set(destinations(inventoryOf(document)).map(({ href }) => href))) {
174
+ const path = relativized(href);
175
+ if (path !== null)
176
+ changes.push({ kind: 'link', href, to: relative(file, path) });
252
177
  }
253
- return reparsed(held, shellRelinked(held.content, bodyStartOf(held.content), file, handle));
178
+ return apply(document, changes);
254
179
  }
255
180
  export function relativizeBody(body, file, handle) {
256
- const relinkedBody = shellRelinked(body, 0, file, handle);
181
+ const relinkedBody = shellRelinked(body, file, handle);
257
182
  if (typeof relinkedBody !== 'string')
258
183
  return { outcome: 'refuse', refusal: relinkedBody };
259
- const elsewhere = hrefOccurrences(relinkedBody).find(({ href }) => href.startsWith(SHELL_ROOMS));
184
+ const elsewhere = hrefOccurrences(relinkedBody).find(({ href }) => destinationPath(href)?.startsWith(SHELL_ROOMS) === true && roomTarget(href) === null);
260
185
  if (elsewhere !== undefined)
261
186
  return { outcome: 'refuse', refusal: refuse(file, 'unresolved-link', elsewhere.href) };
262
187
  return { outcome: 'applied', body: relinkedBody };
@@ -265,11 +190,11 @@ export function relinkBody(body, file, moves) {
265
190
  let rewritten = '';
266
191
  let cursor = 0;
267
192
  for (const match of hrefOccurrences(body)) {
268
- const from = target(file, match.href);
193
+ const from = target(file, match.href) ?? roomPath(match.href);
269
194
  const to = from === null ? undefined : moves.get(from);
270
195
  if (to === undefined)
271
196
  continue;
272
- const written = retarget(match.href, relative(file, to));
197
+ const written = retarget(match.href, from.startsWith(SHELL_ROOMS) || to.startsWith(SHELL_ROOMS) ? to : relative(file, to));
273
198
  const text = destinationText(written, match.bracketed);
274
199
  if (text === null)
275
200
  return { outcome: 'refuse', refusal: refuse(file, 'unwritable-link', written) };
@@ -278,10 +203,34 @@ export function relinkBody(body, file, moves) {
278
203
  }
279
204
  return { outcome: 'applied', body: rewritten + body.slice(cursor) };
280
205
  }
281
- function linksIn(text, file) {
206
+ export function unlinkBody(body, hrefs) {
207
+ const { uses, blocks } = linkInventory(body);
208
+ const links = new Map();
209
+ for (const use of uses) {
210
+ const { href, bracketed } = use.destination;
211
+ if (!hrefs.has(href) || links.has(href))
212
+ continue;
213
+ const label = body.slice(use.labelStart, use.labelEnd);
214
+ const image = body[use.start] === '!' ? '!' : '';
215
+ links.set(href, `${image}[${label}](${destinationText(href, bracketed) ?? href})`);
216
+ }
217
+ const cut = [...uses, ...blocks]
218
+ .filter((span) => hrefs.has(span.destination.href))
219
+ .sort((left, right) => left.start - right.start);
220
+ let kept = '';
221
+ let cursor = 0;
222
+ for (const span of cut) {
223
+ if (span.start < cursor)
224
+ continue;
225
+ kept += body.slice(cursor, span.start);
226
+ cursor = span.end;
227
+ }
228
+ return { body: kept + body.slice(cursor), links };
229
+ }
230
+ function linksIn(occurrences, file) {
282
231
  const found = [];
283
232
  const seen = new Set();
284
- for (const occurrence of hrefOccurrences(text)) {
233
+ for (const occurrence of occurrences) {
285
234
  if (seen.has(occurrence.href))
286
235
  continue;
287
236
  const resolved = target(file, occurrence.href);
@@ -293,25 +242,250 @@ function linksIn(text, file) {
293
242
  return found;
294
243
  }
295
244
  export function links(document, file) {
296
- return linksIn(document.content.slice(bodyStartOf(document.content)), file);
245
+ return linksIn(destinations(inventoryOf(document)), file);
297
246
  }
298
247
  export function bodyLinks(body, file) {
299
- return linksIn(body, file);
248
+ return linksIn(hrefOccurrences(body), file);
300
249
  }
301
- export function apply(document, change) {
250
+ function internalOf(document) {
251
+ const held = heldOf(document);
252
+ if (held !== undefined)
253
+ return held.internal;
254
+ const read = opened(document.content, '');
255
+ if (!read.ok)
256
+ return read.refusal;
257
+ return {
258
+ root: read.root,
259
+ yamlEnd: read.yamlEnd,
260
+ bodyStart: read.root === null ? 0 : bodyStartAfterYaml(document.content, read.yamlEnd),
261
+ };
262
+ }
263
+ function partOf(change) {
264
+ if (change.kind === 'field' || change.kind === 'section')
265
+ return `${change.kind} ${change.name}`;
302
266
  if (change.kind === 'link')
303
- return applyLink(document, change.href, change.to);
267
+ return `link ${change.href}`;
304
268
  if (change.kind === 'reference')
305
- return applyReference(document, change.pointer, change.value, change.prior);
306
- if (change.kind === 'preamble')
307
- return applyPreamble(document, change.value, change.prior);
308
- if (change.kind === 'field')
309
- return applyField(document, change.name, change.value, change.prior);
310
- return applySection(document, change.name, change.value, change.prior);
269
+ return `reference ${change.pointer}`;
270
+ return 'preamble';
271
+ }
272
+ function planner(document, internal) {
273
+ const content = document.content;
274
+ const keyed = new Map();
275
+ let spans;
276
+ let occurrences;
277
+ let ending;
278
+ let added = 0;
279
+ const entryOf = (map, key) => {
280
+ let index = keyed.get(map);
281
+ if (index === undefined) {
282
+ index = new Map();
283
+ for (const entry of map.entries)
284
+ if (!index.has(entry.key))
285
+ index.set(entry.key, entry);
286
+ keyed.set(map, index);
287
+ }
288
+ return index.get(key);
289
+ };
290
+ const field = (name, value, prior, at) => {
291
+ const root = internal.root;
292
+ if (root === null)
293
+ return refuse('', 'frontmatter-fence', name);
294
+ if (!equalValue(document.fields[name], prior))
295
+ return 'stale';
296
+ if (!frontmatterValue(value))
297
+ return refuse('', 'frontmatter-fence', name);
298
+ const existing = entryOf(root, name);
299
+ if (existing !== undefined) {
300
+ const held = existing.value;
301
+ const inline = held.start > existing.after && !/[\r\n]/.test(content.slice(existing.after, held.start));
302
+ return inline
303
+ ? [{ start: held.start, end: held.end, text: serializeJs(value), at }]
304
+ : [{ start: existing.after, end: held.end, text: ` ${serializeJs(value)}`, at }];
305
+ }
306
+ const entry = `${serializeKey(name)}: ${serializeJs(value)}`;
307
+ added += 1;
308
+ if (content[root.start] === '{') {
309
+ const separator = root.entries.length === 0 && added === 1 ? '' : ', ';
310
+ return [{ start: root.end - 1, end: root.end - 1, text: `${separator}${entry}`, at }];
311
+ }
312
+ const lineStart = content.lastIndexOf('\n', root.start - 1) + 1;
313
+ ending ??= lineEnding(content);
314
+ const line = `${content.slice(lineStart, root.start)}${entry}${ending}`;
315
+ return [{ start: internal.yamlEnd, end: internal.yamlEnd, text: line, at, entry: true }];
316
+ };
317
+ const section = (name, value, prior, at) => {
318
+ if (spans === undefined) {
319
+ spans = new Map();
320
+ for (const span of headingSpans(content, internal.bodyStart))
321
+ if (!spans.has(span.name))
322
+ spans.set(span.name, span);
323
+ }
324
+ const span = spans.get(name);
325
+ if (span === undefined)
326
+ return refuse('', 'required-section', name);
327
+ if (content.slice(span.bodyStart, span.bodyEnd) !== prior)
328
+ return 'stale';
329
+ return [{ start: span.bodyStart, end: span.bodyEnd, text: value, at }];
330
+ };
331
+ const link = (href, to, at) => {
332
+ if (occurrences === undefined) {
333
+ occurrences = new Map();
334
+ for (const occurrence of destinations(inventoryOf(document))) {
335
+ const same = occurrences.get(occurrence.href);
336
+ if (same === undefined)
337
+ occurrences.set(occurrence.href, [occurrence]);
338
+ else
339
+ same.push(occurrence);
340
+ }
341
+ }
342
+ const found = occurrences.get(href);
343
+ if (found === undefined)
344
+ return 'stale';
345
+ const written = retarget(href, to);
346
+ if (destinationText(written, false) === null)
347
+ return refuse('', 'unwritable-link', written);
348
+ return found.map((occurrence) => ({
349
+ start: internal.bodyStart + occurrence.start,
350
+ end: internal.bodyStart + occurrence.end,
351
+ text: destinationText(written, occurrence.bracketed),
352
+ at,
353
+ }));
354
+ };
355
+ const reference = (pointer, value, prior, at) => {
356
+ const node = internal.root === null ? undefined : nodeAt(internal.root, pointer, entryOf);
357
+ if (node?.kind !== 'scalar' || node.value !== prior)
358
+ return 'stale';
359
+ return [
360
+ { start: node.start, end: node.end, text: scalarText(content[node.start], value), at },
361
+ ];
362
+ };
363
+ return (change, at) => {
364
+ if (change.kind === 'field')
365
+ return field(change.name, change.value, change.prior, at);
366
+ if (change.kind === 'section')
367
+ return section(change.name, change.value, change.prior, at);
368
+ if (change.kind === 'link')
369
+ return link(change.href, change.to, at);
370
+ if (change.kind === 'reference')
371
+ return reference(change.pointer, change.value, change.prior, at);
372
+ if (document.preamble !== change.prior)
373
+ return 'stale';
374
+ const start = internal.bodyStart;
375
+ return [{ start, end: start + document.preamble.length, text: change.value, at }];
376
+ };
377
+ }
378
+ function overlapping(edits, stale) {
379
+ let reach = -1;
380
+ let owner = -1;
381
+ for (const edit of edits) {
382
+ if (edit.start < reach)
383
+ stale.add(Math.max(edit.at, owner));
384
+ if (edit.end > reach) {
385
+ reach = edit.end;
386
+ owner = edit.at;
387
+ }
388
+ }
389
+ }
390
+ function firstHeadings(content, bodyStart) {
391
+ const first = new Map();
392
+ for (const span of headingSpans(content, bodyStart)) {
393
+ if (!first.has(span.name))
394
+ first.set(span.name, span.headingStart);
395
+ }
396
+ return first;
397
+ }
398
+ function hidden(before, bodyStart, after, shifts) {
399
+ const placed = firstHeadings(after, bodyStartOf(after));
400
+ let shift = 0;
401
+ let index = 0;
402
+ for (const [name, at] of firstHeadings(before, bodyStart)) {
403
+ while (index < shifts.length && shifts[index][0] <= at) {
404
+ shift += shifts[index][1];
405
+ index += 1;
406
+ }
407
+ if (placed.get(name) !== at + shift)
408
+ return name;
409
+ }
410
+ return undefined;
411
+ }
412
+ function spliced(source, edits) {
413
+ const shifts = [];
414
+ const pieces = [];
415
+ let cursor = 0;
416
+ let entered = false;
417
+ let ended = false;
418
+ for (const edit of edits) {
419
+ const kept = source.slice(cursor, edit.start);
420
+ pieces.push(kept);
421
+ if (kept !== '')
422
+ ended = kept.endsWith('\n');
423
+ let text = edit.text;
424
+ if (edit.entry === true && !entered) {
425
+ entered = true;
426
+ if (!ended)
427
+ text = `${lineEnding(source)}${text}`;
428
+ }
429
+ pieces.push(text);
430
+ if (text !== '')
431
+ ended = text.endsWith('\n');
432
+ shifts.push([edit.start, text.length - (edit.end - edit.start)]);
433
+ cursor = edit.end;
434
+ }
435
+ pieces.push(source.slice(cursor));
436
+ return { content: pieces.join(''), shifts };
437
+ }
438
+ export function apply(document, changes) {
439
+ const internal = internalOf(document);
440
+ if (!('bodyStart' in internal))
441
+ return { outcome: 'refuse', refusal: internal };
442
+ const plan = planner(document, internal);
443
+ const edits = [];
444
+ const stale = new Set();
445
+ const named = new Set();
446
+ for (const [at, change] of changes.entries()) {
447
+ const planned = plan(change, at);
448
+ if (planned === 'stale') {
449
+ stale.add(at);
450
+ continue;
451
+ }
452
+ if (!Array.isArray(planned))
453
+ return { outcome: 'refuse', refusal: planned };
454
+ const part = partOf(change);
455
+ if (named.has(part)) {
456
+ stale.add(at);
457
+ continue;
458
+ }
459
+ named.add(part);
460
+ for (const edit of planned)
461
+ edits.push(edit);
462
+ }
463
+ edits.sort((left, right) => left.start - right.start || left.end - right.end || left.at - right.at);
464
+ overlapping(edits, stale);
465
+ if (stale.size > 0)
466
+ return { outcome: 'stale', document, stale: [...stale].sort((left, right) => left - right) };
467
+ const source = document.content;
468
+ const { content } = spliced(source, edits);
469
+ if (content === source)
470
+ return { outcome: 'applied', document };
471
+ const replaced = edits.filter((edit) => {
472
+ const kind = changes[edit.at].kind;
473
+ return kind === 'section' || kind === 'preamble';
474
+ });
475
+ if (replaced.length > 0) {
476
+ const checked = spliced(source, replaced);
477
+ const name = hidden(source, internal.bodyStart, checked.content, checked.shifts);
478
+ if (name !== undefined)
479
+ return { outcome: 'refuse', refusal: refuse('', 'overlapping-section', name) };
480
+ }
481
+ const parsed = parse(content);
482
+ if (!parsed.ok)
483
+ return { outcome: 'refuse', refusal: parsed.refusal };
484
+ return { outcome: 'applied', document: parsed.document };
311
485
  }
312
486
  export function serialize(document) {
313
487
  return document.content;
314
488
  }
315
489
  export function frontmatter(document) {
316
- return internals.get(document)?.root ?? null;
490
+ return heldOf(document)?.internal.root ?? null;
317
491
  }