@ai-markdown/core 3.2.2 → 3.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1026 +1,976 @@
1
1
  "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var src_exports = {};
22
- __export(src_exports, {
23
- buildAggregateTree: () => buildAggregateTree,
24
- buildBlocks: () => buildBlocks,
25
- buildContributionChain: () => buildContributionChain,
26
- cloneHastForRender: () => cloneHastForRender,
27
- computeBlockFingerprint: () => computeBlockFingerprint,
28
- computeHtmlBlockDigest: () => computeHtmlBlockDigest,
29
- computeHtmlBlockDigestWithExtent: () => computeHtmlBlockDigestWithExtent,
30
- createBlockPlanner: () => createBlockPlanner,
31
- createContributionSession: () => createContributionSession,
32
- createPipelineSession: () => createPipelineSession,
33
- createSmoothCoordinator: () => createSmoothCoordinator2,
34
- deriveCoordinationPolicy: () => deriveCoordinationPolicy,
35
- derivePhantomTargets: () => derivePhantomTargets,
36
- deriveTailSignal: () => deriveTailSignal,
37
- evaluateGateWarn: () => evaluateGateWarn,
38
- hasMdastSource: () => hasMdastSource,
39
- isFootnoteSection: () => import_engine.isFootnoteSection
40
- });
41
- module.exports = __toCommonJS(src_exports);
42
-
43
- // src/blockPlan.ts
44
- var import_unist_util_visit = require("unist-util-visit");
45
- var import_engine = require("@ai-markdown/engine");
46
- var TAINT_TYPES = /* @__PURE__ */ new Set([
47
- "footnoteReference",
48
- "footnoteDefinition",
49
- "linkReference",
50
- "imageReference",
51
- "definition"
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ let unist_util_visit = require("unist-util-visit");
4
+ let _ai_markdown_engine = require("@ai-markdown/engine");
5
+ const TAINT_TYPES = /* @__PURE__ */ new Set([
6
+ "footnoteReference",
7
+ "footnoteDefinition",
8
+ "linkReference",
9
+ "imageReference",
10
+ "definition"
52
11
  ]);
53
- var CTX_TYPES = TAINT_TYPES;
12
+ const CTX_TYPES = TAINT_TYPES;
54
13
  function extractRaw(node, source) {
55
- if (!node.position) return "";
56
- return source.slice(node.position.start.offset, node.position.end.offset);
14
+ if (!node.position) return "";
15
+ return source.slice(node.position.start.offset, node.position.end.offset);
57
16
  }
58
17
  function hasMdastSource(node) {
59
- return node.position !== void 0;
18
+ return node.position !== void 0;
60
19
  }
61
20
  function computeHtmlBlockDigest(el, source, ownEnd) {
62
- return computeHtmlBlockDigestWithExtent(el, source, ownEnd).digest;
21
+ return computeHtmlBlockDigestWithExtent(el, source, ownEnd).digest;
63
22
  }
64
23
  function computeHtmlBlockDigestWithExtent(el, source, ownEnd) {
65
- let maxEnd = el.position?.end?.offset ?? 0;
66
- let count = 0;
67
- let hasFootnoteSection = false;
68
- const stack = [...el.children];
69
- while (stack.length > 0) {
70
- const node = stack.pop();
71
- count++;
72
- const end = node.position?.end?.offset;
73
- if (end !== void 0 && end > maxEnd) {
74
- maxEnd = end;
75
- }
76
- if (node.type === "element") {
77
- if ((0, import_engine.isFootnoteSection)(node)) {
78
- hasFootnoteSection = true;
79
- }
80
- for (const child of node.children) {
81
- stack.push(child);
82
- }
83
- }
84
- }
85
- const swallowed = source !== void 0 && ownEnd !== void 0 && maxEnd > ownEnd ? source.slice(ownEnd, maxEnd) : "";
86
- return { digest: `${maxEnd}:${count}:${hasFootnoteSection ? 1 : 0}:${fnv1a(swallowed)}`, maxEnd };
24
+ let maxEnd = el.position?.end?.offset ?? 0;
25
+ let count = 0;
26
+ let hasFootnoteSection = false;
27
+ const stack = [...el.children];
28
+ while (stack.length > 0) {
29
+ const node = stack.pop();
30
+ count++;
31
+ const end = node.position?.end?.offset;
32
+ if (end !== void 0 && end > maxEnd) maxEnd = end;
33
+ if (node.type === "element") {
34
+ if ((0, _ai_markdown_engine.isFootnoteSection)(node)) hasFootnoteSection = true;
35
+ for (const child of node.children) stack.push(child);
36
+ }
37
+ }
38
+ const swallowed = source !== void 0 && ownEnd !== void 0 && maxEnd > ownEnd ? source.slice(ownEnd, maxEnd) : "";
39
+ return {
40
+ digest: `${maxEnd}:${count}:${hasFootnoteSection ? 1 : 0}:${fnv1a(swallowed)}`,
41
+ maxEnd
42
+ };
87
43
  }
88
44
  function fnv1a(text) {
89
- let h = 2166136261;
90
- for (let i = 0; i < text.length; i++) {
91
- h ^= text.charCodeAt(i);
92
- h = Math.imul(h, 16777619) >>> 0;
93
- }
94
- return h.toString(36);
45
+ let h = 2166136261;
46
+ for (let i = 0; i < text.length; i++) {
47
+ h ^= text.charCodeAt(i);
48
+ h = Math.imul(h, 16777619) >>> 0;
49
+ }
50
+ return h.toString(36);
95
51
  }
96
- var EMPTY_LABELS = /* @__PURE__ */ new Set();
97
- var FOOTNOTE_SECTION_KEY = "__footnote_section__";
52
+ const EMPTY_LABELS = /* @__PURE__ */ new Set();
53
+ const FOOTNOTE_SECTION_KEY = "__footnote_section__";
98
54
  function buildBlocks(mdast, hast, source, options = {}) {
99
- const phantomFootnotes = options.phantomFootnoteLabels ?? EMPTY_LABELS;
100
- const mdastByOffset = /* @__PURE__ */ new Map();
101
- const mdastRanges = [];
102
- for (const child of mdast.children) {
103
- const off = child.position?.start.offset;
104
- const endOff = child.position?.end.offset;
105
- if (off !== void 0) {
106
- mdastByOffset.set(off, child);
107
- }
108
- if (off !== void 0 && endOff !== void 0) {
109
- mdastRanges.push({ start: off, end: endOff, node: child });
110
- }
111
- }
112
- if (true) {
113
- for (let i = 1; i < mdastRanges.length; i++) {
114
- if (mdastRanges[i].start < mdastRanges[i - 1].start) {
115
- throw new Error(
116
- "block-memo: mdast.children not sorted by source offset \u2014 a remark plugin is reordering top-level children."
117
- );
118
- }
119
- }
120
- }
121
- function findContainingMdast(offset) {
122
- let lo = 0;
123
- let hi = mdastRanges.length;
124
- while (lo < hi) {
125
- const mid = lo + hi >>> 1;
126
- if (mdastRanges[mid].start <= offset) lo = mid + 1;
127
- else hi = mid;
128
- }
129
- const idx = lo - 1;
130
- if (idx < 0) return void 0;
131
- const r = mdastRanges[idx];
132
- return offset < r.end ? r.node : void 0;
133
- }
134
- const ctxParts = [];
135
- const taintOffsets = [];
136
- const firstTaintAtOrAfter = (offset) => {
137
- let lo = 0;
138
- let hi = taintOffsets.length;
139
- while (lo < hi) {
140
- const mid = lo + hi >>> 1;
141
- if (taintOffsets[mid] < offset) lo = mid + 1;
142
- else hi = mid;
143
- }
144
- return lo;
145
- };
146
- (0, import_unist_util_visit.visit)(options.contextMdast ?? mdast, (n) => {
147
- if (!CTX_TYPES.has(n.type)) return;
148
- const at = n.position?.start?.offset;
149
- if (at !== void 0) taintOffsets.push(at);
150
- if (n.type === "footnoteReference") ctxParts.push(["fr", n.identifier]);
151
- else if (n.type === "footnoteDefinition") ctxParts.push(["fd", n.identifier, extractRaw(n, source)]);
152
- else if (n.type === "linkReference") ctxParts.push(["lr", n.identifier]);
153
- else if (n.type === "imageReference") ctxParts.push(["ir", n.identifier]);
154
- else if (n.type === "definition") ctxParts.push(["d", n.identifier, n.url, n.title ?? null]);
155
- });
156
- if (true) {
157
- for (let i = 1; i < taintOffsets.length; i++) {
158
- if (taintOffsets[i] < taintOffsets[i - 1]) {
159
- throw new Error(
160
- "block-memo: taint node start offsets are not source-ordered \u2014 a remark plugin is reordering nodes or emitting bad positions."
161
- );
162
- }
163
- }
164
- }
165
- const globalCtx = JSON.stringify(ctxParts);
166
- const plan = [];
167
- const blocks = [];
168
- const blockHasts = [];
169
- let synthetic;
170
- const refLocalCtx = /* @__PURE__ */ new Map();
171
- {
172
- const counts = /* @__PURE__ */ new Map();
173
- const ranks = /* @__PURE__ */ new Map();
174
- const rankOf = (id) => {
175
- if (phantomFootnotes.has(id)) return -1;
176
- let rank = ranks.get(id);
177
- if (rank === void 0) {
178
- rank = ranks.size;
179
- ranks.set(id, rank);
180
- }
181
- return rank;
182
- };
183
- (0, import_unist_util_visit.visit)(options.contextMdast ?? mdast, (n) => {
184
- if (n.type === "footnoteDefinition") {
185
- rankOf((0, import_engine.normalizeId)(String(n.identifier)));
186
- return import_unist_util_visit.SKIP;
187
- }
188
- if (n.type !== "footnoteReference") return;
189
- const id = (0, import_engine.normalizeId)(String(n.identifier));
190
- const prior = counts.get(id) ?? 0;
191
- refLocalCtx.set(n, [prior, rankOf(id)]);
192
- counts.set(id, prior + 1);
193
- });
194
- }
195
- for (let i = 0; i < hast.children.length; i++) {
196
- const hastChild = hast.children[i];
197
- if (hastChild.type !== "element") {
198
- const off = hastChild.position?.start.offset;
199
- const key = off !== void 0 ? `inline-${off}` : `inline-i${i}`;
200
- plan.push({ kind: "inline", el: hastChild, key });
201
- continue;
202
- }
203
- const el = hastChild;
204
- if ((0, import_engine.isFootnoteSection)(el)) {
205
- synthetic = el;
206
- plan.push({ kind: "synthetic", el, key: FOOTNOTE_SECTION_KEY });
207
- continue;
208
- }
209
- const hastOffset = el.position?.start.offset;
210
- if (hastOffset === void 0) {
211
- plan.push({ kind: "inline", el, key: `inline-i${i}` });
212
- continue;
213
- }
214
- let mdastNode = mdastByOffset.get(hastOffset);
215
- let viaRangeFallback = false;
216
- if (!mdastNode) {
217
- mdastNode = findContainingMdast(hastOffset);
218
- viaRangeFallback = mdastNode !== void 0;
219
- }
220
- if (!mdastNode) {
221
- if (true) {
222
- throw new Error(
223
- `block-memo: hast block at offset ${hastOffset} has no mdast counterpart. A rehype plugin may have synthesized positions outside source. tagName=${el.tagName}`
224
- );
225
- }
226
- plan.push({ kind: "inline", el, key: `inline-${hastOffset}` });
227
- continue;
228
- }
229
- if (mdastNode.type === "footnoteDefinition") {
230
- plan.push({ kind: "inline", el, key: `inline-${hastOffset}` });
231
- continue;
232
- }
233
- const isRawHtmlBlock = mdastNode.type === "html" || viaRangeFallback;
234
- let hasReference = false;
235
- const swallowed = isRawHtmlBlock ? scanSwallowedSubtree(el) : null;
236
- const footnoteRefLabels = [];
237
- const linkRefLabels = [];
238
- const imageRefLabels = [];
239
- const footnoteDefLabels = [];
240
- const local = [];
241
- (0, import_unist_util_visit.visit)(mdastNode, (n) => {
242
- if (!TAINT_TYPES.has(n.type)) return;
243
- hasReference = true;
244
- const id = "identifier" in n ? (0, import_engine.normalizeId)(String(n.identifier)) : null;
245
- if (id === null) return;
246
- if (n.type === "footnoteReference") {
247
- footnoteRefLabels.push(id);
248
- const ctx = refLocalCtx.get(n);
249
- if (ctx) local.push([id, ctx[0], ctx[1]]);
250
- } else if (n.type === "linkReference") linkRefLabels.push(id);
251
- else if (n.type === "imageReference") imageRefLabels.push(id);
252
- else if (n.type === "footnoteDefinition") footnoteDefLabels.push(id);
253
- });
254
- if (swallowed !== null && swallowed.hasReference) {
255
- hasReference = true;
256
- footnoteRefLabels.push(...swallowed.refLabels);
257
- linkRefLabels.push(...swallowed.linkLabels);
258
- imageRefLabels.push(...swallowed.imageLabels);
259
- local.push(...swallowed.local);
260
- }
261
- const footnoteRefLocalCtx = local.length > 0 ? JSON.stringify(local) : void 0;
262
- const swallowedDefCtx = swallowed !== null && swallowed.bakedDefs.length > 0 ? JSON.stringify(swallowed.bakedDefs) : void 0;
263
- const mdastPos = mdastNode.position;
264
- if (!mdastPos || mdastPos.start?.offset === void 0 || mdastPos.end?.offset === void 0) {
265
- plan.push({ kind: "inline", el, key: `inline-${hastOffset}` });
266
- continue;
267
- }
268
- let hastDigest;
269
- let swallowedSource;
270
- let swallowedTaint = false;
271
- if (isRawHtmlBlock) {
272
- const d = computeHtmlBlockDigestWithExtent(el, source, mdastPos.end.offset);
273
- hastDigest = d.digest;
274
- swallowedSource = source.slice(mdastPos.end.offset, d.maxEnd);
275
- const first = firstTaintAtOrAfter(mdastPos.end.offset);
276
- swallowedTaint = first < taintOffsets.length && taintOffsets[first] < d.maxEnd;
277
- }
278
- if (swallowedTaint) hasReference = true;
279
- const info = {
280
- raw: extractRaw(mdastNode, source),
281
- startOffset: mdastPos.start.offset,
282
- endOffset: mdastPos.end.offset,
283
- startLine: mdastPos.start.line,
284
- startColumn: mdastPos.start.column,
285
- hasReference,
286
- ...hastDigest !== void 0 ? { hastDigest } : {},
287
- ...swallowedSource !== void 0 ? { swallowedSource } : {},
288
- ...swallowed?.hasFootnoteSection ? { containsFootnoteSection: true } : {},
289
- ...hasReference ? {
290
- taintLabels: {
291
- footnoteRefLabels,
292
- linkRefLabels,
293
- imageRefLabels,
294
- footnoteDefLabels,
295
- ...footnoteRefLocalCtx !== void 0 ? { footnoteRefLocalCtx } : {},
296
- ...swallowedDefCtx !== void 0 ? { swallowedDefCtx } : {}
297
- }
298
- } : {}
299
- };
300
- blocks.push(info);
301
- blockHasts.push(el);
302
- plan.push({ kind: "block", el, info, key: `block-${hastOffset}` });
303
- }
304
- return { plan, globalCtx, blocks, blockHasts, synthetic };
55
+ const phantomFootnotes = options.phantomFootnoteLabels ?? EMPTY_LABELS;
56
+ const mdastByOffset = /* @__PURE__ */ new Map();
57
+ const mdastRanges = [];
58
+ for (const child of mdast.children) {
59
+ const off = child.position?.start.offset;
60
+ const endOff = child.position?.end.offset;
61
+ if (off !== void 0) mdastByOffset.set(off, child);
62
+ if (off !== void 0 && endOff !== void 0) mdastRanges.push({
63
+ start: off,
64
+ end: endOff,
65
+ node: child
66
+ });
67
+ }
68
+ for (let i = 1; i < mdastRanges.length; i++) if (mdastRanges[i].start < mdastRanges[i - 1].start) throw new Error("block-memo: mdast.children not sorted by source offset — a remark plugin is reordering top-level children.");
69
+ function findContainingMdast(offset) {
70
+ let lo = 0;
71
+ let hi = mdastRanges.length;
72
+ while (lo < hi) {
73
+ const mid = lo + hi >>> 1;
74
+ if (mdastRanges[mid].start <= offset) lo = mid + 1;
75
+ else hi = mid;
76
+ }
77
+ const idx = lo - 1;
78
+ if (idx < 0) return void 0;
79
+ const r = mdastRanges[idx];
80
+ return offset < r.end ? r.node : void 0;
81
+ }
82
+ const ctxParts = [];
83
+ const taintOffsets = [];
84
+ const firstTaintAtOrAfter = (offset) => {
85
+ let lo = 0;
86
+ let hi = taintOffsets.length;
87
+ while (lo < hi) {
88
+ const mid = lo + hi >>> 1;
89
+ if (taintOffsets[mid] < offset) lo = mid + 1;
90
+ else hi = mid;
91
+ }
92
+ return lo;
93
+ };
94
+ (0, unist_util_visit.visit)(options.contextMdast ?? mdast, (n) => {
95
+ if (!CTX_TYPES.has(n.type)) return;
96
+ const at = n.position?.start?.offset;
97
+ if (at !== void 0) taintOffsets.push(at);
98
+ if (n.type === "footnoteReference") ctxParts.push(["fr", n.identifier]);
99
+ else if (n.type === "footnoteDefinition") ctxParts.push([
100
+ "fd",
101
+ n.identifier,
102
+ extractRaw(n, source)
103
+ ]);
104
+ else if (n.type === "linkReference") ctxParts.push(["lr", n.identifier]);
105
+ else if (n.type === "imageReference") ctxParts.push(["ir", n.identifier]);
106
+ else if (n.type === "definition") ctxParts.push([
107
+ "d",
108
+ n.identifier,
109
+ n.url,
110
+ n.title ?? null
111
+ ]);
112
+ });
113
+ for (let i = 1; i < taintOffsets.length; i++) if (taintOffsets[i] < taintOffsets[i - 1]) throw new Error("block-memo: taint node start offsets are not source-ordered — a remark plugin is reordering nodes or emitting bad positions.");
114
+ const globalCtx = JSON.stringify(ctxParts);
115
+ const plan = [];
116
+ const blocks = [];
117
+ const blockHasts = [];
118
+ let synthetic;
119
+ const refLocalCtx = /* @__PURE__ */ new Map();
120
+ {
121
+ const counts = /* @__PURE__ */ new Map();
122
+ const ranks = /* @__PURE__ */ new Map();
123
+ const rankOf = (id) => {
124
+ if (phantomFootnotes.has(id)) return -1;
125
+ let rank = ranks.get(id);
126
+ if (rank === void 0) {
127
+ rank = ranks.size;
128
+ ranks.set(id, rank);
129
+ }
130
+ return rank;
131
+ };
132
+ (0, unist_util_visit.visit)(options.contextMdast ?? mdast, (n) => {
133
+ if (n.type === "footnoteDefinition") {
134
+ rankOf((0, _ai_markdown_engine.normalizeId)(String(n.identifier)));
135
+ return unist_util_visit.SKIP;
136
+ }
137
+ if (n.type !== "footnoteReference") return;
138
+ const id = (0, _ai_markdown_engine.normalizeId)(String(n.identifier));
139
+ const prior = counts.get(id) ?? 0;
140
+ refLocalCtx.set(n, [prior, rankOf(id)]);
141
+ counts.set(id, prior + 1);
142
+ });
143
+ }
144
+ for (let i = 0; i < hast.children.length; i++) {
145
+ const hastChild = hast.children[i];
146
+ if (hastChild.type !== "element") {
147
+ const off = hastChild.position?.start.offset;
148
+ const key = off !== void 0 ? `inline-${off}` : `inline-i${i}`;
149
+ plan.push({
150
+ kind: "inline",
151
+ el: hastChild,
152
+ key
153
+ });
154
+ continue;
155
+ }
156
+ const el = hastChild;
157
+ if ((0, _ai_markdown_engine.isFootnoteSection)(el)) {
158
+ synthetic = el;
159
+ plan.push({
160
+ kind: "synthetic",
161
+ el,
162
+ key: FOOTNOTE_SECTION_KEY
163
+ });
164
+ continue;
165
+ }
166
+ const hastOffset = el.position?.start.offset;
167
+ if (hastOffset === void 0) {
168
+ plan.push({
169
+ kind: "inline",
170
+ el,
171
+ key: `inline-i${i}`
172
+ });
173
+ continue;
174
+ }
175
+ let mdastNode = mdastByOffset.get(hastOffset);
176
+ let viaRangeFallback = false;
177
+ if (!mdastNode) {
178
+ mdastNode = findContainingMdast(hastOffset);
179
+ viaRangeFallback = mdastNode !== void 0;
180
+ }
181
+ if (!mdastNode) throw new Error(`block-memo: hast block at offset ${hastOffset} has no mdast counterpart. A rehype plugin may have synthesized positions outside source. tagName=${el.tagName}`);
182
+ if (mdastNode.type === "footnoteDefinition") {
183
+ plan.push({
184
+ kind: "inline",
185
+ el,
186
+ key: `inline-${hastOffset}`
187
+ });
188
+ continue;
189
+ }
190
+ const isRawHtmlBlock = mdastNode.type === "html" || viaRangeFallback;
191
+ let hasReference = false;
192
+ const swallowed = isRawHtmlBlock ? scanSwallowedSubtree(el) : null;
193
+ const footnoteRefLabels = [];
194
+ const linkRefLabels = [];
195
+ const imageRefLabels = [];
196
+ const footnoteDefLabels = [];
197
+ const local = [];
198
+ (0, unist_util_visit.visit)(mdastNode, (n) => {
199
+ if (!TAINT_TYPES.has(n.type)) return;
200
+ hasReference = true;
201
+ const id = "identifier" in n ? (0, _ai_markdown_engine.normalizeId)(String(n.identifier)) : null;
202
+ if (id === null) return;
203
+ if (n.type === "footnoteReference") {
204
+ footnoteRefLabels.push(id);
205
+ const ctx = refLocalCtx.get(n);
206
+ if (ctx) local.push([
207
+ id,
208
+ ctx[0],
209
+ ctx[1]
210
+ ]);
211
+ } else if (n.type === "linkReference") linkRefLabels.push(id);
212
+ else if (n.type === "imageReference") imageRefLabels.push(id);
213
+ else if (n.type === "footnoteDefinition") footnoteDefLabels.push(id);
214
+ });
215
+ if (swallowed !== null && swallowed.hasReference) {
216
+ hasReference = true;
217
+ footnoteRefLabels.push(...swallowed.refLabels);
218
+ linkRefLabels.push(...swallowed.linkLabels);
219
+ imageRefLabels.push(...swallowed.imageLabels);
220
+ local.push(...swallowed.local);
221
+ }
222
+ const footnoteRefLocalCtx = local.length > 0 ? JSON.stringify(local) : void 0;
223
+ const swallowedDefCtx = swallowed !== null && swallowed.bakedDefs.length > 0 ? JSON.stringify(swallowed.bakedDefs) : void 0;
224
+ const mdastPos = mdastNode.position;
225
+ if (!mdastPos || mdastPos.start?.offset === void 0 || mdastPos.end?.offset === void 0) {
226
+ plan.push({
227
+ kind: "inline",
228
+ el,
229
+ key: `inline-${hastOffset}`
230
+ });
231
+ continue;
232
+ }
233
+ let hastDigest;
234
+ let swallowedSource;
235
+ let swallowedTaint = false;
236
+ if (isRawHtmlBlock) {
237
+ const d = computeHtmlBlockDigestWithExtent(el, source, mdastPos.end.offset);
238
+ hastDigest = d.digest;
239
+ swallowedSource = source.slice(mdastPos.end.offset, d.maxEnd);
240
+ const first = firstTaintAtOrAfter(mdastPos.end.offset);
241
+ swallowedTaint = first < taintOffsets.length && taintOffsets[first] < d.maxEnd;
242
+ }
243
+ if (swallowedTaint) hasReference = true;
244
+ const info = {
245
+ raw: extractRaw(mdastNode, source),
246
+ startOffset: mdastPos.start.offset,
247
+ endOffset: mdastPos.end.offset,
248
+ startLine: mdastPos.start.line,
249
+ startColumn: mdastPos.start.column,
250
+ hasReference,
251
+ ...hastDigest !== void 0 ? { hastDigest } : {},
252
+ ...swallowedSource !== void 0 ? { swallowedSource } : {},
253
+ ...swallowed?.hasFootnoteSection ? { containsFootnoteSection: true } : {},
254
+ ...hasReference ? { taintLabels: {
255
+ footnoteRefLabels,
256
+ linkRefLabels,
257
+ imageRefLabels,
258
+ footnoteDefLabels,
259
+ ...footnoteRefLocalCtx !== void 0 ? { footnoteRefLocalCtx } : {},
260
+ ...swallowedDefCtx !== void 0 ? { swallowedDefCtx } : {}
261
+ } } : {}
262
+ };
263
+ blocks.push(info);
264
+ blockHasts.push(el);
265
+ plan.push({
266
+ kind: "block",
267
+ el,
268
+ info,
269
+ key: `block-${hastOffset}`
270
+ });
271
+ }
272
+ return {
273
+ plan,
274
+ globalCtx,
275
+ blocks,
276
+ blockHasts,
277
+ synthetic
278
+ };
305
279
  }
306
280
  function computeBlockFingerprint(taintLabels, registry, thisChunkSym, clobberPrefix) {
307
- const parts = [clobberPrefix];
308
- for (const label of taintLabels.footnoteRefLabels) {
309
- parts.push(`fn:${label}=${registry.globalNumber(label) ?? "null"}`);
310
- }
311
- if (taintLabels.footnoteRefLocalCtx !== void 0) parts.push(`fl:${taintLabels.footnoteRefLocalCtx}`);
312
- if (taintLabels.swallowedDefCtx !== void 0) parts.push(`sd:${taintLabels.swallowedDefCtx}`);
313
- for (const label of taintLabels.linkRefLabels) {
314
- const def = registry.resolveLinkDef(label);
315
- parts.push(`lr:${label}=${def ? JSON.stringify([def.url, def.title ?? null]) : "null"}`);
316
- }
317
- for (const label of taintLabels.imageRefLabels) {
318
- const def = registry.resolveLinkDef(label);
319
- parts.push(`ir:${label}=${def ? JSON.stringify([def.url, def.title ?? null]) : "null"}`);
320
- }
321
- for (const label of taintLabels.footnoteDefLabels) {
322
- const isCanonical = registry.canonicalFootnoteFor(label) === thisChunkSym ? 1 : 0;
323
- parts.push(`fd:${label}=${isCanonical}/${registry.getRefsForLabel(label)}`);
324
- }
325
- return parts.join("|");
281
+ const parts = [clobberPrefix];
282
+ for (const label of taintLabels.footnoteRefLabels) parts.push(`fn:${label}=${registry.globalNumber(label) ?? "null"}`);
283
+ if (taintLabels.footnoteRefLocalCtx !== void 0) parts.push(`fl:${taintLabels.footnoteRefLocalCtx}`);
284
+ if (taintLabels.swallowedDefCtx !== void 0) parts.push(`sd:${taintLabels.swallowedDefCtx}`);
285
+ for (const label of taintLabels.linkRefLabels) {
286
+ const def = registry.resolveLinkDef(label);
287
+ parts.push(`lr:${label}=${def ? JSON.stringify([def.url, def.title ?? null]) : "null"}`);
288
+ }
289
+ for (const label of taintLabels.imageRefLabels) {
290
+ const def = registry.resolveLinkDef(label);
291
+ parts.push(`ir:${label}=${def ? JSON.stringify([def.url, def.title ?? null]) : "null"}`);
292
+ }
293
+ for (const label of taintLabels.footnoteDefLabels) {
294
+ const isCanonical = registry.canonicalFootnoteFor(label) === thisChunkSym ? 1 : 0;
295
+ parts.push(`fd:${label}=${isCanonical}/${registry.getRefsForLabel(label)}`);
296
+ }
297
+ return parts.join("|");
326
298
  }
327
- var PLACEHOLDER_TAGS = /* @__PURE__ */ new Set(["footnote-sup", "cross-chunk-link", "cross-chunk-image"]);
299
+ const PLACEHOLDER_TAGS = /* @__PURE__ */ new Set([
300
+ "footnote-sup",
301
+ "cross-chunk-link",
302
+ "cross-chunk-image"
303
+ ]);
328
304
  function scanSwallowedSubtree(el) {
329
- const refLabels = [];
330
- const linkLabels = [];
331
- const imageLabels = [];
332
- const local = [];
333
- const bakedDefs = [];
334
- let hasReference = false;
335
- let hasFootnoteSection = false;
336
- (0, import_unist_util_visit.visit)(el, "element", (node) => {
337
- if ((0, import_engine.isFootnoteSection)(node)) {
338
- hasFootnoteSection = true;
339
- hasReference = true;
340
- return;
341
- }
342
- const props = node.properties ?? {};
343
- if (PLACEHOLDER_TAGS.has(node.tagName)) {
344
- hasReference = true;
345
- const identifier = props.identifier ?? props.label;
346
- const label = identifier === void 0 ? null : (0, import_engine.normalizeId)(String(identifier));
347
- if (label === null) return;
348
- if (node.tagName === "footnote-sup") {
349
- refLabels.push(label);
350
- const occ = Number(props.localOccurrence);
351
- const num = Number(props.localNumber);
352
- local.push([label, Number.isFinite(occ) ? occ : -1, Number.isFinite(num) ? num : -1]);
353
- return;
354
- }
355
- if (node.tagName === "cross-chunk-link") linkLabels.push(label);
356
- else imageLabels.push(label);
357
- if (typeof props.localUrl === "string") {
358
- bakedDefs.push([label, props.localUrl, typeof props.localTitle === "string" ? props.localTitle : null]);
359
- }
360
- return;
361
- }
362
- if (node.tagName === "a" && props.dataFootnoteRef !== void 0) hasReference = true;
363
- });
364
- return { hasReference, refLabels, linkLabels, imageLabels, local, bakedDefs, hasFootnoteSection };
305
+ const refLabels = [];
306
+ const linkLabels = [];
307
+ const imageLabels = [];
308
+ const local = [];
309
+ const bakedDefs = [];
310
+ let hasReference = false;
311
+ let hasFootnoteSection = false;
312
+ (0, unist_util_visit.visit)(el, "element", (node) => {
313
+ if ((0, _ai_markdown_engine.isFootnoteSection)(node)) {
314
+ hasFootnoteSection = true;
315
+ hasReference = true;
316
+ return;
317
+ }
318
+ const props = node.properties ?? {};
319
+ if (PLACEHOLDER_TAGS.has(node.tagName)) {
320
+ hasReference = true;
321
+ const identifier = props.identifier ?? props.label;
322
+ const label = identifier === void 0 ? null : (0, _ai_markdown_engine.normalizeId)(String(identifier));
323
+ if (label === null) return;
324
+ if (node.tagName === "footnote-sup") {
325
+ refLabels.push(label);
326
+ const occ = Number(props.localOccurrence);
327
+ const num = Number(props.localNumber);
328
+ local.push([
329
+ label,
330
+ Number.isFinite(occ) ? occ : -1,
331
+ Number.isFinite(num) ? num : -1
332
+ ]);
333
+ return;
334
+ }
335
+ if (node.tagName === "cross-chunk-link") linkLabels.push(label);
336
+ else imageLabels.push(label);
337
+ if (typeof props.localUrl === "string") bakedDefs.push([
338
+ label,
339
+ props.localUrl,
340
+ typeof props.localTitle === "string" ? props.localTitle : null
341
+ ]);
342
+ return;
343
+ }
344
+ if (node.tagName === "a" && props.dataFootnoteRef !== void 0) hasReference = true;
345
+ });
346
+ return {
347
+ hasReference,
348
+ refLabels,
349
+ linkLabels,
350
+ imageLabels,
351
+ local,
352
+ bakedDefs,
353
+ hasFootnoteSection
354
+ };
365
355
  }
366
-
367
- // src/blockPlanner.ts
368
- var import_unist_util_visit2 = require("unist-util-visit");
369
- var UNPAIRED_TYPES = /* @__PURE__ */ new Set(["html", "definition", "footnoteDefinition"]);
356
+ const UNPAIRED_TYPES = /* @__PURE__ */ new Set([
357
+ "html",
358
+ "definition",
359
+ "footnoteDefinition"
360
+ ]);
370
361
  function createBlockPlanner() {
371
- let previous;
372
- const eligible = /* @__PURE__ */ new WeakMap();
373
- const isEligible = (node) => {
374
- let result = eligible.get(node);
375
- if (result === void 0) {
376
- result = true;
377
- (0, import_unist_util_visit2.visit)(node, (child) => {
378
- if (UNPAIRED_TYPES.has(child.type)) result = false;
379
- });
380
- eligible.set(node, result);
381
- }
382
- return result;
383
- };
384
- return (mdast, hast, source, options = {}) => {
385
- let m = 0;
386
- let h = 0;
387
- let reusedContext = false;
388
- if (previous && source.startsWith(previous.source) && options.phantomFootnoteLabels === previous.phantoms) {
389
- const prevHast = previous.hast.children;
390
- const prevPlan = previous.result.plan;
391
- const isRetainedGap = (i) => {
392
- const gap = hast.children[i];
393
- return gap === prevHast[i] && gap.type === "text" && !/\S/.test(gap.value);
394
- };
395
- while (m < mdast.children.length) {
396
- const node = mdast.children[m];
397
- const el = hast.children[h];
398
- const item = prevPlan[h];
399
- if (node !== previous.mdast.children[m] || el !== prevHast[h] || !el || el.type !== "element" || !item || item.kind !== "block" || item.info.startOffset !== node.position?.start.offset || !isEligible(node))
400
- break;
401
- const startOffset = item.info.startOffset;
402
- let next = h + 1;
403
- let complete = true;
404
- for (; ; ) {
405
- let probe = next;
406
- while (probe < hast.children.length && isRetainedGap(probe)) probe++;
407
- const sibling = prevPlan[probe];
408
- if (!sibling || sibling.kind !== "block" || sibling.info.startOffset !== startOffset) break;
409
- if (hast.children[probe] !== prevHast[probe]) {
410
- complete = false;
411
- break;
412
- }
413
- next = probe + 1;
414
- }
415
- if (!complete) break;
416
- reusedContext ||= item.info.hasReference;
417
- m++;
418
- h = next;
419
- while (h < hast.children.length && isRetainedGap(h)) h++;
420
- }
421
- if (m > 0) {
422
- const prefixEnd = mdast.children[m - 1].position?.end.offset ?? 0;
423
- for (let i = h; i < hast.children.length; i++) {
424
- const child = hast.children[i];
425
- const at = child.type === "element" ? child.position?.start.offset : void 0;
426
- if (at !== void 0 && at < prefixEnd) {
427
- m = 0;
428
- h = 0;
429
- reusedContext = false;
430
- break;
431
- }
432
- }
433
- }
434
- }
435
- let result;
436
- if (m > 0 && previous) {
437
- const tail = buildBlocks(
438
- { ...mdast, children: mdast.children.slice(m) },
439
- { ...hast, children: hast.children.slice(h) },
440
- source,
441
- reusedContext ? { ...options, contextMdast: options.contextMdast ?? mdast } : options
442
- );
443
- const prefix = previous.result.plan.slice(0, h);
444
- const prefixBlocks = prefix.filter(
445
- (item) => item.kind === "block"
446
- );
447
- result = {
448
- ...tail,
449
- plan: [
450
- ...prefix,
451
- ...tail.plan.map(
452
- (item) => /^inline-i\d+$/.test(item.key) ? { ...item, key: `inline-i${Number(item.key.slice(8)) + h}` } : item
453
- )
454
- ],
455
- blocks: [...prefixBlocks.map((item) => item.info), ...tail.blocks],
456
- blockHasts: [...prefixBlocks.map((item) => item.el), ...tail.blockHasts]
457
- };
458
- } else result = buildBlocks(mdast, hast, source, options);
459
- previous = { mdast, hast, source, result, phantoms: options.phantomFootnoteLabels };
460
- return result;
461
- };
362
+ let previous;
363
+ const eligible = /* @__PURE__ */ new WeakMap();
364
+ const isEligible = (node) => {
365
+ let result = eligible.get(node);
366
+ if (result === void 0) {
367
+ result = true;
368
+ (0, unist_util_visit.visit)(node, (child) => {
369
+ if (UNPAIRED_TYPES.has(child.type)) result = false;
370
+ });
371
+ eligible.set(node, result);
372
+ }
373
+ return result;
374
+ };
375
+ return (mdast, hast, source, options = {}) => {
376
+ let m = 0;
377
+ let h = 0;
378
+ let reusedContext = false;
379
+ if (previous && source.startsWith(previous.source) && options.phantomFootnoteLabels === previous.phantoms) {
380
+ const prevHast = previous.hast.children;
381
+ const prevPlan = previous.result.plan;
382
+ const isRetainedGap = (i) => {
383
+ const gap = hast.children[i];
384
+ return gap === prevHast[i] && gap.type === "text" && !/\S/.test(gap.value);
385
+ };
386
+ while (m < mdast.children.length) {
387
+ const node = mdast.children[m];
388
+ const el = hast.children[h];
389
+ const item = prevPlan[h];
390
+ if (node !== previous.mdast.children[m] || el !== prevHast[h] || !el || el.type !== "element" || !item || item.kind !== "block" || item.info.startOffset !== node.position?.start.offset || !isEligible(node)) break;
391
+ const startOffset = item.info.startOffset;
392
+ let next = h + 1;
393
+ let complete = true;
394
+ for (;;) {
395
+ let probe = next;
396
+ while (probe < hast.children.length && isRetainedGap(probe)) probe++;
397
+ const sibling = prevPlan[probe];
398
+ if (!sibling || sibling.kind !== "block" || sibling.info.startOffset !== startOffset) break;
399
+ if (hast.children[probe] !== prevHast[probe]) {
400
+ complete = false;
401
+ break;
402
+ }
403
+ next = probe + 1;
404
+ }
405
+ if (!complete) break;
406
+ reusedContext ||= item.info.hasReference;
407
+ m++;
408
+ h = next;
409
+ while (h < hast.children.length && isRetainedGap(h)) h++;
410
+ }
411
+ if (m > 0) {
412
+ const prefixEnd = mdast.children[m - 1].position?.end.offset ?? 0;
413
+ for (let i = h; i < hast.children.length; i++) {
414
+ const child = hast.children[i];
415
+ const at = child.type === "element" ? child.position?.start.offset : void 0;
416
+ if (at !== void 0 && at < prefixEnd) {
417
+ m = 0;
418
+ h = 0;
419
+ reusedContext = false;
420
+ break;
421
+ }
422
+ }
423
+ }
424
+ }
425
+ let result;
426
+ if (m > 0 && previous) {
427
+ const tail = buildBlocks({
428
+ ...mdast,
429
+ children: mdast.children.slice(m)
430
+ }, {
431
+ ...hast,
432
+ children: hast.children.slice(h)
433
+ }, source, reusedContext ? {
434
+ ...options,
435
+ contextMdast: options.contextMdast ?? mdast
436
+ } : options);
437
+ const prefix = previous.result.plan.slice(0, h);
438
+ const prefixBlocks = prefix.filter((item) => item.kind === "block");
439
+ result = {
440
+ ...tail,
441
+ plan: [...prefix, ...tail.plan.map((item) => /^inline-i\d+$/.test(item.key) ? {
442
+ ...item,
443
+ key: `inline-i${Number(item.key.slice(8)) + h}`
444
+ } : item)],
445
+ blocks: [...prefixBlocks.map((item) => item.info), ...tail.blocks],
446
+ blockHasts: [...prefixBlocks.map((item) => item.el), ...tail.blockHasts]
447
+ };
448
+ } else result = buildBlocks(mdast, hast, source, options);
449
+ previous = {
450
+ mdast,
451
+ hast,
452
+ source,
453
+ result,
454
+ phantoms: options.phantomFootnoteLabels
455
+ };
456
+ return result;
457
+ };
462
458
  }
463
-
464
- // src/contribution.ts
465
- var import_engine2 = require("@ai-markdown/engine");
466
459
  function createContributionSession() {
467
- let lastContribution = null;
468
- return {
469
- commit({ pipeline, ownLabels, registry, targetPhantoms, sym, clobberPrefix, chain }) {
470
- if (!registry || !sym) return;
471
- const refs = [];
472
- const defMeta = /* @__PURE__ */ new Map();
473
- const linkDefs = /* @__PURE__ */ new Map();
474
- for (const node of (0, import_engine2.extractContributions)(pipeline.mdast, {
475
- phantomFootnoteLabels: targetPhantoms.missingFootnotes
476
- })) {
477
- if (node.kind === "ref") {
478
- refs.push({
479
- label: node.label,
480
- kind: node.refKind,
481
- referenceType: node.referenceType,
482
- ...node.nestedIn !== void 0 ? { nestedIn: node.nestedIn } : {}
483
- });
484
- } else if (node.kind === "fnDef") {
485
- defMeta.set(node.label, {
486
- identifier: node.label,
487
- sourceIdentifier: node.sourceIdentifier,
488
- contentSource: node.content
489
- });
490
- } else if (node.kind === "linkDef") {
491
- linkDefs.set(node.label, { identifier: node.label, url: node.url, title: node.title });
492
- }
493
- }
494
- const fp = JSON.stringify({
495
- r: refs,
496
- d: Array.from(defMeta.entries()).map(([k, v]) => [k, v.sourceIdentifier, v.contentSource]),
497
- l: Array.from(linkDefs.entries()).map(([k, v]) => [k, v.url, v.title ?? ""]),
498
- ofn: Array.from(ownLabels.footnoteLabels).sort(),
499
- ol: Array.from(ownLabels.linkLabels).sort(),
500
- // Include targetPhantoms in the fingerprint: a phantom→resolved
501
- // transition (another chunk publishes a def for a label this chunk
502
- // references inside one of its OWN def bodies) changes the rendered
503
- // hast — the `<cross-chunk-link>` / `<cross-chunk-image>` placeholder
504
- // disappears and a real `<a>` / `<img>` takes its place — without
505
- // touching this chunk's refs / defMeta / linkDefs / ownLabels. Without
506
- // including the phantom snapshot in the fingerprint, the fp check
507
- // would short-circuit and the registry would keep stale bodyHast
508
- // forever, leaving the aggregate footer rendering the placeholder
509
- // long after the label was resolved.
510
- tpfn: Array.from(targetPhantoms.missingFootnotes).sort(),
511
- tpl: Array.from(targetPhantoms.missingLinks).sort()
512
- });
513
- const last = lastContribution;
514
- if (last?.registry === registry && last.symbol === sym && last.fp === fp && last.chain.length === chain.length && last.chain.every((dep, i) => dep === chain[i])) {
515
- return;
516
- }
517
- const bodiesBySafeId = (0, import_engine2.extractDefBodiesFromHast)(pipeline.hast, clobberPrefix);
518
- const defs = /* @__PURE__ */ new Map();
519
- for (const [label, meta] of defMeta) {
520
- defs.set(label, {
521
- identifier: meta.identifier,
522
- sourceIdentifier: meta.sourceIdentifier,
523
- contentSource: meta.contentSource,
524
- bodyHast: bodiesBySafeId.get((0, import_engine2.footnoteSafeId)(meta.sourceIdentifier)) ?? []
525
- });
526
- }
527
- lastContribution = { registry, symbol: sym, fp, chain };
528
- registry.contributeChunkData(sym, {
529
- refs,
530
- defs,
531
- linkDefs,
532
- ownFootnoteLabels: ownLabels.footnoteLabels,
533
- ownLinkLabels: ownLabels.linkLabels
534
- });
535
- }
536
- };
460
+ let lastContribution = null;
461
+ return { commit({ pipeline, ownLabels, registry, targetPhantoms, sym, clobberPrefix, chain }) {
462
+ if (!registry || !sym) return;
463
+ const refs = [];
464
+ const defMeta = /* @__PURE__ */ new Map();
465
+ const linkDefs = /* @__PURE__ */ new Map();
466
+ for (const node of (0, _ai_markdown_engine.extractContributions)(pipeline.mdast, { phantomFootnoteLabels: targetPhantoms.missingFootnotes })) if (node.kind === "ref") refs.push({
467
+ label: node.label,
468
+ kind: node.refKind,
469
+ referenceType: node.referenceType,
470
+ ...node.nestedIn !== void 0 ? { nestedIn: node.nestedIn } : {}
471
+ });
472
+ else if (node.kind === "fnDef") defMeta.set(node.label, {
473
+ identifier: node.label,
474
+ sourceIdentifier: node.sourceIdentifier,
475
+ contentSource: node.content
476
+ });
477
+ else if (node.kind === "linkDef") linkDefs.set(node.label, {
478
+ identifier: node.label,
479
+ url: node.url,
480
+ title: node.title
481
+ });
482
+ const fp = JSON.stringify({
483
+ r: refs,
484
+ d: Array.from(defMeta.entries()).map(([k, v]) => [
485
+ k,
486
+ v.sourceIdentifier,
487
+ v.contentSource
488
+ ]),
489
+ l: Array.from(linkDefs.entries()).map(([k, v]) => [
490
+ k,
491
+ v.url,
492
+ v.title ?? ""
493
+ ]),
494
+ ofn: Array.from(ownLabels.footnoteLabels).sort(),
495
+ ol: Array.from(ownLabels.linkLabels).sort(),
496
+ tpfn: Array.from(targetPhantoms.missingFootnotes).sort(),
497
+ tpl: Array.from(targetPhantoms.missingLinks).sort()
498
+ });
499
+ const last = lastContribution;
500
+ if (last?.registry === registry && last.symbol === sym && last.fp === fp && last.chain.length === chain.length && last.chain.every((dep, i) => dep === chain[i])) return;
501
+ const bodiesBySafeId = (0, _ai_markdown_engine.extractDefBodiesFromHast)(pipeline.hast, clobberPrefix);
502
+ const defs = /* @__PURE__ */ new Map();
503
+ for (const [label, meta] of defMeta) defs.set(label, {
504
+ identifier: meta.identifier,
505
+ sourceIdentifier: meta.sourceIdentifier,
506
+ contentSource: meta.contentSource,
507
+ bodyHast: bodiesBySafeId.get((0, _ai_markdown_engine.footnoteSafeId)(meta.sourceIdentifier)) ?? []
508
+ });
509
+ lastContribution = {
510
+ registry,
511
+ symbol: sym,
512
+ fp,
513
+ chain
514
+ };
515
+ registry.contributeChunkData(sym, {
516
+ refs,
517
+ defs,
518
+ linkDefs,
519
+ ownFootnoteLabels: ownLabels.footnoteLabels,
520
+ ownLinkLabels: ownLabels.linkLabels
521
+ });
522
+ } };
537
523
  }
538
-
539
- // src/smoothCoordinator.ts
540
- function createSmoothCoordinator(onEmpty) {
541
- const order = [];
542
- const done = /* @__PURE__ */ new Set();
543
- const lastProgressAt = /* @__PURE__ */ new Map();
544
- const coord = {
545
- order,
546
- done,
547
- lastProgressAt,
548
- version: 0,
549
- _refcounts: /* @__PURE__ */ new Map(),
550
- _subscribers: /* @__PURE__ */ new Set(),
551
- _notifyScheduled: false,
552
- register(chunkId) {
553
- const count = this._refcounts.get(chunkId) ?? 0;
554
- this._refcounts.set(chunkId, count + 1);
555
- if (count === 0 && !order.includes(chunkId)) {
556
- order.push(chunkId);
557
- this._notify();
558
- }
559
- },
560
- release(chunkId) {
561
- const count = this._refcounts.get(chunkId);
562
- if (count === void 0) return;
563
- if (count > 1) {
564
- this._refcounts.set(chunkId, count - 1);
565
- return;
566
- }
567
- this._refcounts.set(chunkId, 0);
568
- queueMicrotask(() => {
569
- if (this._refcounts.get(chunkId) !== 0) return;
570
- this._refcounts.delete(chunkId);
571
- const idx = order.indexOf(chunkId);
572
- if (idx !== -1) order.splice(idx, 1);
573
- done.delete(chunkId);
574
- lastProgressAt.delete(chunkId);
575
- this._notify();
576
- if (order.length === 0 && onEmpty) onEmpty();
577
- });
578
- },
579
- markDone(chunkId) {
580
- if (done.has(chunkId)) return;
581
- done.add(chunkId);
582
- this._notify();
583
- },
584
- stampProgress(chunkId, at) {
585
- lastProgressAt.set(chunkId, at);
586
- },
587
- isReleased(chunkId) {
588
- for (const id of order) {
589
- if (id === chunkId) return true;
590
- if (!done.has(id)) return false;
591
- }
592
- return true;
593
- },
594
- earliestBlockerOf(chunkId) {
595
- for (const id of order) {
596
- if (id === chunkId) return null;
597
- if (!done.has(id)) return id;
598
- }
599
- return null;
600
- },
601
- subscribe(cb) {
602
- this._subscribers.add(cb);
603
- return () => {
604
- this._subscribers.delete(cb);
605
- };
606
- },
607
- _notify() {
608
- this.version++;
609
- if (this._notifyScheduled) return;
610
- this._notifyScheduled = true;
611
- queueMicrotask(() => {
612
- this._notifyScheduled = false;
613
- for (const cb of [...this._subscribers]) cb();
614
- });
615
- }
616
- };
617
- return coord;
524
+ function createSmoothCoordinator$1(onEmpty) {
525
+ const order = [];
526
+ const done = /* @__PURE__ */ new Set();
527
+ const lastProgressAt = /* @__PURE__ */ new Map();
528
+ return {
529
+ order,
530
+ done,
531
+ lastProgressAt,
532
+ version: 0,
533
+ _refcounts: /* @__PURE__ */ new Map(),
534
+ _subscribers: /* @__PURE__ */ new Set(),
535
+ _notifyScheduled: false,
536
+ register(chunkId) {
537
+ const count = this._refcounts.get(chunkId) ?? 0;
538
+ this._refcounts.set(chunkId, count + 1);
539
+ if (count === 0 && !order.includes(chunkId)) {
540
+ order.push(chunkId);
541
+ this._notify();
542
+ }
543
+ },
544
+ release(chunkId) {
545
+ const count = this._refcounts.get(chunkId);
546
+ if (count === void 0) return;
547
+ if (count > 1) {
548
+ this._refcounts.set(chunkId, count - 1);
549
+ return;
550
+ }
551
+ this._refcounts.set(chunkId, 0);
552
+ queueMicrotask(() => {
553
+ if (this._refcounts.get(chunkId) !== 0) return;
554
+ this._refcounts.delete(chunkId);
555
+ const idx = order.indexOf(chunkId);
556
+ if (idx !== -1) order.splice(idx, 1);
557
+ done.delete(chunkId);
558
+ lastProgressAt.delete(chunkId);
559
+ this._notify();
560
+ if (order.length === 0 && onEmpty) onEmpty();
561
+ });
562
+ },
563
+ markDone(chunkId) {
564
+ if (done.has(chunkId)) return;
565
+ done.add(chunkId);
566
+ this._notify();
567
+ },
568
+ stampProgress(chunkId, at) {
569
+ lastProgressAt.set(chunkId, at);
570
+ },
571
+ isReleased(chunkId) {
572
+ for (const id of order) {
573
+ if (id === chunkId) return true;
574
+ if (!done.has(id)) return false;
575
+ }
576
+ return true;
577
+ },
578
+ earliestBlockerOf(chunkId) {
579
+ for (const id of order) {
580
+ if (id === chunkId) return null;
581
+ if (!done.has(id)) return id;
582
+ }
583
+ return null;
584
+ },
585
+ subscribe(cb) {
586
+ this._subscribers.add(cb);
587
+ return () => {
588
+ this._subscribers.delete(cb);
589
+ };
590
+ },
591
+ _notify() {
592
+ this.version++;
593
+ if (this._notifyScheduled) return;
594
+ this._notifyScheduled = true;
595
+ queueMicrotask(() => {
596
+ this._notifyScheduled = false;
597
+ for (const cb of [...this._subscribers]) cb();
598
+ });
599
+ }
600
+ };
618
601
  }
619
602
  function evaluateGateWarn(coordinator, chunkId, nowMs, thresholdMs) {
620
- const blocker = coordinator.earliestBlockerOf(chunkId);
621
- if (!blocker) return "clear";
622
- const progressedAt = coordinator.lastProgressAt.get(blocker) ?? 0;
623
- return nowMs - progressedAt < thresholdMs ? "rearm" : "warn";
603
+ const blocker = coordinator.earliestBlockerOf(chunkId);
604
+ if (!blocker) return "clear";
605
+ return nowMs - (coordinator.lastProgressAt.get(blocker) ?? 0) < thresholdMs ? "rearm" : "warn";
624
606
  }
625
-
626
- // src/coordinator.ts
627
- function createSmoothCoordinator2(onEmpty) {
628
- return createSmoothCoordinator(onEmpty);
607
+ function createSmoothCoordinator(onEmpty) {
608
+ return createSmoothCoordinator$1(onEmpty);
629
609
  }
630
-
631
- // src/tailSignal.ts
632
- var DESCEND_THROUGH = /* @__PURE__ */ new Set(["blockquote", "list", "listItem", "footnoteDefinition"]);
610
+ const DESCEND_THROUGH = /* @__PURE__ */ new Set([
611
+ "blockquote",
612
+ "list",
613
+ "listItem",
614
+ "footnoteDefinition"
615
+ ]);
633
616
  function deriveTailSignal(mdast, contentLength) {
634
- const children = mdast.children;
635
- let index = children.length - 1;
636
- while (index >= 0) {
637
- const offset = children[index].position?.start?.offset;
638
- if (offset !== void 0 && offset >= contentLength) {
639
- index--;
640
- continue;
641
- }
642
- break;
643
- }
644
- if (index < 0) return null;
645
- let node = children[index];
646
- let deepestFootnoteDef = null;
647
- for (; ; ) {
648
- if (node.type === "footnoteDefinition") deepestFootnoteDef = node;
649
- if (node.type === "definition") {
650
- return { kind: "invisible-def" };
651
- }
652
- if (!DESCEND_THROUGH.has(node.type)) break;
653
- const kids = node.children;
654
- if (!kids || kids.length === 0) break;
655
- node = kids[kids.length - 1];
656
- }
657
- return deepestFootnoteDef ? { kind: "footnote-def", identifier: deepestFootnoteDef.identifier } : null;
617
+ const children = mdast.children;
618
+ let index = children.length - 1;
619
+ while (index >= 0) {
620
+ const offset = children[index].position?.start?.offset;
621
+ if (offset !== void 0 && offset >= contentLength) {
622
+ index--;
623
+ continue;
624
+ }
625
+ break;
626
+ }
627
+ if (index < 0) return null;
628
+ let node = children[index];
629
+ let deepestFootnoteDef = null;
630
+ for (;;) {
631
+ if (node.type === "footnoteDefinition") deepestFootnoteDef = node;
632
+ if (node.type === "definition") return { kind: "invisible-def" };
633
+ if (!DESCEND_THROUGH.has(node.type)) break;
634
+ const kids = node.children;
635
+ if (!kids || kids.length === 0) break;
636
+ node = kids[kids.length - 1];
637
+ }
638
+ return deepestFootnoteDef ? {
639
+ kind: "footnote-def",
640
+ identifier: deepestFootnoteDef.identifier
641
+ } : null;
658
642
  }
659
-
660
- // src/aggregateFootnotes.ts
661
- var import_engine3 = require("@ai-markdown/engine");
662
-
663
- // src/cloneHastForRender.ts
664
643
  function cloneHastForRender(node) {
665
- const copy = { ...node };
666
- const withChildren = copy;
667
- if (Array.isArray(withChildren.children)) {
668
- withChildren.children = withChildren.children.map((child) => cloneHastForRender(child));
669
- }
670
- const withProperties = copy;
671
- if (withProperties.properties) {
672
- withProperties.properties = { ...withProperties.properties };
673
- }
674
- if (copy.data) {
675
- copy.data = { ...copy.data };
676
- const data = copy.data;
677
- if (data.originalUrls) data.originalUrls = { ...data.originalUrls };
678
- }
679
- return copy;
644
+ const copy = { ...node };
645
+ const withChildren = copy;
646
+ if (Array.isArray(withChildren.children)) withChildren.children = withChildren.children.map((child) => cloneHastForRender(child));
647
+ const withProperties = copy;
648
+ if (withProperties.properties) withProperties.properties = { ...withProperties.properties };
649
+ if (copy.data) {
650
+ copy.data = { ...copy.data };
651
+ const data = copy.data;
652
+ if (data.originalUrls) data.originalUrls = { ...data.originalUrls };
653
+ }
654
+ return copy;
680
655
  }
681
-
682
- // src/aggregateFootnotes.ts
683
656
  function buildBackref(href, occurrence, globalNumber) {
684
- const children = [{ type: "text", value: "\u21A9" }];
685
- if (occurrence > 1) {
686
- children.push({
687
- type: "element",
688
- tagName: "sup",
689
- properties: {},
690
- children: [{ type: "text", value: String(occurrence) }]
691
- });
692
- }
693
- const ariaLabel = occurrence === 1 ? `Back to reference ${globalNumber}` : `Back to reference ${globalNumber}-${occurrence}`;
694
- return {
695
- type: "element",
696
- tagName: "a",
697
- properties: {
698
- href,
699
- dataFootnoteBackref: "",
700
- className: ["data-footnote-backref"],
701
- ariaLabel
702
- },
703
- children
704
- };
657
+ const children = [{
658
+ type: "text",
659
+ value: "↩"
660
+ }];
661
+ if (occurrence > 1) children.push({
662
+ type: "element",
663
+ tagName: "sup",
664
+ properties: {},
665
+ children: [{
666
+ type: "text",
667
+ value: String(occurrence)
668
+ }]
669
+ });
670
+ return {
671
+ type: "element",
672
+ tagName: "a",
673
+ properties: {
674
+ href,
675
+ dataFootnoteBackref: "",
676
+ className: ["data-footnote-backref"],
677
+ ariaLabel: occurrence === 1 ? `Back to reference ${globalNumber}` : `Back to reference ${globalNumber}-${occurrence}`
678
+ },
679
+ children
680
+ };
705
681
  }
706
682
  function buildAggregateTree(registry, clobberPrefix, preserveOrphanReferences = false) {
707
- const seen = /* @__PURE__ */ new Set();
708
- const ordered = [];
709
- for (const sym of registry.chunkOrder) {
710
- const data = registry.chunkData.get(sym);
711
- if (!data) continue;
712
- for (const ref of data.refs) {
713
- if (ref.kind !== "footnote") continue;
714
- if (seen.has(ref.label)) continue;
715
- seen.add(ref.label);
716
- const canonicalSym = registry.canonicalFootnoteFor(ref.label);
717
- if (!canonicalSym) continue;
718
- const def = registry.chunkData.get(canonicalSym)?.defs.get(ref.label);
719
- if (!def) continue;
720
- const n = registry.globalNumber(ref.label);
721
- if (n === null) continue;
722
- const sourceIdentifier = def.sourceIdentifier ?? ref.label;
723
- ordered.push({
724
- normalizedLabel: ref.label,
725
- sourceIdentifier,
726
- bodyHast: def.bodyHast ?? [],
727
- n,
728
- withBackref: true
729
- });
730
- }
731
- }
732
- ordered.sort((a, b) => (a.n ?? 0) - (b.n ?? 0));
733
- if (preserveOrphanReferences) {
734
- for (const sym of registry.chunkOrder) {
735
- const data = registry.chunkData.get(sym);
736
- if (!data) continue;
737
- for (const [label, def] of data.defs) {
738
- if (seen.has(label)) continue;
739
- if (registry.canonicalFootnoteFor(label) !== sym) continue;
740
- seen.add(label);
741
- ordered.push({
742
- normalizedLabel: label,
743
- sourceIdentifier: def.sourceIdentifier ?? label,
744
- bodyHast: def.bodyHast ?? [],
745
- n: null,
746
- withBackref: false
747
- });
748
- }
749
- }
750
- }
751
- if (ordered.length === 0) return null;
752
- const liElements = ordered.map(({ normalizedLabel, sourceIdentifier, bodyHast, n, withBackref }) => {
753
- const safeId = (0, import_engine3.footnoteSafeId)(sourceIdentifier);
754
- const liChildren = bodyHast.map((c) => cloneHastForRender(c));
755
- if (withBackref) {
756
- const totalRefs = registry.getRefsForLabel(normalizedLabel);
757
- const tailIdx = (0, import_engine3.lastMeaningfulIdx)(liChildren);
758
- const tail = tailIdx !== -1 ? liChildren[tailIdx] : null;
759
- const dest = tail && tail.type === "element" && tail.tagName === "p" ? tail : null;
760
- const appended = [];
761
- for (let i = 1; i <= Math.max(totalRefs, 1); i++) {
762
- appended.push({ type: "text", value: " " });
763
- const href = i === 1 ? `#${clobberPrefix}fnref-${safeId}` : `#${clobberPrefix}fnref-${safeId}-${i}`;
764
- appended.push(buildBackref(href, i, n ?? 0));
765
- }
766
- if (dest) {
767
- dest.children = [...dest.children, ...appended];
768
- } else if (tailIdx !== -1) {
769
- liChildren.splice(tailIdx + 1, 0, ...appended);
770
- } else {
771
- liChildren.push(...appended);
772
- }
773
- }
774
- return {
775
- type: "element",
776
- tagName: "li",
777
- properties: {
778
- id: `${clobberPrefix}fn-${safeId}`,
779
- // Stringified: @types/hast (≥3.0.5) types li's `value` as string;
780
- // React serializes value={3} and value="3" to identical markup.
781
- ...n !== null ? { value: String(n) } : {}
782
- },
783
- children: liChildren
784
- };
785
- });
786
- return {
787
- type: "element",
788
- tagName: "section",
789
- properties: {
790
- className: ["footnotes"],
791
- dataFootnotes: true,
792
- // a11y: name the section landmark so screen readers still announce it
793
- // even though the visible "Footnotes" h2 is omitted in coordinated mode.
794
- ariaLabel: "Footnotes"
795
- },
796
- children: [
797
- // Conventional separator above the footnote list. The default
798
- // mdast-util-to-hast footer doesn't emit one (GitHub renders the
799
- // separation via CSS `border-top` on `.footnotes`); we render a literal
800
- // `<hr>` so the visual break is preserved without sanitize-friendly CSS.
801
- {
802
- type: "element",
803
- tagName: "hr",
804
- properties: {},
805
- children: []
806
- },
807
- {
808
- type: "element",
809
- tagName: "ol",
810
- properties: {},
811
- children: liElements
812
- }
813
- ]
814
- };
683
+ const seen = /* @__PURE__ */ new Set();
684
+ const ordered = [];
685
+ for (const sym of registry.chunkOrder) {
686
+ const data = registry.chunkData.get(sym);
687
+ if (!data) continue;
688
+ for (const ref of data.refs) {
689
+ if (ref.kind !== "footnote") continue;
690
+ if (seen.has(ref.label)) continue;
691
+ seen.add(ref.label);
692
+ const canonicalSym = registry.canonicalFootnoteFor(ref.label);
693
+ if (!canonicalSym) continue;
694
+ const def = registry.chunkData.get(canonicalSym)?.defs.get(ref.label);
695
+ if (!def) continue;
696
+ const n = registry.globalNumber(ref.label);
697
+ if (n === null) continue;
698
+ const sourceIdentifier = def.sourceIdentifier ?? ref.label;
699
+ ordered.push({
700
+ normalizedLabel: ref.label,
701
+ sourceIdentifier,
702
+ bodyHast: def.bodyHast ?? [],
703
+ n,
704
+ withBackref: true
705
+ });
706
+ }
707
+ }
708
+ ordered.sort((a, b) => (a.n ?? 0) - (b.n ?? 0));
709
+ if (preserveOrphanReferences) for (const sym of registry.chunkOrder) {
710
+ const data = registry.chunkData.get(sym);
711
+ if (!data) continue;
712
+ for (const [label, def] of data.defs) {
713
+ if (seen.has(label)) continue;
714
+ if (registry.canonicalFootnoteFor(label) !== sym) continue;
715
+ seen.add(label);
716
+ ordered.push({
717
+ normalizedLabel: label,
718
+ sourceIdentifier: def.sourceIdentifier ?? label,
719
+ bodyHast: def.bodyHast ?? [],
720
+ n: null,
721
+ withBackref: false
722
+ });
723
+ }
724
+ }
725
+ if (ordered.length === 0) return null;
726
+ return {
727
+ type: "element",
728
+ tagName: "section",
729
+ properties: {
730
+ className: ["footnotes"],
731
+ dataFootnotes: true,
732
+ ariaLabel: "Footnotes"
733
+ },
734
+ children: [{
735
+ type: "element",
736
+ tagName: "hr",
737
+ properties: {},
738
+ children: []
739
+ }, {
740
+ type: "element",
741
+ tagName: "ol",
742
+ properties: {},
743
+ children: ordered.map(({ normalizedLabel, sourceIdentifier, bodyHast, n, withBackref }) => {
744
+ const safeId = (0, _ai_markdown_engine.footnoteSafeId)(sourceIdentifier);
745
+ const liChildren = bodyHast.map((c) => cloneHastForRender(c));
746
+ if (withBackref) {
747
+ const totalRefs = registry.getRefsForLabel(normalizedLabel);
748
+ const tailIdx = (0, _ai_markdown_engine.lastMeaningfulIdx)(liChildren);
749
+ const tail = tailIdx !== -1 ? liChildren[tailIdx] : null;
750
+ const dest = tail && tail.type === "element" && tail.tagName === "p" ? tail : null;
751
+ const appended = [];
752
+ for (let i = 1; i <= Math.max(totalRefs, 1); i++) {
753
+ appended.push({
754
+ type: "text",
755
+ value: " "
756
+ });
757
+ const href = i === 1 ? `#${clobberPrefix}fnref-${safeId}` : `#${clobberPrefix}fnref-${safeId}-${i}`;
758
+ appended.push(buildBackref(href, i, n ?? 0));
759
+ }
760
+ if (dest) dest.children = [...dest.children, ...appended];
761
+ else if (tailIdx !== -1) liChildren.splice(tailIdx + 1, 0, ...appended);
762
+ else liChildren.push(...appended);
763
+ }
764
+ return {
765
+ type: "element",
766
+ tagName: "li",
767
+ properties: {
768
+ id: `${clobberPrefix}fn-${safeId}`,
769
+ ...n !== null ? { value: String(n) } : {}
770
+ },
771
+ children: liChildren
772
+ };
773
+ })
774
+ }]
775
+ };
815
776
  }
816
-
817
- // src/pipelineSession.ts
818
- var import_engine4 = require("@ai-markdown/engine");
819
- var unmeasured = (_stage, fn) => fn();
777
+ const unmeasured = (_stage, fn) => fn();
820
778
  function endPoint(text) {
821
- let line = 1;
822
- let lineStart = 0;
823
- for (let i = 0; i < text.length; i++) {
824
- const code = text.charCodeAt(i);
825
- if (code === 10 || code === 13 && text.charCodeAt(i + 1) !== 10) {
826
- line += 1;
827
- lineStart = i + 1;
828
- }
829
- }
830
- return { line, column: text.length - lineStart + 1, offset: text.length };
779
+ let line = 1;
780
+ let lineStart = 0;
781
+ for (let i = 0; i < text.length; i++) {
782
+ const code = text.charCodeAt(i);
783
+ if (code === 10 || code === 13 && text.charCodeAt(i + 1) !== 10) {
784
+ line += 1;
785
+ lineStart = i + 1;
786
+ }
787
+ }
788
+ return {
789
+ line,
790
+ column: text.length - lineStart + 1,
791
+ offset: text.length
792
+ };
831
793
  }
832
794
  function plainTextTrees(content) {
833
- const position = { start: { line: 1, column: 1, offset: 0 }, end: endPoint(content) };
834
- const text = { type: "text", value: content, position };
835
- return {
836
- mdast: { type: "root", children: [{ type: "paragraph", children: [text], position }], position },
837
- hast: {
838
- type: "root",
839
- children: [{ type: "element", tagName: "p", properties: {}, children: [text], position }],
840
- position
841
- }
842
- };
795
+ const position = {
796
+ start: {
797
+ line: 1,
798
+ column: 1,
799
+ offset: 0
800
+ },
801
+ end: endPoint(content)
802
+ };
803
+ const text = {
804
+ type: "text",
805
+ value: content,
806
+ position
807
+ };
808
+ return {
809
+ mdast: {
810
+ type: "root",
811
+ children: [{
812
+ type: "paragraph",
813
+ children: [text],
814
+ position
815
+ }],
816
+ position
817
+ },
818
+ hast: {
819
+ type: "root",
820
+ children: [{
821
+ type: "element",
822
+ tagName: "p",
823
+ properties: {},
824
+ children: [text],
825
+ position
826
+ }],
827
+ position
828
+ }
829
+ };
843
830
  }
844
831
  function createPipelineSession() {
845
- let state = null;
846
- return {
847
- reset() {
848
- state = null;
849
- },
850
- parse({
851
- content,
852
- targetPhantoms,
853
- remarkPlugins,
854
- rehypePlugins,
855
- remarkRehypeOptions,
856
- handlers,
857
- preserveForBodyHarvest,
858
- documentId,
859
- provenance,
860
- incrementalParse,
861
- defListEnabled,
862
- gfmTaskListItems = false,
863
- // No default: omitted is its own (undeclared) state at the engine.
864
- mathFlow,
865
- measure: measureHere = unmeasured
866
- }) {
867
- const phantomDefs = (0, import_engine4.buildPhantomSuffix)(targetPhantoms);
868
- const phantomSuffix = phantomDefs === "" ? "" : (0, import_engine4.phantomSuffixCloser)(content ?? "") + phantomDefs;
869
- const augmented = (content ?? "") + phantomSuffix;
870
- const baseHandlers = remarkRehypeOptions?.handlers ?? {};
871
- const mergedRemarkRehypeOptions = handlers ? {
872
- ...remarkRehypeOptions,
873
- handlers: { ...baseHandlers, ...handlers },
874
- // Phantom label sets are empty in standalone mode (no PASS 0.5
875
- // injection happened); the footnoteDefinition handler still reads
876
- // them via `state.options.phantomFootnoteLabels.has(id)`, which
877
- // returns false for every id → orphan-protect path proceeds.
878
- phantomFootnoteLabels: targetPhantoms.missingFootnotes,
879
- phantomLinkLabels: targetPhantoms.missingLinks,
880
- preserveOrphan: preserveForBodyHarvest,
881
- documentId,
882
- // The SAME value `buildCoreRehypePlugins` received — the
883
- // verifier unwraps every placeholder stamped with anything else.
884
- provenance
885
- } : {
886
- ...remarkRehypeOptions
887
- };
888
- const fullPipeline = () => {
889
- try {
890
- const parsed = measureHere(
891
- "parse",
892
- () => (0, import_engine4.parseStage)({
893
- children: augmented,
894
- remarkPlugins,
895
- rehypePlugins,
896
- remarkRehypeOptions: mergedRemarkRehypeOptions
897
- })
898
- );
899
- const hastRoot = measureHere("transform", () => (0, import_engine4.transformStage)(parsed));
900
- return { mdast: parsed.mdast, hast: hastRoot };
901
- } catch (error) {
902
- if (!(error instanceof import_engine4.EngineRawHtmlDepthError)) throw error;
903
- if (true) {
904
- console.error(
905
- "[ai-react-markdown] raw HTML nested past the engine depth bound \u2014 rendering this frame as plain text:",
906
- error
907
- );
908
- }
909
- return plainTextTrees(content ?? "");
910
- }
911
- };
912
- if (!incrementalParse) {
913
- state = null;
914
- return fullPipeline();
915
- }
916
- try {
917
- const result = (0, import_engine4.advanceIncrementalParse)(state, content ?? "", {
918
- remarkPlugins,
919
- rehypePlugins,
920
- remarkRehypeOptions: mergedRemarkRehypeOptions,
921
- // Identity tuple over every parse input beyond the content itself.
922
- // Deliberately covers MORE than the G3 flush's 12 fields (handlers /
923
- // preserveForBodyHarvest / documentId can change without touching
924
- // any G3 field — e.g. a `preserveOrphanReferences` flip). The
925
- // phantom label sets are deliberately NOT here: their churn tracks
926
- // the suffix (always re-parsed with the tail), never the prefix.
927
- depsKey: [
928
- remarkPlugins,
929
- rehypePlugins,
930
- remarkRehypeOptions,
931
- handlers,
932
- preserveForBodyHarvest,
933
- documentId,
934
- // Explicit even though `rehypePlugins` already carries it: a
935
- // credential change must never reuse trees stamped under the
936
- // old one.
937
- provenance,
938
- // The boundary scanner's grammar profile. The scan checkpoint
939
- // already refuses to resume under a different profile, but the
940
- // retained TREES were still spliced against — a prefix frozen
941
- // under one profile must not survive into frames under the other.
942
- defListEnabled,
943
- gfmTaskListItems,
944
- mathFlow
945
- ],
946
- defListEnabled,
947
- gfmTaskListItems,
948
- mathFlow,
949
- phantomSuffix,
950
- measure: measureHere
951
- });
952
- state = result.nextState;
953
- return { mdast: result.mdast, hast: result.hast };
954
- } catch (error) {
955
- state = null;
956
- if (true) {
957
- console.error("[ai-react-markdown] incremental parse failed \u2014 full parse fallback for this frame:", error);
958
- }
959
- return fullPipeline();
960
- }
961
- }
962
- };
832
+ let state = null;
833
+ return {
834
+ reset() {
835
+ state = null;
836
+ },
837
+ parse({ content, targetPhantoms, remarkPlugins, rehypePlugins, remarkRehypeOptions, handlers, preserveForBodyHarvest, documentId, provenance, incrementalParse, defListEnabled, gfmTaskListItems = false, mathFlow, measure: measureHere = unmeasured }) {
838
+ const phantomDefs = (0, _ai_markdown_engine.buildPhantomSuffix)(targetPhantoms);
839
+ const phantomSuffix = phantomDefs === "" ? "" : (0, _ai_markdown_engine.phantomSuffixCloser)(content ?? "") + phantomDefs;
840
+ const augmented = (content ?? "") + phantomSuffix;
841
+ const baseHandlers = remarkRehypeOptions?.handlers ?? {};
842
+ const mergedRemarkRehypeOptions = handlers ? {
843
+ ...remarkRehypeOptions,
844
+ handlers: {
845
+ ...baseHandlers,
846
+ ...handlers
847
+ },
848
+ phantomFootnoteLabels: targetPhantoms.missingFootnotes,
849
+ phantomLinkLabels: targetPhantoms.missingLinks,
850
+ preserveOrphan: preserveForBodyHarvest,
851
+ documentId,
852
+ provenance
853
+ } : { ...remarkRehypeOptions };
854
+ const fullPipeline = () => {
855
+ try {
856
+ const parsed = measureHere("parse", () => (0, _ai_markdown_engine.parseStage)({
857
+ children: augmented,
858
+ remarkPlugins,
859
+ rehypePlugins,
860
+ remarkRehypeOptions: mergedRemarkRehypeOptions
861
+ }));
862
+ const hastRoot = measureHere("transform", () => (0, _ai_markdown_engine.transformStage)(parsed));
863
+ return {
864
+ mdast: parsed.mdast,
865
+ hast: hastRoot
866
+ };
867
+ } catch (error) {
868
+ if (!(error instanceof _ai_markdown_engine.EngineRawHtmlDepthError)) throw error;
869
+ console.error("[ai-react-markdown] raw HTML nested past the engine depth bound — rendering this frame as plain text:", error);
870
+ return plainTextTrees(content ?? "");
871
+ }
872
+ };
873
+ if (!incrementalParse) {
874
+ state = null;
875
+ return fullPipeline();
876
+ }
877
+ try {
878
+ const result = (0, _ai_markdown_engine.advanceIncrementalParse)(state, content ?? "", {
879
+ remarkPlugins,
880
+ rehypePlugins,
881
+ remarkRehypeOptions: mergedRemarkRehypeOptions,
882
+ depsKey: [
883
+ remarkPlugins,
884
+ rehypePlugins,
885
+ remarkRehypeOptions,
886
+ handlers,
887
+ preserveForBodyHarvest,
888
+ documentId,
889
+ provenance,
890
+ defListEnabled,
891
+ gfmTaskListItems,
892
+ mathFlow
893
+ ],
894
+ defListEnabled,
895
+ gfmTaskListItems,
896
+ mathFlow,
897
+ phantomSuffix,
898
+ measure: measureHere
899
+ });
900
+ state = result.nextState;
901
+ return {
902
+ mdast: result.mdast,
903
+ hast: result.hast
904
+ };
905
+ } catch (error) {
906
+ state = null;
907
+ console.error("[ai-react-markdown] incremental parse failed — full parse fallback for this frame:", error);
908
+ return fullPipeline();
909
+ }
910
+ }
911
+ };
963
912
  }
964
-
965
- // src/coordinationPreparation.ts
966
- var import_engine5 = require("@ai-markdown/engine");
967
913
  function derivePhantomTargets({ content, ownLabels, labels }, previous) {
968
- const missingFootnotes = /* @__PURE__ */ new Set();
969
- const missingLinks = /* @__PURE__ */ new Set();
970
- if (labels) {
971
- const footnotes = [...labels.footnoteLabels].filter((label) => !ownLabels.footnoteLabels.has(label));
972
- const links = [...labels.linkLabels].filter((label) => !ownLabels.linkLabels.has(label));
973
- if (footnotes.length || links.length) {
974
- const normalized = (0, import_engine5.normalizeForMatch)(content);
975
- for (const label of footnotes) if (normalized.includes(label)) missingFootnotes.add(label);
976
- for (const label of links) if (normalized.includes(label)) missingLinks.add(label);
977
- }
978
- }
979
- if (previous && missingFootnotes.size === previous.missingFootnotes.size && missingLinks.size === previous.missingLinks.size && [...missingFootnotes].every((label) => previous.missingFootnotes.has(label)) && [...missingLinks].every((label) => previous.missingLinks.has(label)))
980
- return previous;
981
- return { missingFootnotes, missingLinks };
914
+ const missingFootnotes = /* @__PURE__ */ new Set();
915
+ const missingLinks = /* @__PURE__ */ new Set();
916
+ if (labels) {
917
+ const footnotes = [...labels.footnoteLabels].filter((label) => !ownLabels.footnoteLabels.has(label));
918
+ const links = [...labels.linkLabels].filter((label) => !ownLabels.linkLabels.has(label));
919
+ if (footnotes.length || links.length) {
920
+ const normalized = (0, _ai_markdown_engine.normalizeForMatch)(content);
921
+ for (const label of footnotes) if (normalized.includes(label)) missingFootnotes.add(label);
922
+ for (const label of links) if (normalized.includes(label)) missingLinks.add(label);
923
+ }
924
+ }
925
+ if (previous && missingFootnotes.size === previous.missingFootnotes.size && missingLinks.size === previous.missingLinks.size && [...missingFootnotes].every((label) => previous.missingFootnotes.has(label)) && [...missingLinks].every((label) => previous.missingLinks.has(label))) return previous;
926
+ return {
927
+ missingFootnotes,
928
+ missingLinks
929
+ };
982
930
  }
983
- function deriveCoordinationPolicy({
984
- coordinated,
985
- registered,
986
- preserveOrphanReferences
987
- }, previous) {
988
- const mode = coordinated ? "coordinated" : preserveOrphanReferences ? "orphan" : "standalone";
989
- const preserveForBodyHarvest = preserveOrphanReferences || coordinated && registered;
990
- if (previous?.mode === mode && previous.preserveForBodyHarvest === preserveForBodyHarvest) return previous;
991
- const handlers = previous?.mode === mode ? previous.handlers : mode === "coordinated" ? (0, import_engine5.buildCrossChunkHandlers)() : mode === "orphan" ? { footnoteDefinition: (0, import_engine5.buildCrossChunkHandlers)().footnoteDefinition } : void 0;
992
- return { mode, handlers, preserveForBodyHarvest };
931
+ function deriveCoordinationPolicy({ coordinated, registered, preserveOrphanReferences }, previous) {
932
+ const mode = coordinated ? "coordinated" : preserveOrphanReferences ? "orphan" : "standalone";
933
+ const preserveForBodyHarvest = preserveOrphanReferences || coordinated && registered;
934
+ if (previous?.mode === mode && previous.preserveForBodyHarvest === preserveForBodyHarvest) return previous;
935
+ return {
936
+ mode,
937
+ handlers: previous?.mode === mode ? previous.handlers : mode === "coordinated" ? (0, _ai_markdown_engine.buildCrossChunkHandlers)() : mode === "orphan" ? { footnoteDefinition: (0, _ai_markdown_engine.buildCrossChunkHandlers)().footnoteDefinition } : void 0,
938
+ preserveForBodyHarvest
939
+ };
993
940
  }
994
941
  function buildContributionChain(inputs) {
995
- return [
996
- inputs.remarkPlugins,
997
- inputs.rehypePlugins,
998
- inputs.remarkRehypeOptions,
999
- inputs.handlers,
1000
- inputs.preserveForBodyHarvest,
1001
- inputs.clobberPrefix,
1002
- inputs.documentId,
1003
- inputs.provenance
1004
- ];
942
+ return [
943
+ inputs.remarkPlugins,
944
+ inputs.rehypePlugins,
945
+ inputs.remarkRehypeOptions,
946
+ inputs.handlers,
947
+ inputs.preserveForBodyHarvest,
948
+ inputs.clobberPrefix,
949
+ inputs.documentId,
950
+ inputs.provenance
951
+ ];
1005
952
  }
1006
- // Annotate the CommonJS export names for ESM import in node:
1007
- 0 && (module.exports = {
1008
- buildAggregateTree,
1009
- buildBlocks,
1010
- buildContributionChain,
1011
- cloneHastForRender,
1012
- computeBlockFingerprint,
1013
- computeHtmlBlockDigest,
1014
- computeHtmlBlockDigestWithExtent,
1015
- createBlockPlanner,
1016
- createContributionSession,
1017
- createPipelineSession,
1018
- createSmoothCoordinator,
1019
- deriveCoordinationPolicy,
1020
- derivePhantomTargets,
1021
- deriveTailSignal,
1022
- evaluateGateWarn,
1023
- hasMdastSource,
1024
- isFootnoteSection
953
+ exports.buildAggregateTree = buildAggregateTree;
954
+ exports.buildBlocks = buildBlocks;
955
+ exports.buildContributionChain = buildContributionChain;
956
+ exports.cloneHastForRender = cloneHastForRender;
957
+ exports.computeBlockFingerprint = computeBlockFingerprint;
958
+ exports.computeHtmlBlockDigest = computeHtmlBlockDigest;
959
+ exports.computeHtmlBlockDigestWithExtent = computeHtmlBlockDigestWithExtent;
960
+ exports.createBlockPlanner = createBlockPlanner;
961
+ exports.createContributionSession = createContributionSession;
962
+ exports.createPipelineSession = createPipelineSession;
963
+ exports.createSmoothCoordinator = createSmoothCoordinator;
964
+ exports.deriveCoordinationPolicy = deriveCoordinationPolicy;
965
+ exports.derivePhantomTargets = derivePhantomTargets;
966
+ exports.deriveTailSignal = deriveTailSignal;
967
+ exports.evaluateGateWarn = evaluateGateWarn;
968
+ exports.hasMdastSource = hasMdastSource;
969
+ Object.defineProperty(exports, "isFootnoteSection", {
970
+ enumerable: true,
971
+ get: function() {
972
+ return _ai_markdown_engine.isFootnoteSection;
973
+ }
1025
974
  });
975
+
1026
976
  //# sourceMappingURL=index.dev.cjs.map