@agentshouse/mdmodel 0.1.0-c0bdbbc92d020 → 0.1.0-c1b026eddaa7c

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