@rebilder/render-md 0.1.1 → 0.3.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.d.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Every field on these types is treated as authoritative merchant data. The
5
5
  * renderers in this package only transform format — they never invent,
6
- * estimate, or reword any value found here (CLAUDE.md Hard Rules 2 & 3).
6
+ * estimate, or reword any value found here (source validation).
7
7
  */
8
8
  /** Monetary value. `amount` is in minor units (e.g. cents for USD). */
9
9
  interface Money {
@@ -51,6 +51,27 @@ interface ProductSource {
51
51
  }[];
52
52
  /** Material, size chart facts, etc. — rendered verbatim. */
53
53
  attributes?: Record<string, string>;
54
+ /**
55
+ * When this product's facts last changed, ISO 8601, verbatim. Same field
56
+ * name and same validation as `DocumentSource.updated`.
57
+ *
58
+ * This is the freshness contract an agent needs in order to decide whether a
59
+ * cached copy is still usable. Without it a caller has only the transport's
60
+ * `Last-Modified`, which describes the response and not the product. Renders
61
+ * as `dateModified` in the JSON-LD and as an `Updated` fact line in the
62
+ * markdown; a malformed value is dropped from both.
63
+ */
64
+ updated?: string;
65
+ /**
66
+ * BCP 47 language tag of this page's prose, verbatim (`en`, `pt-BR`,
67
+ * `zh-Hant-TW`). Emitted as `inLanguage`.
68
+ *
69
+ * Localized storefronts serve the same SKU at several URLs, and a caller
70
+ * comparing them has no way to tell a translation from a distinct product
71
+ * unless the page says so. Paired with `price.currency`, which the offer
72
+ * already carries as `priceCurrency`. A malformed tag is dropped.
73
+ */
74
+ language?: string;
54
75
  }
55
76
  interface PolicySource {
56
77
  title: string;
@@ -82,6 +103,13 @@ declare function formatMoney(m: Money): string;
82
103
  * Render a schema.org Product JSON-LD object from the product source.
83
104
  * Injection-only: every value comes from `p`; only fields present in the
84
105
  * source appear in the output. Key order is fixed for snapshot stability.
106
+ *
107
+ * `inLanguage` and `dateModified` are emitted only when the source value
108
+ * passes its shape check. A malformed value is dropped rather than repaired or
109
+ * reformatted: this renderer feeds `/acp/v0/feed` and the MCP product tool as
110
+ * well as the canonical page, and a date this package invented would be a
111
+ * substantive value it originated (source validation) — in a product feed, where it
112
+ * would read as authoritative.
85
113
  */
86
114
  declare function renderProductJsonLd(p: ProductSource): Record<string, unknown>;
87
115
 
@@ -118,7 +146,7 @@ declare function renderCatalogMarkdown(items: CatalogItemSource[], opts?: Render
118
146
  * The same guarantee as the commerce types applies to every field here: it is
119
147
  * authoritative merchant data, and the renderers only transform format. They
120
148
  * never invent, estimate, or reword a value found on these types (CLAUDE.md
121
- * Hard Rules 2 & 3).
149
+ * source validation).
122
150
  *
123
151
  * Why two types (document + collection) and not one per vertical: see the
124
152
  * promotion bar in README.md. Every vertical evaluated so far reduces to
@@ -281,7 +309,7 @@ interface DocumentSource {
281
309
  * the document past `ttlSeconds` and falls through to HTML. A snapshot is
282
310
  * not a source of truth: without this, a merchant changes their hours and
283
311
  * agents keep receiving the approved bundle — different substance to agents
284
- * and humans at the same URL, which is a Hard Rule 3 breach manufactured by
312
+ * and humans at the same URL, which is a consistent source content breach manufactured by
285
313
  * our own pipeline. Enforced by the gateway, not by this package.
286
314
  */
287
315
  provenance?: {
@@ -307,6 +335,15 @@ interface CollectionSource {
307
335
  title?: string;
308
336
  /** Capped at 500 rendered rows; column union capped at 12. */
309
337
  items: CollectionItemSource[];
338
+ /**
339
+ * When this listing last changed, ISO 8601, verbatim. Same field name and
340
+ * validation as `DocumentSource.updated` and `ProductSource.updated`.
341
+ * Emitted as `dateModified` by `renderCollectionJsonLd`; the markdown
342
+ * renderer does not render it, and did not before this field existed.
343
+ */
344
+ updated?: string;
345
+ /** BCP 47 language tag, verbatim. Emitted as `inLanguage`. Malformed → dropped. */
346
+ language?: string;
310
347
  }
311
348
 
312
349
  /**
@@ -365,6 +402,42 @@ declare function renderDocumentMarkdown(doc: DocumentSource, opts?: RenderOption
365
402
  */
366
403
  declare function renderCollectionMarkdown(collection: CollectionSource, opts?: RenderOptions): string;
367
404
 
405
+ /**
406
+ * `CollectionSource` → schema.org `ItemList` JSON-LD.
407
+ *
408
+ * The listing counterpart to `src/jsonld.ts`'s `Product`. Before this existed,
409
+ * a collection served through the universal gateway carried a markdown table
410
+ * and no structured data at all, so a caller that reads JSON-LD first — and a
411
+ * scorer looking for a recognised type — found nothing on a page whose entire
412
+ * purpose is enumerating things.
413
+ *
414
+ * Injection-only, on the same terms as every other renderer here:
415
+ *
416
+ * - `name` is emitted ONLY when the source supplies a title. The markdown
417
+ * renderer falls back to the fixed `Contents` heading because a document
418
+ * needs a heading for structure; JSON-LD does not, and emitting the fallback
419
+ * would make this package assert a name the merchant never wrote.
420
+ * - URLs pass the same scheme allowlist the markdown path uses. A `ListItem`
421
+ * whose URL is rejected still renders with its name — the item exists, we
422
+ * just decline to publish a link to it. Skipping this check would make the
423
+ * JSON-LD a `javascript:` sink that the markdown renderer already blocks.
424
+ * - `numberOfItems` counts the elements ACTUALLY EMITTED, not `items.length`.
425
+ * A 900-item listing truncates to `MAX_COLLECTION_ROWS`, and a document that
426
+ * announced 900 while listing 500 would be internally inconsistent — an
427
+ * agent trusting the count would page for items that are not there.
428
+ * - Item facts are not projected into the list. `ListItem` has no honest slot
429
+ * for an arbitrary labelled fact, and inventing property names for merchant
430
+ * labels is exactly the inference this package does not do. The facts are in
431
+ * the markdown table, which is where the renderer's contract puts them.
432
+ */
433
+
434
+ /**
435
+ * Render a schema.org ItemList from a collection source. Pure, deterministic,
436
+ * and fixed in key order for snapshot stability — same contract as
437
+ * `renderProductJsonLd`.
438
+ */
439
+ declare function renderCollectionJsonLd(collection: CollectionSource): Record<string, unknown>;
440
+
368
441
  /**
369
442
  * Fact rendering: the deterministic `FactValue` → markdown mapping, the fixed
370
443
  * label maps, the URL scheme allowlist, and the escaping rules.
@@ -380,7 +453,7 @@ declare function renderCollectionMarkdown(collection: CollectionSource, opts?: R
380
453
  * by importing these constants) so that adding scaffolding cannot silently
381
454
  * whitelist itself.
382
455
  * - A malformed value is DROPPED, never repaired. Repairing a fact invents a
383
- * value the merchant never stated (Hard Rule 2); dropping it only loses
456
+ * value the merchant never stated (source validation); dropping it only loses
384
457
  * information, which the agent can still get from the canonical page.
385
458
  * - URLs are checked against a scheme allowlist. The commerce path only ever
386
459
  * emitted merchant-controlled product/policy URLs; the universal path emits
@@ -397,7 +470,7 @@ declare const PERIOD_SUFFIX: Record<BillingPeriod, string>;
397
470
  declare const BOOLEAN_LABELS: Record<'true' | 'false', string>;
398
471
  /** Fixed weekday labels. English only and deliberately not localised: the
399
472
  * output is a machine-readable format transformation, and a locale would make
400
- * the same source render differently for different requesters (Hard Rule 3). */
473
+ * the same source render differently for different requesters (consistent source content). */
401
474
  declare const WEEKDAY_LABELS: Record<Weekday, string>;
402
475
  /** Fixed weekday order. Every one of the seven renders, always. */
403
476
  declare const WEEKDAY_ORDER: readonly Weekday[];
@@ -412,4 +485,28 @@ declare const ACCESS_LABELS: Record<DocumentAccess, string>;
412
485
  /** The only schemes this package will put behind a markdown link. */
413
486
  declare const ALLOWED_URL_SCHEMES: readonly string[];
414
487
 
415
- export { ACCESS_LABELS, ALLOWED_URL_SCHEMES, type ActionKind, type ActionSource, type Availability, BOOLEAN_LABELS, type BillingPeriod, CLOSED_LABEL, type CatalogItemSource, type CollectionItemSource, type CollectionSource, 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, formatMoney, renderCatalogMarkdown, renderCollectionMarkdown, renderDocumentMarkdown, renderPolicyMarkdown, renderProductJsonLd, renderProductMarkdown };
488
+ /** Conservative, compiled-in presentation strategies. No remote code or prose. */
489
+ interface CompatibilityProfile {
490
+ id: 'baseline' | 'source-envelope' | 'section-index';
491
+ version: 1;
492
+ }
493
+ declare const BASELINE_PROFILE: Readonly<CompatibilityProfile>;
494
+ declare const COMPATIBILITY_RUNTIME_VERSION = 1;
495
+ declare function validateCompatibilityProfile(value: unknown): CompatibilityProfile | null;
496
+ interface CompatibilityRendering {
497
+ markdown: string;
498
+ /** Actual presentation served, including budget/invalid-selection fallback. */
499
+ profile: CompatibilityProfile;
500
+ }
501
+ /**
502
+ * Baseline markdown stays a contiguous, byte-identical substring. Candidates
503
+ * add orientation only; they cannot rewrite, remove or reorder any source fact
504
+ * or qualification. Existing renderer truncation still applies. If additions
505
+ * do not fit the caller's budget, use the baseline and report that honestly.
506
+ */
507
+ declare function applyCompatibilityProfile(markdown: string, selected: unknown, options: {
508
+ canonicalUrl: string;
509
+ maxBytes?: number;
510
+ }): CompatibilityRendering;
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 };
package/dist/index.js CHANGED
@@ -56,6 +56,22 @@ function formatMoney(m) {
56
56
  return symbol !== void 0 ? `${sign}${symbol}${grouped}${frac}` : `${sign}${code} ${grouped}${frac}`;
57
57
  }
58
58
 
59
+ // src/internal/validate.ts
60
+ var ISO_DATE = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})?)?$/;
61
+ function isRealCalendarDate(value) {
62
+ const [year, month, day] = value.slice(0, 10).split("-").map(Number);
63
+ const probe = /* @__PURE__ */ new Date(0);
64
+ probe.setUTCFullYear(year, month - 1, day);
65
+ return probe.getUTCFullYear() === year && probe.getUTCMonth() === month - 1 && probe.getUTCDate() === day;
66
+ }
67
+ function isIsoDate(value) {
68
+ return ISO_DATE.test(value) && !Number.isNaN(Date.parse(value)) && isRealCalendarDate(value);
69
+ }
70
+ var BCP_47 = /^[A-Za-z]{2,3}(-[A-Za-z]{4})?(-(?:[A-Za-z]{2}|\d{3}))?$/;
71
+ function isLanguageTag(value) {
72
+ return BCP_47.test(value);
73
+ }
74
+
59
75
  // src/jsonld.ts
60
76
  var SCHEMA_AVAILABILITY = {
61
77
  in_stock: "https://schema.org/InStock",
@@ -85,7 +101,9 @@ function renderProductJsonLd(p) {
85
101
  if (p.brand !== void 0) out.brand = { "@type": "Brand", name: p.brand };
86
102
  if (p.description !== void 0 && p.description.length > 0) out.description = p.description;
87
103
  if (p.images !== void 0 && p.images.length > 0) out.image = p.images.map((img) => img.url);
104
+ if (p.language !== void 0 && isLanguageTag(p.language)) out.inLanguage = p.language;
88
105
  out.offers = p.variants !== void 0 && p.variants.length > 0 ? p.variants.map((v) => offer(v.price, v.availability, { sku: v.sku, name: v.title })) : offer(p.price, p.availability, { url: p.url });
106
+ if (p.updated !== void 0 && isIsoDate(p.updated)) out.dateModified = p.updated;
89
107
  return out;
90
108
  }
91
109
 
@@ -108,6 +126,30 @@ function inline(text) {
108
126
  function cell(text) {
109
127
  return inline(text).replace(/\|/g, "\\|");
110
128
  }
129
+ var ALLOWED_LINK_SCHEMES = ["https:", "http:", "mailto:", "tel:"];
130
+ function isSafeUrl(url) {
131
+ try {
132
+ return ALLOWED_LINK_SCHEMES.includes(new URL(url).protocol);
133
+ } catch {
134
+ return false;
135
+ }
136
+ }
137
+ function linkText(text) {
138
+ return inline(text).replace(/[[\]]/g, (c) => `\\${c}`);
139
+ }
140
+ function safeUrl(url) {
141
+ return url.replace(
142
+ /[()<>\s]/g,
143
+ (c) => `%${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`
144
+ );
145
+ }
146
+ function cellLinkText(text) {
147
+ return linkText(text).replace(/\|/g, "\\|");
148
+ }
149
+ function safeLink(label, url, labelEscaper = linkText) {
150
+ const text = labelEscaper(label);
151
+ return isSafeUrl(url) ? `[${text}](${safeUrl(url)})` : text;
152
+ }
111
153
  function tailText(t) {
112
154
  return `${t.headingLine}
113
155
 
@@ -175,7 +217,7 @@ function renderProductMarkdown(p, opts) {
175
217
  const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES;
176
218
  const level = clampHeadingLevel(opts?.headingLevel ?? 1);
177
219
  const sub = clampHeadingLevel(level + 1);
178
- const facts = [heading(level, `[${inline(p.title)}](${p.url})`), ""];
220
+ const facts = [heading(level, safeLink(p.title, p.url)), ""];
179
221
  if (p.brand !== void 0) facts.push(`- **Brand:** ${inline(p.brand)}`);
180
222
  const price = formatMoney(p.price);
181
223
  facts.push(
@@ -199,10 +241,13 @@ function renderProductMarkdown(p, opts) {
199
241
  if (p.returns.windowDays !== void 0) {
200
242
  facts.push(` - Return window: ${p.returns.windowDays} days`);
201
243
  }
202
- if (p.returns.url !== void 0) {
244
+ if (p.returns.url !== void 0 && isSafeUrl(p.returns.url)) {
203
245
  facts.push(` - Policy: ${p.returns.url}`);
204
246
  }
205
247
  }
248
+ if (p.updated !== void 0 && isIsoDate(p.updated)) {
249
+ facts.push(`- **Updated:** ${inline(p.updated)}`);
250
+ }
206
251
  const requiredBlocks = [facts.join("\n")];
207
252
  if (p.variants !== void 0 && p.variants.length > 0) {
208
253
  requiredBlocks.push(variantsTable(p.variants, sub));
@@ -219,8 +264,8 @@ function renderProductMarkdown(p, opts) {
219
264
  }
220
265
  if (p.images !== void 0 && p.images.length > 0) {
221
266
  const items = p.images.map((img) => {
222
- const label = img.alt !== void 0 && img.alt.length > 0 ? inline(img.alt) : img.url;
223
- return `- [${label}](${img.url})`;
267
+ const label = img.alt !== void 0 && img.alt.length > 0 ? img.alt : img.url;
268
+ return `- ${safeLink(label, img.url)}`;
224
269
  });
225
270
  tail.push({ headingLine: heading(sub, "Images"), items });
226
271
  }
@@ -229,7 +274,7 @@ function renderProductMarkdown(p, opts) {
229
274
  function renderPolicyMarkdown(policies, opts) {
230
275
  const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES;
231
276
  const level = clampHeadingLevel(opts?.headingLevel ?? 1);
232
- const titleLineFor = (pol) => heading(level, `[${inline(pol.title)}](${pol.url})`);
277
+ const titleLineFor = (pol) => heading(level, safeLink(pol.title, pol.url));
233
278
  const blocks = policies.map((pol) => `${titleLineFor(pol)}
234
279
 
235
280
  ${pol.body}`);
@@ -270,7 +315,7 @@ function renderCatalogMarkdown(items, opts) {
270
315
  "| --- | --- | --- |"
271
316
  ].join("\n");
272
317
  const rows = items.map(
273
- (item) => `| [${cell(item.title)}](${item.url}) | ${formatMoney(item.price)} | ${AVAILABILITY_LABELS[item.availability]} |`
318
+ (item) => `| ${safeLink(item.title, item.url, cellLinkText)} | ${formatMoney(item.price)} | ${AVAILABILITY_LABELS[item.availability]} |`
274
319
  );
275
320
  const full = [head, ...rows].join("\n");
276
321
  if (byteLength(full) <= maxBytes) return full;
@@ -368,10 +413,6 @@ function markdownLink(label, url) {
368
413
  function cellLink(label, url) {
369
414
  return markdownLink(label, url).replace(/\|/g, "\\|");
370
415
  }
371
- var ISO_DATE = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})?)?$/;
372
- function isIsoDate(value) {
373
- return ISO_DATE.test(value) && !Number.isNaN(Date.parse(value));
374
- }
375
416
  function isIsoDay(value) {
376
417
  return /^\d{4}-\d{2}-\d{2}$/.test(value) && !Number.isNaN(Date.parse(value));
377
418
  }
@@ -715,6 +756,78 @@ ${TRUNCATION_NOTE}`;
715
756
  return truncated ? `${out}${noteSuffix}` : out;
716
757
  }
717
758
 
718
- export { ACCESS_LABELS, ALLOWED_URL_SCHEMES, BOOLEAN_LABELS, CLOSED_LABEL, NOT_STATED_LABEL, PERIOD_SUFFIX, SEE_PAGE_LABEL, WEEKDAY_LABELS, WEEKDAY_ORDER, formatMoney, renderCatalogMarkdown, renderCollectionMarkdown, renderDocumentMarkdown, renderPolicyMarkdown, renderProductJsonLd, renderProductMarkdown };
759
+ // src/documents/jsonld.ts
760
+ function listItem(item, position) {
761
+ const out = { "@type": "ListItem", position };
762
+ if (isAllowedUrl(item.url)) out.url = item.url;
763
+ out.name = item.title;
764
+ return out;
765
+ }
766
+ function renderCollectionJsonLd(collection) {
767
+ const out = {
768
+ "@context": "https://schema.org",
769
+ "@type": "ItemList"
770
+ };
771
+ if (isAllowedUrl(collection.url)) out.url = collection.url;
772
+ if (collection.title !== void 0) out.name = collection.title;
773
+ if (collection.language !== void 0 && isLanguageTag(collection.language)) {
774
+ out.inLanguage = collection.language;
775
+ }
776
+ const elements = collection.items.slice(0, MAX_COLLECTION_ROWS).map((item, index) => listItem(item, index + 1));
777
+ out.numberOfItems = elements.length;
778
+ out.itemListElement = elements;
779
+ if (collection.updated !== void 0 && isIsoDate(collection.updated)) {
780
+ out.dateModified = collection.updated;
781
+ }
782
+ return out;
783
+ }
784
+
785
+ // src/compatibility.ts
786
+ var BASELINE_PROFILE = Object.freeze({
787
+ id: "baseline",
788
+ version: 1
789
+ });
790
+ var COMPATIBILITY_RUNTIME_VERSION = 1;
791
+ function validateCompatibilityProfile(value) {
792
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
793
+ const profile = value;
794
+ if (Object.keys(profile).some((key) => key !== "id" && key !== "version")) return null;
795
+ if (profile.version !== 1 || typeof profile.id !== "string" || !["baseline", "source-envelope", "section-index"].includes(profile.id))
796
+ return null;
797
+ return { id: profile.id, version: 1 };
798
+ }
799
+ function applyCompatibilityProfile(markdown, selected, options) {
800
+ const profile = validateCompatibilityProfile(selected) ?? BASELINE_PROFILE;
801
+ const baseline = { markdown, profile: { ...BASELINE_PROFILE } };
802
+ if (profile.id === "baseline") return baseline;
803
+ let prefix = "";
804
+ if (profile.id === "source-envelope") {
805
+ let canonical;
806
+ try {
807
+ canonical = new URL(options.canonicalUrl);
808
+ } catch {
809
+ return baseline;
810
+ }
811
+ if (!["https:", "http:"].includes(canonical.protocol) || canonical.username || canonical.password)
812
+ return baseline;
813
+ prefix = `Source: ${JSON.stringify(canonical.href)}
814
+
815
+ `;
816
+ } else {
817
+ const headings = markdown.split("\n").filter((line) => /^#{1,6} /.test(line)).slice(0, 12);
818
+ if (headings.length < 2) return baseline;
819
+ prefix = `Sections on this page:
820
+ ${headings.map((line) => `- ${line.replace(/^#{1,6} /, "")}`).join("\n")}
821
+
822
+ `;
823
+ }
824
+ const output = prefix + markdown;
825
+ const bytes = new TextEncoder().encode(output).byteLength;
826
+ if (new TextEncoder().encode(prefix).byteLength > 1024 || bytes > (options.maxBytes ?? 5120))
827
+ return baseline;
828
+ return { markdown: output, profile };
829
+ }
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 };
719
832
  //# sourceMappingURL=index.js.map
720
833
  //# sourceMappingURL=index.js.map