@equationalapplications/core-okf 9.20.2 → 9.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // src/frontmatter.ts
2
2
  var RESERVED_LITERALS = /* @__PURE__ */ new Set(["true", "false", "yes", "no", "on", "off", "null", "~", ""]);
3
3
  function looksLikeNumber(value) {
4
- return /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(value);
4
+ return /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(value);
5
5
  }
6
6
  function isIso8601Timestamp(value) {
7
7
  return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2}|[+-]\d{4}|[+-]\d{2})$/.test(value);
@@ -85,7 +85,7 @@ function serializeFlowSequenceValue(arr, depth = 0) {
85
85
  });
86
86
  return `[ ${parts.join(", ")} ]`;
87
87
  }
88
- function serializeFrontmatter(fm) {
88
+ function serializeFrontmatter(fm, options) {
89
89
  const lines = ["---"];
90
90
  for (const [key, value] of Object.entries(fm)) {
91
91
  if (value === void 0) continue;
@@ -106,6 +106,9 @@ function serializeFrontmatter(fm) {
106
106
  lines.push(`${serializeKey(key)}: ${serializeValue(value)}`);
107
107
  }
108
108
  }
109
+ for (const block of options?.rawBlocks ?? []) {
110
+ lines.push(block);
111
+ }
109
112
  lines.push("---");
110
113
  return lines.join("\n") + "\n";
111
114
  }
@@ -211,12 +214,38 @@ function matchFrontmatterKeyValue(line) {
211
214
  const tail = line.slice(key.length + 1);
212
215
  return { key, value: tail.trimStart(), hasValue: tail.trim().length > 0 };
213
216
  }
214
- function hasUnquotedAnchorOrAlias(text) {
217
+ function matchBlockKeyValue(line) {
218
+ const kv = matchFrontmatterKeyValue(line);
219
+ if (!kv) return null;
220
+ const tail = line.slice(kv.key.length + 1);
221
+ if (tail.length > 0 && tail[0] !== " " && tail[0] !== " ") return null;
222
+ return kv;
223
+ }
224
+ function indentWidth(line) {
225
+ let n = 0;
226
+ while (n < line.length && (line[n] === " " || line[n] === " ")) n++;
227
+ return n;
228
+ }
229
+ function quoteOpensAtNodeStart(text, i) {
230
+ if (i === 0) return true;
231
+ let j = i - 1;
232
+ while (j >= 0 && (text[j] === " " || text[j] === " ")) j--;
233
+ if (j < 0) return true;
234
+ const c = text[j];
235
+ if (c === "{" || c === "[" || c === "," || c === ":") return true;
236
+ if (c === "-") {
237
+ if (j === 0) return true;
238
+ const d = text[j - 1];
239
+ return d === " " || d === " " || d === "{" || d === "[" || d === "," || d === ":";
240
+ }
241
+ return false;
242
+ }
243
+ function hasNodeStartAnchorOrAlias(text) {
215
244
  let quote = null;
216
245
  for (let i = 0; i < text.length; i++) {
217
246
  const ch = text[i];
218
247
  if (quote) {
219
- if (ch === "\\" && i + 1 < text.length) {
248
+ if (quote === '"' && ch === "\\" && i + 1 < text.length) {
220
249
  i++;
221
250
  continue;
222
251
  }
@@ -224,13 +253,116 @@ function hasUnquotedAnchorOrAlias(text) {
224
253
  continue;
225
254
  }
226
255
  if (ch === '"' || ch === "'") {
227
- quote = ch;
256
+ if (quoteOpensAtNodeStart(text, i)) quote = ch;
257
+ continue;
258
+ }
259
+ if (ch !== "&" && ch !== "*") continue;
260
+ let j = i - 1;
261
+ while (j >= 0 && (text[j] === " " || text[j] === " ")) j--;
262
+ if (j < 0) return true;
263
+ const c = text[j];
264
+ if (c === "{" || c === "[" || c === "," || c === ":") return true;
265
+ if (c === "-") {
266
+ if (j === 0) return true;
267
+ const d = text[j - 1];
268
+ if (d === " " || d === " " || d === "{" || d === "[" || d === "," || d === ":") return true;
269
+ }
270
+ }
271
+ return false;
272
+ }
273
+ function isFullLineComment(line) {
274
+ return /^[ \t]*#/.test(line);
275
+ }
276
+ function stripInlineComment(tail) {
277
+ let start = 0;
278
+ while (start < tail.length && (tail[start] === " " || tail[start] === " ")) start++;
279
+ if (start >= tail.length) return "";
280
+ let quote = null;
281
+ for (let i = start; i < tail.length; i++) {
282
+ const ch = tail[i];
283
+ if (quote) {
284
+ if (ch === "\\" && quote === '"' && i + 1 < tail.length) {
285
+ i++;
286
+ continue;
287
+ }
288
+ if (ch === quote) {
289
+ if (quote === "'" && tail[i + 1] === "'") {
290
+ i++;
291
+ continue;
292
+ }
293
+ quote = null;
294
+ }
228
295
  continue;
229
296
  }
230
- if (ch === "&" || ch === "*") return true;
297
+ if (ch === "#" && i > 0 && (tail[i - 1] === " " || tail[i - 1] === " ")) {
298
+ return tail.slice(0, i).trim();
299
+ }
300
+ if (ch === '"' || ch === "'") {
301
+ let k = i - 1;
302
+ while (k >= start && (tail[k] === " " || tail[k] === " ")) k--;
303
+ const nodeStart = i === start || k < start || (tail[k] === "{" || tail[k] === "[" || tail[k] === "," || tail[k] === ":" || tail[k] === "-");
304
+ if (nodeStart) quote = ch;
305
+ }
306
+ }
307
+ return tail.trim();
308
+ }
309
+ function quoteCloses(text) {
310
+ const q = text[0];
311
+ for (let i = 1; i < text.length; i++) {
312
+ if (q === '"' && text[i] === "\\") {
313
+ i++;
314
+ continue;
315
+ }
316
+ if (text[i] === q) {
317
+ if (q === "'" && text[i + 1] === "'") {
318
+ i++;
319
+ continue;
320
+ }
321
+ return true;
322
+ }
231
323
  }
232
324
  return false;
233
325
  }
326
+ function flowIsOpen(text) {
327
+ let quote = null;
328
+ let brace = 0;
329
+ let bracket = 0;
330
+ for (let i = 0; i < text.length; i++) {
331
+ const ch = text[i];
332
+ if (quote) {
333
+ if (quote === '"' && ch === "\\" && i + 1 < text.length) {
334
+ i++;
335
+ continue;
336
+ }
337
+ if (ch === quote) quote = null;
338
+ continue;
339
+ }
340
+ if ((ch === '"' || ch === "'") && quoteOpensAtNodeStart(text, i)) {
341
+ quote = ch;
342
+ continue;
343
+ }
344
+ if (ch === "{") brace++;
345
+ else if (ch === "}") brace--;
346
+ else if (ch === "[") bracket++;
347
+ else if (ch === "]") bracket--;
348
+ }
349
+ return brace !== 0 || bracket !== 0 || quote !== null;
350
+ }
351
+ function captureRawLines(lines, start, closingIndex, includeColumn0Items) {
352
+ const captured = [];
353
+ let j = start;
354
+ while (j < closingIndex) {
355
+ const l = lines[j];
356
+ if (l.trim() === "" || /^[ \t]/.test(l) || includeColumn0Items && (/^-\s/.test(l) || isFullLineComment(l))) {
357
+ captured.push(l);
358
+ j++;
359
+ continue;
360
+ }
361
+ break;
362
+ }
363
+ while (captured.length > 0 && captured[captured.length - 1].trim() === "") captured.pop();
364
+ return { captured, next: j };
365
+ }
234
366
  function splitFlowEntries(inner) {
235
367
  const entries = [];
236
368
  let buf = "";
@@ -242,7 +374,7 @@ function splitFlowEntries(inner) {
242
374
  const ch = inner[i];
243
375
  if (quote) {
244
376
  buf += ch;
245
- if (ch === "\\" && i + 1 < inner.length) {
377
+ if (quote === '"' && ch === "\\" && i + 1 < inner.length) {
246
378
  buf += inner[i + 1];
247
379
  i += 2;
248
380
  continue;
@@ -274,61 +406,176 @@ function splitFlowEntries(inner) {
274
406
  if (depthBrace !== 0 || depthBracket !== 0 || quote !== null) return null;
275
407
  return entries;
276
408
  }
277
- function parseFlowMapping(text, depth = 0) {
409
+ function blockIssueReason(reason) {
410
+ return reason === "too_deep" ? "nested_too_deep" : reason;
411
+ }
412
+ function parseFlowMappingE(text, depth = 0) {
278
413
  const trimmed = text.trim();
279
- if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) return null;
280
- if (hasUnquotedAnchorOrAlias(trimmed)) return null;
414
+ if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) return { ok: false, reason: "malformed" };
415
+ if (hasNodeStartAnchorOrAlias(trimmed)) return { ok: false, reason: "anchor_or_alias" };
281
416
  const inner = trimmed.slice(1, -1).trim();
282
- if (inner.length === 0) return {};
417
+ if (inner.length === 0) return { ok: true, value: {} };
283
418
  const entries = splitFlowEntries(inner);
284
- if (!entries) return null;
419
+ if (!entries) return { ok: false, reason: "malformed" };
285
420
  const out = {};
286
421
  for (const entry of entries) {
287
422
  const kv = matchFrontmatterKeyValue(entry);
288
- if (!kv || !kv.hasValue) return null;
423
+ if (!kv || !kv.hasValue) return { ok: false, reason: "malformed" };
289
424
  const v = kv.value.trim();
290
425
  if (v.startsWith("{") || v.startsWith("[")) {
291
- if (depth >= 1) return null;
292
- const nested = v.startsWith("{") ? parseFlowMapping(v, depth + 1) : parseFlowSequence(v, depth + 1);
293
- if (nested === null) return null;
294
- out[parseKey(kv.key)] = nested;
426
+ if (depth >= 1) return { ok: false, reason: "too_deep" };
427
+ const nested = v.startsWith("{") ? parseFlowMappingE(v, depth + 1) : parseFlowSequenceE(v, depth + 1);
428
+ if (!nested.ok) return nested;
429
+ const fk = parseKey(kv.key);
430
+ if (fk !== "__proto__") out[fk] = nested.value;
295
431
  continue;
296
432
  }
297
433
  out[parseKey(kv.key)] = parseScalarValue(v);
298
434
  }
299
- return out;
435
+ return { ok: true, value: out };
300
436
  }
301
- function parseFlowSequence(text, depth = 0) {
437
+ function parseFlowSequenceE(text, depth = 0) {
302
438
  const trimmed = text.trim();
303
- if (!trimmed.startsWith("[") || !trimmed.endsWith("]")) return null;
304
- if (hasUnquotedAnchorOrAlias(trimmed)) return null;
439
+ if (!trimmed.startsWith("[") || !trimmed.endsWith("]")) return { ok: false, reason: "malformed" };
440
+ if (hasNodeStartAnchorOrAlias(trimmed)) return { ok: false, reason: "anchor_or_alias" };
305
441
  const inner = trimmed.slice(1, -1).trim();
306
- if (inner.length === 0) return [];
442
+ if (inner.length === 0) return { ok: true, value: [] };
307
443
  const entries = splitFlowEntries(inner);
308
- if (!entries) return null;
444
+ if (!entries) return { ok: false, reason: "malformed" };
309
445
  const out = [];
310
446
  for (const entry of entries) {
311
447
  const v = entry.trim();
312
448
  if (v.startsWith("{")) {
313
- const nested = parseFlowMapping(v, depth);
314
- if (nested === null) return null;
315
- out.push(nested);
449
+ const nested = parseFlowMappingE(v, depth);
450
+ if (!nested.ok) return nested;
451
+ out.push(nested.value);
316
452
  continue;
317
453
  }
318
454
  if (v.startsWith("[")) {
319
- if (depth >= 1) return null;
320
- const nested = parseFlowSequence(v, depth + 1);
321
- if (nested === null) return null;
322
- out.push(nested);
455
+ if (depth >= 1) return { ok: false, reason: "too_deep" };
456
+ const nested = parseFlowSequenceE(v, depth + 1);
457
+ if (!nested.ok) return nested;
458
+ out.push(nested.value);
323
459
  continue;
324
460
  }
325
461
  out.push(parseScalarValue(v));
326
462
  }
327
- return out;
463
+ return { ok: true, value: out };
464
+ }
465
+ function parseFlowMapping(text, depth = 0) {
466
+ const res = parseFlowMappingE(text, depth);
467
+ return res.ok ? res.value : null;
468
+ }
469
+ function parseFlowSequence(text, depth = 0) {
470
+ const res = parseFlowSequenceE(text, depth);
471
+ return res.ok ? res.value : null;
472
+ }
473
+ function parseBlockLines(blockLines) {
474
+ if (/^[|>][-+0-9]*$/.test(blockLines[0].trim())) {
475
+ return { ok: false, reason: "block_scalar" };
476
+ }
477
+ return /^-\s/.test(blockLines[0].trimStart()) ? parseBlockList(blockLines) : parseBlockMapping(blockLines);
478
+ }
479
+ function setBlockMappingEntry(out, kv, content) {
480
+ const key = parseKey(kv.key);
481
+ const valueText = stripInlineComment(content.slice(kv.key.length + 1));
482
+ if (valueText.length === 0) {
483
+ out[key] = [];
484
+ return { ok: true };
485
+ }
486
+ if (/^[|>][-+0-9]*$/.test(valueText)) return { ok: false, reason: "block_scalar" };
487
+ if ((valueText[0] === '"' || valueText[0] === "'") && !quoteCloses(valueText)) {
488
+ return { ok: false, reason: "multiline_scalar" };
489
+ }
490
+ if (hasNodeStartAnchorOrAlias(valueText)) return { ok: false, reason: "anchor_or_alias" };
491
+ if (valueText.startsWith("{") || valueText.startsWith("[")) {
492
+ const flow = valueText.startsWith("{") ? parseFlowMappingE(valueText, 1) : parseFlowSequenceE(valueText, 1);
493
+ if (!flow.ok) return { ok: false, reason: blockIssueReason(flow.reason) };
494
+ if (key !== "__proto__") out[key] = flow.value;
495
+ return { ok: true };
496
+ }
497
+ out[key] = parseScalarValue(valueText);
498
+ return { ok: true };
499
+ }
500
+ function parseBlockMapping(blockLines) {
501
+ const indent = indentWidth(blockLines[0]);
502
+ const out = {};
503
+ for (const line of blockLines) {
504
+ const content = line.trimStart();
505
+ if (indentWidth(line) !== indent || /^-\s/.test(content)) {
506
+ return { ok: false, reason: "nested_too_deep" };
507
+ }
508
+ if (content[0] === "{" || content[0] === "[") return { ok: false, reason: "nested_too_deep" };
509
+ if (hasNodeStartAnchorOrAlias(content)) return { ok: false, reason: "anchor_or_alias" };
510
+ const kv = matchBlockKeyValue(content);
511
+ if (!kv) return { ok: false, reason: "nested_too_deep" };
512
+ const stored = setBlockMappingEntry(out, kv, content);
513
+ if (!stored.ok) return stored;
514
+ }
515
+ return { ok: true, value: out };
516
+ }
517
+ function parseBlockList(blockLines) {
518
+ const dashIndent = indentWidth(blockLines[0]);
519
+ const out = [];
520
+ let idx = 0;
521
+ while (idx < blockLines.length) {
522
+ const line = blockLines[idx];
523
+ const content = line.trimStart();
524
+ if (indentWidth(line) !== dashIndent || !/^-\s/.test(content)) {
525
+ return { ok: false, reason: "nested_too_deep" };
526
+ }
527
+ const afterDash = line.slice(dashIndent + 1);
528
+ const itemWs = afterDash.length - afterDash.trimStart().length;
529
+ const itemText = stripInlineComment(` ${afterDash.trimStart()}`).trim();
530
+ if (hasNodeStartAnchorOrAlias(itemText)) return { ok: false, reason: "anchor_or_alias" };
531
+ if ((itemText[0] === '"' || itemText[0] === "'") && !quoteCloses(itemText)) {
532
+ return { ok: false, reason: "multiline_scalar" };
533
+ }
534
+ if (itemText.startsWith("{") || itemText.startsWith("[")) {
535
+ const flow = itemText.startsWith("{") ? parseFlowMappingE(itemText, 0) : parseFlowSequenceE(itemText, 1);
536
+ if (!flow.ok) return { ok: false, reason: blockIssueReason(flow.reason) };
537
+ out.push(flow.value);
538
+ idx++;
539
+ continue;
540
+ }
541
+ const kv = matchBlockKeyValue(itemText);
542
+ if (!kv) {
543
+ out.push(parseScalarValue(itemText));
544
+ idx++;
545
+ continue;
546
+ }
547
+ const item = {};
548
+ const contIndent = dashIndent + 1 + itemWs;
549
+ const started = setBlockMappingEntry(item, kv, itemText);
550
+ if (!started.ok) return started;
551
+ idx++;
552
+ while (idx < blockLines.length) {
553
+ const cont = blockLines[idx];
554
+ const ci = indentWidth(cont);
555
+ if (ci === dashIndent && /^-\s/.test(cont.trimStart())) break;
556
+ if (ci !== contIndent) return { ok: false, reason: "nested_too_deep" };
557
+ const cc = cont.trimStart();
558
+ if (/^-\s/.test(cc)) return { ok: false, reason: "nested_too_deep" };
559
+ if (cc[0] === "{" || cc[0] === "[") return { ok: false, reason: "nested_too_deep" };
560
+ if (hasNodeStartAnchorOrAlias(cc)) return { ok: false, reason: "anchor_or_alias" };
561
+ const ckv = matchBlockKeyValue(cc);
562
+ if (!ckv) return { ok: false, reason: "nested_too_deep" };
563
+ const stored = setBlockMappingEntry(item, ckv, cc);
564
+ if (!stored.ok) return stored;
565
+ idx++;
566
+ }
567
+ out.push(item);
568
+ }
569
+ return { ok: true, value: out };
328
570
  }
329
571
  function parseFrontmatter(content) {
330
572
  const lines = content.split(/\r?\n/);
331
- const fallback = { frontmatter: { type: "" }, rest: content };
573
+ const fallback = {
574
+ frontmatter: { type: "" },
575
+ rest: content,
576
+ raw: {},
577
+ issues: []
578
+ };
332
579
  if (lines[0]?.trim() !== "---") return fallback;
333
580
  let closingIndex = -1;
334
581
  for (let i2 = 1; i2 < lines.length; i2++) {
@@ -339,78 +586,158 @@ function parseFrontmatter(content) {
339
586
  }
340
587
  if (closingIndex === -1) return fallback;
341
588
  const frontmatter = {};
589
+ const raw = {};
590
+ const issues = [];
591
+ const capturedLinesHaveAnchorOrAlias = (allLines) => {
592
+ for (const l of allLines) {
593
+ if (l.trim() === "" || isFullLineComment(l)) continue;
594
+ let i2 = 0;
595
+ while (i2 < l.length && (l[i2] === " " || l[i2] === " ")) i2++;
596
+ let colon = -1;
597
+ if (l[i2] === '"' || l[i2] === "'") {
598
+ let close = -1;
599
+ for (let s = i2 + 1; s < l.length; s++) {
600
+ if (l[i2] === '"' && l[s] === "\\") {
601
+ s++;
602
+ continue;
603
+ }
604
+ if (l[s] === l[i2]) {
605
+ close = s;
606
+ break;
607
+ }
608
+ }
609
+ if (close !== -1 && l[close + 1] === ":") {
610
+ colon = close + 1;
611
+ if (hasNodeStartAnchorOrAlias(l.slice(i2, close))) return true;
612
+ }
613
+ } else {
614
+ let j = i2;
615
+ while (j < l.length && l[j] !== ":" && l[j] !== "#") j++;
616
+ if (j < l.length && l[j] === ":" && j > i2) {
617
+ colon = j;
618
+ if (hasNodeStartAnchorOrAlias(l.slice(i2, j))) return true;
619
+ }
620
+ }
621
+ const tail = colon !== -1 ? l.slice(colon + 1) : l.trimStart();
622
+ if (hasNodeStartAnchorOrAlias(tail)) return true;
623
+ }
624
+ return false;
625
+ };
626
+ const handBack = (key, line, captured, opts) => {
627
+ if (!opts?.allowAnchors && capturedLinesHaveAnchorOrAlias([line, ...captured])) {
628
+ issues.push({ key, reason: "anchor_or_alias" });
629
+ return false;
630
+ }
631
+ raw[key] = [line, ...captured].join("\n");
632
+ return true;
633
+ };
342
634
  let i = 1;
343
635
  while (i < closingIndex) {
344
636
  const line = lines[i];
345
- const kv = matchFrontmatterKeyValue(line);
346
- if (!kv) {
637
+ if (line.trim() === "" || isFullLineComment(line) || /^[ \t]/.test(line)) {
347
638
  i++;
348
639
  continue;
349
640
  }
350
- if (kv.value.trim() === "[]") {
351
- frontmatter[parseKey(kv.key)] = [];
641
+ if (line[0] === "&" || line[0] === "*") {
642
+ const guess = matchFrontmatterKeyValue(line);
643
+ issues.push({ key: guess ? parseKey(guess.key) : line.trim(), reason: "anchor_or_alias" });
352
644
  i++;
353
645
  continue;
354
646
  }
355
- if (!kv.hasValue) {
356
- const key = parseKey(kv.key);
357
- const items = [];
647
+ const kv = matchFrontmatterKeyValue(line);
648
+ if (!kv) {
358
649
  i++;
359
- while (i < closingIndex && /^\s*-\s/.test(lines[i])) {
360
- items.push(parseScalarValue(lines[i].replace(/^\s*-\s/, "")));
361
- i++;
362
- }
363
- frontmatter[key] = items;
364
650
  continue;
365
651
  }
366
- const valueRaw = kv.value.trim();
367
- if (valueRaw.startsWith("{")) {
368
- const flowObj = parseFlowMapping(valueRaw);
369
- if (flowObj !== null) {
370
- frontmatter[parseKey(kv.key)] = flowObj;
371
- i++;
372
- continue;
652
+ const key = parseKey(kv.key);
653
+ const valueText = stripInlineComment(line.slice(kv.key.length + 1));
654
+ if (valueText.length === 0) {
655
+ const region2 = captureRawLines(lines, i + 1, closingIndex, true);
656
+ const blockLines = region2.captured.filter((l) => l.trim() !== "" && !isFullLineComment(l));
657
+ if (blockLines.length === 0) {
658
+ frontmatter[key] = [];
659
+ } else {
660
+ const block = parseBlockLines(blockLines);
661
+ if (block.ok) {
662
+ if (key !== "__proto__") frontmatter[key] = block.value;
663
+ } else if (block.reason === "anchor_or_alias") {
664
+ issues.push({ key, reason: "anchor_or_alias" });
665
+ } else {
666
+ if (handBack(key, line, region2.captured)) issues.push({ key, reason: block.reason });
667
+ }
373
668
  }
374
- frontmatter[parseKey(kv.key)] = null;
669
+ i = region2.next;
670
+ continue;
671
+ }
672
+ if (hasNodeStartAnchorOrAlias(valueText)) {
673
+ issues.push({ key, reason: "anchor_or_alias" });
375
674
  i++;
376
675
  continue;
377
676
  }
378
- if (valueRaw.startsWith("[")) {
379
- if (valueRaw === "[]") {
380
- frontmatter[parseKey(kv.key)] = [];
677
+ if (/^[|>][-+0-9]*$/.test(valueText)) {
678
+ const region2 = captureRawLines(lines, i + 1, closingIndex, false);
679
+ handBack(key, line, region2.captured, { allowAnchors: true });
680
+ issues.push({ key, reason: "block_scalar" });
681
+ i = region2.next;
682
+ continue;
683
+ }
684
+ const region = captureRawLines(lines, i + 1, closingIndex, false);
685
+ const hasContinuation = region.captured.some((l) => l.trim() !== "" && !isFullLineComment(l));
686
+ if (valueText.startsWith("{") || valueText.startsWith("[")) {
687
+ const flow = valueText.startsWith("{") ? parseFlowMappingE(valueText) : parseFlowSequenceE(valueText);
688
+ if (flow.ok) {
689
+ if (hasContinuation) {
690
+ if (handBack(key, line, region.captured)) issues.push({ key, reason: "multiline_scalar" });
691
+ } else {
692
+ if (key !== "__proto__") frontmatter[key] = flow.value;
693
+ }
694
+ i = region.next;
695
+ continue;
696
+ }
697
+ if (flow.reason === "anchor_or_alias") {
698
+ issues.push({ key, reason: "anchor_or_alias" });
381
699
  i++;
382
700
  continue;
383
701
  }
384
- const flowSeq = parseFlowSequence(valueRaw);
385
- if (flowSeq !== null) {
386
- frontmatter[parseKey(kv.key)] = flowSeq;
702
+ if (flowIsOpen(valueText) && region.captured.length === 0) {
703
+ issues.push({ key, reason: "malformed" });
387
704
  i++;
388
705
  continue;
389
706
  }
390
- frontmatter[parseKey(kv.key)] = null;
391
- i++;
707
+ if (handBack(key, line, region.captured)) issues.push({ key, reason: "malformed" });
708
+ i = region.next;
392
709
  continue;
393
710
  }
394
- frontmatter[parseKey(kv.key)] = parseScalarValue(kv.value);
395
- i++;
711
+ const quoteOpen = (valueText[0] === '"' || valueText[0] === "'") && !quoteCloses(valueText);
712
+ const value = parseScalarValue(valueText);
713
+ if (quoteOpen || hasContinuation) {
714
+ if (handBack(key, line, region.captured)) issues.push({ key, reason: "multiline_scalar" });
715
+ i = region.next;
716
+ continue;
717
+ }
718
+ frontmatter[key] = value;
719
+ if (valueText[0] !== '"' && valueText[0] !== "'" && serializeValue(value) !== valueText) {
720
+ raw[key] = line;
721
+ }
722
+ i = region.next;
396
723
  }
397
724
  if (typeof frontmatter["type"] !== "string") {
398
725
  frontmatter["type"] = "";
399
726
  }
400
727
  const restLines = lines.slice(closingIndex + 1);
401
728
  const rest = restLines.length > 0 ? restLines.join("\n") : "";
402
- return { frontmatter, rest };
729
+ return { frontmatter, rest, raw, issues };
403
730
  }
404
731
 
405
732
  // src/concept.ts
406
- function buildConceptDocument(fm, body) {
407
- return `${serializeFrontmatter(fm)}
733
+ function buildConceptDocument(fm, body, options) {
734
+ return `${serializeFrontmatter(fm, options)}
408
735
  ${body}`;
409
736
  }
410
737
  function parseConcept(content) {
411
- const { frontmatter, rest } = parseFrontmatter(content);
738
+ const { frontmatter, rest, raw, issues } = parseFrontmatter(content);
412
739
  const body = rest.startsWith("\n") ? rest.slice(1) : rest;
413
- return { frontmatter, body };
740
+ return { frontmatter, body, raw, issues };
414
741
  }
415
742
 
416
743
  // src/index-md.ts
@@ -436,21 +763,97 @@ function renderSections(sections) {
436
763
  function buildIndexMd(sections) {
437
764
  return renderSections(sections);
438
765
  }
766
+ var RAW_SLOT_KEY = "x-llm-wiki-raw";
439
767
  function buildRootIndexMd(okfVersion, sections, options) {
440
- const lines = ["---", `okf_version: ${serializeScalarString(okfVersion)}`];
441
- if (options?.profile) {
442
- lines.push(`profile: ${serializeScalarString(options.profile)}`);
768
+ const metadata = {};
769
+ const OWNED_RAW_KEYS = /* @__PURE__ */ new Set(["okf_version", "profile", RAW_SLOT_KEY]);
770
+ const rawBlockKeyOf = (lines) => {
771
+ const first = lines.slice(0, lines.indexOf("\n") === -1 ? lines.length : lines.indexOf("\n"));
772
+ const m = first.match(/^[ \t]*(?:"([^"]*)"|'([^']*)'|([^:#\s][^:]*)):/);
773
+ if (!m) return void 0;
774
+ return parseKey(m[1] ?? m[2] ?? m[3] ?? "");
775
+ };
776
+ const isOwnedRawBlock = (lines) => {
777
+ const key = rawBlockKeyOf(lines);
778
+ return key !== void 0 && OWNED_RAW_KEYS.has(key);
779
+ };
780
+ const rawBlocks = (options?.rawBlocks ?? []).filter((b) => !isOwnedRawBlock(b));
781
+ for (const [key, value] of Object.entries(options?.bundleMetadata ?? {})) {
782
+ if (key === "okf_version" || key === "profile") continue;
783
+ if (key === RAW_SLOT_KEY) {
784
+ if (options?.profile === "llm-wiki/3" && value !== null && typeof value === "object" && !Array.isArray(value)) {
785
+ for (const lines of Object.values(value)) {
786
+ if (typeof lines === "string" && lines.length > 0 && !isOwnedRawBlock(lines)) rawBlocks.push(lines);
787
+ }
788
+ }
789
+ continue;
790
+ }
791
+ metadata[key] = value;
443
792
  }
444
- lines.push("---", "");
445
- return `${lines.join("\n")}
793
+ const claimedByRaw = /* @__PURE__ */ new Set();
794
+ for (const b of rawBlocks) {
795
+ const k = rawBlockKeyOf(b);
796
+ if (k !== void 0) claimedByRaw.add(k);
797
+ }
798
+ for (const k of claimedByRaw) delete metadata[k];
799
+ const fm = {
800
+ okf_version: okfVersion,
801
+ ...options?.profile ? { profile: options.profile } : {},
802
+ ...metadata
803
+ };
804
+ const seenRawKeys = /* @__PURE__ */ new Set();
805
+ const uniqueRawBlocks = [];
806
+ for (const b of rawBlocks) {
807
+ const k = rawBlockKeyOf(b);
808
+ if (k !== void 0 && seenRawKeys.has(k)) continue;
809
+ if (k !== void 0) seenRawKeys.add(k);
810
+ uniqueRawBlocks.push(b);
811
+ }
812
+ return `${serializeFrontmatter(fm, { rawBlocks: uniqueRawBlocks })}
446
813
  ${renderSections(sections)}`;
447
814
  }
448
815
  function parseRootIndexMd(content) {
449
- const { frontmatter } = parseFrontmatter(content);
816
+ const { frontmatter, raw, issues } = parseFrontmatter(content);
817
+ const metadata = {};
818
+ let literalReservedRaw = false;
819
+ for (const [key, value] of Object.entries(frontmatter)) {
820
+ if (value === void 0) continue;
821
+ if (key === "okf_version" || key === "profile") continue;
822
+ if (key === RAW_SLOT_KEY) {
823
+ literalReservedRaw = true;
824
+ continue;
825
+ }
826
+ if (key === "type" && value === "") continue;
827
+ metadata[key] = value;
828
+ }
829
+ if (literalReservedRaw) issues.push({ key: RAW_SLOT_KEY, reason: "reserved_key" });
830
+ const builderOwnedRaw = Object.fromEntries(
831
+ Object.entries(raw).filter(
832
+ ([key]) => key !== "okf_version" && key !== "profile" && key !== RAW_SLOT_KEY
833
+ )
834
+ );
835
+ if (Object.keys(builderOwnedRaw).length > 0) {
836
+ metadata[RAW_SLOT_KEY] = { ...builderOwnedRaw };
837
+ }
450
838
  const okf = frontmatter.okf_version;
839
+ let okfVersion;
840
+ if (typeof okf === "string") okfVersion = okf;
841
+ else {
842
+ const rawLine = raw["okf_version"];
843
+ let rawText = rawLine != null ? rawLine.slice(rawLine.indexOf(":") + 1).trim() : void 0;
844
+ if (rawText != null) {
845
+ const hash = rawText.indexOf(" #");
846
+ if (hash !== -1) rawText = rawText.slice(0, hash).trim();
847
+ }
848
+ if (rawText != null && /^\d+\.\d+$/.test(rawText)) okfVersion = rawText;
849
+ else if (typeof okf === "number" && Number.isFinite(okf)) okfVersion = String(okf);
850
+ }
451
851
  return {
452
- okf_version: typeof okf === "string" ? okf : typeof okf === "number" && Number.isFinite(okf) ? String(okf) : void 0,
453
- profile: typeof frontmatter.profile === "string" ? frontmatter.profile : void 0
852
+ okf_version: okfVersion,
853
+ profile: typeof frontmatter.profile === "string" ? frontmatter.profile : void 0,
854
+ metadata,
855
+ raw,
856
+ issues
454
857
  };
455
858
  }
456
859
 
@@ -883,34 +1286,96 @@ function serializeFootnotes(footnotes) {
883
1286
  }).join("\n");
884
1287
  }
885
1288
 
886
- // src/v02-helpers.ts
887
- function deriveTrustTier(verified) {
888
- if (!verified || verified.length === 0) return "unverified";
889
- for (const v of verified) {
890
- if (typeof v?.by === "string" && v.by.startsWith("human:")) return "human-reviewed";
1289
+ // src/v03-helpers.ts
1290
+ var DATE_ONLY = /^(\d{4})-(\d{2})-(\d{2})$/;
1291
+ var DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/;
1292
+ function epochFromDateTime(dt) {
1293
+ const year = Number(dt[1]);
1294
+ const month = Number(dt[2]);
1295
+ const day = Number(dt[3]);
1296
+ const hour = Number(dt[4]);
1297
+ const minute = Number(dt[5]);
1298
+ const second = Number(dt[6]);
1299
+ const frac = dt[7];
1300
+ const fracMs = frac ? Number(frac.slice(1, 4).padEnd(3, "0")) : 0;
1301
+ let ms = Date.UTC(year, month - 1, day, hour, minute, second, fracMs);
1302
+ const offset = dt[8];
1303
+ if (offset[0] === "+" || offset[0] === "-") {
1304
+ const sign = offset[0] === "-" ? -1 : 1;
1305
+ const oh = Number(offset.slice(1, 3));
1306
+ const om = Number(offset.slice(4, 6));
1307
+ ms -= sign * (oh * 60 + om) * 6e4;
891
1308
  }
892
- return "machine-confirmed";
1309
+ return ms;
893
1310
  }
894
- function parseStaleAfter(staleAfter) {
895
- if (staleAfter == null) return null;
896
- if (typeof staleAfter === "number") return Number.isFinite(staleAfter) ? staleAfter : null;
897
- const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(staleAfter);
898
- if (!match) return null;
899
- const year = Number(match[1]);
900
- const month = Number(match[2]);
901
- const day = Number(match[3]);
1311
+ function utcDayValid(year, month, day) {
902
1312
  const ts = Date.UTC(year, month - 1, day);
903
- if (!Number.isFinite(ts)) return null;
904
1313
  const d = new Date(ts);
905
- if (d.getUTCFullYear() !== year || d.getUTCMonth() + 1 !== month || d.getUTCDate() !== day) {
906
- return null;
1314
+ return d.getUTCFullYear() === year && d.getUTCMonth() + 1 === month && d.getUTCDate() === day;
1315
+ }
1316
+ function parseOkfTimestamp(value) {
1317
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
1318
+ if (typeof value !== "string") return null;
1319
+ const s = value.trim();
1320
+ if (s.length === 0) return null;
1321
+ const dateOnly = DATE_ONLY.exec(s);
1322
+ if (dateOnly) {
1323
+ const year2 = Number(dateOnly[1]);
1324
+ const month2 = Number(dateOnly[2]);
1325
+ const day2 = Number(dateOnly[3]);
1326
+ if (!utcDayValid(year2, month2, day2)) return null;
1327
+ return Date.UTC(year2, month2 - 1, day2);
1328
+ }
1329
+ const dt = DATE_TIME.exec(s);
1330
+ if (!dt) return null;
1331
+ const year = Number(dt[1]);
1332
+ const month = Number(dt[2]);
1333
+ const day = Number(dt[3]);
1334
+ const hour = Number(dt[4]);
1335
+ const minute = Number(dt[5]);
1336
+ const second = Number(dt[6]);
1337
+ if (!utcDayValid(year, month, day)) return null;
1338
+ if (hour > 23 || minute > 59 || second > 60) return null;
1339
+ const offset = dt[8];
1340
+ if (offset[0] !== "Z" && offset[0] !== "z") {
1341
+ const oh = Number(offset.slice(1, 3));
1342
+ const om = Number(offset.slice(4, 6));
1343
+ if (oh > 23 || om > 59) return null;
1344
+ }
1345
+ return epochFromDateTime(dt);
1346
+ }
1347
+
1348
+ // src/v02-helpers.ts
1349
+ function deriveTrustTier(verified, generatedAt) {
1350
+ const events = !verified ? [] : Array.isArray(verified) ? verified : [verified];
1351
+ if (events.length === 0) return "unverified";
1352
+ const restricted = generatedAt !== void 0 && generatedAt !== null;
1353
+ const cutoff = restricted ? parseOkfTimestamp(generatedAt) : null;
1354
+ const isCurrent = (v) => {
1355
+ if (!restricted) return true;
1356
+ const at = parseOkfTimestamp(v.at);
1357
+ if (at == null) return false;
1358
+ return cutoff != null && at >= cutoff;
1359
+ };
1360
+ const current = events.filter(isCurrent);
1361
+ if (current.length === 0) return "unverified";
1362
+ for (const v of current) {
1363
+ if (typeof v?.by === "string" && v.by.startsWith("human:")) {
1364
+ return "human-reviewed";
1365
+ }
907
1366
  }
908
- return ts;
1367
+ return "machine-confirmed";
909
1368
  }
910
1369
  function isStaleAfter(staleAfter, now) {
911
- const cutoff = parseStaleAfter(staleAfter);
912
- if (cutoff == null) return false;
913
- return now >= cutoff;
1370
+ if (staleAfter == null) return false;
1371
+ if (typeof staleAfter === "number") {
1372
+ return Number.isFinite(staleAfter) ? now >= staleAfter : true;
1373
+ }
1374
+ if (typeof staleAfter !== "string") return true;
1375
+ if (staleAfter.trim().length === 0) return false;
1376
+ const cutoff = parseOkfTimestamp(staleAfter);
1377
+ if (cutoff != null) return now >= cutoff;
1378
+ return true;
914
1379
  }
915
1380
  function parseVerifiedFlexible(value) {
916
1381
  if (value == null) return [];
@@ -924,12 +1389,28 @@ function parseVerifiedFlexible(value) {
924
1389
  }
925
1390
  return [];
926
1391
  }
1392
+ function parseSourcesFlexible(value) {
1393
+ const isValidSource = (v) => !!v && typeof v === "object" && !Array.isArray(v) && typeof v.resource === "string" && v.resource !== "";
1394
+ if (value == null) return { sources: [], ignored: 0 };
1395
+ if (Array.isArray(value)) {
1396
+ const sources = [];
1397
+ let ignored = 0;
1398
+ for (const entry of value) {
1399
+ if (isValidSource(entry)) sources.push(entry);
1400
+ else ignored += 1;
1401
+ }
1402
+ return { sources, ignored };
1403
+ }
1404
+ if (isValidSource(value)) return { sources: [value], ignored: 0 };
1405
+ if (typeof value === "object") return { sources: [], ignored: 1 };
1406
+ return { sources: [], ignored: 0 };
1407
+ }
927
1408
  function formatVerifiedJson(entries) {
928
1409
  const sorted = [...entries].sort((a, b) => {
929
- const ta = Date.parse(a.at);
930
- const tb = Date.parse(b.at);
931
- const fa = Number.isFinite(ta);
932
- const fb = Number.isFinite(tb);
1410
+ const ta = parseOkfTimestamp(a.at);
1411
+ const tb = parseOkfTimestamp(b.at);
1412
+ const fa = ta != null;
1413
+ const fb = tb != null;
933
1414
  if (fa && fb) return ta - tb;
934
1415
  if (fa && !fb) return -1;
935
1416
  if (!fa && fb) return 1;
@@ -948,8 +1429,8 @@ function latestVerified(entries, _now) {
948
1429
  let best = null;
949
1430
  let bestAt = -Infinity;
950
1431
  for (const e of entries) {
951
- const ts = Date.parse(e.at);
952
- if (Number.isFinite(ts) && ts > bestAt) {
1432
+ const ts = parseOkfTimestamp(e.at);
1433
+ if (ts != null && ts > bestAt) {
953
1434
  best = e;
954
1435
  bestAt = ts;
955
1436
  }
@@ -1018,6 +1499,6 @@ function parseCitationsList(body) {
1018
1499
  return out;
1019
1500
  }
1020
1501
 
1021
- export { appendEventIdComment, appendRelatedSection, buildConceptDocument, buildEntityIndexMd, buildIndexMd, buildLogMd, buildRootIndexMd, createEventIdDeriver, deriveEventId, deriveTrustTier, extractFootnotes, extractMarkdownLinks, formatSourcesJson, formatVerifiedJson, isAllowedOkfPath, isStaleAfter, latestVerified, parseCitationsList, parseConcept, parseEntityIndexMd, parseEventIdComment, parseFlowMapping, parseFlowSequence, parseFrontmatter, parseLogMd, parseRootIndexMd, parseVerifiedFlexible, serializeActorString, serializeFootnotes, serializeFrontmatter, splitRelatedSection };
1502
+ export { appendEventIdComment, appendRelatedSection, buildConceptDocument, buildEntityIndexMd, buildIndexMd, buildLogMd, buildRootIndexMd, createEventIdDeriver, deriveEventId, deriveTrustTier, extractFootnotes, extractMarkdownLinks, formatSourcesJson, formatVerifiedJson, isAllowedOkfPath, isStaleAfter, latestVerified, parseCitationsList, parseConcept, parseEntityIndexMd, parseEventIdComment, parseFlowMapping, parseFlowSequence, parseFrontmatter, parseLogMd, parseOkfTimestamp, parseRootIndexMd, parseSourcesFlexible, parseVerifiedFlexible, serializeActorString, serializeFootnotes, serializeFrontmatter, splitRelatedSection };
1022
1503
  //# sourceMappingURL=index.mjs.map
1023
1504
  //# sourceMappingURL=index.mjs.map