@ai-markdown/core 3.0.0-beta.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,942 @@
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"
52
+ ]);
53
+ var CTX_TYPES = TAINT_TYPES;
54
+ function extractRaw(node, source) {
55
+ if (!node.position) return "";
56
+ return source.slice(node.position.start.offset, node.position.end.offset);
57
+ }
58
+ function hasMdastSource(node) {
59
+ return node.position !== void 0;
60
+ }
61
+ function computeHtmlBlockDigest(el, source, ownEnd) {
62
+ return computeHtmlBlockDigestWithExtent(el, source, ownEnd).digest;
63
+ }
64
+ 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 };
87
+ }
88
+ 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);
95
+ }
96
+ var EMPTY_LABELS = /* @__PURE__ */ new Set();
97
+ var FOOTNOTE_SECTION_KEY = "__footnote_section__";
98
+ 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 (false) {
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 (false) {
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 (false) {
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 swallowedTaint = false;
270
+ if (isRawHtmlBlock) {
271
+ const d = computeHtmlBlockDigestWithExtent(el, source, mdastPos.end.offset);
272
+ hastDigest = d.digest;
273
+ const first = firstTaintAtOrAfter(mdastPos.end.offset);
274
+ swallowedTaint = first < taintOffsets.length && taintOffsets[first] < d.maxEnd;
275
+ }
276
+ if (swallowedTaint) hasReference = true;
277
+ const info = {
278
+ raw: extractRaw(mdastNode, source),
279
+ startOffset: mdastPos.start.offset,
280
+ endOffset: mdastPos.end.offset,
281
+ startLine: mdastPos.start.line,
282
+ startColumn: mdastPos.start.column,
283
+ hasReference,
284
+ ...hastDigest !== void 0 ? { hastDigest } : {},
285
+ ...swallowed?.hasFootnoteSection ? { containsFootnoteSection: true } : {},
286
+ ...hasReference ? {
287
+ taintLabels: {
288
+ footnoteRefLabels,
289
+ linkRefLabels,
290
+ imageRefLabels,
291
+ footnoteDefLabels,
292
+ ...footnoteRefLocalCtx !== void 0 ? { footnoteRefLocalCtx } : {},
293
+ ...swallowedDefCtx !== void 0 ? { swallowedDefCtx } : {}
294
+ }
295
+ } : {}
296
+ };
297
+ blocks.push(info);
298
+ blockHasts.push(el);
299
+ plan.push({ kind: "block", el, info, key: `block-${hastOffset}` });
300
+ }
301
+ return { plan, globalCtx, blocks, blockHasts, synthetic };
302
+ }
303
+ function computeBlockFingerprint(taintLabels, registry, thisChunkSym, clobberPrefix) {
304
+ const parts = [clobberPrefix];
305
+ for (const label of taintLabels.footnoteRefLabels) {
306
+ parts.push(`fn:${label}=${registry.globalNumber(label) ?? "null"}`);
307
+ }
308
+ if (taintLabels.footnoteRefLocalCtx !== void 0) parts.push(`fl:${taintLabels.footnoteRefLocalCtx}`);
309
+ if (taintLabels.swallowedDefCtx !== void 0) parts.push(`sd:${taintLabels.swallowedDefCtx}`);
310
+ for (const label of taintLabels.linkRefLabels) {
311
+ const def = registry.resolveLinkDef(label);
312
+ parts.push(`lr:${label}=${def ? JSON.stringify([def.url, def.title ?? null]) : "null"}`);
313
+ }
314
+ for (const label of taintLabels.imageRefLabels) {
315
+ const def = registry.resolveLinkDef(label);
316
+ parts.push(`ir:${label}=${def ? JSON.stringify([def.url, def.title ?? null]) : "null"}`);
317
+ }
318
+ for (const label of taintLabels.footnoteDefLabels) {
319
+ const isCanonical = registry.canonicalFootnoteFor(label) === thisChunkSym ? 1 : 0;
320
+ parts.push(`fd:${label}=${isCanonical}/${registry.getRefsForLabel(label)}`);
321
+ }
322
+ return parts.join("|");
323
+ }
324
+ var PLACEHOLDER_TAGS = /* @__PURE__ */ new Set(["footnote-sup", "cross-chunk-link", "cross-chunk-image"]);
325
+ function scanSwallowedSubtree(el) {
326
+ const refLabels = [];
327
+ const linkLabels = [];
328
+ const imageLabels = [];
329
+ const local = [];
330
+ const bakedDefs = [];
331
+ let hasReference = false;
332
+ let hasFootnoteSection = false;
333
+ (0, import_unist_util_visit.visit)(el, "element", (node) => {
334
+ if ((0, import_engine.isFootnoteSection)(node)) {
335
+ hasFootnoteSection = true;
336
+ hasReference = true;
337
+ return;
338
+ }
339
+ const props = node.properties ?? {};
340
+ if (PLACEHOLDER_TAGS.has(node.tagName)) {
341
+ hasReference = true;
342
+ const identifier = props.identifier ?? props.label;
343
+ const label = identifier === void 0 ? null : (0, import_engine.normalizeId)(String(identifier));
344
+ if (label === null) return;
345
+ if (node.tagName === "footnote-sup") {
346
+ refLabels.push(label);
347
+ const occ = Number(props.localOccurrence);
348
+ const num = Number(props.localNumber);
349
+ local.push([label, Number.isFinite(occ) ? occ : -1, Number.isFinite(num) ? num : -1]);
350
+ return;
351
+ }
352
+ if (node.tagName === "cross-chunk-link") linkLabels.push(label);
353
+ else imageLabels.push(label);
354
+ if (typeof props.localUrl === "string") {
355
+ bakedDefs.push([label, props.localUrl, typeof props.localTitle === "string" ? props.localTitle : null]);
356
+ }
357
+ return;
358
+ }
359
+ if (node.tagName === "a" && props.dataFootnoteRef !== void 0) hasReference = true;
360
+ });
361
+ return { hasReference, refLabels, linkLabels, imageLabels, local, bakedDefs, hasFootnoteSection };
362
+ }
363
+
364
+ // src/blockPlanner.ts
365
+ var import_unist_util_visit2 = require("unist-util-visit");
366
+ var UNPAIRED_TYPES = /* @__PURE__ */ new Set(["html", "definition", "footnoteDefinition"]);
367
+ function createBlockPlanner() {
368
+ let previous;
369
+ const eligible = /* @__PURE__ */ new WeakMap();
370
+ const isEligible = (node) => {
371
+ let result = eligible.get(node);
372
+ if (result === void 0) {
373
+ result = true;
374
+ (0, import_unist_util_visit2.visit)(node, (child) => {
375
+ if (UNPAIRED_TYPES.has(child.type)) result = false;
376
+ });
377
+ eligible.set(node, result);
378
+ }
379
+ return result;
380
+ };
381
+ return (mdast, hast, source, options = {}) => {
382
+ let m = 0;
383
+ let h = 0;
384
+ let reusedContext = false;
385
+ if (previous && source.startsWith(previous.source) && options.phantomFootnoteLabels === previous.phantoms) {
386
+ while (m < mdast.children.length) {
387
+ const node = mdast.children[m];
388
+ const el = hast.children[h];
389
+ const item = previous.result.plan[h];
390
+ if (node !== previous.mdast.children[m] || el !== previous.hast.children[h] || !el || el.type !== "element" || !item || item.kind !== "block" || item.info.startOffset !== node.position?.start.offset || !isEligible(node))
391
+ break;
392
+ reusedContext ||= item.info.hasReference;
393
+ m++;
394
+ h++;
395
+ while (h < hast.children.length) {
396
+ const gap = hast.children[h];
397
+ if (gap !== previous.hast.children[h] || gap.type !== "text" || /\S/.test(gap.value)) break;
398
+ h++;
399
+ }
400
+ }
401
+ }
402
+ let result;
403
+ if (m > 0 && previous) {
404
+ const tail = buildBlocks(
405
+ { ...mdast, children: mdast.children.slice(m) },
406
+ { ...hast, children: hast.children.slice(h) },
407
+ source,
408
+ reusedContext ? { ...options, contextMdast: options.contextMdast ?? mdast } : options
409
+ );
410
+ const prefix = previous.result.plan.slice(0, h);
411
+ const prefixBlocks = prefix.filter(
412
+ (item) => item.kind === "block"
413
+ );
414
+ result = {
415
+ ...tail,
416
+ plan: [
417
+ ...prefix,
418
+ ...tail.plan.map(
419
+ (item) => /^inline-i\d+$/.test(item.key) ? { ...item, key: `inline-i${Number(item.key.slice(8)) + h}` } : item
420
+ )
421
+ ],
422
+ blocks: [...prefixBlocks.map((item) => item.info), ...tail.blocks],
423
+ blockHasts: [...prefixBlocks.map((item) => item.el), ...tail.blockHasts]
424
+ };
425
+ } else result = buildBlocks(mdast, hast, source, options);
426
+ previous = { mdast, hast, source, result, phantoms: options.phantomFootnoteLabels };
427
+ return result;
428
+ };
429
+ }
430
+
431
+ // src/contribution.ts
432
+ var import_engine2 = require("@ai-markdown/engine");
433
+ function createContributionSession() {
434
+ let lastContribution = null;
435
+ return {
436
+ commit({ pipeline, ownLabels, registry, targetPhantoms, sym, clobberPrefix, chain }) {
437
+ if (!registry || !sym) return;
438
+ const refs = [];
439
+ const defMeta = /* @__PURE__ */ new Map();
440
+ const linkDefs = /* @__PURE__ */ new Map();
441
+ for (const node of (0, import_engine2.extractContributions)(pipeline.mdast, {
442
+ phantomFootnoteLabels: targetPhantoms.missingFootnotes
443
+ })) {
444
+ if (node.kind === "ref") {
445
+ refs.push({ label: node.label, kind: node.refKind, referenceType: node.referenceType });
446
+ } else if (node.kind === "fnDef") {
447
+ defMeta.set(node.label, {
448
+ identifier: node.label,
449
+ sourceIdentifier: node.sourceIdentifier,
450
+ contentSource: node.content
451
+ });
452
+ } else if (node.kind === "linkDef") {
453
+ linkDefs.set(node.label, { identifier: node.label, url: node.url, title: node.title });
454
+ }
455
+ }
456
+ const fp = JSON.stringify({
457
+ r: refs,
458
+ d: Array.from(defMeta.entries()).map(([k, v]) => [k, v.sourceIdentifier, v.contentSource]),
459
+ l: Array.from(linkDefs.entries()).map(([k, v]) => [k, v.url, v.title ?? ""]),
460
+ ofn: Array.from(ownLabels.footnoteLabels).sort(),
461
+ ol: Array.from(ownLabels.linkLabels).sort(),
462
+ // Include targetPhantoms in the fingerprint: a phantom→resolved
463
+ // transition (another chunk publishes a def for a label this chunk
464
+ // references inside one of its OWN def bodies) changes the rendered
465
+ // hast — the `<cross-chunk-link>` / `<cross-chunk-image>` placeholder
466
+ // disappears and a real `<a>` / `<img>` takes its place — without
467
+ // touching this chunk's refs / defMeta / linkDefs / ownLabels. Without
468
+ // including the phantom snapshot in the fingerprint, the fp check
469
+ // would short-circuit and the registry would keep stale bodyHast
470
+ // forever, leaving the aggregate footer rendering the placeholder
471
+ // long after the label was resolved.
472
+ tpfn: Array.from(targetPhantoms.missingFootnotes).sort(),
473
+ tpl: Array.from(targetPhantoms.missingLinks).sort()
474
+ });
475
+ const last = lastContribution;
476
+ if (last?.registry === registry && last.symbol === sym && last.fp === fp && last.chain.length === chain.length && last.chain.every((dep, i) => dep === chain[i])) {
477
+ return;
478
+ }
479
+ const bodiesByLabel = (0, import_engine2.extractDefBodiesFromHast)(pipeline.hast, clobberPrefix);
480
+ const defs = /* @__PURE__ */ new Map();
481
+ for (const [label, meta] of defMeta) {
482
+ defs.set(label, {
483
+ identifier: meta.identifier,
484
+ sourceIdentifier: meta.sourceIdentifier,
485
+ contentSource: meta.contentSource,
486
+ bodyHast: bodiesByLabel.get(label) ?? []
487
+ });
488
+ }
489
+ lastContribution = { registry, symbol: sym, fp, chain };
490
+ registry.contributeChunkData(sym, {
491
+ refs,
492
+ defs,
493
+ linkDefs,
494
+ ownFootnoteLabels: ownLabels.footnoteLabels,
495
+ ownLinkLabels: ownLabels.linkLabels
496
+ });
497
+ }
498
+ };
499
+ }
500
+
501
+ // src/smoothCoordinator.ts
502
+ function createSmoothCoordinator(onEmpty) {
503
+ const order = [];
504
+ const done = /* @__PURE__ */ new Set();
505
+ const lastProgressAt = /* @__PURE__ */ new Map();
506
+ const coord = {
507
+ order,
508
+ done,
509
+ lastProgressAt,
510
+ version: 0,
511
+ _refcounts: /* @__PURE__ */ new Map(),
512
+ _subscribers: /* @__PURE__ */ new Set(),
513
+ _notifyScheduled: false,
514
+ register(chunkId) {
515
+ const count = this._refcounts.get(chunkId) ?? 0;
516
+ this._refcounts.set(chunkId, count + 1);
517
+ if (count === 0 && !order.includes(chunkId)) {
518
+ order.push(chunkId);
519
+ this._notify();
520
+ }
521
+ },
522
+ release(chunkId) {
523
+ const count = this._refcounts.get(chunkId);
524
+ if (count === void 0) return;
525
+ if (count > 1) {
526
+ this._refcounts.set(chunkId, count - 1);
527
+ return;
528
+ }
529
+ this._refcounts.set(chunkId, 0);
530
+ queueMicrotask(() => {
531
+ if (this._refcounts.get(chunkId) !== 0) return;
532
+ this._refcounts.delete(chunkId);
533
+ const idx = order.indexOf(chunkId);
534
+ if (idx !== -1) order.splice(idx, 1);
535
+ done.delete(chunkId);
536
+ lastProgressAt.delete(chunkId);
537
+ this._notify();
538
+ if (order.length === 0 && onEmpty) onEmpty();
539
+ });
540
+ },
541
+ markDone(chunkId) {
542
+ if (done.has(chunkId)) return;
543
+ done.add(chunkId);
544
+ this._notify();
545
+ },
546
+ stampProgress(chunkId, at) {
547
+ lastProgressAt.set(chunkId, at);
548
+ },
549
+ isReleased(chunkId) {
550
+ for (const id of order) {
551
+ if (id === chunkId) return true;
552
+ if (!done.has(id)) return false;
553
+ }
554
+ return true;
555
+ },
556
+ earliestBlockerOf(chunkId) {
557
+ for (const id of order) {
558
+ if (id === chunkId) return null;
559
+ if (!done.has(id)) return id;
560
+ }
561
+ return null;
562
+ },
563
+ subscribe(cb) {
564
+ this._subscribers.add(cb);
565
+ return () => {
566
+ this._subscribers.delete(cb);
567
+ };
568
+ },
569
+ _notify() {
570
+ this.version++;
571
+ if (this._notifyScheduled) return;
572
+ this._notifyScheduled = true;
573
+ queueMicrotask(() => {
574
+ this._notifyScheduled = false;
575
+ for (const cb of [...this._subscribers]) cb();
576
+ });
577
+ }
578
+ };
579
+ return coord;
580
+ }
581
+ function evaluateGateWarn(coordinator, chunkId, nowMs, thresholdMs) {
582
+ const blocker = coordinator.earliestBlockerOf(chunkId);
583
+ if (!blocker) return "clear";
584
+ const progressedAt = coordinator.lastProgressAt.get(blocker) ?? 0;
585
+ return nowMs - progressedAt < thresholdMs ? "rearm" : "warn";
586
+ }
587
+
588
+ // src/coordinator.ts
589
+ function createSmoothCoordinator2(onEmpty) {
590
+ return createSmoothCoordinator(onEmpty);
591
+ }
592
+
593
+ // src/tailSignal.ts
594
+ var DESCEND_THROUGH = /* @__PURE__ */ new Set(["blockquote", "list", "listItem", "footnoteDefinition"]);
595
+ function deriveTailSignal(mdast, contentLength) {
596
+ const children = mdast.children;
597
+ let index = children.length - 1;
598
+ while (index >= 0) {
599
+ const offset = children[index].position?.start?.offset;
600
+ if (offset !== void 0 && offset >= contentLength) {
601
+ index--;
602
+ continue;
603
+ }
604
+ break;
605
+ }
606
+ if (index < 0) return null;
607
+ let node = children[index];
608
+ let deepestFootnoteDef = null;
609
+ for (; ; ) {
610
+ if (node.type === "footnoteDefinition") deepestFootnoteDef = node;
611
+ if (node.type === "definition") {
612
+ return { kind: "invisible-def" };
613
+ }
614
+ if (!DESCEND_THROUGH.has(node.type)) break;
615
+ const kids = node.children;
616
+ if (!kids || kids.length === 0) break;
617
+ node = kids[kids.length - 1];
618
+ }
619
+ return deepestFootnoteDef ? { kind: "footnote-def", identifier: deepestFootnoteDef.identifier } : null;
620
+ }
621
+
622
+ // src/aggregateFootnotes.ts
623
+ var import_engine3 = require("@ai-markdown/engine");
624
+
625
+ // src/cloneHastForRender.ts
626
+ function cloneHastForRender(node) {
627
+ const copy = { ...node };
628
+ const withChildren = copy;
629
+ if (Array.isArray(withChildren.children)) {
630
+ withChildren.children = withChildren.children.map((child) => cloneHastForRender(child));
631
+ }
632
+ const withProperties = copy;
633
+ if (withProperties.properties) {
634
+ withProperties.properties = { ...withProperties.properties };
635
+ }
636
+ return copy;
637
+ }
638
+
639
+ // src/aggregateFootnotes.ts
640
+ function buildBackref(href, occurrence, globalNumber) {
641
+ const children = [{ type: "text", value: "\u21A9" }];
642
+ if (occurrence > 1) {
643
+ children.push({
644
+ type: "element",
645
+ tagName: "sup",
646
+ properties: {},
647
+ children: [{ type: "text", value: String(occurrence) }]
648
+ });
649
+ }
650
+ const ariaLabel = occurrence === 1 ? `Back to reference ${globalNumber}` : `Back to reference ${globalNumber}-${occurrence}`;
651
+ return {
652
+ type: "element",
653
+ tagName: "a",
654
+ properties: {
655
+ href,
656
+ dataFootnoteBackref: "",
657
+ className: ["data-footnote-backref"],
658
+ ariaLabel
659
+ },
660
+ children
661
+ };
662
+ }
663
+ function buildAggregateTree(registry, clobberPrefix, preserveOrphanReferences = false) {
664
+ const seen = /* @__PURE__ */ new Set();
665
+ const ordered = [];
666
+ for (const sym of registry.chunkOrder) {
667
+ const data = registry.chunkData.get(sym);
668
+ if (!data) continue;
669
+ for (const ref of data.refs) {
670
+ if (ref.kind !== "footnote") continue;
671
+ if (seen.has(ref.label)) continue;
672
+ seen.add(ref.label);
673
+ const canonicalSym = registry.canonicalFootnoteFor(ref.label);
674
+ if (!canonicalSym) continue;
675
+ const def = registry.chunkData.get(canonicalSym)?.defs.get(ref.label);
676
+ if (!def) continue;
677
+ const n = registry.globalNumber(ref.label);
678
+ if (n === null) continue;
679
+ const sourceIdentifier = def.sourceIdentifier ?? ref.label;
680
+ ordered.push({
681
+ normalizedLabel: ref.label,
682
+ sourceIdentifier,
683
+ bodyHast: def.bodyHast ?? [],
684
+ n,
685
+ withBackref: true
686
+ });
687
+ }
688
+ }
689
+ if (preserveOrphanReferences) {
690
+ for (const sym of registry.chunkOrder) {
691
+ const data = registry.chunkData.get(sym);
692
+ if (!data) continue;
693
+ for (const [label, def] of data.defs) {
694
+ if (seen.has(label)) continue;
695
+ if (registry.canonicalFootnoteFor(label) !== sym) continue;
696
+ seen.add(label);
697
+ ordered.push({
698
+ normalizedLabel: label,
699
+ sourceIdentifier: def.sourceIdentifier ?? label,
700
+ bodyHast: def.bodyHast ?? [],
701
+ n: null,
702
+ withBackref: false
703
+ });
704
+ }
705
+ }
706
+ }
707
+ if (ordered.length === 0) return null;
708
+ const liElements = ordered.map(({ normalizedLabel, sourceIdentifier, bodyHast, n, withBackref }) => {
709
+ const safeId = (0, import_engine3.footnoteSafeId)(sourceIdentifier);
710
+ const liChildren = bodyHast.map((c) => cloneHastForRender(c));
711
+ if (withBackref) {
712
+ const totalRefs = registry.getRefsForLabel(normalizedLabel);
713
+ const tailIdx = (0, import_engine3.lastMeaningfulIdx)(liChildren);
714
+ const tail = tailIdx !== -1 ? liChildren[tailIdx] : null;
715
+ const dest = tail && tail.type === "element" && tail.tagName === "p" ? tail : null;
716
+ const appended = [];
717
+ for (let i = 1; i <= Math.max(totalRefs, 1); i++) {
718
+ appended.push({ type: "text", value: " " });
719
+ const href = i === 1 ? `#${clobberPrefix}fnref-${safeId}` : `#${clobberPrefix}fnref-${safeId}-${i}`;
720
+ appended.push(buildBackref(href, i, n ?? 0));
721
+ }
722
+ if (dest) {
723
+ dest.children = [...dest.children, ...appended];
724
+ } else if (tailIdx !== -1) {
725
+ liChildren.splice(tailIdx + 1, 0, ...appended);
726
+ } else {
727
+ liChildren.push(...appended);
728
+ }
729
+ }
730
+ return {
731
+ type: "element",
732
+ tagName: "li",
733
+ properties: {
734
+ id: `${clobberPrefix}fn-${safeId}`,
735
+ // Stringified: @types/hast (≥3.0.5) types li's `value` as string;
736
+ // React serializes value={3} and value="3" to identical markup.
737
+ ...n !== null ? { value: String(n) } : {}
738
+ },
739
+ children: liChildren
740
+ };
741
+ });
742
+ return {
743
+ type: "element",
744
+ tagName: "section",
745
+ properties: {
746
+ className: ["footnotes"],
747
+ dataFootnotes: true,
748
+ // a11y: name the section landmark so screen readers still announce it
749
+ // even though the visible "Footnotes" h2 is omitted in coordinated mode.
750
+ ariaLabel: "Footnotes"
751
+ },
752
+ children: [
753
+ // Conventional separator above the footnote list. The default
754
+ // mdast-util-to-hast footer doesn't emit one (GitHub renders the
755
+ // separation via CSS `border-top` on `.footnotes`); we render a literal
756
+ // `<hr>` so the visual break is preserved without sanitize-friendly CSS.
757
+ {
758
+ type: "element",
759
+ tagName: "hr",
760
+ properties: {},
761
+ children: []
762
+ },
763
+ {
764
+ type: "element",
765
+ tagName: "ol",
766
+ properties: {},
767
+ children: liElements
768
+ }
769
+ ]
770
+ };
771
+ }
772
+
773
+ // src/pipelineSession.ts
774
+ var import_engine4 = require("@ai-markdown/engine");
775
+ var unmeasured = (_stage, fn) => fn();
776
+ function createPipelineSession() {
777
+ let state = null;
778
+ return {
779
+ reset() {
780
+ state = null;
781
+ },
782
+ parse({
783
+ content,
784
+ targetPhantoms,
785
+ remarkPlugins,
786
+ rehypePlugins,
787
+ remarkRehypeOptions,
788
+ handlers,
789
+ preserveForBodyHarvest,
790
+ documentId,
791
+ provenance,
792
+ incrementalParse,
793
+ defListEnabled,
794
+ measure: measureHere = unmeasured
795
+ }) {
796
+ const phantomDefs = (0, import_engine4.buildPhantomSuffix)(targetPhantoms);
797
+ const phantomSuffix = phantomDefs === "" ? "" : (0, import_engine4.phantomSuffixCloser)(content ?? "") + phantomDefs;
798
+ const augmented = (content ?? "") + phantomSuffix;
799
+ const baseHandlers = remarkRehypeOptions?.handlers ?? {};
800
+ const mergedRemarkRehypeOptions = handlers ? {
801
+ ...remarkRehypeOptions,
802
+ handlers: { ...baseHandlers, ...handlers },
803
+ // Phantom label sets are empty in standalone mode (no PASS 0.5
804
+ // injection happened); the footnoteDefinition handler still reads
805
+ // them via `state.options.phantomFootnoteLabels.has(id)`, which
806
+ // returns false for every id → orphan-protect path proceeds.
807
+ phantomFootnoteLabels: targetPhantoms.missingFootnotes,
808
+ phantomLinkLabels: targetPhantoms.missingLinks,
809
+ preserveOrphan: preserveForBodyHarvest,
810
+ documentId,
811
+ // The SAME value `buildCoreRehypePlugins` received — the
812
+ // verifier unwraps every placeholder stamped with anything else.
813
+ provenance
814
+ } : {
815
+ ...remarkRehypeOptions
816
+ };
817
+ if (!incrementalParse) {
818
+ state = null;
819
+ const parsed = measureHere(
820
+ "parse",
821
+ () => (0, import_engine4.parseStage)({
822
+ children: augmented,
823
+ remarkPlugins,
824
+ rehypePlugins,
825
+ remarkRehypeOptions: mergedRemarkRehypeOptions
826
+ })
827
+ );
828
+ const hastRoot = measureHere("transform", () => (0, import_engine4.transformStage)(parsed));
829
+ return { mdast: parsed.mdast, hast: hastRoot };
830
+ }
831
+ try {
832
+ const result = (0, import_engine4.advanceIncrementalParse)(state, content ?? "", {
833
+ remarkPlugins,
834
+ rehypePlugins,
835
+ remarkRehypeOptions: mergedRemarkRehypeOptions,
836
+ // Identity tuple over every parse input beyond the content itself.
837
+ // Deliberately covers MORE than the G3 flush's 12 fields (handlers /
838
+ // preserveForBodyHarvest / documentId can change without touching
839
+ // any G3 field — e.g. a `preserveOrphanReferences` flip). The
840
+ // phantom label sets are deliberately NOT here: their churn tracks
841
+ // the suffix (always re-parsed with the tail), never the prefix.
842
+ depsKey: [
843
+ remarkPlugins,
844
+ rehypePlugins,
845
+ remarkRehypeOptions,
846
+ handlers,
847
+ preserveForBodyHarvest,
848
+ documentId,
849
+ // Explicit even though `rehypePlugins` already carries it: a
850
+ // credential change must never reuse trees stamped under the
851
+ // old one.
852
+ provenance
853
+ ],
854
+ defListEnabled,
855
+ phantomSuffix,
856
+ measure: measureHere
857
+ });
858
+ state = result.nextState;
859
+ return { mdast: result.mdast, hast: result.hast };
860
+ } catch (error) {
861
+ state = null;
862
+ if (false) {
863
+ console.error("[ai-react-markdown] incremental parse failed \u2014 full parse fallback for this frame:", error);
864
+ }
865
+ const parsed = measureHere(
866
+ "parse",
867
+ () => (0, import_engine4.parseStage)({
868
+ children: augmented,
869
+ remarkPlugins,
870
+ rehypePlugins,
871
+ remarkRehypeOptions: mergedRemarkRehypeOptions
872
+ })
873
+ );
874
+ const hastRoot = measureHere("transform", () => (0, import_engine4.transformStage)(parsed));
875
+ return { mdast: parsed.mdast, hast: hastRoot };
876
+ }
877
+ }
878
+ };
879
+ }
880
+
881
+ // src/coordinationPreparation.ts
882
+ var import_engine5 = require("@ai-markdown/engine");
883
+ function derivePhantomTargets({ content, ownLabels, labels }, previous) {
884
+ const missingFootnotes = /* @__PURE__ */ new Set();
885
+ const missingLinks = /* @__PURE__ */ new Set();
886
+ if (labels) {
887
+ const footnotes = [...labels.footnoteLabels].filter((label) => !ownLabels.footnoteLabels.has(label));
888
+ const links = [...labels.linkLabels].filter((label) => !ownLabels.linkLabels.has(label));
889
+ if (footnotes.length || links.length) {
890
+ const normalized = (0, import_engine5.normalizeForMatch)(content);
891
+ for (const label of footnotes) if (normalized.includes(label)) missingFootnotes.add(label);
892
+ for (const label of links) if (normalized.includes(label)) missingLinks.add(label);
893
+ }
894
+ }
895
+ 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)))
896
+ return previous;
897
+ return { missingFootnotes, missingLinks };
898
+ }
899
+ function deriveCoordinationPolicy({
900
+ coordinated,
901
+ registered,
902
+ preserveOrphanReferences
903
+ }, previous) {
904
+ const mode = coordinated ? "coordinated" : preserveOrphanReferences ? "orphan" : "standalone";
905
+ const preserveForBodyHarvest = preserveOrphanReferences || coordinated && registered;
906
+ if (previous?.mode === mode && previous.preserveForBodyHarvest === preserveForBodyHarvest) return previous;
907
+ const handlers = previous?.mode === mode ? previous.handlers : mode === "coordinated" ? (0, import_engine5.buildCrossChunkHandlers)() : mode === "orphan" ? { footnoteDefinition: (0, import_engine5.buildCrossChunkHandlers)().footnoteDefinition } : void 0;
908
+ return { mode, handlers, preserveForBodyHarvest };
909
+ }
910
+ function buildContributionChain(inputs) {
911
+ return [
912
+ inputs.remarkPlugins,
913
+ inputs.rehypePlugins,
914
+ inputs.remarkRehypeOptions,
915
+ inputs.handlers,
916
+ inputs.preserveForBodyHarvest,
917
+ inputs.clobberPrefix,
918
+ inputs.documentId,
919
+ inputs.provenance
920
+ ];
921
+ }
922
+ // Annotate the CommonJS export names for ESM import in node:
923
+ 0 && (module.exports = {
924
+ buildAggregateTree,
925
+ buildBlocks,
926
+ buildContributionChain,
927
+ cloneHastForRender,
928
+ computeBlockFingerprint,
929
+ computeHtmlBlockDigest,
930
+ computeHtmlBlockDigestWithExtent,
931
+ createBlockPlanner,
932
+ createContributionSession,
933
+ createPipelineSession,
934
+ createSmoothCoordinator,
935
+ deriveCoordinationPolicy,
936
+ derivePhantomTargets,
937
+ deriveTailSignal,
938
+ evaluateGateWarn,
939
+ hasMdastSource,
940
+ isFootnoteSection
941
+ });
942
+ //# sourceMappingURL=index.cjs.map