@aglyn/aglyn 1.16.0 → 1.17.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.
@@ -34,6 +34,15 @@
34
34
  export declare const NODE_COLOR_SCHEME_PROP = "colorScheme";
35
35
  /** "Match the site": follow the visitor's scheme, as if the prop were unset. */
36
36
  export declare const ELEMENT_COLOR_SCHEME_SITE = "site";
37
+ /**
38
+ * Back to the visitor's own scheme inside a part of the page pinned to the
39
+ * other one (AGL-4152). Never offered in the Color scheme field, so no author
40
+ * and no model picks it: the AI layout compiler writes it on a filled button
41
+ * inside a band pinned dark, so that button wears the same primary as every
42
+ * other filled button on the site, light or dark, as the visitor picked. It
43
+ * paints nothing of its own, so the band shows at the button's rounded corners.
44
+ */
45
+ export declare const ELEMENT_COLOR_SCHEME_VISITOR = "visitor";
37
46
  export type ElementColorScheme = 'light' | 'dark';
38
47
  /**
39
48
  * The scheme an element is pinned to, or `undefined` when it follows the site.
@@ -30,6 +30,14 @@
30
30
  * attribute and one switched back to "Match the site" render identically.
31
31
  */ /** The node prop carrying the pinned scheme. */ export const NODE_COLOR_SCHEME_PROP = 'colorScheme';
32
32
  /** "Match the site": follow the visitor's scheme, as if the prop were unset. */ export const ELEMENT_COLOR_SCHEME_SITE = 'site';
33
+ /**
34
+ * Back to the visitor's own scheme inside a part of the page pinned to the
35
+ * other one (AGL-4152). Never offered in the Color scheme field, so no author
36
+ * and no model picks it: the AI layout compiler writes it on a filled button
37
+ * inside a band pinned dark, so that button wears the same primary as every
38
+ * other filled button on the site, light or dark, as the visitor picked. It
39
+ * paints nothing of its own, so the band shows at the button's rounded corners.
40
+ */ export const ELEMENT_COLOR_SCHEME_VISITOR = 'visitor';
33
41
  /**
34
42
  * The scheme an element is pinned to, or `undefined` when it follows the site.
35
43
  * Anything other than `light`/`dark` — the sentinel, a cleared `null`, a
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/element-color-scheme.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An element's pinned color scheme (AGL-3284).\n *\n * A layout element — Section, Container, Stack, Box, Grid — may say \"Always\n * light\" or \"Always dark\", and everything inside it then renders with the\n * site's theme for that scheme, whatever the visitor picked: palette tokens\n * (`background.default`, `text.primary`, `divider`, …) and every node's\n * `@scheme dark` sx slice resolve for the pinned scheme. The renderer's leaf\n * consumes the prop; it never reaches the DOM or the MUI component.\n *\n * Stored as a real value for all three choices. \"Match the site\" is the\n * {@link ELEMENT_COLOR_SCHEME_SITE} sentinel rather than `''`, because an empty\n * option value cannot survive the attributes form's save (AGL-1453) — and it\n * resolves exactly like a missing prop, so an element that never had the\n * attribute and one switched back to \"Match the site\" render identically.\n */\n\n/** The node prop carrying the pinned scheme. */\nexport const NODE_COLOR_SCHEME_PROP = 'colorScheme'\n\n/** \"Match the site\": follow the visitor's scheme, as if the prop were unset. */\nexport const ELEMENT_COLOR_SCHEME_SITE = 'site'\n\nexport type ElementColorScheme = 'light' | 'dark'\n\n/**\n * The scheme an element is pinned to, or `undefined` when it follows the site.\n * Anything other than `light`/`dark` — the sentinel, a cleared `null`, a\n * stray paste — follows the site.\n */\nexport function resolveElementColorScheme(\n value: unknown,\n): ElementColorScheme | undefined {\n return value === 'light' || value === 'dark' ? value : undefined\n}\n"],"names":["NODE_COLOR_SCHEME_PROP","ELEMENT_COLOR_SCHEME_SITE","resolveElementColorScheme","value","undefined"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;CAeC,GAED,8CAA8C,GAC9C,OAAO,MAAMA,yBAAyB,cAAa;AAEnD,8EAA8E,GAC9E,OAAO,MAAMC,4BAA4B,OAAM;AAI/C;;;;CAIC,GACD,OAAO,SAASC,0BACdC,KAAc;IAEd,OAAOA,UAAU,WAAWA,UAAU,SAASA,QAAQC;AACzD"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/element-color-scheme.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An element's pinned color scheme (AGL-3284).\n *\n * A layout element — Section, Container, Stack, Box, Grid — may say \"Always\n * light\" or \"Always dark\", and everything inside it then renders with the\n * site's theme for that scheme, whatever the visitor picked: palette tokens\n * (`background.default`, `text.primary`, `divider`, …) and every node's\n * `@scheme dark` sx slice resolve for the pinned scheme. The renderer's leaf\n * consumes the prop; it never reaches the DOM or the MUI component.\n *\n * Stored as a real value for all three choices. \"Match the site\" is the\n * {@link ELEMENT_COLOR_SCHEME_SITE} sentinel rather than `''`, because an empty\n * option value cannot survive the attributes form's save (AGL-1453) — and it\n * resolves exactly like a missing prop, so an element that never had the\n * attribute and one switched back to \"Match the site\" render identically.\n */\n\n/** The node prop carrying the pinned scheme. */\nexport const NODE_COLOR_SCHEME_PROP = 'colorScheme'\n\n/** \"Match the site\": follow the visitor's scheme, as if the prop were unset. */\nexport const ELEMENT_COLOR_SCHEME_SITE = 'site'\n\n/**\n * Back to the visitor's own scheme inside a part of the page pinned to the\n * other one (AGL-4152). Never offered in the Color scheme field, so no author\n * and no model picks it: the AI layout compiler writes it on a filled button\n * inside a band pinned dark, so that button wears the same primary as every\n * other filled button on the site, light or dark, as the visitor picked. It\n * paints nothing of its own, so the band shows at the button's rounded corners.\n */\nexport const ELEMENT_COLOR_SCHEME_VISITOR = 'visitor'\n\nexport type ElementColorScheme = 'light' | 'dark'\n\n/**\n * The scheme an element is pinned to, or `undefined` when it follows the site.\n * Anything other than `light`/`dark` — the sentinel, a cleared `null`, a\n * stray paste — follows the site.\n */\nexport function resolveElementColorScheme(\n value: unknown,\n): ElementColorScheme | undefined {\n return value === 'light' || value === 'dark' ? value : undefined\n}\n"],"names":["NODE_COLOR_SCHEME_PROP","ELEMENT_COLOR_SCHEME_SITE","ELEMENT_COLOR_SCHEME_VISITOR","resolveElementColorScheme","value","undefined"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;CAeC,GAED,8CAA8C,GAC9C,OAAO,MAAMA,yBAAyB,cAAa;AAEnD,8EAA8E,GAC9E,OAAO,MAAMC,4BAA4B,OAAM;AAE/C;;;;;;;CAOC,GACD,OAAO,MAAMC,+BAA+B,UAAS;AAIrD;;;;CAIC,GACD,OAAO,SAASC,0BACdC,KAAc;IAEd,OAAOA,UAAU,WAAWA,UAAU,SAASA,QAAQC;AACzD"}
@@ -27,7 +27,27 @@ export type MarkdownInline = {
27
27
  type: 'link';
28
28
  text: string;
29
29
  href: string;
30
+ }
31
+ /**
32
+ * `inline code` — emitted ONLY when the caller opts in with
33
+ * {@link MarkdownLiteOptions.inlineCode}. A plugin README names settings,
34
+ * hosts and scopes in backticks; a site's blog post and the visual editor
35
+ * never asked for it, so their parse is unchanged and a backtick there stays
36
+ * the character it was typed as.
37
+ */
38
+ | {
39
+ type: 'code';
40
+ text: string;
30
41
  };
42
+ /**
43
+ * Parse options for {@link parseMarkdownLite}. Every option is OFF unless a
44
+ * caller names it, so a site renderer and the visual editor keep the dialect
45
+ * they were built for.
46
+ */
47
+ export interface MarkdownLiteOptions {
48
+ /** Read a backtick-delimited run as inline code (a listing README, AGL-4197). */
49
+ inlineCode?: boolean;
50
+ }
31
51
  /** A table cell's content. Cells hold inline runs only — no nesting. */
32
52
  export type MarkdownTableCell = MarkdownInline[];
33
53
  export type MarkdownTableAlign = 'left' | 'center' | 'right';
@@ -177,14 +197,14 @@ export declare function resolveMarkdownLink(href: string, context?: {
177
197
  screens?: Record<string, string> | null;
178
198
  suppressNavigation?: boolean;
179
199
  }): MarkdownLinkResolution;
180
- export declare function parseMarkdownInlines(text: string): MarkdownInline[];
200
+ export declare function parseMarkdownInlines(text: string, options?: MarkdownLiteOptions): MarkdownInline[];
181
201
  /**
182
202
  * Blocks are blank-line separated, EXCEPT inside a ``` fence — a code
183
203
  * block owns its blank lines, so the scan is line-driven rather than a
184
204
  * split on `\n{2,}` (AGL-974). An unterminated fence runs to the end of
185
205
  * the document, which is what a README truncated mid-snippet needs.
186
206
  */
187
- export declare function parseMarkdownLite(body: string): MarkdownBlock[];
207
+ export declare function parseMarkdownLite(body: string, options?: MarkdownLiteOptions): MarkdownBlock[];
188
208
  /**
189
209
  * Markdown-lite SOURCE with its link references resolved (AGL-3118), for a
190
210
  * reader that hands the source on instead of rendering it — the Markdown twin
@@ -195,7 +195,32 @@ const INLINE_PATTERN = /(\*\*([^*]+)\*\*)|(\*([^*]+)\*)|(\[([^\]]+)\]\(([^)\s]+)
195
195
  text
196
196
  });
197
197
  }
198
- export function parseMarkdownInlines(text) {
198
+ /** One backtick-delimited run on a single line — no escapes, no nesting. */ const INLINE_CODE_PATTERN = /`([^`\n]+)`/g;
199
+ export function parseMarkdownInlines(text, options = {}) {
200
+ if (!options.inlineCode || !text.includes('`')) return parseEmphasis(text);
201
+ // Code first, so `**not bold**` inside backticks stays the characters it is.
202
+ const inlines = [];
203
+ let cursor = 0;
204
+ for (const match of text.matchAll(INLINE_CODE_PATTERN)){
205
+ var _match_index, _match_;
206
+ const index = (_match_index = match.index) != null ? _match_index : 0;
207
+ appendInlines(inlines, parseEmphasis(text.slice(cursor, index)));
208
+ inlines.push({
209
+ type: 'code',
210
+ text: (_match_ = match[1]) != null ? _match_ : ''
211
+ });
212
+ cursor = index + match[0].length;
213
+ }
214
+ appendInlines(inlines, parseEmphasis(text.slice(cursor)));
215
+ return inlines;
216
+ }
217
+ /** Appends a run, merging a leading text inline into a trailing one. */ function appendInlines(into, run) {
218
+ for (const inline of run){
219
+ if (inline.type === 'text') pushText(into, inline.text);
220
+ else into.push(inline);
221
+ }
222
+ }
223
+ function parseEmphasis(text) {
199
224
  const inlines = [];
200
225
  let cursor = 0;
201
226
  for (const match of text.matchAll(INLINE_PATTERN)){
@@ -284,18 +309,18 @@ function alignOfDelimiter(cell) {
284
309
  * still a paragraph. Cells are squared off to the header's width: ragged
285
310
  * rows pad with empty cells and overflow is dropped, so the model the
286
311
  * serializer writes back re-parses to itself.
287
- */ function parseTable(lines) {
312
+ */ function parseTable(lines, options) {
288
313
  const [headerLine, delimiterLine] = lines;
289
314
  if (!headerLine || !delimiterLine || !headerLine.includes('|')) return null;
290
315
  const delimiters = splitTableRow(delimiterLine);
291
316
  if (!delimiters.every((cell)=>DELIMITER_CELL.test(cell))) return null;
292
- const header = splitTableRow(headerLine).map(parseMarkdownInlines);
317
+ const header = splitTableRow(headerLine).map((cell)=>parseMarkdownInlines(cell, options));
293
318
  const columns = header.length;
294
319
  const squared = (cells)=>Array.from({
295
320
  length: columns
296
321
  }, (_, index)=>{
297
322
  var _cells_index;
298
- return parseMarkdownInlines((_cells_index = cells[index]) != null ? _cells_index : '');
323
+ return parseMarkdownInlines((_cells_index = cells[index]) != null ? _cells_index : '', options);
299
324
  });
300
325
  return {
301
326
  type: 'table',
@@ -343,7 +368,7 @@ function alignOfDelimiter(cell) {
343
368
  * first line that is not an item; whatever follows starts a fresh paragraph,
344
369
  * which a later list may interrupt in turn. The serializer writes the pieces
345
370
  * back as separate blank-line-delimited chunks, so the split round-trips.
346
- */ function parseChunk(chunk) {
371
+ */ function parseChunk(chunk, options) {
347
372
  const trimmed = chunk.trim();
348
373
  if (!trimmed) return [];
349
374
  const image = /^!\[([^\]]*)\]\(([^)\s]+)\)$/.exec(trimmed);
@@ -363,12 +388,12 @@ function alignOfDelimiter(cell) {
363
388
  {
364
389
  type: 'heading',
365
390
  level: clampHeadingLevel(heading[1].length),
366
- inlines: parseMarkdownInlines(heading[2])
391
+ inlines: parseMarkdownInlines(heading[2], options)
367
392
  }
368
393
  ];
369
394
  }
370
395
  const lines = trimmed.split('\n');
371
- const table = parseTable(lines);
396
+ const table = parseTable(lines, options);
372
397
  if (table) return [
373
398
  table
374
399
  ];
@@ -383,7 +408,7 @@ function alignOfDelimiter(cell) {
383
408
  return [
384
409
  {
385
410
  type: 'quote',
386
- inlines: parseMarkdownInlines(text)
411
+ inlines: parseMarkdownInlines(text, options)
387
412
  }
388
413
  ];
389
414
  }
@@ -395,7 +420,7 @@ function alignOfDelimiter(cell) {
395
420
  if (prose.length) {
396
421
  blocks.push({
397
422
  type: 'paragraph',
398
- inlines: parseMarkdownInlines(prose.join(' '))
423
+ inlines: parseMarkdownInlines(prose.join(' '), options)
399
424
  });
400
425
  }
401
426
  prose = [];
@@ -416,21 +441,30 @@ function alignOfDelimiter(cell) {
416
441
  // bullet closes a numbered run and vice versa. Only the FIRST ordered
417
442
  // marker is read, which is why a source numbered `1. 1. 1.` renumbers on
418
443
  // the way out.
444
+ //
445
+ // An INDENTED line that is not an item continues the item above it
446
+ // (AGL-4197): a README wraps a long item at 80 columns and indents the
447
+ // rest under the text, and splitting there broke one list into a list, a
448
+ // stray paragraph and a second list. An unindented line still ends the
449
+ // run and starts the next paragraph, as it always has.
419
450
  while(index < lines.length){
420
451
  var _lines_index2;
421
- const item = ((_lines_index2 = lines[index]) != null ? _lines_index2 : '').trim();
422
- if (!pattern.test(item)) break;
423
- items.push(parseMarkdownInlines(item.replace(pattern, '')));
452
+ const raw = (_lines_index2 = lines[index]) != null ? _lines_index2 : '';
453
+ const item = raw.trim();
454
+ if (pattern.test(item)) items.push(item.replace(pattern, ''));
455
+ else if (items.length && /^\s/.test(raw) && !BULLET_ITEM_PATTERN.test(item) && !ORDERED_ITEM_PATTERN.test(item)) items[items.length - 1] += ` ${item}`;
456
+ else break;
424
457
  index++;
425
458
  }
426
459
  index--;
460
+ const parsed = items.map((item)=>parseMarkdownInlines(item, options));
427
461
  blocks.push(list.kind === 'list' ? {
428
462
  type: 'list',
429
- items
463
+ items: parsed
430
464
  } : {
431
465
  type: 'orderedList',
432
466
  start: list.start,
433
- items
467
+ items: parsed
434
468
  });
435
469
  }
436
470
  flushProse();
@@ -441,14 +475,14 @@ function alignOfDelimiter(cell) {
441
475
  * block owns its blank lines, so the scan is line-driven rather than a
442
476
  * split on `\n{2,}` (AGL-974). An unterminated fence runs to the end of
443
477
  * the document, which is what a README truncated mid-snippet needs.
444
- */ export function parseMarkdownLite(body) {
478
+ */ export function parseMarkdownLite(body, options = {}) {
445
479
  const blocks = [];
446
480
  const lines = body.split('\n');
447
481
  let pending = [];
448
482
  const flush = ()=>{
449
483
  // A chunk yields MORE than one block when a list interrupts its prose
450
484
  // (AGL-1320) — and none at all when it holds nothing renderable.
451
- if (pending.length) blocks.push(...parseChunk(pending.join('\n')));
485
+ if (pending.length) blocks.push(...parseChunk(pending.join('\n'), options));
452
486
  pending = [];
453
487
  };
454
488
  for(let index = 0; index < lines.length; index++){
@@ -616,6 +650,9 @@ export function slugifyHeading(text) {
616
650
  const text = flattenInlineText(inline.text).replace(/\]/g, '');
617
651
  const href = inline.href.replace(/[)\s]/g, '');
618
652
  out += text && href ? `[${text}](${href})` : text;
653
+ } else if (inline.type === 'code') {
654
+ const text = flattenInlineText(inline.text).replace(/`/g, '');
655
+ if (text) out += `\`${text}\``;
619
656
  } else {
620
657
  out += flattenInlineText(inline.text);
621
658
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/markdown-lite.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Markdown-lite (AGL-123): the tiny subset blog entries use — headings,\n * bold/italic, links, images, bullet and numbered lists, paragraphs, fenced\n * code blocks, tables and blockquotes. Parsed into plain data blocks that\n * renderers turn into elements themselves (no HTML string is ever produced,\n * so there is nothing to sanitize).\n */\n\nimport { isMediaRef, parseMediaRef } from './media-ref'\nimport {\n parseCollectionLinkValue,\n parseEntryLinkValue,\n parseFeedLinkValue,\n parseScreenLinkValue,\n resolveScreenHref,\n SCREEN_LINK_VALUE_PREFIX,\n screenRoutesAnswerFor,\n} from './screen-link-value'\n\nexport type MarkdownInline =\n | { type: 'text'; text: string }\n | { type: 'bold'; text: string }\n | { type: 'italic'; text: string }\n | { type: 'link'; text: string; href: string }\n\n/** A table cell's content. Cells hold inline runs only — no nesting. */\nexport type MarkdownTableCell = MarkdownInline[]\nexport type MarkdownTableAlign = 'left' | 'center' | 'right'\n\nexport type MarkdownBlock =\n | { type: 'heading'; level: 2 | 3; inlines: MarkdownInline[] }\n | { type: 'paragraph'; inlines: MarkdownInline[] }\n /**\n * A `> ` quote (AGL-1315) — the article template's pull-quote. Like a\n * paragraph, one inline run: consecutive `> ` lines of a chunk join with\n * spaces (a bare `>` continues the group and contributes nothing). The\n * dialect has NO nesting — a second `>` is just text of the quote.\n */\n | { type: 'quote'; inlines: MarkdownInline[] }\n | { type: 'image'; src: string; alt: string }\n | { type: 'list'; items: MarkdownInline[][] }\n /**\n * A `1. ` / `1) ` numbered list (AGL-1320) — what a statute's enumerated\n * elements need, and what `/legal/dmca` was flattening into run-on prose.\n * `start` is the FIRST marker's number, so a notice continuing at `7.`\n * keeps counting from seven; the rest renumber from it, which is how the\n * serializer round-trips a `1. 1. 1.` source. A separate block rather than\n * a flag on `list`, so the six renderers have to name it and no ordered\n * list can silently render as bullets. NO nesting, like the rest of the\n * dialect: indentation is trimmed, so a ` 1. ` sub-item is a sibling.\n */\n | { type: 'orderedList'; start: number; items: MarkdownInline[][] }\n /** Fenced block. `text` is verbatim; `lang` is '' when none was given. */\n | { type: 'code'; lang: string; text: string }\n /**\n * A GFM pipe table (AGL-974). Rectangular by construction: every row and\n * `align` carry exactly `header.length` cells, so renderers never have to\n * reason about ragged input and the serializer round-trips exactly.\n */\n | {\n type: 'table'\n align: MarkdownTableAlign[]\n header: MarkdownTableCell[]\n rows: MarkdownTableCell[][]\n }\n\nconst INLINE_PATTERN =\n /(\\*\\*([^*]+)\\*\\*)|(\\*([^*]+)\\*)|(\\[([^\\]]+)\\]\\(([^)\\s]+)\\))|(?<![\\w_])_([^_\\n]+)_(?![\\w_])/g\n\n/**\n * Only absolute http(s) survives; anything else renders as text. The `http:`\n * half reaches LINKS only — {@link safeImageUrl} refuses it before it gets\n * here (AGL-1713).\n */\nfunction safeUrl(url: string): string | null {\n return /^https?:\\/\\//i.test(url) ? url : null\n}\n\n/**\n * Whether a link target is one the parser will keep — the PUBLIC half of\n * {@link safeLinkUrl}, so an editor can refuse what the parser would drop\n * instead of discovering the disagreement on the published page (AGL-1686).\n */\nexport function isSupportedLinkHref(url: string): boolean {\n return safeLinkUrl(url) !== null\n}\n\n/**\n * Whether an image source is one the parser will keep. The predicate an\n * authoring surface must validate against, for the reason\n * {@link isSupportedLinkHref} exists and one the editor learned the hard way:\n * AGL-1645 widened the visual editor's image check to accept site-relative\n * paths without widening this file, so every image picked from the media\n * library serialized into the document and then vanished on the next parse.\n * One predicate, two callers, no drift.\n */\nexport function isSupportedImageSrc(url: string): boolean {\n return safeImageUrl(url) !== null\n}\n\n/**\n * Whether a link target is a stored REFERENCE rather than an address\n * (AGL-3118): a screen, a collection listing, an entry or a feed, named by id\n * so a rename cannot break it. Only the marked, well-formed forms count — a\n * bare id is indistinguishable from a relative path with no slash, so it\n * stays what the dialect has always made of it.\n *\n * Kept verbatim in the parsed link: a renderer resolves it against the same\n * routing map element links use, and the serializer writes it back as typed.\n */\nexport function isMarkdownLinkReference(url: string): boolean {\n if (url.startsWith(SCREEN_LINK_VALUE_PREFIX)) {\n return parseScreenLinkValue(url) !== undefined\n }\n return (\n parseCollectionLinkValue(url) !== undefined ||\n parseEntryLinkValue(url) !== undefined ||\n parseFeedLinkValue(url) !== undefined\n )\n}\n\n/**\n * Link targets additionally allow SITE-RELATIVE paths (AGL-582) so entry\n * markdown can link to other pages of the same site — renderers give those\n * client-side navigation — and link REFERENCES (AGL-3118), which renderers\n * resolve to wherever the target lives now. Protocol-relative `//host` is\n * rejected: it would silently leave the site.\n */\nfunction safeLinkUrl(url: string): string | null {\n if (/^\\/(?!\\/)/.test(url)) return url\n if (isMarkdownLinkReference(url)) return url\n return safeUrl(url)\n}\n\n/**\n * Image sources take everything a link takes, PLUS a media reference\n * (AGL-1686).\n *\n * Images were the one slot still on absolute-`http(s)`-only, and that was\n * silently eating two forms the product now produces:\n *\n * 1. `media:{scope}/{mediaId}` — what \"Browse media\" stores everywhere else\n * (AGL-1215). The reference names the asset and lets the renderer decide\n * how to fetch it, which is the only form that survives a folder move, a\n * replace, a route change, and a component shared across sites.\n * 2. A site-relative `/api/media/cdn/…` or `/images/hero.png`. The visual\n * editor's own `isValidImageUrl` accepts these (AGL-1645) and\n * `safeLinkUrl` always has — so the parser was the one place that\n * disagreed, and it disagreed by DROPPING the whole block. An image with\n * an unparseable src emits no block at all, so the failure was not a\n * broken-image icon or a console error; the picture simply was not there.\n *\n * A malformed reference is still refused. `parseMediaRef` is the same grammar\n * `formatMediaRef` mints against, so `media:` junk an author typed never\n * becomes a block whose src no renderer can resolve — the parse boundary\n * keeps the promise `resolveMediaSrc` makes on the other side.\n *\n * Protocol-relative stays refused here exactly as it is for links.\n *\n * It takes two things LESS than a link. A link REFERENCE (AGL-3118) names a\n * page, not a file, so no renderer has a picture to fetch for one; kept, it\n * would reach an `<img src=\"entry:…\">`.\n *\n * And `http:` (AGL-1713). An image is fetched the moment the page renders; a\n * link is followed by the reader's\n * choice, past an interstitial the browser puts up. So an `http:` image on our\n * TLS pages is mixed content that every current browser blocks outright — the\n * permissive form never rendered a picture, it only moved the failure from\n * authoring time to the viewer, and stored a src that is a CSP violation\n * waiting for AGL-1702 to enforce. Refusing it here reports at authoring time\n * through `isSupportedImageSrc`, which the editor and the besigner picker both\n * validate against. This is the same asymmetry AGL-1701 struck between\n * `SAFE_SRC` and `SAFE_HREF` on the published marketplace node, and the same\n * reason it left `homepageUrl`/`repositoryUrl` as any-https.\n */\nfunction safeImageUrl(url: string): string | null {\n if (isMediaRef(url)) return parseMediaRef(url) ? url : null\n if (/^http:\\/\\//i.test(url)) return null\n if (isMarkdownLinkReference(url)) return null\n return safeLinkUrl(url)\n}\n\n/**\n * True for hrefs the parser emitted as site-relative (start with `/`) AND that\n * a client router can actually settle on.\n *\n * `/api/…` is excluded because those paths serve FILES, not pages —\n * `/api/media/cdn/{scope}/{id}` is the download URL every media reference\n * resolves to, and it is what \"Browse media\" hands an author who links a PDF\n * or a logo kit. Routed through `AppLink` the click starts a client-side\n * navigation that can never complete: the response is an attachment, so the\n * router mounts its navigation-pending overlay and waits forever.\n *\n * The tell is a page trapped behind a spinner, NOT a failed download — the\n * browser fetches the attachment underneath the overlay, so the file lands in\n * Downloads while the site sits there looking broken. That mismatch sends you\n * hunting the media endpoint, which answers `200` with a correct\n * `Content-Disposition: attachment` every time.\n *\n * Both callers use this purely to choose `AppLink` vs a plain anchor, so\n * narrowing it here fixes markdown bodies and collection item links together.\n */\nexport function isInternalMarkdownHref(href: string): boolean {\n return /^\\/(?!\\/)/.test(href) && !/^\\/api\\//.test(href)\n}\n\n/** How a renderer draws one parsed link — see {@link resolveMarkdownLink}. */\nexport type MarkdownLinkResolution =\n /** The link's text alone, with no anchor: a reference to a missing target. */\n | { kind: 'text' }\n /** Drawn as a link with nothing to follow, on an editing surface. */\n | { kind: 'inert' }\n /** A page of this site, for client-side navigation. */\n | { kind: 'internal'; href: string }\n /** Anything else the parser kept, as a plain anchor. */\n | { kind: 'external'; href: string }\n\n/**\n * What one parsed link renders as (AGL-3118), for every markdown-lite\n * renderer on a site: the Markdown element, the entry body and the legacy\n * article surface.\n *\n * A link REFERENCE resolves against the routing map element links use, so a\n * link in a post follows its target through a rename exactly as a button\n * does, and a target the map does not have (unpublished, deleted, or never\n * asked for) renders as the link's text — never as an anchor whose href is\n * the stored reference. Every other href is the one the parser kept.\n *\n * An editing surface withholds every href, so there the only question is\n * whether a link is drawn at all: a reference the map KNOWS is gone reads as\n * the text the published page will show, and one the map cannot judge yet —\n * nothing of its kind has loaded — keeps the link look, for the reason\n * `isScreenLinkBroken` gives.\n */\nexport function resolveMarkdownLink(\n href: string,\n context: {\n screens?: Record<string, string> | null\n suppressNavigation?: boolean\n } = {},\n): MarkdownLinkResolution {\n const screens = context.screens ?? undefined\n const reference = isMarkdownLinkReference(href)\n const resolved = reference ? resolveScreenHref(screens, href) : href\n if (context.suppressNavigation) {\n const gone =\n reference &&\n resolved === undefined &&\n screenRoutesAnswerFor(screens, href)\n return gone ? { kind: 'text' } : { kind: 'inert' }\n }\n if (resolved === undefined) return { kind: 'text' }\n return isInternalMarkdownHref(resolved)\n ? { kind: 'internal', href: resolved }\n : { kind: 'external', href: resolved }\n}\n\n/**\n * Appends plain text, merging into a trailing text inline so the emitted\n * model is canonical (no adjacent text runs). Canonical inlines are what\n * makes `serializeMarkdownLite` a true inverse: a degraded link squeezed\n * between two text gaps re-parses to the same single text inline (AGL-582).\n */\nfunction pushText(inlines: MarkdownInline[], text: string): void {\n if (!text) return\n const last = inlines[inlines.length - 1]\n if (last?.type === 'text') last.text += text\n else inlines.push({ type: 'text', text })\n}\n\nexport function parseMarkdownInlines(text: string): MarkdownInline[] {\n const inlines: MarkdownInline[] = []\n let cursor = 0\n for (const match of text.matchAll(INLINE_PATTERN)) {\n const index = match.index ?? 0\n if (index > cursor) {\n pushText(inlines, text.slice(cursor, index))\n }\n if (match[2] != null) {\n inlines.push({ type: 'bold', text: match[2] })\n } else if (match[4] != null) {\n inlines.push({ type: 'italic', text: match[4] })\n } else if (match[8] != null) {\n // `_italic_` (AGL-4182). Only as a whole word, so `snake_case_name` and\n // a file name stay as they were typed.\n inlines.push({ type: 'italic', text: match[8] })\n } else if (match[6] != null) {\n const href = safeLinkUrl(match[7])\n if (href) inlines.push({ type: 'link', text: match[6], href })\n else pushText(inlines, match[6])\n }\n cursor = index + match[0].length\n }\n if (cursor < text.length) {\n pushText(inlines, text.slice(cursor))\n }\n return inlines\n}\n\n/**\n * An ATX heading at ANY of markdown's six levels (AGL-1082). The dialect only\n * RENDERS two, but it must not mistake the other four for prose: matching just\n * `#{2,3}` made `# Title` — how essentially every repo README opens — fall\n * through to a paragraph carrying a literal `#`, silently, in every renderer.\n */\nconst HEADING_PATTERN = /^(#{1,6})\\s+(.*)$/\n\n/**\n * Clamps an ATX level onto the two the block union carries. `#` promotes to\n * the top rendered level and `####`+ demote to the bottom one, so an out-of-\n * range heading degrades to the NEAREST heading rather than to prose — the\n * same lossy-but-visible degradation the dialect already applies to a `*`\n * inside a bold run. Deliberately NOT widening `level` to `1 | 2 | 3`: every\n * renderer reads it as `level === 2 ? h2 : h3`, so a third value would type-\n * check clean and silently render an h1 as an h3 in six places. This also\n * makes the markdown path agree with the HTML-paste path, which has always\n * mapped `<h1>` to a level-2 heading.\n */\nfunction clampHeadingLevel(hashes: number): 2 | 3 {\n return hashes <= 2 ? 2 : 3\n}\n\n/** ```` ``` ```` or longer, optionally naming a language. */\nconst FENCE_PATTERN = /^`{3,}\\s*([^\\s`]*)\\s*$/\n/** A bullet-list marker: `- ` or `* `. */\nconst BULLET_ITEM_PATTERN = /^[-*]\\s+/\n/**\n * An ordered-list marker (AGL-1320): `1. ` or `1) `, capped at nine digits\n * like CommonMark so a stray year cannot become an absurd `start`. The\n * trailing `\\s+` is load-bearing twice over: it keeps `1.no space` prose, and\n * it makes an EMPTY item impossible, which is the other half of CommonMark's\n * interrupt rule (a bare `1.` may not interrupt a paragraph either).\n */\nconst ORDERED_ITEM_PATTERN = /^(\\d{1,9})[.)]\\s+/\n/** A delimiter cell of a GFM table's second row: `---`, `:--`, `:-:`, `--:`. */\nconst DELIMITER_CELL = /^:?-+:?$/\n\n/** Splits a table row on `|`, dropping the optional outer pipes. */\nfunction splitTableRow(line: string): string[] {\n let text = line.trim()\n if (text.startsWith('|')) text = text.slice(1)\n if (text.endsWith('|')) text = text.slice(0, -1)\n return text.split('|').map((cell) => cell.trim())\n}\n\nfunction alignOfDelimiter(cell: string): MarkdownTableAlign {\n const left = cell.startsWith(':')\n const right = cell.endsWith(':')\n if (left && right) return 'center'\n return right ? 'right' : 'left'\n}\n\n/**\n * A pipe table when the chunk's SECOND line is all delimiter cells — the\n * same rule GFM uses, and the reason a paragraph mentioning `a | b` is\n * still a paragraph. Cells are squared off to the header's width: ragged\n * rows pad with empty cells and overflow is dropped, so the model the\n * serializer writes back re-parses to itself.\n */\nfunction parseTable(lines: string[]): MarkdownBlock | null {\n const [headerLine, delimiterLine] = lines\n if (!headerLine || !delimiterLine || !headerLine.includes('|')) return null\n const delimiters = splitTableRow(delimiterLine)\n if (!delimiters.every((cell) => DELIMITER_CELL.test(cell))) return null\n const header = splitTableRow(headerLine).map(parseMarkdownInlines)\n const columns = header.length\n const squared = (cells: string[]): MarkdownTableCell[] =>\n Array.from({ length: columns }, (_, index) =>\n parseMarkdownInlines(cells[index] ?? ''),\n )\n return {\n type: 'table',\n align: Array.from({ length: columns }, (_, index) =>\n alignOfDelimiter(delimiters[index] ?? '---'),\n ),\n header,\n rows: lines.slice(2).map((line) => squared(splitTableRow(line))),\n }\n}\n\n/**\n * Where a list begins, and which one (AGL-1320).\n *\n * `interrupting` is true when prose of the SAME chunk is already pending —\n * i.e. this line would break a paragraph in two. CommonMark's rule, adopted\n * verbatim: bullets may interrupt a paragraph freely, an ordered list only\n * when it starts at 1. That is what keeps prose reading `1997. A good year\n * for the web.` prose, while `…that includes:` followed by `1.`/`2.` becomes\n * the enumerated list a statute describes. At the head of a chunk nothing is\n * being interrupted, so any start number opens a list and a counter-notice\n * resuming at `7.` still counts from seven.\n */\nfunction listStartOf(\n line: string,\n interrupting: boolean,\n): { kind: 'list' | 'orderedList'; start: number } | null {\n if (BULLET_ITEM_PATTERN.test(line)) return { kind: 'list', start: 0 }\n const ordered = ORDERED_ITEM_PATTERN.exec(line)\n if (!ordered) return null\n const start = Number(ordered[1])\n if (interrupting && start !== 1) return null\n return { kind: 'orderedList', start }\n}\n\n/**\n * One blank-line-delimited chunk of non-fenced source, as blocks.\n *\n * Usually one block — but a chunk splits at a list (AGL-1320), because the\n * shape legal and instructional prose reaches for most is an introducing line\n * with its items directly beneath, no blank line between. A list runs to the\n * first line that is not an item; whatever follows starts a fresh paragraph,\n * which a later list may interrupt in turn. The serializer writes the pieces\n * back as separate blank-line-delimited chunks, so the split round-trips.\n */\nfunction parseChunk(chunk: string): MarkdownBlock[] {\n const trimmed = chunk.trim()\n if (!trimmed) return []\n const image = /^!\\[([^\\]]*)\\]\\(([^)\\s]+)\\)$/.exec(trimmed)\n if (image) {\n const src = safeImageUrl(image[2])\n return src ? [{ type: 'image', src, alt: image[1] }] : []\n }\n const heading = HEADING_PATTERN.exec(trimmed)\n if (heading) {\n return [\n {\n type: 'heading',\n level: clampHeadingLevel(heading[1].length),\n inlines: parseMarkdownInlines(heading[2]),\n },\n ]\n }\n const lines = trimmed.split('\\n')\n const table = parseTable(lines)\n if (table) return [table]\n // A quote when EVERY line of the chunk is `>`-prefixed — a paragraph merely\n // mentioning `>` stays a paragraph, and a quote does NOT interrupt prose the\n // way a list does (`> ` is far rarer mid-paragraph than a numbered step, and\n // the all-lines rule is the cheaper guarantee). Fenced code never reaches\n // here (fences are cut out before chunking), so a `> ` inside a snippet is\n // snippet text, not a quote (AGL-1315).\n if (lines.every((line) => /^>(\\s|$)/.test(line.trim()))) {\n const text = lines\n .map((line) => line.trim().replace(/^>\\s?/, ''))\n .filter(Boolean)\n .join(' ')\n return [{ type: 'quote', inlines: parseMarkdownInlines(text) }]\n }\n const blocks: MarkdownBlock[] = []\n // Prose lines are buffered RAW and joined with spaces, the way a multi-line\n // paragraph has always read.\n let prose: string[] = []\n const flushProse = (): void => {\n if (prose.length) {\n blocks.push({\n type: 'paragraph',\n inlines: parseMarkdownInlines(prose.join(' ')),\n })\n }\n prose = []\n }\n for (let index = 0; index < lines.length; index++) {\n const line = (lines[index] ?? '').trim()\n const list = listStartOf(line, prose.length > 0)\n if (!list) {\n prose.push(lines[index] ?? '')\n continue\n }\n flushProse()\n const pattern =\n list.kind === 'list' ? BULLET_ITEM_PATTERN : ORDERED_ITEM_PATTERN\n const items: MarkdownInline[][] = []\n // The run ends at the first line that is not an item of THIS kind, so a\n // bullet closes a numbered run and vice versa. Only the FIRST ordered\n // marker is read, which is why a source numbered `1. 1. 1.` renumbers on\n // the way out.\n while (index < lines.length) {\n const item = (lines[index] ?? '').trim()\n if (!pattern.test(item)) break\n items.push(parseMarkdownInlines(item.replace(pattern, '')))\n index++\n }\n index--\n blocks.push(\n list.kind === 'list'\n ? { type: 'list', items }\n : { type: 'orderedList', start: list.start, items },\n )\n }\n flushProse()\n return blocks\n}\n\n/**\n * Blocks are blank-line separated, EXCEPT inside a ``` fence — a code\n * block owns its blank lines, so the scan is line-driven rather than a\n * split on `\\n{2,}` (AGL-974). An unterminated fence runs to the end of\n * the document, which is what a README truncated mid-snippet needs.\n */\nexport function parseMarkdownLite(body: string): MarkdownBlock[] {\n const blocks: MarkdownBlock[] = []\n const lines = body.split('\\n')\n let pending: string[] = []\n const flush = (): void => {\n // A chunk yields MORE than one block when a list interrupts its prose\n // (AGL-1320) — and none at all when it holds nothing renderable.\n if (pending.length) blocks.push(...parseChunk(pending.join('\\n')))\n pending = []\n }\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index] ?? ''\n const fence = FENCE_PATTERN.exec(line.trim())\n if (fence) {\n flush()\n const text: string[] = []\n while (\n ++index < lines.length &&\n !FENCE_PATTERN.test((lines[index] ?? '').trim())\n ) {\n text.push(lines[index] ?? '')\n }\n // Blank edges are the fence's own padding, not part of the snippet.\n while (text.length && !text[0]?.trim()) text.shift()\n while (text.length && !text[text.length - 1]?.trim()) text.pop()\n blocks.push({ type: 'code', lang: fence[1] ?? '', text: text.join('\\n') })\n continue\n }\n if (line.trim()) pending.push(line)\n else flush()\n }\n flush()\n return blocks\n}\n\n/** A link or an image in markdown-lite source: bang, text, target. */\nconst SOURCE_LINK_PATTERN = /(!?)\\[([^\\]]*)\\]\\(([^)\\s]+)\\)/g\n\n/**\n * Markdown-lite SOURCE with its link references resolved (AGL-3118), for a\n * reader that hands the source on instead of rendering it — the Markdown twin\n * of a page, which an agent follows links out of.\n *\n * `resolve` answers a reference with the URL to write in its place, or with\n * `undefined` for a target that is gone, and that link becomes its text\n * alone: a reference no reader can follow is worse than no link at all. An\n * image whose source is a reference becomes its alt text, because the parser\n * draws no image for one.\n *\n * Everything else stays exactly as written, and fenced code is not touched —\n * a reference quoted in a snippet is the snippet's text, as the parser has it.\n */\nexport function resolveMarkdownSourceLinks(\n source: string,\n resolve: (reference: string) => string | undefined,\n): string {\n if (!source.includes('](')) return source\n let fenced = false\n return source\n .split('\\n')\n .map((line) => {\n if (FENCE_PATTERN.test(line.trim())) {\n fenced = !fenced\n return line\n }\n if (fenced || !line.includes('](')) return line\n return line.replace(\n SOURCE_LINK_PATTERN,\n (match: string, bang: string, text: string, href: string) => {\n if (!isMarkdownLinkReference(href)) return match\n const target = bang ? undefined : resolve(href)\n // A URL cannot close the parentheses it sits in or break at a space.\n return target\n ? `[${text}](${target.replace(/\\)/g, '%29').replace(/\\s/g, '%20')})`\n : text\n },\n )\n })\n .join('\\n')\n}\n\n/**\n * The plain text an inline run reads as — the words with the emphasis and\n * link syntax removed. What a heading contributes to an anchor slug and to a\n * table-of-contents label (AGL-1162), where `## The **fine** print` has to\n * become \"The fine print\" and `the-fine-print`, not two of either.\n */\nexport function markdownInlinesToText(inlines: MarkdownInline[]): string {\n return inlines.map((inline) => inline.text).join('')\n}\n\n/** A heading a table of contents can point at (AGL-1162). */\nexport interface MarkdownHeading {\n level: 2 | 3\n /** Heading text with emphasis/link syntax stripped. */\n text: string\n /** Anchor id, deterministic and unique within the document. */\n slug: string\n /** Position in the block list, so a renderer can id the right heading. */\n index: number\n}\n\n/**\n * Anchor id for one heading's text (AGL-1162).\n *\n * Deterministic by construction — the same words always produce the same id,\n * which is the whole point: a legal page's true source is a markdown file\n * elsewhere, and re-pasting it must not silently break every link that ever\n * pointed into it. Accents fold to their base letter (NFKD then drop the\n * combining marks) so `Résumé` and `Resume` are the same anchor rather than\n * one of them being an unreadable percent-encoded id.\n *\n * A heading of nothing but punctuation or non-Latin script slugifies to\n * empty; those get `SLUG_FALLBACK` here and are told apart by the numbering\n * in {@link collectMarkdownHeadings}, because an id is required for the link\n * to work at all and no id is worse than a dull one.\n */\nexport const SLUG_FALLBACK = 'section'\n\nexport function slugifyHeading(text: string): string {\n return (\n text\n .normalize('NFKD')\n // Combining diacritics left behind by the decomposition above.\n .replace(/[\\u0300-\\u036f]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '') || SLUG_FALLBACK\n )\n}\n\n/**\n * Every heading in a parsed document, with a unique anchor slug (AGL-1162).\n *\n * Duplicates take a `-2`, `-3`, … suffix in document order, and the loop\n * re-checks the suffixed candidate: a document holding two `## Notice`\n * headings AND a literal `## Notice 2` must not hand the same id to two\n * elements, which is exactly what a plain counter would do.\n *\n * Deliberately NOT a widening of the `MarkdownBlock` union. The union is\n * rendered exhaustively in six places, so a slug carried on the heading\n * block would have to be produced by every writer of that union — including\n * the visual editor's serializer, which round-trips through markdown source\n * that has nowhere to put one. Derived here instead, from the same parse the\n * renderer already has, so the markdown text stays the only source of truth.\n */\nexport function collectMarkdownHeadings(\n blocks: MarkdownBlock[],\n): MarkdownHeading[] {\n const headings: MarkdownHeading[] = []\n const used = new Set<string>()\n blocks.forEach((block, index) => {\n if (block.type !== 'heading') return\n const text = markdownInlinesToText(block.inlines).trim()\n const base = slugifyHeading(text)\n let slug = base\n let suffix = 1\n while (used.has(slug)) {\n suffix += 1\n slug = `${base}-${suffix}`\n }\n used.add(slug)\n headings.push({ level: block.level, text, slug, index })\n })\n return headings\n}\n\n/**\n * The same headings keyed by block index, which is the shape every renderer\n * actually wants (AGL-1162).\n *\n * A renderer maps over `blocks` and needs the slug for the block in hand;\n * {@link collectMarkdownHeadings} returns a list, so each of them had to\n * rebuild this map. There were six markdown renderers and one of them did —\n * five published headings a table of contents could never link to, and the\n * one that worked did it with a private `useMemo` nobody else could reach.\n * Living here means a new renderer gets the numbering, the fallback and the\n * duplicate-suffix rules for free rather than approximating them.\n */\nexport function markdownHeadingSlugs(\n blocks: MarkdownBlock[],\n): Record<number, string> {\n const map: Record<number, string> = {}\n for (const heading of collectMarkdownHeadings(blocks)) {\n map[heading.index] = heading.slug\n }\n return map\n}\n\n/**\n * How far below a heading's anchor the viewport stops (AGL-1162) — enough to\n * clear a sticky site header, so a `#slug` link does not land with the\n * heading hidden underneath the nav. Shared so the published page, the entry\n * body and the console preview all scroll to the same place.\n */\nexport const HEADING_ANCHOR_SCROLL_MARGIN = 96\n\n/** Newlines cannot exist inside an inline run — flatten them to a space. */\nconst flattenInlineText = (text: string): string =>\n text.replace(/\\s*\\n+\\s*/g, ' ')\n\n/**\n * Serializes inlines back to markdown-lite source (AGL-582). Characters an\n * inline run cannot represent (the dialect has NO escapes) are dropped:\n * `*` inside bold/italic, `]` in link text/alt, `)` or whitespace in URLs.\n * Parser-emitted inlines never contain them, so for those this is exact.\n */\nexport function serializeMarkdownInlines(inlines: MarkdownInline[]): string {\n let out = ''\n for (const inline of inlines) {\n if (inline.type === 'bold' || inline.type === 'italic') {\n const text = flattenInlineText(inline.text).replace(/\\*/g, '')\n if (!text) continue\n out += inline.type === 'bold' ? `**${text}**` : `*${text}*`\n } else if (inline.type === 'link') {\n const text = flattenInlineText(inline.text).replace(/\\]/g, '')\n const href = inline.href.replace(/[)\\s]/g, '')\n out += text && href ? `[${text}](${href})` : text\n } else {\n out += flattenInlineText(inline.text)\n }\n }\n return out\n}\n\n/**\n * Inverse of `parseMarkdownLite` — the WYSIWYG round-trip contract\n * (AGL-582): for any parser-produced model, the serialized string re-parses\n * to a deep-equal model, and serializing is stable (a second\n * parse→serialize round-trip returns the identical string). Editor-produced\n * models are additionally NORMALIZED the same way the parser would: blocks\n * and list items that would parse to nothing (empty text) are omitted, and\n * block lines are edge-trimmed. Entry bodies stay markdown-lite strings in\n * Firestore — this is the only writer the visual editor goes through.\n *\n * Every block is written as its own chunk, separated by a BLANK line, which\n * is what holds the invariant now that a list may interrupt a paragraph\n * (AGL-1320): `intro:` + `1. a` re-parses to the same paragraph + list pair\n * whether or not the author left a blank line between them. The blank line is\n * therefore load-bearing, not cosmetic: writing the two chunks adjacent would\n * re-parse correctly today only by luck of the interrupt rule.\n */\nexport function serializeMarkdownLite(blocks: MarkdownBlock[]): string {\n const chunks: string[] = []\n for (const block of blocks) {\n if (block.type === 'image') {\n const src = block.src.replace(/[)\\s]/g, '')\n const alt = flattenInlineText(block.alt).replace(/\\]/g, '')\n if (src) chunks.push(`![${alt}](${src})`)\n continue\n }\n if (block.type === 'list') {\n const lines = block.items\n .map((item) => serializeMarkdownInlines(item).trim())\n .filter(Boolean)\n .map((line) => `- ${line}`)\n if (lines.length) chunks.push(lines.join('\\n'))\n continue\n }\n if (block.type === 'orderedList') {\n // Markers are RE-NUMBERED from `start` (AGL-1320) rather than written\n // back verbatim: the parser only reads the first one, so contiguous\n // markers are the single form that re-parses to this exact model.\n // A missing/absurd start falls back to 1, the way a hand-written list\n // reads anyway.\n const start = Number.isFinite(block.start)\n ? Math.max(0, Math.trunc(block.start))\n : 1\n const lines = block.items\n .map((item) => serializeMarkdownInlines(item).trim())\n .filter(Boolean)\n .map((line, index) => `${start + index}. ${line}`)\n if (lines.length) chunks.push(lines.join('\\n'))\n continue\n }\n if (block.type === 'code') {\n // The fence is the only delimiter the dialect has, so a fence INSIDE\n // the snippet would end it early — those backticks drop, the same way\n // an unrepresentable `*` drops from a bold run.\n const text = block.text\n .replace(/^(\\s*)`{3,}/gm, '$1')\n .replace(/^(?:[ \\t]*\\n)+/, '')\n .replace(/(?:\\n[ \\t]*)+$/, '')\n const lang = block.lang.replace(/[^\\w+#.-]/g, '')\n chunks.push([`\\`\\`\\`${lang}`, ...(text ? [text] : []), '```'].join('\\n'))\n continue\n }\n if (block.type === 'table') {\n // `|` separates cells and there are no escapes, so a pipe inside a\n // cell drops. Empty cells are kept — they are meaningful in a table.\n const row = (cells: MarkdownTableCell[]): string =>\n `| ${cells\n .map((cell) => serializeMarkdownInlines(cell).replace(/\\|/g, '').trim())\n .join(' | ')} |`\n if (!block.header.length) continue\n const delimiters = block.header.map((_, index) => {\n const align = block.align[index] ?? 'left'\n return align === 'center' ? ':-:' : align === 'right' ? '--:' : '---'\n })\n chunks.push(\n [\n row(block.header),\n `| ${delimiters.join(' | ')} |`,\n // Squared off to the header: the parser reads it back that way,\n // so writing anything else would not round-trip.\n ...block.rows.map((cells) =>\n row(\n Array.from(\n { length: block.header.length },\n (_, index) => cells[index] ?? [],\n ),\n ),\n ),\n ].join('\\n'),\n )\n continue\n }\n const line = serializeMarkdownInlines(block.inlines).trim()\n if (!line) continue\n chunks.push(\n block.type === 'heading'\n ? `${'#'.repeat(block.level)} ${line}`\n : block.type === 'quote'\n ? `> ${line}`\n : line,\n )\n }\n return chunks.join('\\n\\n')\n}\n"],"names":["isMediaRef","parseMediaRef","parseCollectionLinkValue","parseEntryLinkValue","parseFeedLinkValue","parseScreenLinkValue","resolveScreenHref","SCREEN_LINK_VALUE_PREFIX","screenRoutesAnswerFor","INLINE_PATTERN","safeUrl","url","test","isSupportedLinkHref","safeLinkUrl","isSupportedImageSrc","safeImageUrl","isMarkdownLinkReference","startsWith","undefined","isInternalMarkdownHref","href","resolveMarkdownLink","context","screens","reference","resolved","suppressNavigation","gone","kind","pushText","inlines","text","last","length","type","push","parseMarkdownInlines","cursor","match","matchAll","index","slice","HEADING_PATTERN","clampHeadingLevel","hashes","FENCE_PATTERN","BULLET_ITEM_PATTERN","ORDERED_ITEM_PATTERN","DELIMITER_CELL","splitTableRow","line","trim","endsWith","split","map","cell","alignOfDelimiter","left","right","parseTable","lines","headerLine","delimiterLine","includes","delimiters","every","header","columns","squared","cells","Array","from","_","align","rows","listStartOf","interrupting","start","ordered","exec","Number","parseChunk","chunk","trimmed","image","src","alt","heading","level","table","replace","filter","Boolean","join","blocks","prose","flushProse","list","pattern","items","item","parseMarkdownLite","body","pending","flush","fence","shift","pop","lang","SOURCE_LINK_PATTERN","resolveMarkdownSourceLinks","source","resolve","fenced","bang","target","markdownInlinesToText","inline","SLUG_FALLBACK","slugifyHeading","normalize","toLowerCase","collectMarkdownHeadings","headings","used","Set","forEach","block","base","slug","suffix","has","add","markdownHeadingSlugs","HEADING_ANCHOR_SCROLL_MARGIN","flattenInlineText","serializeMarkdownInlines","out","serializeMarkdownLite","chunks","isFinite","Math","max","trunc","row","repeat"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;CAMC,GAED,SAASA,UAAU,EAAEC,aAAa,QAAQ,iBAAa;AACvD,SACEC,wBAAwB,EACxBC,mBAAmB,EACnBC,kBAAkB,EAClBC,oBAAoB,EACpBC,iBAAiB,EACjBC,wBAAwB,EACxBC,qBAAqB,QAChB,yBAAqB;AAiD5B,MAAMC,iBACJ;AAEF;;;;CAIC,GACD,SAASC,QAAQC,GAAW;IAC1B,OAAO,gBAAgBC,IAAI,CAACD,OAAOA,MAAM;AAC3C;AAEA;;;;CAIC,GACD,OAAO,SAASE,oBAAoBF,GAAW;IAC7C,OAAOG,YAAYH,SAAS;AAC9B;AAEA;;;;;;;;C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AQ8F,MAAM7D,MAAM,CAACjC,MAAM;oBAAC,GAC9B,CAACuC,GAAGhC;4BAAU6B;gCAAAA,eAAAA,KAAK,CAAC7B,MAAM,YAAZ6B,eAAgB,EAAE;;aAIvC,CAACwB,IAAI,CAAC;YAET;QACF;QACA,MAAM3C,OAAOsF,yBAAyBT,MAAMjG,OAAO,EAAEqB,IAAI;QACzD,IAAI,CAACD,MAAM;QACXyF,OAAOxG,IAAI,CACT4F,MAAM7F,IAAI,KAAK,YACX,GAAG,IAAI+G,MAAM,CAAClB,MAAMvC,KAAK,EAAE,CAAC,EAAEtC,MAAM,GACpC6E,MAAM7F,IAAI,KAAK,UACb,CAAC,EAAE,EAAEgB,MAAM,GACXA;IAEV;IACA,OAAOyF,OAAO9C,IAAI,CAAC;AACrB"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/markdown-lite.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Markdown-lite (AGL-123): the tiny subset blog entries use — headings,\n * bold/italic, links, images, bullet and numbered lists, paragraphs, fenced\n * code blocks, tables and blockquotes. Parsed into plain data blocks that\n * renderers turn into elements themselves (no HTML string is ever produced,\n * so there is nothing to sanitize).\n */\n\nimport { isMediaRef, parseMediaRef } from './media-ref'\nimport {\n parseCollectionLinkValue,\n parseEntryLinkValue,\n parseFeedLinkValue,\n parseScreenLinkValue,\n resolveScreenHref,\n SCREEN_LINK_VALUE_PREFIX,\n screenRoutesAnswerFor,\n} from './screen-link-value'\n\nexport type MarkdownInline =\n | { type: 'text'; text: string }\n | { type: 'bold'; text: string }\n | { type: 'italic'; text: string }\n | { type: 'link'; text: string; href: string }\n /**\n * `inline code` — emitted ONLY when the caller opts in with\n * {@link MarkdownLiteOptions.inlineCode}. A plugin README names settings,\n * hosts and scopes in backticks; a site's blog post and the visual editor\n * never asked for it, so their parse is unchanged and a backtick there stays\n * the character it was typed as.\n */\n | { type: 'code'; text: string }\n\n/**\n * Parse options for {@link parseMarkdownLite}. Every option is OFF unless a\n * caller names it, so a site renderer and the visual editor keep the dialect\n * they were built for.\n */\nexport interface MarkdownLiteOptions {\n /** Read a backtick-delimited run as inline code (a listing README, AGL-4197). */\n inlineCode?: boolean\n}\n\n/** A table cell's content. Cells hold inline runs only — no nesting. */\nexport type MarkdownTableCell = MarkdownInline[]\nexport type MarkdownTableAlign = 'left' | 'center' | 'right'\n\nexport type MarkdownBlock =\n | { type: 'heading'; level: 2 | 3; inlines: MarkdownInline[] }\n | { type: 'paragraph'; inlines: MarkdownInline[] }\n /**\n * A `> ` quote (AGL-1315) — the article template's pull-quote. Like a\n * paragraph, one inline run: consecutive `> ` lines of a chunk join with\n * spaces (a bare `>` continues the group and contributes nothing). The\n * dialect has NO nesting — a second `>` is just text of the quote.\n */\n | { type: 'quote'; inlines: MarkdownInline[] }\n | { type: 'image'; src: string; alt: string }\n | { type: 'list'; items: MarkdownInline[][] }\n /**\n * A `1. ` / `1) ` numbered list (AGL-1320) — what a statute's enumerated\n * elements need, and what `/legal/dmca` was flattening into run-on prose.\n * `start` is the FIRST marker's number, so a notice continuing at `7.`\n * keeps counting from seven; the rest renumber from it, which is how the\n * serializer round-trips a `1. 1. 1.` source. A separate block rather than\n * a flag on `list`, so the six renderers have to name it and no ordered\n * list can silently render as bullets. NO nesting, like the rest of the\n * dialect: indentation is trimmed, so a ` 1. ` sub-item is a sibling.\n */\n | { type: 'orderedList'; start: number; items: MarkdownInline[][] }\n /** Fenced block. `text` is verbatim; `lang` is '' when none was given. */\n | { type: 'code'; lang: string; text: string }\n /**\n * A GFM pipe table (AGL-974). Rectangular by construction: every row and\n * `align` carry exactly `header.length` cells, so renderers never have to\n * reason about ragged input and the serializer round-trips exactly.\n */\n | {\n type: 'table'\n align: MarkdownTableAlign[]\n header: MarkdownTableCell[]\n rows: MarkdownTableCell[][]\n }\n\nconst INLINE_PATTERN =\n /(\\*\\*([^*]+)\\*\\*)|(\\*([^*]+)\\*)|(\\[([^\\]]+)\\]\\(([^)\\s]+)\\))|(?<![\\w_])_([^_\\n]+)_(?![\\w_])/g\n\n/**\n * Only absolute http(s) survives; anything else renders as text. The `http:`\n * half reaches LINKS only — {@link safeImageUrl} refuses it before it gets\n * here (AGL-1713).\n */\nfunction safeUrl(url: string): string | null {\n return /^https?:\\/\\//i.test(url) ? url : null\n}\n\n/**\n * Whether a link target is one the parser will keep — the PUBLIC half of\n * {@link safeLinkUrl}, so an editor can refuse what the parser would drop\n * instead of discovering the disagreement on the published page (AGL-1686).\n */\nexport function isSupportedLinkHref(url: string): boolean {\n return safeLinkUrl(url) !== null\n}\n\n/**\n * Whether an image source is one the parser will keep. The predicate an\n * authoring surface must validate against, for the reason\n * {@link isSupportedLinkHref} exists and one the editor learned the hard way:\n * AGL-1645 widened the visual editor's image check to accept site-relative\n * paths without widening this file, so every image picked from the media\n * library serialized into the document and then vanished on the next parse.\n * One predicate, two callers, no drift.\n */\nexport function isSupportedImageSrc(url: string): boolean {\n return safeImageUrl(url) !== null\n}\n\n/**\n * Whether a link target is a stored REFERENCE rather than an address\n * (AGL-3118): a screen, a collection listing, an entry or a feed, named by id\n * so a rename cannot break it. Only the marked, well-formed forms count — a\n * bare id is indistinguishable from a relative path with no slash, so it\n * stays what the dialect has always made of it.\n *\n * Kept verbatim in the parsed link: a renderer resolves it against the same\n * routing map element links use, and the serializer writes it back as typed.\n */\nexport function isMarkdownLinkReference(url: string): boolean {\n if (url.startsWith(SCREEN_LINK_VALUE_PREFIX)) {\n return parseScreenLinkValue(url) !== undefined\n }\n return (\n parseCollectionLinkValue(url) !== undefined ||\n parseEntryLinkValue(url) !== undefined ||\n parseFeedLinkValue(url) !== undefined\n )\n}\n\n/**\n * Link targets additionally allow SITE-RELATIVE paths (AGL-582) so entry\n * markdown can link to other pages of the same site — renderers give those\n * client-side navigation — and link REFERENCES (AGL-3118), which renderers\n * resolve to wherever the target lives now. Protocol-relative `//host` is\n * rejected: it would silently leave the site.\n */\nfunction safeLinkUrl(url: string): string | null {\n if (/^\\/(?!\\/)/.test(url)) return url\n if (isMarkdownLinkReference(url)) return url\n return safeUrl(url)\n}\n\n/**\n * Image sources take everything a link takes, PLUS a media reference\n * (AGL-1686).\n *\n * Images were the one slot still on absolute-`http(s)`-only, and that was\n * silently eating two forms the product now produces:\n *\n * 1. `media:{scope}/{mediaId}` — what \"Browse media\" stores everywhere else\n * (AGL-1215). The reference names the asset and lets the renderer decide\n * how to fetch it, which is the only form that survives a folder move, a\n * replace, a route change, and a component shared across sites.\n * 2. A site-relative `/api/media/cdn/…` or `/images/hero.png`. The visual\n * editor's own `isValidImageUrl` accepts these (AGL-1645) and\n * `safeLinkUrl` always has — so the parser was the one place that\n * disagreed, and it disagreed by DROPPING the whole block. An image with\n * an unparseable src emits no block at all, so the failure was not a\n * broken-image icon or a console error; the picture simply was not there.\n *\n * A malformed reference is still refused. `parseMediaRef` is the same grammar\n * `formatMediaRef` mints against, so `media:` junk an author typed never\n * becomes a block whose src no renderer can resolve — the parse boundary\n * keeps the promise `resolveMediaSrc` makes on the other side.\n *\n * Protocol-relative stays refused here exactly as it is for links.\n *\n * It takes two things LESS than a link. A link REFERENCE (AGL-3118) names a\n * page, not a file, so no renderer has a picture to fetch for one; kept, it\n * would reach an `<img src=\"entry:…\">`.\n *\n * And `http:` (AGL-1713). An image is fetched the moment the page renders; a\n * link is followed by the reader's\n * choice, past an interstitial the browser puts up. So an `http:` image on our\n * TLS pages is mixed content that every current browser blocks outright — the\n * permissive form never rendered a picture, it only moved the failure from\n * authoring time to the viewer, and stored a src that is a CSP violation\n * waiting for AGL-1702 to enforce. Refusing it here reports at authoring time\n * through `isSupportedImageSrc`, which the editor and the besigner picker both\n * validate against. This is the same asymmetry AGL-1701 struck between\n * `SAFE_SRC` and `SAFE_HREF` on the published marketplace node, and the same\n * reason it left `homepageUrl`/`repositoryUrl` as any-https.\n */\nfunction safeImageUrl(url: string): string | null {\n if (isMediaRef(url)) return parseMediaRef(url) ? url : null\n if (/^http:\\/\\//i.test(url)) return null\n if (isMarkdownLinkReference(url)) return null\n return safeLinkUrl(url)\n}\n\n/**\n * True for hrefs the parser emitted as site-relative (start with `/`) AND that\n * a client router can actually settle on.\n *\n * `/api/…` is excluded because those paths serve FILES, not pages —\n * `/api/media/cdn/{scope}/{id}` is the download URL every media reference\n * resolves to, and it is what \"Browse media\" hands an author who links a PDF\n * or a logo kit. Routed through `AppLink` the click starts a client-side\n * navigation that can never complete: the response is an attachment, so the\n * router mounts its navigation-pending overlay and waits forever.\n *\n * The tell is a page trapped behind a spinner, NOT a failed download — the\n * browser fetches the attachment underneath the overlay, so the file lands in\n * Downloads while the site sits there looking broken. That mismatch sends you\n * hunting the media endpoint, which answers `200` with a correct\n * `Content-Disposition: attachment` every time.\n *\n * Both callers use this purely to choose `AppLink` vs a plain anchor, so\n * narrowing it here fixes markdown bodies and collection item links together.\n */\nexport function isInternalMarkdownHref(href: string): boolean {\n return /^\\/(?!\\/)/.test(href) && !/^\\/api\\//.test(href)\n}\n\n/** How a renderer draws one parsed link — see {@link resolveMarkdownLink}. */\nexport type MarkdownLinkResolution =\n /** The link's text alone, with no anchor: a reference to a missing target. */\n | { kind: 'text' }\n /** Drawn as a link with nothing to follow, on an editing surface. */\n | { kind: 'inert' }\n /** A page of this site, for client-side navigation. */\n | { kind: 'internal'; href: string }\n /** Anything else the parser kept, as a plain anchor. */\n | { kind: 'external'; href: string }\n\n/**\n * What one parsed link renders as (AGL-3118), for every markdown-lite\n * renderer on a site: the Markdown element, the entry body and the legacy\n * article surface.\n *\n * A link REFERENCE resolves against the routing map element links use, so a\n * link in a post follows its target through a rename exactly as a button\n * does, and a target the map does not have (unpublished, deleted, or never\n * asked for) renders as the link's text — never as an anchor whose href is\n * the stored reference. Every other href is the one the parser kept.\n *\n * An editing surface withholds every href, so there the only question is\n * whether a link is drawn at all: a reference the map KNOWS is gone reads as\n * the text the published page will show, and one the map cannot judge yet —\n * nothing of its kind has loaded — keeps the link look, for the reason\n * `isScreenLinkBroken` gives.\n */\nexport function resolveMarkdownLink(\n href: string,\n context: {\n screens?: Record<string, string> | null\n suppressNavigation?: boolean\n } = {},\n): MarkdownLinkResolution {\n const screens = context.screens ?? undefined\n const reference = isMarkdownLinkReference(href)\n const resolved = reference ? resolveScreenHref(screens, href) : href\n if (context.suppressNavigation) {\n const gone =\n reference &&\n resolved === undefined &&\n screenRoutesAnswerFor(screens, href)\n return gone ? { kind: 'text' } : { kind: 'inert' }\n }\n if (resolved === undefined) return { kind: 'text' }\n return isInternalMarkdownHref(resolved)\n ? { kind: 'internal', href: resolved }\n : { kind: 'external', href: resolved }\n}\n\n/**\n * Appends plain text, merging into a trailing text inline so the emitted\n * model is canonical (no adjacent text runs). Canonical inlines are what\n * makes `serializeMarkdownLite` a true inverse: a degraded link squeezed\n * between two text gaps re-parses to the same single text inline (AGL-582).\n */\nfunction pushText(inlines: MarkdownInline[], text: string): void {\n if (!text) return\n const last = inlines[inlines.length - 1]\n if (last?.type === 'text') last.text += text\n else inlines.push({ type: 'text', text })\n}\n\n/** One backtick-delimited run on a single line — no escapes, no nesting. */\nconst INLINE_CODE_PATTERN = /`([^`\\n]+)`/g\n\nexport function parseMarkdownInlines(\n text: string,\n options: MarkdownLiteOptions = {},\n): MarkdownInline[] {\n if (!options.inlineCode || !text.includes('`')) return parseEmphasis(text)\n // Code first, so `**not bold**` inside backticks stays the characters it is.\n const inlines: MarkdownInline[] = []\n let cursor = 0\n for (const match of text.matchAll(INLINE_CODE_PATTERN)) {\n const index = match.index ?? 0\n appendInlines(inlines, parseEmphasis(text.slice(cursor, index)))\n inlines.push({ type: 'code', text: match[1] ?? '' })\n cursor = index + match[0].length\n }\n appendInlines(inlines, parseEmphasis(text.slice(cursor)))\n return inlines\n}\n\n/** Appends a run, merging a leading text inline into a trailing one. */\nfunction appendInlines(into: MarkdownInline[], run: MarkdownInline[]): void {\n for (const inline of run) {\n if (inline.type === 'text') pushText(into, inline.text)\n else into.push(inline)\n }\n}\n\nfunction parseEmphasis(text: string): MarkdownInline[] {\n const inlines: MarkdownInline[] = []\n let cursor = 0\n for (const match of text.matchAll(INLINE_PATTERN)) {\n const index = match.index ?? 0\n if (index > cursor) {\n pushText(inlines, text.slice(cursor, index))\n }\n if (match[2] != null) {\n inlines.push({ type: 'bold', text: match[2] })\n } else if (match[4] != null) {\n inlines.push({ type: 'italic', text: match[4] })\n } else if (match[8] != null) {\n // `_italic_` (AGL-4182). Only as a whole word, so `snake_case_name` and\n // a file name stay as they were typed.\n inlines.push({ type: 'italic', text: match[8] })\n } else if (match[6] != null) {\n const href = safeLinkUrl(match[7])\n if (href) inlines.push({ type: 'link', text: match[6], href })\n else pushText(inlines, match[6])\n }\n cursor = index + match[0].length\n }\n if (cursor < text.length) {\n pushText(inlines, text.slice(cursor))\n }\n return inlines\n}\n\n/**\n * An ATX heading at ANY of markdown's six levels (AGL-1082). The dialect only\n * RENDERS two, but it must not mistake the other four for prose: matching just\n * `#{2,3}` made `# Title` — how essentially every repo README opens — fall\n * through to a paragraph carrying a literal `#`, silently, in every renderer.\n */\nconst HEADING_PATTERN = /^(#{1,6})\\s+(.*)$/\n\n/**\n * Clamps an ATX level onto the two the block union carries. `#` promotes to\n * the top rendered level and `####`+ demote to the bottom one, so an out-of-\n * range heading degrades to the NEAREST heading rather than to prose — the\n * same lossy-but-visible degradation the dialect already applies to a `*`\n * inside a bold run. Deliberately NOT widening `level` to `1 | 2 | 3`: every\n * renderer reads it as `level === 2 ? h2 : h3`, so a third value would type-\n * check clean and silently render an h1 as an h3 in six places. This also\n * makes the markdown path agree with the HTML-paste path, which has always\n * mapped `<h1>` to a level-2 heading.\n */\nfunction clampHeadingLevel(hashes: number): 2 | 3 {\n return hashes <= 2 ? 2 : 3\n}\n\n/** ```` ``` ```` or longer, optionally naming a language. */\nconst FENCE_PATTERN = /^`{3,}\\s*([^\\s`]*)\\s*$/\n/** A bullet-list marker: `- ` or `* `. */\nconst BULLET_ITEM_PATTERN = /^[-*]\\s+/\n/**\n * An ordered-list marker (AGL-1320): `1. ` or `1) `, capped at nine digits\n * like CommonMark so a stray year cannot become an absurd `start`. The\n * trailing `\\s+` is load-bearing twice over: it keeps `1.no space` prose, and\n * it makes an EMPTY item impossible, which is the other half of CommonMark's\n * interrupt rule (a bare `1.` may not interrupt a paragraph either).\n */\nconst ORDERED_ITEM_PATTERN = /^(\\d{1,9})[.)]\\s+/\n/** A delimiter cell of a GFM table's second row: `---`, `:--`, `:-:`, `--:`. */\nconst DELIMITER_CELL = /^:?-+:?$/\n\n/** Splits a table row on `|`, dropping the optional outer pipes. */\nfunction splitTableRow(line: string): string[] {\n let text = line.trim()\n if (text.startsWith('|')) text = text.slice(1)\n if (text.endsWith('|')) text = text.slice(0, -1)\n return text.split('|').map((cell) => cell.trim())\n}\n\nfunction alignOfDelimiter(cell: string): MarkdownTableAlign {\n const left = cell.startsWith(':')\n const right = cell.endsWith(':')\n if (left && right) return 'center'\n return right ? 'right' : 'left'\n}\n\n/**\n * A pipe table when the chunk's SECOND line is all delimiter cells — the\n * same rule GFM uses, and the reason a paragraph mentioning `a | b` is\n * still a paragraph. Cells are squared off to the header's width: ragged\n * rows pad with empty cells and overflow is dropped, so the model the\n * serializer writes back re-parses to itself.\n */\nfunction parseTable(\n lines: string[],\n options: MarkdownLiteOptions,\n): MarkdownBlock | null {\n const [headerLine, delimiterLine] = lines\n if (!headerLine || !delimiterLine || !headerLine.includes('|')) return null\n const delimiters = splitTableRow(delimiterLine)\n if (!delimiters.every((cell) => DELIMITER_CELL.test(cell))) return null\n const header = splitTableRow(headerLine).map((cell) =>\n parseMarkdownInlines(cell, options),\n )\n const columns = header.length\n const squared = (cells: string[]): MarkdownTableCell[] =>\n Array.from({ length: columns }, (_, index) =>\n parseMarkdownInlines(cells[index] ?? '', options),\n )\n return {\n type: 'table',\n align: Array.from({ length: columns }, (_, index) =>\n alignOfDelimiter(delimiters[index] ?? '---'),\n ),\n header,\n rows: lines.slice(2).map((line) => squared(splitTableRow(line))),\n }\n}\n\n/**\n * Where a list begins, and which one (AGL-1320).\n *\n * `interrupting` is true when prose of the SAME chunk is already pending —\n * i.e. this line would break a paragraph in two. CommonMark's rule, adopted\n * verbatim: bullets may interrupt a paragraph freely, an ordered list only\n * when it starts at 1. That is what keeps prose reading `1997. A good year\n * for the web.` prose, while `…that includes:` followed by `1.`/`2.` becomes\n * the enumerated list a statute describes. At the head of a chunk nothing is\n * being interrupted, so any start number opens a list and a counter-notice\n * resuming at `7.` still counts from seven.\n */\nfunction listStartOf(\n line: string,\n interrupting: boolean,\n): { kind: 'list' | 'orderedList'; start: number } | null {\n if (BULLET_ITEM_PATTERN.test(line)) return { kind: 'list', start: 0 }\n const ordered = ORDERED_ITEM_PATTERN.exec(line)\n if (!ordered) return null\n const start = Number(ordered[1])\n if (interrupting && start !== 1) return null\n return { kind: 'orderedList', start }\n}\n\n/**\n * One blank-line-delimited chunk of non-fenced source, as blocks.\n *\n * Usually one block — but a chunk splits at a list (AGL-1320), because the\n * shape legal and instructional prose reaches for most is an introducing line\n * with its items directly beneath, no blank line between. A list runs to the\n * first line that is not an item; whatever follows starts a fresh paragraph,\n * which a later list may interrupt in turn. The serializer writes the pieces\n * back as separate blank-line-delimited chunks, so the split round-trips.\n */\nfunction parseChunk(\n chunk: string,\n options: MarkdownLiteOptions,\n): MarkdownBlock[] {\n const trimmed = chunk.trim()\n if (!trimmed) return []\n const image = /^!\\[([^\\]]*)\\]\\(([^)\\s]+)\\)$/.exec(trimmed)\n if (image) {\n const src = safeImageUrl(image[2])\n return src ? [{ type: 'image', src, alt: image[1] }] : []\n }\n const heading = HEADING_PATTERN.exec(trimmed)\n if (heading) {\n return [\n {\n type: 'heading',\n level: clampHeadingLevel(heading[1].length),\n inlines: parseMarkdownInlines(heading[2], options),\n },\n ]\n }\n const lines = trimmed.split('\\n')\n const table = parseTable(lines, options)\n if (table) return [table]\n // A quote when EVERY line of the chunk is `>`-prefixed — a paragraph merely\n // mentioning `>` stays a paragraph, and a quote does NOT interrupt prose the\n // way a list does (`> ` is far rarer mid-paragraph than a numbered step, and\n // the all-lines rule is the cheaper guarantee). Fenced code never reaches\n // here (fences are cut out before chunking), so a `> ` inside a snippet is\n // snippet text, not a quote (AGL-1315).\n if (lines.every((line) => /^>(\\s|$)/.test(line.trim()))) {\n const text = lines\n .map((line) => line.trim().replace(/^>\\s?/, ''))\n .filter(Boolean)\n .join(' ')\n return [{ type: 'quote', inlines: parseMarkdownInlines(text, options) }]\n }\n const blocks: MarkdownBlock[] = []\n // Prose lines are buffered RAW and joined with spaces, the way a multi-line\n // paragraph has always read.\n let prose: string[] = []\n const flushProse = (): void => {\n if (prose.length) {\n blocks.push({\n type: 'paragraph',\n inlines: parseMarkdownInlines(prose.join(' '), options),\n })\n }\n prose = []\n }\n for (let index = 0; index < lines.length; index++) {\n const line = (lines[index] ?? '').trim()\n const list = listStartOf(line, prose.length > 0)\n if (!list) {\n prose.push(lines[index] ?? '')\n continue\n }\n flushProse()\n const pattern =\n list.kind === 'list' ? BULLET_ITEM_PATTERN : ORDERED_ITEM_PATTERN\n const items: string[] = []\n // The run ends at the first line that is not an item of THIS kind, so a\n // bullet closes a numbered run and vice versa. Only the FIRST ordered\n // marker is read, which is why a source numbered `1. 1. 1.` renumbers on\n // the way out.\n //\n // An INDENTED line that is not an item continues the item above it\n // (AGL-4197): a README wraps a long item at 80 columns and indents the\n // rest under the text, and splitting there broke one list into a list, a\n // stray paragraph and a second list. An unindented line still ends the\n // run and starts the next paragraph, as it always has.\n while (index < lines.length) {\n const raw = lines[index] ?? ''\n const item = raw.trim()\n if (pattern.test(item)) items.push(item.replace(pattern, ''))\n else if (\n items.length &&\n /^\\s/.test(raw) &&\n !BULLET_ITEM_PATTERN.test(item) &&\n !ORDERED_ITEM_PATTERN.test(item)\n )\n items[items.length - 1] += ` ${item}`\n else break\n index++\n }\n index--\n const parsed = items.map((item) => parseMarkdownInlines(item, options))\n blocks.push(\n list.kind === 'list'\n ? { type: 'list', items: parsed }\n : { type: 'orderedList', start: list.start, items: parsed },\n )\n }\n flushProse()\n return blocks\n}\n\n/**\n * Blocks are blank-line separated, EXCEPT inside a ``` fence — a code\n * block owns its blank lines, so the scan is line-driven rather than a\n * split on `\\n{2,}` (AGL-974). An unterminated fence runs to the end of\n * the document, which is what a README truncated mid-snippet needs.\n */\nexport function parseMarkdownLite(\n body: string,\n options: MarkdownLiteOptions = {},\n): MarkdownBlock[] {\n const blocks: MarkdownBlock[] = []\n const lines = body.split('\\n')\n let pending: string[] = []\n const flush = (): void => {\n // A chunk yields MORE than one block when a list interrupts its prose\n // (AGL-1320) — and none at all when it holds nothing renderable.\n if (pending.length) blocks.push(...parseChunk(pending.join('\\n'), options))\n pending = []\n }\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index] ?? ''\n const fence = FENCE_PATTERN.exec(line.trim())\n if (fence) {\n flush()\n const text: string[] = []\n while (\n ++index < lines.length &&\n !FENCE_PATTERN.test((lines[index] ?? '').trim())\n ) {\n text.push(lines[index] ?? '')\n }\n // Blank edges are the fence's own padding, not part of the snippet.\n while (text.length && !text[0]?.trim()) text.shift()\n while (text.length && !text[text.length - 1]?.trim()) text.pop()\n blocks.push({ type: 'code', lang: fence[1] ?? '', text: text.join('\\n') })\n continue\n }\n if (line.trim()) pending.push(line)\n else flush()\n }\n flush()\n return blocks\n}\n\n/** A link or an image in markdown-lite source: bang, text, target. */\nconst SOURCE_LINK_PATTERN = /(!?)\\[([^\\]]*)\\]\\(([^)\\s]+)\\)/g\n\n/**\n * Markdown-lite SOURCE with its link references resolved (AGL-3118), for a\n * reader that hands the source on instead of rendering it — the Markdown twin\n * of a page, which an agent follows links out of.\n *\n * `resolve` answers a reference with the URL to write in its place, or with\n * `undefined` for a target that is gone, and that link becomes its text\n * alone: a reference no reader can follow is worse than no link at all. An\n * image whose source is a reference becomes its alt text, because the parser\n * draws no image for one.\n *\n * Everything else stays exactly as written, and fenced code is not touched —\n * a reference quoted in a snippet is the snippet's text, as the parser has it.\n */\nexport function resolveMarkdownSourceLinks(\n source: string,\n resolve: (reference: string) => string | undefined,\n): string {\n if (!source.includes('](')) return source\n let fenced = false\n return source\n .split('\\n')\n .map((line) => {\n if (FENCE_PATTERN.test(line.trim())) {\n fenced = !fenced\n return line\n }\n if (fenced || !line.includes('](')) return line\n return line.replace(\n SOURCE_LINK_PATTERN,\n (match: string, bang: string, text: string, href: string) => {\n if (!isMarkdownLinkReference(href)) return match\n const target = bang ? undefined : resolve(href)\n // A URL cannot close the parentheses it sits in or break at a space.\n return target\n ? `[${text}](${target.replace(/\\)/g, '%29').replace(/\\s/g, '%20')})`\n : text\n },\n )\n })\n .join('\\n')\n}\n\n/**\n * The plain text an inline run reads as — the words with the emphasis and\n * link syntax removed. What a heading contributes to an anchor slug and to a\n * table-of-contents label (AGL-1162), where `## The **fine** print` has to\n * become \"The fine print\" and `the-fine-print`, not two of either.\n */\nexport function markdownInlinesToText(inlines: MarkdownInline[]): string {\n return inlines.map((inline) => inline.text).join('')\n}\n\n/** A heading a table of contents can point at (AGL-1162). */\nexport interface MarkdownHeading {\n level: 2 | 3\n /** Heading text with emphasis/link syntax stripped. */\n text: string\n /** Anchor id, deterministic and unique within the document. */\n slug: string\n /** Position in the block list, so a renderer can id the right heading. */\n index: number\n}\n\n/**\n * Anchor id for one heading's text (AGL-1162).\n *\n * Deterministic by construction — the same words always produce the same id,\n * which is the whole point: a legal page's true source is a markdown file\n * elsewhere, and re-pasting it must not silently break every link that ever\n * pointed into it. Accents fold to their base letter (NFKD then drop the\n * combining marks) so `Résumé` and `Resume` are the same anchor rather than\n * one of them being an unreadable percent-encoded id.\n *\n * A heading of nothing but punctuation or non-Latin script slugifies to\n * empty; those get `SLUG_FALLBACK` here and are told apart by the numbering\n * in {@link collectMarkdownHeadings}, because an id is required for the link\n * to work at all and no id is worse than a dull one.\n */\nexport const SLUG_FALLBACK = 'section'\n\nexport function slugifyHeading(text: string): string {\n return (\n text\n .normalize('NFKD')\n // Combining diacritics left behind by the decomposition above.\n .replace(/[\\u0300-\\u036f]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '') || SLUG_FALLBACK\n )\n}\n\n/**\n * Every heading in a parsed document, with a unique anchor slug (AGL-1162).\n *\n * Duplicates take a `-2`, `-3`, … suffix in document order, and the loop\n * re-checks the suffixed candidate: a document holding two `## Notice`\n * headings AND a literal `## Notice 2` must not hand the same id to two\n * elements, which is exactly what a plain counter would do.\n *\n * Deliberately NOT a widening of the `MarkdownBlock` union. The union is\n * rendered exhaustively in six places, so a slug carried on the heading\n * block would have to be produced by every writer of that union — including\n * the visual editor's serializer, which round-trips through markdown source\n * that has nowhere to put one. Derived here instead, from the same parse the\n * renderer already has, so the markdown text stays the only source of truth.\n */\nexport function collectMarkdownHeadings(\n blocks: MarkdownBlock[],\n): MarkdownHeading[] {\n const headings: MarkdownHeading[] = []\n const used = new Set<string>()\n blocks.forEach((block, index) => {\n if (block.type !== 'heading') return\n const text = markdownInlinesToText(block.inlines).trim()\n const base = slugifyHeading(text)\n let slug = base\n let suffix = 1\n while (used.has(slug)) {\n suffix += 1\n slug = `${base}-${suffix}`\n }\n used.add(slug)\n headings.push({ level: block.level, text, slug, index })\n })\n return headings\n}\n\n/**\n * The same headings keyed by block index, which is the shape every renderer\n * actually wants (AGL-1162).\n *\n * A renderer maps over `blocks` and needs the slug for the block in hand;\n * {@link collectMarkdownHeadings} returns a list, so each of them had to\n * rebuild this map. There were six markdown renderers and one of them did —\n * five published headings a table of contents could never link to, and the\n * one that worked did it with a private `useMemo` nobody else could reach.\n * Living here means a new renderer gets the numbering, the fallback and the\n * duplicate-suffix rules for free rather than approximating them.\n */\nexport function markdownHeadingSlugs(\n blocks: MarkdownBlock[],\n): Record<number, string> {\n const map: Record<number, string> = {}\n for (const heading of collectMarkdownHeadings(blocks)) {\n map[heading.index] = heading.slug\n }\n return map\n}\n\n/**\n * How far below a heading's anchor the viewport stops (AGL-1162) — enough to\n * clear a sticky site header, so a `#slug` link does not land with the\n * heading hidden underneath the nav. Shared so the published page, the entry\n * body and the console preview all scroll to the same place.\n */\nexport const HEADING_ANCHOR_SCROLL_MARGIN = 96\n\n/** Newlines cannot exist inside an inline run — flatten them to a space. */\nconst flattenInlineText = (text: string): string =>\n text.replace(/\\s*\\n+\\s*/g, ' ')\n\n/**\n * Serializes inlines back to markdown-lite source (AGL-582). Characters an\n * inline run cannot represent (the dialect has NO escapes) are dropped:\n * `*` inside bold/italic, `]` in link text/alt, `)` or whitespace in URLs.\n * Parser-emitted inlines never contain them, so for those this is exact.\n */\nexport function serializeMarkdownInlines(inlines: MarkdownInline[]): string {\n let out = ''\n for (const inline of inlines) {\n if (inline.type === 'bold' || inline.type === 'italic') {\n const text = flattenInlineText(inline.text).replace(/\\*/g, '')\n if (!text) continue\n out += inline.type === 'bold' ? `**${text}**` : `*${text}*`\n } else if (inline.type === 'link') {\n const text = flattenInlineText(inline.text).replace(/\\]/g, '')\n const href = inline.href.replace(/[)\\s]/g, '')\n out += text && href ? `[${text}](${href})` : text\n } else if (inline.type === 'code') {\n const text = flattenInlineText(inline.text).replace(/`/g, '')\n if (text) out += `\\`${text}\\``\n } else {\n out += flattenInlineText(inline.text)\n }\n }\n return out\n}\n\n/**\n * Inverse of `parseMarkdownLite` — the WYSIWYG round-trip contract\n * (AGL-582): for any parser-produced model, the serialized string re-parses\n * to a deep-equal model, and serializing is stable (a second\n * parse→serialize round-trip returns the identical string). Editor-produced\n * models are additionally NORMALIZED the same way the parser would: blocks\n * and list items that would parse to nothing (empty text) are omitted, and\n * block lines are edge-trimmed. Entry bodies stay markdown-lite strings in\n * Firestore — this is the only writer the visual editor goes through.\n *\n * Every block is written as its own chunk, separated by a BLANK line, which\n * is what holds the invariant now that a list may interrupt a paragraph\n * (AGL-1320): `intro:` + `1. a` re-parses to the same paragraph + list pair\n * whether or not the author left a blank line between them. The blank line is\n * therefore load-bearing, not cosmetic: writing the two chunks adjacent would\n * re-parse correctly today only by luck of the interrupt rule.\n */\nexport function serializeMarkdownLite(blocks: MarkdownBlock[]): string {\n const chunks: string[] = []\n for (const block of blocks) {\n if (block.type === 'image') {\n const src = block.src.replace(/[)\\s]/g, '')\n const alt = flattenInlineText(block.alt).replace(/\\]/g, '')\n if (src) chunks.push(`![${alt}](${src})`)\n continue\n }\n if (block.type === 'list') {\n const lines = block.items\n .map((item) => serializeMarkdownInlines(item).trim())\n .filter(Boolean)\n .map((line) => `- ${line}`)\n if (lines.length) chunks.push(lines.join('\\n'))\n continue\n }\n if (block.type === 'orderedList') {\n // Markers are RE-NUMBERED from `start` (AGL-1320) rather than written\n // back verbatim: the parser only reads the first one, so contiguous\n // markers are the single form that re-parses to this exact model.\n // A missing/absurd start falls back to 1, the way a hand-written list\n // reads anyway.\n const start = Number.isFinite(block.start)\n ? Math.max(0, Math.trunc(block.start))\n : 1\n const lines = block.items\n .map((item) => serializeMarkdownInlines(item).trim())\n .filter(Boolean)\n .map((line, index) => `${start + index}. ${line}`)\n if (lines.length) chunks.push(lines.join('\\n'))\n continue\n }\n if (block.type === 'code') {\n // The fence is the only delimiter the dialect has, so a fence INSIDE\n // the snippet would end it early — those backticks drop, the same way\n // an unrepresentable `*` drops from a bold run.\n const text = block.text\n .replace(/^(\\s*)`{3,}/gm, '$1')\n .replace(/^(?:[ \\t]*\\n)+/, '')\n .replace(/(?:\\n[ \\t]*)+$/, '')\n const lang = block.lang.replace(/[^\\w+#.-]/g, '')\n chunks.push([`\\`\\`\\`${lang}`, ...(text ? [text] : []), '```'].join('\\n'))\n continue\n }\n if (block.type === 'table') {\n // `|` separates cells and there are no escapes, so a pipe inside a\n // cell drops. Empty cells are kept — they are meaningful in a table.\n const row = (cells: MarkdownTableCell[]): string =>\n `| ${cells\n .map((cell) => serializeMarkdownInlines(cell).replace(/\\|/g, '').trim())\n .join(' | ')} |`\n if (!block.header.length) continue\n const delimiters = block.header.map((_, index) => {\n const align = block.align[index] ?? 'left'\n return align === 'center' ? ':-:' : align === 'right' ? '--:' : '---'\n })\n chunks.push(\n [\n row(block.header),\n `| ${delimiters.join(' | ')} |`,\n // Squared off to the header: the parser reads it back that way,\n // so writing anything else would not round-trip.\n ...block.rows.map((cells) =>\n row(\n Array.from(\n { length: block.header.length },\n (_, index) => cells[index] ?? [],\n ),\n ),\n ),\n ].join('\\n'),\n )\n continue\n }\n const line = serializeMarkdownInlines(block.inlines).trim()\n if (!line) continue\n chunks.push(\n block.type === 'heading'\n ? `${'#'.repeat(block.level)} ${line}`\n : block.type === 'quote'\n ? `> ${line}`\n : line,\n )\n }\n return chunks.join('\\n\\n')\n}\n"],"names":["isMediaRef","parseMediaRef","parseCollectionLinkValue","parseEntryLinkValue","parseFeedLinkValue","parseScreenLinkValue","resolveScreenHref","SCREEN_LINK_VALUE_PREFIX","screenRoutesAnswerFor","INLINE_PATTERN","safeUrl","url","test","isSupportedLinkHref","safeLinkUrl","isSupportedImageSrc","safeImageUrl","isMarkdownLinkReference","startsWith","undefined","isInternalMarkdownHref","href","resolveMarkdownLink","context","screens","reference","resolved","suppressNavigation","gone","kind","pushText","inlines","text","last","length","type","push","INLINE_CODE_PATTERN","parseMarkdownInlines","options","inlineCode","includes","parseEmphasis","cursor","match","matchAll","index","appendInlines","slice","into","run","inline","HEADING_PATTERN","clampHeadingLevel","hashes","FENCE_PATTERN","BULLET_ITEM_PATTERN","ORDERED_ITEM_PATTERN","DELIMITER_CELL","splitTableRow","line","trim","endsWith","split","map","cell","alignOfDelimiter","left","right","parseTable","lines","headerLine","delimiterLine","delimiters","every","header","columns","squared","cells","Array","from","_","align","rows","listStartOf","interrupting","start","ordered","exec","Number","parseChunk","chunk","trimmed","image","src","alt","heading","level","table","replace","filter","Boolean","join","blocks","prose","flushProse","list","pattern","items","raw","item","parsed","parseMarkdownLite","body","pending","flush","fence","shift","pop","lang","SOURCE_LINK_PATTERN","resolveMarkdownSourceLinks","source","resolve","fenced","bang","target","markdownInlinesToText","SLUG_FALLBACK","slugifyHeading","normalize","toLowerCase","collectMarkdownHeadings","headings","used","Set","forEach","block","base","slug","suffix","has","add","markdownHeadingSlugs","HEADING_ANCHOR_SCROLL_MARGIN","flattenInlineText","serializeMarkdownInlines","out","serializeMarkdownLite","chunks","isFinite","Math","max","trunc","row","repeat"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;CAMC,GAED,SAASA,UAAU,EAAEC,aAAa,QAAQ,iBAAa;AACvD,SACEC,wBAAwB,EACxBC,mBAAmB,EACnBC,kBAAkB,EAClBC,oBAAoB,EACpBC,iBAAiB,EACjBC,wBAAwB,EACxBC,qBAAqB,QAChB,yBAAqB;AAmE5B,MAAMC,iBACJ;AAEF;;;;CAIC,GACD,SAASC,QAAQC,GAAW;IAC1B,OAAO,gBAAgBC,IAAI,CAACD,OAAOA,MAAM;AAC3C;AAEA;;;;CAIC,GACD,OAAO,SAASE,oBAAoBF,GAAW;IAC7C,OAAOG,YAAYH,SAAS;AAC9B;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASI,oBAAoBJ,GAAW;IAC7C,OAAOK,aAAaL,SAAS;AAC/B;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASM,wBAAwBN,GAAW;IACjD,IAAIA,IAAIO,UAAU,CAACX,2BAA2B;QAC5C,OAAOF,qBAAqBM,SAASQ;IACvC;IACA,OACEjB,yBAAyBS,SAASQ,aAClChB,oBAAoBQ,SAASQ,aAC7Bf,mBAAmBO,SAASQ;AAEhC;AAEA;;;;;;CAMC,GACD,SAASL,YAAYH,GAAW;IAC9B,IAAI,YAAYC,IAAI,CAACD,MAAM,OAAOA;IAClC,IAAIM,wBAAwBN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nC;4BAAUgC;gCAAAA,eAAAA,KAAK,CAAChC,MAAM,YAAZgC,eAAgB,EAAE;;aAIvC,CAACwB,IAAI,CAAC;YAET;QACF;QACA,MAAM1C,OAAOsF,yBAAyBT,MAAM1G,OAAO,EAAE8B,IAAI;QACzD,IAAI,CAACD,MAAM;QACXyF,OAAOjH,IAAI,CACTqG,MAAMtG,IAAI,KAAK,YACX,GAAG,IAAIwH,MAAM,CAAClB,MAAMxC,KAAK,EAAE,CAAC,EAAErC,MAAM,GACpC6E,MAAMtG,IAAI,KAAK,UACb,CAAC,EAAE,EAAEyB,MAAM,GACXA;IAEV;IACA,OAAOyF,OAAO/C,IAAI,CAAC;AACrB"}
@@ -61,16 +61,17 @@ export function isReleaseFlagStage(value) {
61
61
  description: 'Storefront shoppers pay on the merchant\u2019s own site: the Payment ' + 'Element, email, shipping address and method, and a live total with ' + 'tax open in place under the Buy or Checkout button, styled with the ' + 'site theme, instead of a redirect to checkout.stripe.com (AGL-1944). ' + 'Released to every workspace 2026-10-06 (AGL-3606). The webhook is ' + 'still the only thing that fulfils. Also gated on ' + 'NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY, so a deployment without one keeps ' + 'the redirect; turning this off returns every storefront to the redirect.',
62
62
  defaultEnabled: true
63
63
  },
64
- // Off until the Terms of Service say a site's own Stripe account is the
65
- // seller of record. On (globally or for one org by override), a store that
66
- // sets up payments gets a full Stripe account of its own and its site sales
67
- // become direct charges on it. Off changes nothing for an account already
68
- // created: the account itself decides how its sales are charged.
64
+ // Released to every store 2026-11-06, after the Terms (v24) named a site's
65
+ // own Stripe account as the seller of record. On, a store that sets up
66
+ // payments gets a full Stripe account of its own and its sales, online and
67
+ // in person, become direct charges on it. It stays the kill switch: off,
68
+ // new setups get the platform-managed account again. Neither state changes
69
+ // an account already created: the account itself decides how it charges.
69
70
  {
70
71
  key: 'release_direct_charges',
71
72
  label: 'Sellers get their own Stripe account',
72
73
  description: 'When a store sets up payments it gets a full Stripe account of its own ' + '(Stripe bills it, Stripe Dashboard included), and its site sales, ' + 'quotes, invoices and bookings are charged directly on that account: ' + 'the store is the seller of record, owns refunds, disputes and sales ' + 'tax, and the platform keeps only its plan take as an application fee. The ' + 'register, Tap to Pay and plugin marketplace sales stay on the ' + 'platform account. Off: new stores get the platform-managed account ' + 'and destination charges, as before. Accounts already created keep ' + 'whichever shape they were created with.',
73
- defaultEnabled: false
74
+ defaultEnabled: true
74
75
  },
75
76
  // Released to every site 2026-09-16 (AGL-3041). Still the whole surface's
76
77
  // kill switch, globally or for one org by override: off, the tenant slot