@rebilder/render-md 0.1.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.cjs ADDED
@@ -0,0 +1,737 @@
1
+ 'use strict';
2
+
3
+ // src/money.ts
4
+ var ZERO_DECIMAL = /* @__PURE__ */ new Set([
5
+ "BIF",
6
+ "CLP",
7
+ "DJF",
8
+ "GNF",
9
+ "ISK",
10
+ "JPY",
11
+ "KMF",
12
+ "KRW",
13
+ "MGA",
14
+ "PYG",
15
+ "RWF",
16
+ "UGX",
17
+ "VND",
18
+ "VUV",
19
+ "XAF",
20
+ "XOF",
21
+ "XPF"
22
+ ]);
23
+ var THREE_DECIMAL = /* @__PURE__ */ new Set(["BHD", "IQD", "JOD", "KWD", "LYD", "OMR", "TND"]);
24
+ var SYMBOLS = {
25
+ USD: "$",
26
+ EUR: "\u20AC",
27
+ GBP: "\xA3",
28
+ JPY: "\xA5"
29
+ };
30
+ function minorUnitDigits(code) {
31
+ if (ZERO_DECIMAL.has(code)) return 0;
32
+ if (THREE_DECIMAL.has(code)) return 3;
33
+ return 2;
34
+ }
35
+ function splitAmount(m) {
36
+ if (!Number.isInteger(m.amount)) {
37
+ throw new TypeError(
38
+ `Money.amount must be an integer number of minor units, got: ${String(m.amount)}`
39
+ );
40
+ }
41
+ const digits = minorUnitDigits(m.currency.toUpperCase());
42
+ const sign = m.amount < 0 ? "-" : "";
43
+ const abs = Math.abs(m.amount);
44
+ const factor = 10 ** digits;
45
+ const major = Math.floor(abs / factor).toString();
46
+ const frac = digits === 0 ? "" : `.${(abs % factor).toString().padStart(digits, "0")}`;
47
+ return { sign, major, frac };
48
+ }
49
+ function toDecimalString(m) {
50
+ const { sign, major, frac } = splitAmount(m);
51
+ return `${sign}${major}${frac}`;
52
+ }
53
+ function formatMoney(m) {
54
+ const { sign, major, frac } = splitAmount(m);
55
+ const code = m.currency.toUpperCase();
56
+ const grouped = major.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
57
+ const symbol = SYMBOLS[code];
58
+ return symbol !== void 0 ? `${sign}${symbol}${grouped}${frac}` : `${sign}${code} ${grouped}${frac}`;
59
+ }
60
+
61
+ // src/jsonld.ts
62
+ var SCHEMA_AVAILABILITY = {
63
+ in_stock: "https://schema.org/InStock",
64
+ out_of_stock: "https://schema.org/OutOfStock",
65
+ preorder: "https://schema.org/PreOrder",
66
+ backorder: "https://schema.org/BackOrder"
67
+ };
68
+ function offer(price, availability, extra) {
69
+ const o = {
70
+ "@type": "Offer",
71
+ price: toDecimalString(price),
72
+ priceCurrency: price.currency,
73
+ availability: SCHEMA_AVAILABILITY[availability]
74
+ };
75
+ if (extra.url !== void 0) o.url = extra.url;
76
+ if (extra.sku !== void 0) o.sku = extra.sku;
77
+ if (extra.name !== void 0) o.name = extra.name;
78
+ return o;
79
+ }
80
+ function renderProductJsonLd(p) {
81
+ const out = {
82
+ "@context": "https://schema.org",
83
+ "@type": "Product",
84
+ name: p.title,
85
+ url: p.url
86
+ };
87
+ if (p.brand !== void 0) out.brand = { "@type": "Brand", name: p.brand };
88
+ if (p.description !== void 0 && p.description.length > 0) out.description = p.description;
89
+ if (p.images !== void 0 && p.images.length > 0) out.image = p.images.map((img) => img.url);
90
+ 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 });
91
+ return out;
92
+ }
93
+
94
+ // src/internal/budget.ts
95
+ var DEFAULT_MAX_BYTES = 5120;
96
+ var TRUNCATION_NOTE = "*Truncated to fit size budget; remaining content omitted.*";
97
+ var encoder = new TextEncoder();
98
+ function byteLength(s) {
99
+ return encoder.encode(s).length;
100
+ }
101
+ function clampHeadingLevel(level) {
102
+ return Math.min(Math.max(Math.trunc(level), 1), 6);
103
+ }
104
+ function heading(level, text) {
105
+ return `${"#".repeat(clampHeadingLevel(level))} ${text}`;
106
+ }
107
+ function inline(text) {
108
+ return text.replace(/\s*\r?\n\s*/g, " ");
109
+ }
110
+ function cell(text) {
111
+ return inline(text).replace(/\|/g, "\\|");
112
+ }
113
+ function tailText(t) {
114
+ return `${t.headingLine}
115
+
116
+ ${t.items.join("\n")}`;
117
+ }
118
+ function assembleWithBudget(requiredBlocks, tail, maxBytes) {
119
+ const full = [...requiredBlocks, ...tail.map(tailText)].join("\n\n");
120
+ if (byteLength(full) <= maxBytes) return full;
121
+ const noteSuffix = `
122
+
123
+ ${TRUNCATION_NOTE}`;
124
+ const budget = maxBytes - byteLength(noteSuffix);
125
+ let out = requiredBlocks.join("\n\n");
126
+ for (const section of tail) {
127
+ const whole = `${out}
128
+
129
+ ${tailText(section)}`;
130
+ if (byteLength(whole) <= budget) {
131
+ out = whole;
132
+ continue;
133
+ }
134
+ let partial = `${out}
135
+
136
+ ${section.headingLine}`;
137
+ let added = 0;
138
+ for (const item of section.items) {
139
+ const next = `${partial}${added === 0 ? "\n\n" : "\n"}${item}`;
140
+ if (byteLength(next) > budget) break;
141
+ partial = next;
142
+ added += 1;
143
+ }
144
+ if (added > 0) out = partial;
145
+ break;
146
+ }
147
+ return `${out}${noteSuffix}`;
148
+ }
149
+
150
+ // src/markdown.ts
151
+ var AVAILABILITY_LABELS = {
152
+ in_stock: "In stock",
153
+ out_of_stock: "Out of stock",
154
+ preorder: "Preorder",
155
+ backorder: "Backorder"
156
+ };
157
+ function etaText(eta) {
158
+ const [min, max] = eta;
159
+ return min === max ? `${min} days` : `${min}-${max} days`;
160
+ }
161
+ function variantsTable(variants, level) {
162
+ const lines = [
163
+ heading(level, "Variants"),
164
+ "",
165
+ "| ID | Title | Options | Price | Availability |",
166
+ "| --- | --- | --- | --- | --- |"
167
+ ];
168
+ for (const v of variants) {
169
+ const options = v.options !== void 0 ? Object.entries(v.options).map(([key, value]) => `${cell(key)}: ${cell(value)}`).join("; ") : "";
170
+ lines.push(
171
+ `| ${cell(v.id)} | ${cell(v.title)} | ${options} | ${formatMoney(v.price)} | ${AVAILABILITY_LABELS[v.availability]} |`
172
+ );
173
+ }
174
+ return lines.join("\n");
175
+ }
176
+ function renderProductMarkdown(p, opts) {
177
+ const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES;
178
+ const level = clampHeadingLevel(opts?.headingLevel ?? 1);
179
+ const sub = clampHeadingLevel(level + 1);
180
+ const facts = [heading(level, `[${inline(p.title)}](${p.url})`), ""];
181
+ if (p.brand !== void 0) facts.push(`- **Brand:** ${inline(p.brand)}`);
182
+ const price = formatMoney(p.price);
183
+ facts.push(
184
+ p.compareAtPrice !== void 0 ? `- **Price:** ~~${formatMoney(p.compareAtPrice)}~~ ${price}` : `- **Price:** ${price}`
185
+ );
186
+ facts.push(`- **Availability:** ${AVAILABILITY_LABELS[p.availability]}`);
187
+ if (p.shipping !== void 0) {
188
+ facts.push(`- **Shipping:** ${inline(p.shipping.summary)}`);
189
+ if (p.shipping.freeThreshold !== void 0) {
190
+ facts.push(` - Free shipping threshold: ${formatMoney(p.shipping.freeThreshold)}`);
191
+ }
192
+ if (p.shipping.regions !== void 0 && p.shipping.regions.length > 0) {
193
+ facts.push(` - Ships to: ${p.shipping.regions.map(inline).join(", ")}`);
194
+ }
195
+ if (p.shipping.etaDays !== void 0) {
196
+ facts.push(` - Delivery estimate: ${etaText(p.shipping.etaDays)}`);
197
+ }
198
+ }
199
+ if (p.returns !== void 0) {
200
+ facts.push(`- **Returns:** ${inline(p.returns.summary)}`);
201
+ if (p.returns.windowDays !== void 0) {
202
+ facts.push(` - Return window: ${p.returns.windowDays} days`);
203
+ }
204
+ if (p.returns.url !== void 0) {
205
+ facts.push(` - Policy: ${p.returns.url}`);
206
+ }
207
+ }
208
+ const requiredBlocks = [facts.join("\n")];
209
+ if (p.variants !== void 0 && p.variants.length > 0) {
210
+ requiredBlocks.push(variantsTable(p.variants, sub));
211
+ }
212
+ const tail = [];
213
+ if (p.description !== void 0 && p.description.length > 0) {
214
+ tail.push({ headingLine: heading(sub, "Description"), items: p.description.split("\n") });
215
+ }
216
+ if (p.attributes !== void 0) {
217
+ const items = Object.entries(p.attributes).map(
218
+ ([key, value]) => `- **${inline(key)}:** ${inline(value)}`
219
+ );
220
+ if (items.length > 0) tail.push({ headingLine: heading(sub, "Details"), items });
221
+ }
222
+ if (p.images !== void 0 && p.images.length > 0) {
223
+ const items = p.images.map((img) => {
224
+ const label = img.alt !== void 0 && img.alt.length > 0 ? inline(img.alt) : img.url;
225
+ return `- [${label}](${img.url})`;
226
+ });
227
+ tail.push({ headingLine: heading(sub, "Images"), items });
228
+ }
229
+ return assembleWithBudget(requiredBlocks, tail, maxBytes);
230
+ }
231
+ function renderPolicyMarkdown(policies, opts) {
232
+ const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES;
233
+ const level = clampHeadingLevel(opts?.headingLevel ?? 1);
234
+ const titleLineFor = (pol) => heading(level, `[${inline(pol.title)}](${pol.url})`);
235
+ const blocks = policies.map((pol) => `${titleLineFor(pol)}
236
+
237
+ ${pol.body}`);
238
+ const full = blocks.join("\n\n");
239
+ if (byteLength(full) <= maxBytes) return full;
240
+ const noteSuffix = `
241
+
242
+ ${TRUNCATION_NOTE}`;
243
+ const budget = maxBytes - byteLength(noteSuffix);
244
+ let out = "";
245
+ for (const pol of policies) {
246
+ const titleLine = titleLineFor(pol);
247
+ const block = `${titleLine}
248
+
249
+ ${pol.body}`;
250
+ const withBlock = out === "" ? block : `${out}
251
+
252
+ ${block}`;
253
+ if (byteLength(withBlock) <= budget) {
254
+ out = withBlock;
255
+ continue;
256
+ }
257
+ const withTitle = out === "" ? titleLine : `${out}
258
+
259
+ ${titleLine}`;
260
+ if (byteLength(withTitle) <= budget) out = withTitle;
261
+ break;
262
+ }
263
+ return out === "" ? TRUNCATION_NOTE : `${out}${noteSuffix}`;
264
+ }
265
+ function renderCatalogMarkdown(items, opts) {
266
+ const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES;
267
+ const level = clampHeadingLevel(opts?.headingLevel ?? 1);
268
+ const head = [
269
+ heading(level, "Catalog"),
270
+ "",
271
+ "| Title | Price | Availability |",
272
+ "| --- | --- | --- |"
273
+ ].join("\n");
274
+ const rows = items.map(
275
+ (item) => `| [${cell(item.title)}](${item.url}) | ${formatMoney(item.price)} | ${AVAILABILITY_LABELS[item.availability]} |`
276
+ );
277
+ const full = [head, ...rows].join("\n");
278
+ if (byteLength(full) <= maxBytes) return full;
279
+ const noteSuffix = `
280
+
281
+ ${TRUNCATION_NOTE}`;
282
+ const budget = maxBytes - byteLength(noteSuffix);
283
+ let out = head;
284
+ for (const row of rows) {
285
+ const next = `${out}
286
+ ${row}`;
287
+ if (byteLength(next) > budget) break;
288
+ out = next;
289
+ }
290
+ return `${out}${noteSuffix}`;
291
+ }
292
+
293
+ // src/documents/facts.ts
294
+ var PERIOD_SUFFIX = {
295
+ one_time: "one-time",
296
+ hour: "per hour",
297
+ day: "per day",
298
+ week: "per week",
299
+ month: "per month",
300
+ quarter: "per quarter",
301
+ year: "per year"
302
+ };
303
+ var BOOLEAN_LABELS = {
304
+ true: "Yes",
305
+ false: "No"
306
+ };
307
+ var WEEKDAY_LABELS = {
308
+ monday: "Monday",
309
+ tuesday: "Tuesday",
310
+ wednesday: "Wednesday",
311
+ thursday: "Thursday",
312
+ friday: "Friday",
313
+ saturday: "Saturday",
314
+ sunday: "Sunday"
315
+ };
316
+ var WEEKDAY_ORDER = [
317
+ "monday",
318
+ "tuesday",
319
+ "wednesday",
320
+ "thursday",
321
+ "friday",
322
+ "saturday",
323
+ "sunday"
324
+ ];
325
+ var CLOSED_LABEL = "Closed";
326
+ var NOT_STATED_LABEL = "Not stated";
327
+ var SEE_PAGE_LABEL = "See page";
328
+ var UPDATED_LABEL = "Updated";
329
+ var PHONE_LABEL = "Phone";
330
+ var EMAIL_LABEL = "Email";
331
+ var ADDRESS_LABEL = "Address";
332
+ var DAY_LABEL = "Day";
333
+ var DATE_LABEL = "Date";
334
+ var HOURS_LABEL = "Hours";
335
+ var NOTE_LABEL = "Note";
336
+ var TITLE_LABEL = "Title";
337
+ var EXCEPTIONS_HEADING = "Exceptions";
338
+ var CONTACT_HEADING = "Contact";
339
+ var ACTIONS_HEADING = "Actions";
340
+ var RELATED_HEADING = "Related";
341
+ var CONTENTS_HEADING = "Contents";
342
+ var ACCESS_LABELS = {
343
+ free: "free",
344
+ registered: "registration required",
345
+ metered: "metered",
346
+ subscriber: "subscription required"
347
+ };
348
+ function accessNotice(access) {
349
+ return `*Full text is not served to agents at this URL (access: ${ACCESS_LABELS[access]}).*`;
350
+ }
351
+ function timeZoneSentence(timeZone) {
352
+ return `All times are local to ${inline(timeZone)}.`;
353
+ }
354
+ var ALLOWED_URL_SCHEMES = ["https:", "http:", "mailto:", "tel:"];
355
+ function isAllowedUrl(raw) {
356
+ let parsed;
357
+ try {
358
+ parsed = new URL(raw);
359
+ } catch {
360
+ return false;
361
+ }
362
+ return ALLOWED_URL_SCHEMES.includes(parsed.protocol);
363
+ }
364
+ function linkLabel(text) {
365
+ return inline(text).replace(/[\]()]/g, (c) => `\\${c}`);
366
+ }
367
+ function markdownLink(label, url) {
368
+ return `[${linkLabel(label)}](${url})`;
369
+ }
370
+ function cellLink(label, url) {
371
+ return markdownLink(label, url).replace(/\|/g, "\\|");
372
+ }
373
+ var ISO_DATE = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})?)?$/;
374
+ function isIsoDate(value) {
375
+ return ISO_DATE.test(value) && !Number.isNaN(Date.parse(value));
376
+ }
377
+ function isIsoDay(value) {
378
+ return /^\d{4}-\d{2}-\d{2}$/.test(value) && !Number.isNaN(Date.parse(value));
379
+ }
380
+ var HH_MM = /^([01]\d|2[0-3]):[0-5]\d$/;
381
+ function isValidInterval(i) {
382
+ return HH_MM.test(i.opens) && HH_MM.test(i.closes) && i.closes > i.opens;
383
+ }
384
+ function intervalsText(intervals) {
385
+ return intervals.map((i) => `${i.opens}-${i.closes}`).join(", ");
386
+ }
387
+ function numberText(value, unit) {
388
+ if (!Number.isFinite(value)) return null;
389
+ const text = String(value);
390
+ if (text.includes("e") || text.includes("E")) return null;
391
+ return unit !== void 0 ? `${text} ${inline(unit)}` : text;
392
+ }
393
+ function moneyText(v) {
394
+ let text = formatMoney(v.value);
395
+ if (v.maxValue !== void 0) {
396
+ if (v.maxValue.currency.toUpperCase() !== v.value.currency.toUpperCase()) {
397
+ throw new TypeError(
398
+ `Money range currencies must match, got: ${v.value.currency} and ${v.maxValue.currency}`
399
+ );
400
+ }
401
+ if (v.maxValue.amount < v.value.amount) {
402
+ throw new TypeError(
403
+ `Money range maxValue must not be below value, got: ${String(v.value.amount)} and ${String(v.maxValue.amount)}`
404
+ );
405
+ }
406
+ text = `${text}-${formatMoney(v.maxValue)}`;
407
+ }
408
+ if (v.period !== void 0) text = `${text} ${PERIOD_SUFFIX[v.period]}`;
409
+ if (v.per !== void 0) text = `${text} ${inline(v.per)}`;
410
+ return text;
411
+ }
412
+ function factValueText(value) {
413
+ switch (value.type) {
414
+ case "text":
415
+ return inline(value.value);
416
+ case "list":
417
+ return value.value.length > 0 ? value.value.map(inline).join(", ") : null;
418
+ case "number":
419
+ return numberText(value.value, value.unit);
420
+ case "boolean":
421
+ return BOOLEAN_LABELS[value.value ? "true" : "false"];
422
+ case "money":
423
+ return moneyText(value);
424
+ case "date":
425
+ return isIsoDate(value.value) ? value.value : null;
426
+ case "url":
427
+ if (!isAllowedUrl(value.value)) return null;
428
+ return value.label !== void 0 ? markdownLink(value.label, value.value) : value.value;
429
+ case "hours":
430
+ return null;
431
+ }
432
+ }
433
+ function renderFactLine(fact) {
434
+ const text = factValueText(fact.value);
435
+ if (text === null) return null;
436
+ const line = `- **${inline(fact.label)}:** ${text}`;
437
+ return fact.note !== void 0 ? `${line}
438
+ - ${inline(fact.note)}` : line;
439
+ }
440
+ function factCellText(value, itemUrl) {
441
+ if (value.type === "hours") {
442
+ return isAllowedUrl(itemUrl) ? cellLink(SEE_PAGE_LABEL, itemUrl) : SEE_PAGE_LABEL;
443
+ }
444
+ if (value.type === "url") {
445
+ if (!isAllowedUrl(value.value)) return null;
446
+ return value.label !== void 0 ? cellLink(value.label, value.value) : value.value.replace(/\|/g, "\\|");
447
+ }
448
+ const text = factValueText(value);
449
+ return text === null ? null : cell(text);
450
+ }
451
+ function exceptionRow(e) {
452
+ if (!isIsoDay(e.date)) return null;
453
+ let hours;
454
+ if (e.closed === true) {
455
+ hours = CLOSED_LABEL;
456
+ } else if (e.intervals !== void 0 && e.intervals.length > 0) {
457
+ if (!e.intervals.every(isValidInterval)) return null;
458
+ hours = intervalsText(e.intervals);
459
+ } else if (e.intervals !== void 0) {
460
+ hours = CLOSED_LABEL;
461
+ } else {
462
+ hours = NOT_STATED_LABEL;
463
+ }
464
+ const note = e.note !== void 0 ? cell(e.note) : "";
465
+ return `| ${e.date} | ${hours} | ${note} |`;
466
+ }
467
+ function renderHoursBlock(label, spec, level, subLevel) {
468
+ if (typeof spec.timeZone !== "string" || spec.timeZone.trim() === "") return null;
469
+ const byDay = /* @__PURE__ */ new Map();
470
+ for (const rule of spec.weekly) {
471
+ if (!rule.intervals.every(isValidInterval)) return null;
472
+ byDay.set(rule.day, rule.intervals);
473
+ }
474
+ const lines = [
475
+ heading(level, inline(label)),
476
+ "",
477
+ timeZoneSentence(spec.timeZone),
478
+ "",
479
+ `| ${DAY_LABEL} | ${HOURS_LABEL} |`,
480
+ "| --- | --- |"
481
+ ];
482
+ for (const day of WEEKDAY_ORDER) {
483
+ const intervals = byDay.get(day);
484
+ const text = intervals === void 0 ? NOT_STATED_LABEL : intervals.length === 0 ? CLOSED_LABEL : intervalsText(intervals);
485
+ lines.push(`| ${WEEKDAY_LABELS[day]} | ${text} |`);
486
+ }
487
+ if (spec.note !== void 0) {
488
+ lines.push("", `- **${NOTE_LABEL}:** ${inline(spec.note)}`);
489
+ }
490
+ const exceptionRows = (spec.exceptions ?? []).map(exceptionRow).filter((row) => row !== null);
491
+ if (exceptionRows.length > 0) {
492
+ lines.push(
493
+ "",
494
+ heading(subLevel, EXCEPTIONS_HEADING),
495
+ "",
496
+ `| ${DATE_LABEL} | ${HOURS_LABEL} | ${NOTE_LABEL} |`,
497
+ "| --- | --- | --- |",
498
+ ...exceptionRows
499
+ );
500
+ }
501
+ return lines.join("\n");
502
+ }
503
+
504
+ // src/documents/markdown.ts
505
+ var MAX_FACTS = 60;
506
+ var MAX_ACTIONS = 20;
507
+ var MAX_COLLECTION_ROWS = 500;
508
+ var MAX_COLLECTION_COLUMNS = 12;
509
+ var HARD_CEILING_MULTIPLE = 4;
510
+ function applyHardCeiling(out, maxBytes) {
511
+ const ceiling = maxBytes * HARD_CEILING_MULTIPLE;
512
+ if (byteLength(out) <= ceiling) return out;
513
+ const noteSuffix = `
514
+
515
+ ${TRUNCATION_NOTE}`;
516
+ const budget = ceiling - byteLength(noteSuffix);
517
+ let kept = "";
518
+ for (const line of out.split("\n")) {
519
+ const next = kept === "" ? line : `${kept}
520
+ ${line}`;
521
+ if (byteLength(next) > budget) break;
522
+ kept = next;
523
+ }
524
+ return kept === "" ? TRUNCATION_NOTE : `${kept}${noteSuffix}`;
525
+ }
526
+ function blockquote(text) {
527
+ return text.split("\n").map((line) => line.length > 0 ? `> ${line}` : ">");
528
+ }
529
+ function sectionTail(section, level) {
530
+ const lines = section.body.split("\n");
531
+ if (section.heading !== void 0 && section.heading.length > 0) {
532
+ return { headingLine: heading(level, inline(section.heading)), items: lines };
533
+ }
534
+ const rest = lines.slice(1);
535
+ if (rest[0] === "") rest.shift();
536
+ return { headingLine: lines[0] ?? "", items: rest };
537
+ }
538
+ function renderDocumentMarkdown(doc, opts) {
539
+ const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES;
540
+ const level = clampHeadingLevel(opts?.headingLevel ?? 1);
541
+ const sub = clampHeadingLevel(level + 1);
542
+ const subSub = clampHeadingLevel(sub + 1);
543
+ const access = doc.access ?? "free";
544
+ const titleText = isAllowedUrl(doc.url) ? markdownLink(doc.title, doc.url) : linkLabel(doc.title);
545
+ const updated = doc.updated !== void 0 && isIsoDate(doc.updated) ? doc.updated : void 0;
546
+ const facts = (doc.facts ?? []).slice(0, MAX_FACTS);
547
+ const factLines = [];
548
+ if (updated !== void 0) factLines.push(`- **${UPDATED_LABEL}:** ${updated}`);
549
+ for (const fact of facts) {
550
+ if (updated !== void 0 && fact.label.trim().toLowerCase() === UPDATED_LABEL.toLowerCase()) {
551
+ continue;
552
+ }
553
+ const line = renderFactLine(fact);
554
+ if (line !== null) factLines.push(line);
555
+ }
556
+ const head = [heading(level, titleText)];
557
+ if (doc.summary !== void 0 && doc.summary.length > 0) {
558
+ head.push("", ...blockquote(doc.summary));
559
+ }
560
+ if (factLines.length > 0) head.push("", ...factLines);
561
+ const requiredBlocks = [head.join("\n")];
562
+ for (const fact of facts) {
563
+ if (fact.value.type !== "hours") continue;
564
+ const block = renderHoursBlock(fact.label, fact.value.value, sub, subSub);
565
+ if (block !== null) requiredBlocks.push(block);
566
+ }
567
+ const contactLines = [];
568
+ const contact = doc.contact;
569
+ if (contact !== void 0) {
570
+ if (contact.phone !== void 0) contactLines.push(`- **${PHONE_LABEL}:** ${inline(contact.phone)}`);
571
+ if (contact.email !== void 0) contactLines.push(`- **${EMAIL_LABEL}:** ${inline(contact.email)}`);
572
+ if (contact.address !== void 0 && contact.address.length > 0) {
573
+ contactLines.push(`- **${ADDRESS_LABEL}:** ${contact.address.map(inline).join(", ")}`);
574
+ }
575
+ if (contact.url !== void 0 && isAllowedUrl(contact.url)) contactLines.push(`- ${contact.url}`);
576
+ }
577
+ if (contactLines.length > 0) {
578
+ requiredBlocks.push([heading(sub, CONTACT_HEADING), "", ...contactLines].join("\n"));
579
+ }
580
+ const actionLines = [];
581
+ for (const action of (doc.actions ?? []).slice(0, MAX_ACTIONS)) {
582
+ if (!isAllowedUrl(action.url)) continue;
583
+ actionLines.push(`- ${markdownLink(action.label, action.url)}`);
584
+ if (action.note !== void 0) actionLines.push(` - ${inline(action.note)}`);
585
+ }
586
+ if (actionLines.length > 0) {
587
+ requiredBlocks.push([heading(sub, ACTIONS_HEADING), "", ...actionLines].join("\n"));
588
+ }
589
+ if (access !== "free") requiredBlocks.push(accessNotice(access));
590
+ const tail = [];
591
+ if (access === "free") {
592
+ for (const section of doc.sections ?? []) tail.push(sectionTail(section, sub));
593
+ }
594
+ const relatedItems = [];
595
+ for (const link of doc.related ?? []) {
596
+ if (!isAllowedUrl(link.url)) continue;
597
+ relatedItems.push(`- ${markdownLink(link.title, link.url)}`);
598
+ if (link.note !== void 0) relatedItems.push(` - ${inline(link.note)}`);
599
+ }
600
+ if (relatedItems.length > 0) {
601
+ tail.push({ headingLine: heading(sub, RELATED_HEADING), items: relatedItems });
602
+ }
603
+ return applyHardCeiling(assembleWithBudget(requiredBlocks, tail, maxBytes), maxBytes);
604
+ }
605
+ function rowBytes(cellByteSum, columnCount) {
606
+ return cellByteSum + 3 * columnCount + 1;
607
+ }
608
+ function tableRow(cells) {
609
+ return `| ${cells.join(" | ")} |`;
610
+ }
611
+ function itemCells(item) {
612
+ const cells = [];
613
+ if (item.summary !== void 0 && item.summary.length > 0) {
614
+ cells.push({ label: NOTE_LABEL, text: cell(item.summary) });
615
+ }
616
+ for (const fact of item.facts ?? []) {
617
+ const text = factCellText(fact.value, item.url);
618
+ if (text === null) continue;
619
+ cells.push({ label: cell(fact.label), text });
620
+ }
621
+ return cells;
622
+ }
623
+ function titleCell(item) {
624
+ return isAllowedUrl(item.url) ? cellLink(item.title, item.url) : cell(item.title);
625
+ }
626
+ function renderCollectionMarkdown(collection, opts) {
627
+ const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES;
628
+ const level = clampHeadingLevel(opts?.headingLevel ?? 1);
629
+ const title = collection.title !== void 0 ? collection.title : CONTENTS_HEADING;
630
+ const titleText = isAllowedUrl(collection.url) ? markdownLink(title, collection.url) : linkLabel(title);
631
+ const head = heading(level, titleText);
632
+ const items = collection.items;
633
+ if (items.length === 0) return head;
634
+ const noteSuffix = `
635
+
636
+ ${TRUNCATION_NOTE}`;
637
+ const budget = maxBytes - byteLength(noteSuffix);
638
+ const anyFacts = items.some((item) => (item.facts ?? []).length > 0);
639
+ if (!anyFacts) return linkList(head, items, budget);
640
+ const columns = [];
641
+ const rows = [];
642
+ let headerCellBytes = byteLength(TITLE_LABEL);
643
+ let bodyCellBytes = 0;
644
+ let truncated = false;
645
+ const base = byteLength(head) + 2;
646
+ const totalBytes = (columnCount, rowCount) => base + rowBytes(headerCellBytes, columnCount) + 1 + rowBytes(3 * columnCount, columnCount) + bodyCellBytes + rowCount * (3 * columnCount + 2);
647
+ for (const item of items) {
648
+ if (rows.length >= MAX_COLLECTION_ROWS) {
649
+ truncated = true;
650
+ break;
651
+ }
652
+ const cells = itemCells(item);
653
+ const values = /* @__PURE__ */ new Map();
654
+ const newColumns = [];
655
+ for (const { label, text } of cells) {
656
+ if (values.has(label)) continue;
657
+ if (!columns.includes(label) && !newColumns.includes(label)) {
658
+ if (columns.length + newColumns.length >= MAX_COLLECTION_COLUMNS) continue;
659
+ newColumns.push(label);
660
+ }
661
+ values.set(label, text);
662
+ }
663
+ values.set(TITLE_LABEL, titleCell(item));
664
+ const nextColumnCount = 1 + columns.length + newColumns.length;
665
+ const addedHeaderBytes = newColumns.reduce((sum, label) => sum + byteLength(label), 0);
666
+ const addedBodyBytes = [...values.values()].reduce((sum, text) => sum + byteLength(text), 0);
667
+ const savedHeader = headerCellBytes;
668
+ const savedBody = bodyCellBytes;
669
+ headerCellBytes += addedHeaderBytes;
670
+ bodyCellBytes += addedBodyBytes;
671
+ if (totalBytes(nextColumnCount, rows.length + 1) > budget) {
672
+ headerCellBytes = savedHeader;
673
+ bodyCellBytes = savedBody;
674
+ truncated = true;
675
+ break;
676
+ }
677
+ columns.push(...newColumns);
678
+ rows.push(values);
679
+ }
680
+ if (rows.length === 0) return `${head}${noteSuffix}`;
681
+ const header = [TITLE_LABEL, ...columns];
682
+ const lines = [
683
+ head,
684
+ "",
685
+ tableRow(header),
686
+ tableRow(header.map(() => "---")),
687
+ ...rows.map((values) => tableRow(header.map((label) => values.get(label) ?? "")))
688
+ ];
689
+ const out = lines.join("\n");
690
+ return truncated ? `${out}${noteSuffix}` : out;
691
+ }
692
+ function linkList(head, items, budget) {
693
+ const noteSuffix = `
694
+
695
+ ${TRUNCATION_NOTE}`;
696
+ let out = head;
697
+ let truncated = false;
698
+ let rendered = 0;
699
+ for (const item of items) {
700
+ if (rendered >= MAX_COLLECTION_ROWS) {
701
+ truncated = true;
702
+ break;
703
+ }
704
+ const link = isAllowedUrl(item.url) ? markdownLink(item.title, item.url) : inline(item.title);
705
+ const entry = [`- ${link}`];
706
+ if (item.summary !== void 0 && item.summary.length > 0) {
707
+ entry.push(` - ${inline(item.summary)}`);
708
+ }
709
+ const next = `${out}${rendered === 0 ? "\n\n" : "\n"}${entry.join("\n")}`;
710
+ if (byteLength(next) > budget) {
711
+ truncated = true;
712
+ break;
713
+ }
714
+ out = next;
715
+ rendered += 1;
716
+ }
717
+ return truncated ? `${out}${noteSuffix}` : out;
718
+ }
719
+
720
+ exports.ACCESS_LABELS = ACCESS_LABELS;
721
+ exports.ALLOWED_URL_SCHEMES = ALLOWED_URL_SCHEMES;
722
+ exports.BOOLEAN_LABELS = BOOLEAN_LABELS;
723
+ exports.CLOSED_LABEL = CLOSED_LABEL;
724
+ exports.NOT_STATED_LABEL = NOT_STATED_LABEL;
725
+ exports.PERIOD_SUFFIX = PERIOD_SUFFIX;
726
+ exports.SEE_PAGE_LABEL = SEE_PAGE_LABEL;
727
+ exports.WEEKDAY_LABELS = WEEKDAY_LABELS;
728
+ exports.WEEKDAY_ORDER = WEEKDAY_ORDER;
729
+ exports.formatMoney = formatMoney;
730
+ exports.renderCatalogMarkdown = renderCatalogMarkdown;
731
+ exports.renderCollectionMarkdown = renderCollectionMarkdown;
732
+ exports.renderDocumentMarkdown = renderDocumentMarkdown;
733
+ exports.renderPolicyMarkdown = renderPolicyMarkdown;
734
+ exports.renderProductJsonLd = renderProductJsonLd;
735
+ exports.renderProductMarkdown = renderProductMarkdown;
736
+ //# sourceMappingURL=index.cjs.map
737
+ //# sourceMappingURL=index.cjs.map