@rebilder/render-md 0.3.0 → 0.4.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.d.ts CHANGED
@@ -145,8 +145,8 @@ declare function renderCatalogMarkdown(items: CatalogItemSource[], opts?: Render
145
145
  *
146
146
  * The same guarantee as the commerce types applies to every field here: it is
147
147
  * authoritative merchant data, and the renderers only transform format. They
148
- * never invent, estimate, or reword a value found on these types (CLAUDE.md
149
- * source validation).
148
+ * never invent, estimate, or reword a value found on these types (project
149
+ * convention: source validation).
150
150
  *
151
151
  * Why two types (document + collection) and not one per vertical: see the
152
152
  * promotion bar in README.md. Every vertical evaluated so far reduces to
@@ -509,4 +509,58 @@ declare function applyCompatibilityProfile(markdown: string, selected: unknown,
509
509
  maxBytes?: number;
510
510
  }): CompatibilityRendering;
511
511
 
512
- export { ACCESS_LABELS, ALLOWED_URL_SCHEMES, type ActionKind, type ActionSource, type Availability, BASELINE_PROFILE, BOOLEAN_LABELS, type BillingPeriod, CLOSED_LABEL, COMPATIBILITY_RUNTIME_VERSION, type CatalogItemSource, type CollectionItemSource, type CollectionSource, type CompatibilityProfile, type CompatibilityRendering, type ContactSource, type DocumentAccess, type DocumentKind, type DocumentSectionSource, type DocumentSource, type Fact, type FactValue, type HoursException, type HoursInterval, type HoursRule, type HoursSpec, type LinkSource, type Money, NOT_STATED_LABEL, PERIOD_SUFFIX, type PolicySource, type ProductSource, type ProductVariantSource, type RenderOptions, type ReturnsSource, SEE_PAGE_LABEL, type ShippingSource, WEEKDAY_LABELS, WEEKDAY_ORDER, type Weekday, applyCompatibilityProfile, formatMoney, renderCatalogMarkdown, renderCollectionJsonLd, renderCollectionMarkdown, renderDocumentMarkdown, renderPolicyMarkdown, renderProductJsonLd, renderProductMarkdown, validateCompatibilityProfile };
512
+ /**
513
+ * YAML frontmatter for a markdown document: the page's title, description,
514
+ * canonical URL and last-updated date, as a block a caller can put in front of
515
+ * any rendered markdown.
516
+ *
517
+ * OPT-IN. No renderer in this package calls it, so every existing output stays
518
+ * byte-for-byte what it was. `@rebilder/gateway` prepends it only when a
519
+ * merchant sets `frontmatter: true`.
520
+ *
521
+ * Same contract as the renderers:
522
+ *
523
+ * - Every value is injected verbatim from the caller's fields. Nothing is
524
+ * generated: no default title, no summary written from the body, no date
525
+ * from a clock. A field the caller does not have is absent from the block.
526
+ * - Values are gated, never repaired. `canonicalUrl` must be an absolute
527
+ * `http:` or `https:` URL and `lastUpdated` a real ISO 8601 date or datetime;
528
+ * anything else is dropped.
529
+ * - The four keys and the `---` fences are the only text this function adds.
530
+ *
531
+ * Scalars: a value is written bare when YAML reads it back as exactly that
532
+ * string: one line, starting with a letter or digit, with no `: ` or ` #`, and
533
+ * not a word or number YAML would turn into a boolean, null, number or date.
534
+ * Everything else is double-quoted with JSON string escapes, which YAML
535
+ * accepts. Bare where possible, because a bare value is byte-for-byte the
536
+ * source text, so anything reading `description: …` as a labelled line sees
537
+ * the same sentence the page states elsewhere rather than a quoted copy of it.
538
+ * A newline, quote or `---` inside a value always lands inside quotes on one
539
+ * line, so source text can never close the block early or add a key of its own.
540
+ *
541
+ * Bounded: a block over {@link FRONTMATTER_MAX_BYTES} drops `description`, the
542
+ * one long free-text field; if it is still over, no frontmatter is returned.
543
+ * The markdown body is never cut to make room.
544
+ */
545
+ interface FrontmatterFields {
546
+ /** Page title, verbatim. Emitted as `title`. */
547
+ title?: string;
548
+ /** Short description of the page, verbatim. Emitted as `description`. */
549
+ description?: string;
550
+ /**
551
+ * Absolute `http:` or `https:` URL of the canonical HTML page this markdown
552
+ * represents. Emitted as `canonical_url`.
553
+ */
554
+ canonicalUrl?: string;
555
+ /** ISO 8601 date or datetime. Emitted as `last_updated`. */
556
+ lastUpdated?: string;
557
+ }
558
+ /** Largest frontmatter block, fences included, in UTF-8 bytes. */
559
+ declare const FRONTMATTER_MAX_BYTES = 2048;
560
+ /**
561
+ * Render the frontmatter block, ending in a newline, or `''` when no field
562
+ * survives validation. Put it first in the document: `block + '\n' + markdown`.
563
+ */
564
+ declare function renderFrontmatter(fields: FrontmatterFields): string;
565
+
566
+ export { ACCESS_LABELS, ALLOWED_URL_SCHEMES, type ActionKind, type ActionSource, type Availability, BASELINE_PROFILE, BOOLEAN_LABELS, type BillingPeriod, CLOSED_LABEL, COMPATIBILITY_RUNTIME_VERSION, type CatalogItemSource, type CollectionItemSource, type CollectionSource, type CompatibilityProfile, type CompatibilityRendering, type ContactSource, type DocumentAccess, type DocumentKind, type DocumentSectionSource, type DocumentSource, FRONTMATTER_MAX_BYTES, type Fact, type FactValue, type FrontmatterFields, type HoursException, type HoursInterval, type HoursRule, type HoursSpec, type LinkSource, type Money, NOT_STATED_LABEL, PERIOD_SUFFIX, type PolicySource, type ProductSource, type ProductVariantSource, type RenderOptions, type ReturnsSource, SEE_PAGE_LABEL, type ShippingSource, WEEKDAY_LABELS, WEEKDAY_ORDER, type Weekday, applyCompatibilityProfile, formatMoney, renderCatalogMarkdown, renderCollectionJsonLd, renderCollectionMarkdown, renderDocumentMarkdown, renderFrontmatter, renderPolicyMarkdown, renderProductJsonLd, renderProductMarkdown, validateCompatibilityProfile };
package/dist/index.js CHANGED
@@ -117,14 +117,14 @@ function byteLength(s) {
117
117
  function clampHeadingLevel(level) {
118
118
  return Math.min(Math.max(Math.trunc(level), 1), 6);
119
119
  }
120
- function heading(level, text) {
121
- return `${"#".repeat(clampHeadingLevel(level))} ${text}`;
120
+ function heading(level, text2) {
121
+ return `${"#".repeat(clampHeadingLevel(level))} ${text2}`;
122
122
  }
123
- function inline(text) {
124
- return text.replace(/\s*\r?\n\s*/g, " ");
123
+ function inline(text2) {
124
+ return text2.replace(/\s*\r?\n\s*/g, " ");
125
125
  }
126
- function cell(text) {
127
- return inline(text).replace(/\|/g, "\\|");
126
+ function cell(text2) {
127
+ return inline(text2).replace(/\|/g, "\\|");
128
128
  }
129
129
  var ALLOWED_LINK_SCHEMES = ["https:", "http:", "mailto:", "tel:"];
130
130
  function isSafeUrl(url) {
@@ -134,8 +134,8 @@ function isSafeUrl(url) {
134
134
  return false;
135
135
  }
136
136
  }
137
- function linkText(text) {
138
- return inline(text).replace(/[[\]]/g, (c) => `\\${c}`);
137
+ function linkText(text2) {
138
+ return inline(text2).replace(/[[\]]/g, (c) => `\\${c}`);
139
139
  }
140
140
  function safeUrl(url) {
141
141
  return url.replace(
@@ -143,12 +143,12 @@ function safeUrl(url) {
143
143
  (c) => `%${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`
144
144
  );
145
145
  }
146
- function cellLinkText(text) {
147
- return linkText(text).replace(/\|/g, "\\|");
146
+ function cellLinkText(text2) {
147
+ return linkText(text2).replace(/\|/g, "\\|");
148
148
  }
149
149
  function safeLink(label, url, labelEscaper = linkText) {
150
- const text = labelEscaper(label);
151
- return isSafeUrl(url) ? `[${text}](${safeUrl(url)})` : text;
150
+ const text2 = labelEscaper(label);
151
+ return isSafeUrl(url) ? `[${text2}](${safeUrl(url)})` : text2;
152
152
  }
153
153
  function tailText(t) {
154
154
  return `${t.headingLine}
@@ -287,12 +287,12 @@ ${TRUNCATION_NOTE}`;
287
287
  let out = "";
288
288
  for (const pol of policies) {
289
289
  const titleLine = titleLineFor(pol);
290
- const block = `${titleLine}
290
+ const block2 = `${titleLine}
291
291
 
292
292
  ${pol.body}`;
293
- const withBlock = out === "" ? block : `${out}
293
+ const withBlock = out === "" ? block2 : `${out}
294
294
 
295
- ${block}`;
295
+ ${block2}`;
296
296
  if (byteLength(withBlock) <= budget) {
297
297
  out = withBlock;
298
298
  continue;
@@ -404,8 +404,8 @@ function isAllowedUrl(raw) {
404
404
  }
405
405
  return ALLOWED_URL_SCHEMES.includes(parsed.protocol);
406
406
  }
407
- function linkLabel(text) {
408
- return inline(text).replace(/[\]()]/g, (c) => `\\${c}`);
407
+ function linkLabel(text2) {
408
+ return inline(text2).replace(/[\]()]/g, (c) => `\\${c}`);
409
409
  }
410
410
  function markdownLink(label, url) {
411
411
  return `[${linkLabel(label)}](${url})`;
@@ -425,12 +425,12 @@ function intervalsText(intervals) {
425
425
  }
426
426
  function numberText(value, unit) {
427
427
  if (!Number.isFinite(value)) return null;
428
- const text = String(value);
429
- if (text.includes("e") || text.includes("E")) return null;
430
- return unit !== void 0 ? `${text} ${inline(unit)}` : text;
428
+ const text2 = String(value);
429
+ if (text2.includes("e") || text2.includes("E")) return null;
430
+ return unit !== void 0 ? `${text2} ${inline(unit)}` : text2;
431
431
  }
432
432
  function moneyText(v) {
433
- let text = formatMoney(v.value);
433
+ let text2 = formatMoney(v.value);
434
434
  if (v.maxValue !== void 0) {
435
435
  if (v.maxValue.currency.toUpperCase() !== v.value.currency.toUpperCase()) {
436
436
  throw new TypeError(
@@ -442,11 +442,11 @@ function moneyText(v) {
442
442
  `Money range maxValue must not be below value, got: ${String(v.value.amount)} and ${String(v.maxValue.amount)}`
443
443
  );
444
444
  }
445
- text = `${text}-${formatMoney(v.maxValue)}`;
445
+ text2 = `${text2}-${formatMoney(v.maxValue)}`;
446
446
  }
447
- if (v.period !== void 0) text = `${text} ${PERIOD_SUFFIX[v.period]}`;
448
- if (v.per !== void 0) text = `${text} ${inline(v.per)}`;
449
- return text;
447
+ if (v.period !== void 0) text2 = `${text2} ${PERIOD_SUFFIX[v.period]}`;
448
+ if (v.per !== void 0) text2 = `${text2} ${inline(v.per)}`;
449
+ return text2;
450
450
  }
451
451
  function factValueText(value) {
452
452
  switch (value.type) {
@@ -470,9 +470,9 @@ function factValueText(value) {
470
470
  }
471
471
  }
472
472
  function renderFactLine(fact) {
473
- const text = factValueText(fact.value);
474
- if (text === null) return null;
475
- const line = `- **${inline(fact.label)}:** ${text}`;
473
+ const text2 = factValueText(fact.value);
474
+ if (text2 === null) return null;
475
+ const line = `- **${inline(fact.label)}:** ${text2}`;
476
476
  return fact.note !== void 0 ? `${line}
477
477
  - ${inline(fact.note)}` : line;
478
478
  }
@@ -484,8 +484,8 @@ function factCellText(value, itemUrl) {
484
484
  if (!isAllowedUrl(value.value)) return null;
485
485
  return value.label !== void 0 ? cellLink(value.label, value.value) : value.value.replace(/\|/g, "\\|");
486
486
  }
487
- const text = factValueText(value);
488
- return text === null ? null : cell(text);
487
+ const text2 = factValueText(value);
488
+ return text2 === null ? null : cell(text2);
489
489
  }
490
490
  function exceptionRow(e) {
491
491
  if (!isIsoDay(e.date)) return null;
@@ -520,8 +520,8 @@ function renderHoursBlock(label, spec, level, subLevel) {
520
520
  ];
521
521
  for (const day of WEEKDAY_ORDER) {
522
522
  const intervals = byDay.get(day);
523
- const text = intervals === void 0 ? NOT_STATED_LABEL : intervals.length === 0 ? CLOSED_LABEL : intervalsText(intervals);
524
- lines.push(`| ${WEEKDAY_LABELS[day]} | ${text} |`);
523
+ const text2 = intervals === void 0 ? NOT_STATED_LABEL : intervals.length === 0 ? CLOSED_LABEL : intervalsText(intervals);
524
+ lines.push(`| ${WEEKDAY_LABELS[day]} | ${text2} |`);
525
525
  }
526
526
  if (spec.note !== void 0) {
527
527
  lines.push("", `- **${NOTE_LABEL}:** ${inline(spec.note)}`);
@@ -562,8 +562,8 @@ ${line}`;
562
562
  }
563
563
  return kept === "" ? TRUNCATION_NOTE : `${kept}${noteSuffix}`;
564
564
  }
565
- function blockquote(text) {
566
- return text.split("\n").map((line) => line.length > 0 ? `> ${line}` : ">");
565
+ function blockquote(text2) {
566
+ return text2.split("\n").map((line) => line.length > 0 ? `> ${line}` : ">");
567
567
  }
568
568
  function sectionTail(section, level) {
569
569
  const lines = section.body.split("\n");
@@ -600,8 +600,8 @@ function renderDocumentMarkdown(doc, opts) {
600
600
  const requiredBlocks = [head.join("\n")];
601
601
  for (const fact of facts) {
602
602
  if (fact.value.type !== "hours") continue;
603
- const block = renderHoursBlock(fact.label, fact.value.value, sub, subSub);
604
- if (block !== null) requiredBlocks.push(block);
603
+ const block2 = renderHoursBlock(fact.label, fact.value.value, sub, subSub);
604
+ if (block2 !== null) requiredBlocks.push(block2);
605
605
  }
606
606
  const contactLines = [];
607
607
  const contact = doc.contact;
@@ -653,9 +653,9 @@ function itemCells(item) {
653
653
  cells.push({ label: NOTE_LABEL, text: cell(item.summary) });
654
654
  }
655
655
  for (const fact of item.facts ?? []) {
656
- const text = factCellText(fact.value, item.url);
657
- if (text === null) continue;
658
- cells.push({ label: cell(fact.label), text });
656
+ const text2 = factCellText(fact.value, item.url);
657
+ if (text2 === null) continue;
658
+ cells.push({ label: cell(fact.label), text: text2 });
659
659
  }
660
660
  return cells;
661
661
  }
@@ -691,18 +691,18 @@ ${TRUNCATION_NOTE}`;
691
691
  const cells = itemCells(item);
692
692
  const values = /* @__PURE__ */ new Map();
693
693
  const newColumns = [];
694
- for (const { label, text } of cells) {
694
+ for (const { label, text: text2 } of cells) {
695
695
  if (values.has(label)) continue;
696
696
  if (!columns.includes(label) && !newColumns.includes(label)) {
697
697
  if (columns.length + newColumns.length >= MAX_COLLECTION_COLUMNS) continue;
698
698
  newColumns.push(label);
699
699
  }
700
- values.set(label, text);
700
+ values.set(label, text2);
701
701
  }
702
702
  values.set(TITLE_LABEL, titleCell(item));
703
703
  const nextColumnCount = 1 + columns.length + newColumns.length;
704
704
  const addedHeaderBytes = newColumns.reduce((sum, label) => sum + byteLength(label), 0);
705
- const addedBodyBytes = [...values.values()].reduce((sum, text) => sum + byteLength(text), 0);
705
+ const addedBodyBytes = [...values.values()].reduce((sum, text2) => sum + byteLength(text2), 0);
706
706
  const savedHeader = headerCellBytes;
707
707
  const savedBody = bodyCellBytes;
708
708
  headerCellBytes += addedHeaderBytes;
@@ -828,6 +828,76 @@ ${headings.map((line) => `- ${line.replace(/^#{1,6} /, "")}`).join("\n")}
828
828
  return { markdown: output, profile };
829
829
  }
830
830
 
831
- export { ACCESS_LABELS, ALLOWED_URL_SCHEMES, BASELINE_PROFILE, BOOLEAN_LABELS, CLOSED_LABEL, COMPATIBILITY_RUNTIME_VERSION, NOT_STATED_LABEL, PERIOD_SUFFIX, SEE_PAGE_LABEL, WEEKDAY_LABELS, WEEKDAY_ORDER, applyCompatibilityProfile, formatMoney, renderCatalogMarkdown, renderCollectionJsonLd, renderCollectionMarkdown, renderDocumentMarkdown, renderPolicyMarkdown, renderProductJsonLd, renderProductMarkdown, validateCompatibilityProfile };
831
+ // src/frontmatter.ts
832
+ var FRONTMATTER_MAX_BYTES = 2048;
833
+ function text(value) {
834
+ return typeof value === "string" && value.trim() !== "" ? value : null;
835
+ }
836
+ function httpUrl(value) {
837
+ const raw = text(value);
838
+ if (raw === null) return null;
839
+ try {
840
+ const parsed = new URL(raw);
841
+ return parsed.protocol === "https:" || parsed.protocol === "http:" ? raw : null;
842
+ } catch {
843
+ return null;
844
+ }
845
+ }
846
+ function isoDate(value) {
847
+ const raw = text(value);
848
+ return raw !== null && isIsoDate(raw) ? raw : null;
849
+ }
850
+ var LINE_SEPARATOR = String.fromCharCode(8232);
851
+ var PARAGRAPH_SEPARATOR = String.fromCharCode(8233);
852
+ function quoted(value) {
853
+ return JSON.stringify(value).split(LINE_SEPARATOR).join("\\u2028").split(PARAGRAPH_SEPARATOR).join("\\u2029");
854
+ }
855
+ var TYPED_WORD = /^(?:true|false|yes|no|on|off|y|n|null|~)$/i;
856
+ var NUMBER_LIKE = /^[0-9][0-9a-fA-FxXoO_.:+-]*$/;
857
+ var DATE_LIKE = /^\d{4}-\d{1,2}-\d{1,2}/;
858
+ function hasUnprintable(value) {
859
+ for (let i = 0; i < value.length; i += 1) {
860
+ const code = value.charCodeAt(i);
861
+ if (code < 32 || code >= 127 && code <= 159) return true;
862
+ if (code === 8232 || code === 8233 || code === 65279) return true;
863
+ }
864
+ return false;
865
+ }
866
+ function isPlainSafe(value) {
867
+ if (value !== value.trim() || hasUnprintable(value)) return false;
868
+ if (!/^[\p{L}\p{N}]/u.test(value)) return false;
869
+ if (value.includes(": ") || value.includes(" #") || value.endsWith(":")) return false;
870
+ return !TYPED_WORD.test(value) && !NUMBER_LIKE.test(value) && !DATE_LIKE.test(value);
871
+ }
872
+ function scalar(value) {
873
+ return isPlainSafe(value) ? value : quoted(value);
874
+ }
875
+ function block(entries) {
876
+ const lines = entries.filter((entry) => entry[1] !== null).map(([key, value]) => `${key}: ${scalar(value)}`);
877
+ return lines.length === 0 ? "" : `---
878
+ ${lines.join("\n")}
879
+ ---
880
+ `;
881
+ }
882
+ function renderFrontmatter(fields) {
883
+ const title = text(fields.title);
884
+ const canonical = httpUrl(fields.canonicalUrl);
885
+ const updated = isoDate(fields.lastUpdated);
886
+ const full = block([
887
+ ["title", title],
888
+ ["description", text(fields.description)],
889
+ ["canonical_url", canonical],
890
+ ["last_updated", updated]
891
+ ]);
892
+ if (byteLength(full) <= FRONTMATTER_MAX_BYTES) return full;
893
+ const short = block([
894
+ ["title", title],
895
+ ["canonical_url", canonical],
896
+ ["last_updated", updated]
897
+ ]);
898
+ return byteLength(short) <= FRONTMATTER_MAX_BYTES ? short : "";
899
+ }
900
+
901
+ export { ACCESS_LABELS, ALLOWED_URL_SCHEMES, BASELINE_PROFILE, BOOLEAN_LABELS, CLOSED_LABEL, COMPATIBILITY_RUNTIME_VERSION, FRONTMATTER_MAX_BYTES, NOT_STATED_LABEL, PERIOD_SUFFIX, SEE_PAGE_LABEL, WEEKDAY_LABELS, WEEKDAY_ORDER, applyCompatibilityProfile, formatMoney, renderCatalogMarkdown, renderCollectionJsonLd, renderCollectionMarkdown, renderDocumentMarkdown, renderFrontmatter, renderPolicyMarkdown, renderProductJsonLd, renderProductMarkdown, validateCompatibilityProfile };
832
902
  //# sourceMappingURL=index.js.map
833
903
  //# sourceMappingURL=index.js.map