@aglyn/aglyn 1.11.0 → 1.12.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.
Files changed (45) hide show
  1. package/package.json +11 -11
  2. package/src/lib/app-utils/account-preferences.d.ts +15 -13
  3. package/src/lib/app-utils/account-preferences.js +20 -20
  4. package/src/lib/app-utils/account-preferences.js.map +1 -1
  5. package/src/lib/app-utils/crm.d.ts +3 -1
  6. package/src/lib/app-utils/crm.js +6 -3
  7. package/src/lib/app-utils/crm.js.map +1 -1
  8. package/src/lib/app-utils/docs-help-sections.generated.js +2 -2
  9. package/src/lib/app-utils/docs-help-sections.generated.js.map +1 -1
  10. package/src/lib/app-utils/docs-help.generated.d.ts +1 -1
  11. package/src/lib/app-utils/docs-help.generated.js +1 -0
  12. package/src/lib/app-utils/docs-help.generated.js.map +1 -1
  13. package/src/lib/app-utils/docs-index.generated.js +74 -67
  14. package/src/lib/app-utils/docs-index.generated.js.map +1 -1
  15. package/src/lib/app-utils/markdown-lite.js +8 -1
  16. package/src/lib/app-utils/markdown-lite.js.map +1 -1
  17. package/src/lib/app-utils/org-role-grants.d.ts +6 -0
  18. package/src/lib/app-utils/org-role-grants.js +3 -1
  19. package/src/lib/app-utils/org-role-grants.js.map +1 -1
  20. package/src/lib/app-utils/person-erasure.d.ts +8 -0
  21. package/src/lib/app-utils/person-erasure.js +6 -0
  22. package/src/lib/app-utils/person-erasure.js.map +1 -1
  23. package/src/lib/app-utils/site-preview.d.ts +6 -2
  24. package/src/lib/app-utils/site-preview.js +5 -3
  25. package/src/lib/app-utils/site-preview.js.map +1 -1
  26. package/src/lib/app-utils/site-unavailable.d.ts +4 -7
  27. package/src/lib/app-utils/site-unavailable.js +4 -8
  28. package/src/lib/app-utils/site-unavailable.js.map +1 -1
  29. package/src/lib/foundation/definitions/org-billing.types.js +2 -2
  30. package/src/lib/foundation/definitions/org-billing.types.js.map +1 -1
  31. package/src/lib/foundation/definitions/platform.types.d.ts +1 -1
  32. package/src/lib/foundation/definitions/platform.types.js.map +1 -1
  33. package/src/lib/foundation/definitions/write-deny-coverage.util.d.ts +1 -1
  34. package/src/lib/foundation/definitions/write-deny-coverage.util.js +1 -1
  35. package/src/lib/foundation/definitions/write-deny-coverage.util.js.map +1 -1
  36. package/src/lib/plugin-manager/first-party-plugins.generated.js +1 -1
  37. package/src/lib/plugin-manager/first-party-plugins.generated.js.map +1 -1
  38. package/src/lib/plugin-manager/plugin-contact-capture.d.ts +18 -0
  39. package/src/lib/plugin-manager/plugin-contact-capture.js +26 -0
  40. package/src/lib/plugin-manager/plugin-contact-capture.js.map +1 -1
  41. package/src/lib/plugin-manager/plugin-person-erasure-notes.d.ts +61 -0
  42. package/src/lib/plugin-manager/plugin-person-erasure-notes.js +114 -0
  43. package/src/lib/plugin-manager/plugin-person-erasure-notes.js.map +1 -0
  44. package/src/lib/plugin-manager/plugin-site-starters.d.ts +7 -0
  45. package/src/lib/plugin-manager/plugin-site-starters.js.map +1 -1
@@ -21,7 +21,7 @@
21
21
  * so there is nothing to sanitize).
22
22
  */ import { isMediaRef, parseMediaRef } from "./media-ref.js";
23
23
  import { parseCollectionLinkValue, parseEntryLinkValue, parseFeedLinkValue, parseScreenLinkValue, resolveScreenHref, SCREEN_LINK_VALUE_PREFIX, screenRoutesAnswerFor } from "./screen-link-value.js";
24
- const INLINE_PATTERN = /(\*\*([^*]+)\*\*)|(\*([^*]+)\*)|(\[([^\]]+)\]\(([^)\s]+)\))/g;
24
+ const INLINE_PATTERN = /(\*\*([^*]+)\*\*)|(\*([^*]+)\*)|(\[([^\]]+)\]\(([^)\s]+)\))|(?<![\w_])_([^_\n]+)_(?![\w_])/g;
25
25
  /**
26
26
  * Only absolute http(s) survives; anything else renders as text. The `http:`
27
27
  * half reaches LINKS only — {@link safeImageUrl} refuses it before it gets
@@ -214,6 +214,13 @@ export function parseMarkdownInlines(text) {
214
214
  type: 'italic',
215
215
  text: match[4]
216
216
  });
217
+ } else if (match[8] != null) {
218
+ // `_italic_` (AGL-4182). Only as a whole word, so `snake_case_name` and
219
+ // a file name stay as they were typed.
220
+ inlines.push({
221
+ type: 'italic',
222
+ text: match[8]
223
+ });
217
224
  } else if (match[6] != null) {
218
225
  const href = safeLinkUrl(match[7]);
219
226
  if (href) inlines.push({
@@ -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]+)\\))/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[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;;;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MC,IAAI,CACR;wBAAEtC,QAAQ8F,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/** 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;;;;;;;;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,MAAM,OAAOA;IACzC,OAAOD,QAAQC;AACjB;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwCC,GACD,SAASK,aAAaL,GAAW;IAC/B,IAAIX,WAAWW,MAAM,OAAOV,cAAcU,OAAOA,MAAM;IACvD,IAA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AAG,CAAC,CAACC,OAASiF,yBAAyBjF,MAAMmC,OAAO,CAAC,OAAO,IAAIvC,IAAI,IACpE0C,IAAI,CAAC,OAAO,EAAE,CAAC;YACpB,IAAI,CAACkC,MAAM7D,MAAM,CAACjC,MAAM,EAAE;YAC1B,MAAM+B,aAAa+D,MAAM7D,MAAM,CAACZ,GAAG,CAAC,CAACkB,GAAGhC;oBACxBuF;gBAAd,MAAMtD,SAAQsD,qBAAAA,MAAMtD,KAAK,CAACjC,MAAM,YAAlBuF,qBAAsB;gBACpC,OAAOtD,UAAU,WAAW,QAAQA,UAAU,UAAU,QAAQ;YAClE;YACAkE,OAAOxG,IAAI,CACT;gBACE6G,IAAIjB,MAAM7D,MAAM;gBAChB,CAAC,EAAE,EAAEF,WAAW6B,IAAI,CAAC,OAAO,EAAE,CAAC;gBAC/B,gEAAgE;gBAChE,iDAAiD;mBAC9CkC,MAAMrD,IAAI,CAACpB,GAAG,CAAC,CAACe,QACjB2E,IACE1E,MAAMC,IAAI,CACR;wBAAEtC,QAAQ8F,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"}
@@ -66,6 +66,12 @@ export interface OrgPermissionEntry {
66
66
  * refines.
67
67
  */
68
68
  follows?: string;
69
+ /**
70
+ * Whether a site can narrow the key (`narrowsPerSite`, AGL-4047), so the
71
+ * role and member editors offer its "follow the site role" choice. Absent
72
+ * for a key a site cannot narrow.
73
+ */
74
+ narrowable?: boolean;
69
75
  }
70
76
  /** A heading the role editor groups keys under. */
71
77
  export interface OrgPermissionGroup {
@@ -207,7 +207,7 @@ export const ORG_ROLE_NAMES = [
207
207
  key: 'data.manage',
208
208
  group: 'datasets',
209
209
  label: 'Manage data',
210
- description: 'Create, edit, and delete organization datasets.'
210
+ description: 'Create, edit, and delete organization datasets, the CRM’s records, and marketing lists and topics.'
211
211
  },
212
212
  // Workspace content that asked for the owner, admin or editor role
213
213
  // (AGL-4047), each a key whose default is exactly those roles.
@@ -352,6 +352,8 @@ const CORE_KEYS = CORE_ORG_PERMISSION_ENTRIES.map((entry)=>entry.key);
352
352
  refines: declaration.refines
353
353
  } : {}, declaration.follows && declaration.follows !== declaration.key && !declaration.refines ? {
354
354
  follows: declaration.follows
355
+ } : {}, declaration.narrowsPerSite ? {
356
+ narrowable: true
355
357
  } : {}));
356
358
  if (group && !groupIds.has(group)) {
357
359
  var _declaration_groupLabel;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/org-role-grants.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 * WHAT EACH ORG ROLE MAY DO, AS DATA (AGL-243, AGL-3950).\n *\n * The core permission catalog and the core keys each org role holds when\n * nothing refines it. `org-permissions.ts` builds the console's live\n * catalog from these (adding the keys plugins declare, with their own role\n * defaults), and the native apps read the same grants through the generated\n * contracts, so a native gate (`hosts.create`, `data.manage`) answers as the\n * console does for a member row that carries no `resolvedPermissions` stamp.\n *\n * `ORG_ROLE_GRANTS` in the contracts is this table with every plugin's\n * declared catalog keys added (`assembleOrgRoleGrants`, run by\n * `generate:native-contracts` over each plugin's declarations), which is\n * exactly the set the console's `DEFAULT_ROLE_PERMISSIONS` holds once the\n * plugins have registered.\n *\n * NO IMPORTS, on purpose: the native apps read it through the generated\n * contracts.\n */\n\n/** The four org roles. */\nexport type OrgRoleName = 'owner' | 'admin' | 'editor' | 'viewer'\n\n/**\n * Where a key is decided (AGL-4047). `org`: by the member's org role, custom\n * role and overrides, the same on every site. `site`: as `org` for a member\n * who reaches the whole workspace, and per site for a site collaborator,\n * from the host role they hold there and that site's toggle.\n */\nexport type OrgPermissionScope = 'org' | 'site'\n\n/** One key of the org permission catalog. */\nexport interface OrgPermissionEntry {\n key: string\n label: string\n description: string\n /** The plugin that declared it; absent for a core key. */\n pluginId?: string\n /** The group the role editor files it under (`ORG_PERMISSION_GROUPS`, or the declaring plugin's id). */\n group?: string\n /** Where it is decided; absent reads as `org`. */\n scope?: OrgPermissionScope\n /**\n * The broader key this one is a finer part of (AGL-4047): never granted\n * without it, and following it where no custom role or override sets this\n * key. Absent for a key that refines nothing.\n */\n refines?: string\n /**\n * The key this one follows where no custom role or override sets it,\n * without needing it (AGL-4047): granted on its own, it holds while that\n * key is refused. Absent for a key that follows nothing, and for one that\n * refines.\n */\n follows?: string\n}\n\n/** A heading the role editor groups keys under. */\nexport interface OrgPermissionGroup {\n id: string\n label: string\n /** The plugin whose keys it holds; absent for a core group. */\n pluginId?: string\n}\n\n/** The catalog and each role's default grants. */\nexport interface OrgRoleGrants {\n /** Every key, in the order the role editor lists them. */\n permissions: OrgPermissionEntry[]\n /** The keys each role holds when no custom role or per-member override sets them. */\n grants: Record<OrgRoleName, string[]>\n /** The groups the keys are filed under, in display order; absent in a catalog written before them. */\n groups?: OrgPermissionGroup[]\n}\n\n/**\n * A key a plugin declares into the catalog: `PluginOrgPermissionDeclaration`\n * with org-role defaults, or a `registerPluginPermissions` key (`managePos`),\n * whose `defaults` are per role tier, the owner holding the admin tier's.\n */\nexport interface OrgPermissionDeclaration {\n key: string\n label: string\n description?: string\n roleDefaults?: Record<OrgRoleName, boolean>\n /** The tier defaults of a `registerPluginPermissions` key, used when `roleDefaults` is absent. */\n defaults?: { admin: boolean; editor: boolean; viewer: boolean }\n /** The host-role defaults of a key a site collaborator holds per site. */\n hostRoleDefaults?: Record<string, boolean>\n /** The group it is filed under; absent: a group named by the declaring plugin's id. */\n group?: string\n /** That group's heading, for a group the core does not name. */\n groupLabel?: string\n pluginId?: string\n /** The broader key it refines (AGL-4047). */\n refines?: string\n /** The key it follows without needing it (AGL-4047). */\n follows?: string\n}\n\n/** A custom role (`orgs/{orgId}/roles/{roleId}`) or a member's overrides: explicit verdicts per key. */\nexport interface OrgPermissionLayer {\n permissions?: Record<string, boolean>\n}\n\nexport const ORG_ROLE_NAMES: readonly OrgRoleName[] = ['owner', 'admin', 'editor', 'viewer']\n\n/**\n * The core groups, in display order. A plugin's keys are filed under a group\n * named by the plugin's id unless its declaration names one of these, so no\n * core group id is a plugin id.\n */\nexport const CORE_ORG_PERMISSION_GROUPS: readonly OrgPermissionGroup[] = [\n { id: 'organization', label: 'Organization' },\n { id: 'billing', label: 'Billing' },\n { id: 'team', label: 'Team' },\n { id: 'sites', label: 'Sites' },\n { id: 'datasets', label: 'Data' },\n { id: 'extensions', label: 'Marketplace and plugins' },\n]\n\n/**\n * A declaration's verdict for each org role: its `roleDefaults`, or, for a\n * `registerPluginPermissions` key, its tier `defaults` with the owner on the\n * admin tier (the tier `ORG_ROLE_TIER` resolves the owner onto).\n */\nexport function declarationRoleDefaults(\n declaration: Pick<OrgPermissionDeclaration, 'roleDefaults' | 'defaults'>,\n): Record<OrgRoleName, boolean> {\n if (declaration.roleDefaults) {\n return {\n owner: declaration.roleDefaults.owner === true,\n admin: declaration.roleDefaults.admin === true,\n editor: declaration.roleDefaults.editor === true,\n viewer: declaration.roleDefaults.viewer === true,\n }\n }\n const tiers = declaration.defaults\n return {\n owner: tiers?.admin === true,\n admin: tiers?.admin === true,\n editor: tiers?.editor === true,\n viewer: tiers?.viewer === true,\n }\n}\n\n/**\n * The core keys, in display order for role editors. Every key here is\n * enforced server-side (`apps/console/specs/org-permissions-are-enforced.spec.ts`).\n */\nexport const CORE_ORG_PERMISSION_ENTRIES: readonly OrgPermissionEntry[] = [\n {\n key: 'org.settings',\n group: 'organization',\n label: 'Organization settings',\n description: 'Rename the organization, change its slug, transfer it.',\n },\n {\n key: 'org.auditLog',\n group: 'organization',\n label: 'Activity & audit log',\n description: 'See the organization activity feed.',\n },\n {\n key: 'org.apiKeys',\n group: 'organization',\n label: 'Manage API keys',\n description: 'Create and revoke the workspace’s REST API keys.',\n },\n {\n key: 'org.privacy',\n group: 'organization',\n label: 'Privacy requests',\n description: 'Erase a person from every site in the workspace when they ask.',\n },\n {\n key: 'org.holds',\n group: 'organization',\n label: 'Holds and reviews',\n description: 'See what is held, flagged or locked on the workspace, and request a review.',\n },\n // Workspace acts that asked for the owner or admin role (AGL-4047), each\n // a key of its own whose default is exactly those roles.\n {\n key: 'org.export',\n group: 'organization',\n label: 'Export workspace data',\n description: 'Download a copy of everything the workspace holds.',\n },\n {\n key: 'org.sendingDomains',\n group: 'organization',\n label: 'Sending domains',\n description: 'Add, verify and remove the domains the workspace’s mail is sent from.',\n },\n {\n key: 'org.businessProfile',\n group: 'organization',\n label: 'Business profile',\n description: 'Change the services, audience and tone every site starts from.',\n },\n {\n key: 'billing.view',\n group: 'billing',\n label: 'View billing',\n description: 'See the plan, usage meters, and invoices.',\n },\n {\n key: 'billing.manage',\n group: 'billing',\n label: 'Manage billing',\n description: 'Change plans, buy add-ons, update payment details.',\n },\n {\n key: 'members.manage',\n group: 'team',\n label: 'Manage members',\n description: 'Invite, remove, and re-role organization members.',\n },\n {\n key: 'hosts.create',\n group: 'sites',\n label: 'Create sites',\n description: 'Create new sites in the organization.',\n },\n {\n key: 'hosts.delete',\n group: 'sites',\n label: 'Delete sites',\n description: 'Delete sites the member can access.',\n },\n // The site keys (AGL-4047): each replaced a gate on the member's role on a\n // site, and keeps that role as its preset (`CORE_SITE_ROLE_PRESETS`).\n {\n key: 'site.edit',\n group: 'sites',\n scope: 'site',\n label: 'Edit site content',\n description: 'Create and change pages, content and everything else on a site, without making it live.',\n },\n {\n key: 'site.publish',\n group: 'sites',\n scope: 'site',\n label: 'Publish site content',\n description: 'Make pages and content live, take them down or schedule them, change redirects and change the site’s fonts.',\n },\n {\n key: 'site.sensitive',\n group: 'sites',\n scope: 'site',\n label: 'See orders and webhooks',\n description: 'Read a site’s orders, returns and sending address, and set up its webhooks.',\n },\n {\n key: 'site.manage',\n group: 'sites',\n scope: 'site',\n label: 'Manage site settings',\n description: 'Manage a site’s people, domain, address and plugins, change its plugin settings (live chat, Zapier) and security allow-lists, import, export and delete it.',\n },\n {\n key: 'data.manage',\n group: 'datasets',\n label: 'Manage data',\n description: 'Create, edit, and delete organization datasets.',\n },\n // Workspace content that asked for the owner, admin or editor role\n // (AGL-4047), each a key whose default is exactly those roles.\n {\n key: 'org.media',\n group: 'datasets',\n label: 'Edit the workspace media library',\n description: 'Upload, change, move and remove the files in the media library every site shares.',\n },\n {\n key: 'org.eraseRecords',\n group: 'datasets',\n label: 'Delete workspace records',\n description: 'Delete records the whole workspace shares, such as dataset rows, contacts and lists.',\n },\n {\n key: 'marketplace.publish',\n group: 'extensions',\n label: 'Publish to marketplace',\n description: 'Publish listings under the organization profile.',\n },\n {\n key: 'plugins.install',\n group: 'extensions',\n label: 'Install plugins',\n description: 'Install or remove marketplace plugins.',\n },\n]\n\nconst CORE_KEYS = CORE_ORG_PERMISSION_ENTRIES.map((entry) => entry.key)\n\n/**\n * The core keys whose preset is the member's role ON THE SITE (AGL-4047), and\n * each site role's verdict: the sets the rules' `canWriteHostContent`,\n * `canPublishHostContent`, `canReadHostSensitive` and the site-admin checks\n * asked before they asked these keys. A member's preset on a site is the\n * verdict for the role they hold there (the owner and admins are Admin on\n * every site); a custom role, their own permissions and that site's toggle\n * then grant or refuse it. Each workspace role's default below is the verdict\n * for its own site role, which is the answer with no site named.\n */\nexport const CORE_SITE_ROLE_PRESETS: Readonly<Record<string, Readonly<Record<string, boolean>>>> = {\n 'site.edit': { admin: true, editor: true, author: true, viewer: false },\n 'site.publish': { admin: true, editor: true, author: false, viewer: false },\n 'site.sensitive': { admin: true, editor: true, author: false, viewer: false },\n 'site.manage': { admin: true, editor: false, author: false, viewer: false },\n}\n\n/** The workspace editor's site keys: its own site role's preset. */\nconst EDITOR_SITE_KEYS = Object.keys(CORE_SITE_ROLE_PRESETS).filter((key) => CORE_SITE_ROLE_PRESETS[key].editor)\n\n/**\n * The core keys each org role holds when nothing refines it: owners and\n * admins hold every core key (owner-only acts like deleting the\n * organization stay role-checked, not permission-checked); editors work on\n * content and see no money or roster controls; viewers read only.\n */\nexport const CORE_ORG_ROLE_GRANTS: Readonly<Record<OrgRoleName, readonly string[]>> = {\n owner: CORE_KEYS,\n admin: CORE_KEYS,\n editor: ['data.manage', 'org.media', 'org.eraseRecords', 'marketplace.publish', 'plugins.install', ...EDITOR_SITE_KEYS],\n viewer: [],\n}\n\n/** The core's catalog and grants; the contracts' value adds the plugins' keys. */\nexport const ORG_ROLE_GRANTS: OrgRoleGrants = {\n permissions: CORE_ORG_PERMISSION_ENTRIES.map((entry) => ({ ...entry })),\n groups: CORE_ORG_PERMISSION_GROUPS.map((group) => ({ ...group })),\n grants: {\n owner: [...CORE_ORG_ROLE_GRANTS.owner],\n admin: [...CORE_ORG_ROLE_GRANTS.admin],\n editor: [...CORE_ORG_ROLE_GRANTS.editor],\n viewer: [...CORE_ORG_ROLE_GRANTS.viewer],\n },\n}\n\n/**\n * The catalog with plugins' declared keys after the core ones, each role\n * holding a declared key when its declaration's defaults say so. A\n * declaration naming a key already taken is refused, as the console's\n * catalog refuses it: the first declaration keeps its meaning and defaults.\n * Every declaration list after the first is folded in the same way, so the\n * org catalog keys (`PluginOrgPermissionDeclaration`) and the\n * `registerPluginPermissions` keys land in one catalog (AGL-4047).\n */\nexport function assembleOrgRoleGrants(\n core: OrgRoleGrants,\n ...declarationLists: ReadonlyArray<readonly OrgPermissionDeclaration[]>\n): OrgRoleGrants {\n const permissions = [...core.permissions]\n const groups = [...(core.groups ?? [])]\n const grants = Object.fromEntries(ORG_ROLE_NAMES.map((role) => [role, [...core.grants[role]]])) as Record<\n OrgRoleName,\n string[]\n >\n const taken = new Set(permissions.map((entry) => entry.key))\n const groupIds = new Set(groups.map((group) => group.id))\n for (const declaration of declarationLists.flat()) {\n if (!declaration?.key || taken.has(declaration.key)) continue\n taken.add(declaration.key)\n const group = declaration.group ?? declaration.pluginId\n permissions.push({\n key: declaration.key,\n label: declaration.label,\n description: declaration.description ?? '',\n ...(declaration.pluginId ? { pluginId: declaration.pluginId } : {}),\n ...(group ? { group } : {}),\n scope: declaration.hostRoleDefaults ? 'site' : 'org',\n ...(declaration.refines && declaration.refines !== declaration.key ? { refines: declaration.refines } : {}),\n ...(declaration.follows && declaration.follows !== declaration.key && !declaration.refines\n ? { follows: declaration.follows }\n : {}),\n })\n if (group && !groupIds.has(group)) {\n groupIds.add(group)\n groups.push({\n id: group,\n label: declaration.groupLabel ?? group,\n ...(declaration.pluginId ? { pluginId: declaration.pluginId } : {}),\n })\n } else if (group && declaration.pluginId) {\n // A plugin's group opened by a declaration that names no plugin (an org\n // catalog declaration, AGL-4047) is still that plugin's: the first of\n // its declarations that names one says so.\n const index = groups.findIndex((entry) => entry.id === group)\n if (index >= 0 && !groups[index].pluginId) groups[index] = { ...groups[index], pluginId: declaration.pluginId }\n }\n const defaults = declarationRoleDefaults(declaration)\n for (const role of ORG_ROLE_NAMES) {\n if (defaults[role]) grants[role].push(declaration.key)\n }\n }\n return { permissions, grants, groups }\n}\n\n/**\n * A member's effective permissions, as the console's `resolveOrgPermissions`\n * answers them: the role's defaults, then the custom role's explicit\n * verdicts (when the member has one), then the member's own overrides,\n * later layers winning key by key, over the catalog's keys only. A missing\n * role reads as viewer; a role the catalog does not know holds nothing.\n */\nexport function rolePermissions(\n catalog: OrgRoleGrants,\n role: string | null | undefined,\n customRole?: OrgPermissionLayer | null,\n overrides?: OrgPermissionLayer | null,\n): Record<string, boolean> {\n const keys = catalog.permissions.map((entry) => entry.key)\n const name = role ?? 'viewer'\n const held = new Set((catalog.grants as Record<string, string[] | undefined>)[name] ?? [])\n const out: Record<string, boolean> = Object.fromEntries(keys.map((key) => [key, held.has(key)]))\n for (const layer of [customRole, overrides]) {\n const values = layer?.permissions\n if (!values) continue\n for (const key of keys) {\n if (typeof values[key] === 'boolean') out[key] = values[key]\n }\n }\n // A key that refines a broader one (AGL-4047) is never held without it, and\n // follows it where neither layer set the key; a key that only follows one\n // takes its verdict where neither layer set the key, and nothing more.\n // Applied broader keys first, so a chain settles in one pass; a refinement\n // that loops is left alone.\n const broader = new Map<string, string>()\n const followsOnly = new Set<string>()\n for (const entry of catalog.permissions) {\n if (entry.refines && entry.refines in out) broader.set(entry.key, entry.refines)\n else if (entry.follows && entry.follows in out) {\n broader.set(entry.key, entry.follows)\n followsOnly.add(entry.key)\n }\n }\n const depth = (key: string): number => {\n const seen = new Set<string>()\n let steps = 0\n let current = key\n while (broader.has(current)) {\n if (seen.has(current)) return -1\n seen.add(current)\n current = broader.get(current) as string\n steps += 1\n }\n return steps\n }\n const ordered = [...broader.keys()]\n .map((key) => ({ key, steps: depth(key) }))\n .filter((entry) => entry.steps > 0)\n .sort((a, b) => a.steps - b.steps)\n for (const { key } of ordered) {\n let stored: boolean | undefined\n for (const layer of [customRole, overrides]) {\n const value = layer?.permissions?.[key]\n if (typeof value === 'boolean') stored = value\n }\n const held = out[broader.get(key) as string] === true\n out[key] = followsOnly.has(key) ? (stored === undefined ? held : stored) : held && (stored === undefined ? true : stored)\n }\n return out\n}\n"],"names":["ORG_ROLE_NAMES","CORE_ORG_PERMISSION_GROUPS","id","label","declarationRoleDefaults","declaration","roleDefaults","owner","admin","editor","viewer","tiers","defaults","CORE_ORG_PERMISSION_ENTRIES","key","group","description","scope","CORE_KEYS","map","entry","CORE_SITE_ROLE_PRESETS","author","EDITOR_SITE_KEYS","Object","keys","filter","CORE_ORG_ROLE_GRANTS","ORG_ROLE_GRANTS","permissions","groups","grants","assembleOrgRoleGrants","core","declarationLists","fromEntries","role","taken","Set","groupIds","flat","has","add","pluginId","push","hostRoleDefaults","refines","follows","groupLabel","index","findIndex","rolePermissions","catalog","customRole","overrides","name","held","out","layer","values","broader","Map","followsOnly","set","depth","seen","steps","current","get","ordered","sort","a","b","stored","value","undefined"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;CAkBC,GAED,wBAAwB;AAqFxB,OAAO,MAAMA,iBAAyC;IAAC;IAAS;IAAS;IAAU;CAAS,CAAA;AAE5F;;;;CAIC,GACD,OAAO,MAAMC,6BAA4D;IACvE;QAAEC,IAAI;QAAgBC,OAAO;IAAe;IAC5C;QAAED,IAAI;QAAWC,OAAO;IAAU;IAClC;QAAED,IAAI;QAAQC,OAAO;IAAO;IAC5B;QAAED,IAAI;QAASC,OAAO;IAAQ;IAC9B;QAAED,IAAI;QAAYC,OAAO;IAAO;IAChC;QAAED,IAAI;QAAcC,OAAO;IAA0B;CACtD,CAAA;AAED;;;;CAIC,GACD,OAAO,SAASC,wBACdC,WAAwE;IAExE,IAAIA,YAAYC,YAAY,EAAE;QAC5B,OAAO;YACLC,OAAOF,YAAYC,YAAY,CAACC,KAAK,KAAK;YAC1CC,OAAOH,YAAYC,YAAY,CAACE,KAAK,KAAK;YAC1CC,QAAQJ,YAAYC,YAAY,CAACG,MAAM,KAAK;YAC5CC,QAAQL,YAAYC,YAAY,CAACI,MAAM,KAAK;QAC9C;IACF;IACA,MAAMC,QAAQN,YAAYO,QAAQ;IAClC,OAAO;QACLL,OAAOI,CAAAA,yBAAAA,MAAOH,KAAK,MAAK;QACxBA,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,OAAO,IAAI3B;QACjB,IAAI4B,QAAQ;QACZ,IAAIC,UAAUrD;QACd,MAAO8C,QAAQnB,GAAG,CAAC0B,SAAU;YAC3B,IAAIF,KAAKxB,GAAG,CAAC0B,UAAU,OAAO,CAAC;YAC/BF,KAAKvB,GAAG,CAACyB;YACTA,UAAUP,QAAQQ,GAAG,CAACD;YACtBD,SAAS;QACX;QACA,OAAOA;IACT;IACA,MAAMG,UAAU;WAAIT,QAAQnC,IAAI;KAAG,CAChCN,GAAG,CAAC,CAACL,MAAS,CAAA;YAAEA;YAAKoD,OAAOF,MAAMlD;QAAK,CAAA,GACvCY,MAAM,CAAC,CAACN,QAAUA,MAAM8C,KAAK,GAAG,GAChCI,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAEL,KAAK,GAAGM,EAAEN,KAAK;IACnC,KAAK,MAAM,EAAEpD,GAAG,EAAE,IAAIuD,QAAS;QAC7B,IAAII;QACJ,KAAK,MAAMf,SAAS;YAACL;YAAYC;SAAU,CAAE;gBAC7BI;YAAd,MAAMgB,QAAQhB,0BAAAA,qBAAAA,MAAO7B,WAAW,qBAAlB6B,kBAAoB,CAAC5C,IAAI;YACvC,IAAI,OAAO4D,UAAU,WAAWD,SAASC;QAC3C;QACA,MAAMlB,OAAOC,GAAG,CAACG,QAAQQ,GAAG,CAACtD,KAAe,KAAK;QACjD2C,GAAG,CAAC3C,IAAI,GAAGgD,YAAYrB,GAAG,CAAC3B,OAAQ2D,WAAWE,YAAYnB,OAAOiB,SAAUjB,QAASiB,CAAAA,WAAWE,YAAY,OAAOF,MAAK;IACzH;IACA,OAAOhB;AACT"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/org-role-grants.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 * WHAT EACH ORG ROLE MAY DO, AS DATA (AGL-243, AGL-3950).\n *\n * The core permission catalog and the core keys each org role holds when\n * nothing refines it. `org-permissions.ts` builds the console's live\n * catalog from these (adding the keys plugins declare, with their own role\n * defaults), and the native apps read the same grants through the generated\n * contracts, so a native gate (`hosts.create`, `data.manage`) answers as the\n * console does for a member row that carries no `resolvedPermissions` stamp.\n *\n * `ORG_ROLE_GRANTS` in the contracts is this table with every plugin's\n * declared catalog keys added (`assembleOrgRoleGrants`, run by\n * `generate:native-contracts` over each plugin's declarations), which is\n * exactly the set the console's `DEFAULT_ROLE_PERMISSIONS` holds once the\n * plugins have registered.\n *\n * NO IMPORTS, on purpose: the native apps read it through the generated\n * contracts.\n */\n\n/** The four org roles. */\nexport type OrgRoleName = 'owner' | 'admin' | 'editor' | 'viewer'\n\n/**\n * Where a key is decided (AGL-4047). `org`: by the member's org role, custom\n * role and overrides, the same on every site. `site`: as `org` for a member\n * who reaches the whole workspace, and per site for a site collaborator,\n * from the host role they hold there and that site's toggle.\n */\nexport type OrgPermissionScope = 'org' | 'site'\n\n/** One key of the org permission catalog. */\nexport interface OrgPermissionEntry {\n key: string\n label: string\n description: string\n /** The plugin that declared it; absent for a core key. */\n pluginId?: string\n /** The group the role editor files it under (`ORG_PERMISSION_GROUPS`, or the declaring plugin's id). */\n group?: string\n /** Where it is decided; absent reads as `org`. */\n scope?: OrgPermissionScope\n /**\n * The broader key this one is a finer part of (AGL-4047): never granted\n * without it, and following it where no custom role or override sets this\n * key. Absent for a key that refines nothing.\n */\n refines?: string\n /**\n * The key this one follows where no custom role or override sets it,\n * without needing it (AGL-4047): granted on its own, it holds while that\n * key is refused. Absent for a key that follows nothing, and for one that\n * refines.\n */\n follows?: string\n /**\n * Whether a site can narrow the key (`narrowsPerSite`, AGL-4047), so the\n * role and member editors offer its \"follow the site role\" choice. Absent\n * for a key a site cannot narrow.\n */\n narrowable?: boolean\n}\n\n/** A heading the role editor groups keys under. */\nexport interface OrgPermissionGroup {\n id: string\n label: string\n /** The plugin whose keys it holds; absent for a core group. */\n pluginId?: string\n}\n\n/** The catalog and each role's default grants. */\nexport interface OrgRoleGrants {\n /** Every key, in the order the role editor lists them. */\n permissions: OrgPermissionEntry[]\n /** The keys each role holds when no custom role or per-member override sets them. */\n grants: Record<OrgRoleName, string[]>\n /** The groups the keys are filed under, in display order; absent in a catalog written before them. */\n groups?: OrgPermissionGroup[]\n}\n\n/**\n * A key a plugin declares into the catalog: `PluginOrgPermissionDeclaration`\n * with org-role defaults, or a `registerPluginPermissions` key (`managePos`),\n * whose `defaults` are per role tier, the owner holding the admin tier's.\n */\nexport interface OrgPermissionDeclaration {\n key: string\n label: string\n description?: string\n roleDefaults?: Record<OrgRoleName, boolean>\n /** The tier defaults of a `registerPluginPermissions` key, used when `roleDefaults` is absent. */\n defaults?: { admin: boolean; editor: boolean; viewer: boolean }\n /** The host-role defaults of a key a site collaborator holds per site. */\n hostRoleDefaults?: Record<string, boolean>\n /** The group it is filed under; absent: a group named by the declaring plugin's id. */\n group?: string\n /** That group's heading, for a group the core does not name. */\n groupLabel?: string\n pluginId?: string\n /** The broader key it refines (AGL-4047). */\n refines?: string\n /** The key it follows without needing it (AGL-4047). */\n follows?: string\n}\n\n/** A custom role (`orgs/{orgId}/roles/{roleId}`) or a member's overrides: explicit verdicts per key. */\nexport interface OrgPermissionLayer {\n permissions?: Record<string, boolean>\n}\n\nexport const ORG_ROLE_NAMES: readonly OrgRoleName[] = ['owner', 'admin', 'editor', 'viewer']\n\n/**\n * The core groups, in display order. A plugin's keys are filed under a group\n * named by the plugin's id unless its declaration names one of these, so no\n * core group id is a plugin id.\n */\nexport const CORE_ORG_PERMISSION_GROUPS: readonly OrgPermissionGroup[] = [\n { id: 'organization', label: 'Organization' },\n { id: 'billing', label: 'Billing' },\n { id: 'team', label: 'Team' },\n { id: 'sites', label: 'Sites' },\n { id: 'datasets', label: 'Data' },\n { id: 'extensions', label: 'Marketplace and plugins' },\n]\n\n/**\n * A declaration's verdict for each org role: its `roleDefaults`, or, for a\n * `registerPluginPermissions` key, its tier `defaults` with the owner on the\n * admin tier (the tier `ORG_ROLE_TIER` resolves the owner onto).\n */\nexport function declarationRoleDefaults(\n declaration: Pick<OrgPermissionDeclaration, 'roleDefaults' | 'defaults'>,\n): Record<OrgRoleName, boolean> {\n if (declaration.roleDefaults) {\n return {\n owner: declaration.roleDefaults.owner === true,\n admin: declaration.roleDefaults.admin === true,\n editor: declaration.roleDefaults.editor === true,\n viewer: declaration.roleDefaults.viewer === true,\n }\n }\n const tiers = declaration.defaults\n return {\n owner: tiers?.admin === true,\n admin: tiers?.admin === true,\n editor: tiers?.editor === true,\n viewer: tiers?.viewer === true,\n }\n}\n\n/**\n * The core keys, in display order for role editors. Every key here is\n * enforced server-side (`apps/console/specs/org-permissions-are-enforced.spec.ts`).\n */\nexport const CORE_ORG_PERMISSION_ENTRIES: readonly OrgPermissionEntry[] = [\n {\n key: 'org.settings',\n group: 'organization',\n label: 'Organization settings',\n description: 'Rename the organization, change its slug, transfer it.',\n },\n {\n key: 'org.auditLog',\n group: 'organization',\n label: 'Activity & audit log',\n description: 'See the organization activity feed.',\n },\n {\n key: 'org.apiKeys',\n group: 'organization',\n label: 'Manage API keys',\n description: 'Create and revoke the workspace’s REST API keys.',\n },\n {\n key: 'org.privacy',\n group: 'organization',\n label: 'Privacy requests',\n description: 'Erase a person from every site in the workspace when they ask.',\n },\n {\n key: 'org.holds',\n group: 'organization',\n label: 'Holds and reviews',\n description: 'See what is held, flagged or locked on the workspace, and request a review.',\n },\n // Workspace acts that asked for the owner or admin role (AGL-4047), each\n // a key of its own whose default is exactly those roles.\n {\n key: 'org.export',\n group: 'organization',\n label: 'Export workspace data',\n description: 'Download a copy of everything the workspace holds.',\n },\n {\n key: 'org.sendingDomains',\n group: 'organization',\n label: 'Sending domains',\n description: 'Add, verify and remove the domains the workspace’s mail is sent from.',\n },\n {\n key: 'org.businessProfile',\n group: 'organization',\n label: 'Business profile',\n description: 'Change the services, audience and tone every site starts from.',\n },\n {\n key: 'billing.view',\n group: 'billing',\n label: 'View billing',\n description: 'See the plan, usage meters, and invoices.',\n },\n {\n key: 'billing.manage',\n group: 'billing',\n label: 'Manage billing',\n description: 'Change plans, buy add-ons, update payment details.',\n },\n {\n key: 'members.manage',\n group: 'team',\n label: 'Manage members',\n description: 'Invite, remove, and re-role organization members.',\n },\n {\n key: 'hosts.create',\n group: 'sites',\n label: 'Create sites',\n description: 'Create new sites in the organization.',\n },\n {\n key: 'hosts.delete',\n group: 'sites',\n label: 'Delete sites',\n description: 'Delete sites the member can access.',\n },\n // The site keys (AGL-4047): each replaced a gate on the member's role on a\n // site, and keeps that role as its preset (`CORE_SITE_ROLE_PRESETS`).\n {\n key: 'site.edit',\n group: 'sites',\n scope: 'site',\n label: 'Edit site content',\n description: 'Create and change pages, content and everything else on a site, without making it live.',\n },\n {\n key: 'site.publish',\n group: 'sites',\n scope: 'site',\n label: 'Publish site content',\n description: 'Make pages and content live, take them down or schedule them, change redirects and change the site’s fonts.',\n },\n {\n key: 'site.sensitive',\n group: 'sites',\n scope: 'site',\n label: 'See orders and webhooks',\n description: 'Read a site’s orders, returns and sending address, and set up its webhooks.',\n },\n {\n key: 'site.manage',\n group: 'sites',\n scope: 'site',\n label: 'Manage site settings',\n description: 'Manage a site’s people, domain, address and plugins, change its plugin settings (live chat, Zapier) and security allow-lists, import, export and delete it.',\n },\n {\n key: 'data.manage',\n group: 'datasets',\n label: 'Manage data',\n description: 'Create, edit, and delete organization datasets, the CRM’s records, and marketing lists and topics.',\n },\n // Workspace content that asked for the owner, admin or editor role\n // (AGL-4047), each a key whose default is exactly those roles.\n {\n key: 'org.media',\n group: 'datasets',\n label: 'Edit the workspace media library',\n description: 'Upload, change, move and remove the files in the media library every site shares.',\n },\n {\n key: 'org.eraseRecords',\n group: 'datasets',\n label: 'Delete workspace records',\n description: 'Delete records the whole workspace shares, such as dataset rows, contacts and lists.',\n },\n {\n key: 'marketplace.publish',\n group: 'extensions',\n label: 'Publish to marketplace',\n description: 'Publish listings under the organization profile.',\n },\n {\n key: 'plugins.install',\n group: 'extensions',\n label: 'Install plugins',\n description: 'Install or remove marketplace plugins.',\n },\n]\n\nconst CORE_KEYS = CORE_ORG_PERMISSION_ENTRIES.map((entry) => entry.key)\n\n/**\n * The core keys whose preset is the member's role ON THE SITE (AGL-4047), and\n * each site role's verdict: the sets the rules' `canWriteHostContent`,\n * `canPublishHostContent`, `canReadHostSensitive` and the site-admin checks\n * asked before they asked these keys. A member's preset on a site is the\n * verdict for the role they hold there (the owner and admins are Admin on\n * every site); a custom role, their own permissions and that site's toggle\n * then grant or refuse it. Each workspace role's default below is the verdict\n * for its own site role, which is the answer with no site named.\n */\nexport const CORE_SITE_ROLE_PRESETS: Readonly<Record<string, Readonly<Record<string, boolean>>>> = {\n 'site.edit': { admin: true, editor: true, author: true, viewer: false },\n 'site.publish': { admin: true, editor: true, author: false, viewer: false },\n 'site.sensitive': { admin: true, editor: true, author: false, viewer: false },\n 'site.manage': { admin: true, editor: false, author: false, viewer: false },\n}\n\n/** The workspace editor's site keys: its own site role's preset. */\nconst EDITOR_SITE_KEYS = Object.keys(CORE_SITE_ROLE_PRESETS).filter((key) => CORE_SITE_ROLE_PRESETS[key].editor)\n\n/**\n * The core keys each org role holds when nothing refines it: owners and\n * admins hold every core key (owner-only acts like deleting the\n * organization stay role-checked, not permission-checked); editors work on\n * content and see no money or roster controls; viewers read only.\n */\nexport const CORE_ORG_ROLE_GRANTS: Readonly<Record<OrgRoleName, readonly string[]>> = {\n owner: CORE_KEYS,\n admin: CORE_KEYS,\n editor: ['data.manage', 'org.media', 'org.eraseRecords', 'marketplace.publish', 'plugins.install', ...EDITOR_SITE_KEYS],\n viewer: [],\n}\n\n/** The core's catalog and grants; the contracts' value adds the plugins' keys. */\nexport const ORG_ROLE_GRANTS: OrgRoleGrants = {\n permissions: CORE_ORG_PERMISSION_ENTRIES.map((entry) => ({ ...entry })),\n groups: CORE_ORG_PERMISSION_GROUPS.map((group) => ({ ...group })),\n grants: {\n owner: [...CORE_ORG_ROLE_GRANTS.owner],\n admin: [...CORE_ORG_ROLE_GRANTS.admin],\n editor: [...CORE_ORG_ROLE_GRANTS.editor],\n viewer: [...CORE_ORG_ROLE_GRANTS.viewer],\n },\n}\n\n/**\n * The catalog with plugins' declared keys after the core ones, each role\n * holding a declared key when its declaration's defaults say so. A\n * declaration naming a key already taken is refused, as the console's\n * catalog refuses it: the first declaration keeps its meaning and defaults.\n * Every declaration list after the first is folded in the same way, so the\n * org catalog keys (`PluginOrgPermissionDeclaration`) and the\n * `registerPluginPermissions` keys land in one catalog (AGL-4047).\n */\nexport function assembleOrgRoleGrants(\n core: OrgRoleGrants,\n ...declarationLists: ReadonlyArray<readonly OrgPermissionDeclaration[]>\n): OrgRoleGrants {\n const permissions = [...core.permissions]\n const groups = [...(core.groups ?? [])]\n const grants = Object.fromEntries(ORG_ROLE_NAMES.map((role) => [role, [...core.grants[role]]])) as Record<\n OrgRoleName,\n string[]\n >\n const taken = new Set(permissions.map((entry) => entry.key))\n const groupIds = new Set(groups.map((group) => group.id))\n for (const declaration of declarationLists.flat()) {\n if (!declaration?.key || taken.has(declaration.key)) continue\n taken.add(declaration.key)\n const group = declaration.group ?? declaration.pluginId\n permissions.push({\n key: declaration.key,\n label: declaration.label,\n description: declaration.description ?? '',\n ...(declaration.pluginId ? { pluginId: declaration.pluginId } : {}),\n ...(group ? { group } : {}),\n scope: declaration.hostRoleDefaults ? 'site' : 'org',\n ...(declaration.refines && declaration.refines !== declaration.key ? { refines: declaration.refines } : {}),\n ...(declaration.follows && declaration.follows !== declaration.key && !declaration.refines\n ? { follows: declaration.follows }\n : {}),\n // A plugin's own declaration carries `narrowsPerSite` (a flag or one per role); only whether it is set matters here.\n ...((declaration as { narrowsPerSite?: unknown }).narrowsPerSite ? { narrowable: true } : {}),\n })\n if (group && !groupIds.has(group)) {\n groupIds.add(group)\n groups.push({\n id: group,\n label: declaration.groupLabel ?? group,\n ...(declaration.pluginId ? { pluginId: declaration.pluginId } : {}),\n })\n } else if (group && declaration.pluginId) {\n // A plugin's group opened by a declaration that names no plugin (an org\n // catalog declaration, AGL-4047) is still that plugin's: the first of\n // its declarations that names one says so.\n const index = groups.findIndex((entry) => entry.id === group)\n if (index >= 0 && !groups[index].pluginId) groups[index] = { ...groups[index], pluginId: declaration.pluginId }\n }\n const defaults = declarationRoleDefaults(declaration)\n for (const role of ORG_ROLE_NAMES) {\n if (defaults[role]) grants[role].push(declaration.key)\n }\n }\n return { permissions, grants, groups }\n}\n\n/**\n * A member's effective permissions, as the console's `resolveOrgPermissions`\n * answers them: the role's defaults, then the custom role's explicit\n * verdicts (when the member has one), then the member's own overrides,\n * later layers winning key by key, over the catalog's keys only. A missing\n * role reads as viewer; a role the catalog does not know holds nothing.\n */\nexport function rolePermissions(\n catalog: OrgRoleGrants,\n role: string | null | undefined,\n customRole?: OrgPermissionLayer | null,\n overrides?: OrgPermissionLayer | null,\n): Record<string, boolean> {\n const keys = catalog.permissions.map((entry) => entry.key)\n const name = role ?? 'viewer'\n const held = new Set((catalog.grants as Record<string, string[] | undefined>)[name] ?? [])\n const out: Record<string, boolean> = Object.fromEntries(keys.map((key) => [key, held.has(key)]))\n for (const layer of [customRole, overrides]) {\n const values = layer?.permissions\n if (!values) continue\n for (const key of keys) {\n if (typeof values[key] === 'boolean') out[key] = values[key]\n }\n }\n // A key that refines a broader one (AGL-4047) is never held without it, and\n // follows it where neither layer set the key; a key that only follows one\n // takes its verdict where neither layer set the key, and nothing more.\n // Applied broader keys first, so a chain settles in one pass; a refinement\n // that loops is left alone.\n const broader = new Map<string, string>()\n const followsOnly = new Set<string>()\n for (const entry of catalog.permissions) {\n if (entry.refines && entry.refines in out) broader.set(entry.key, entry.refines)\n else if (entry.follows && entry.follows in out) {\n broader.set(entry.key, entry.follows)\n followsOnly.add(entry.key)\n }\n }\n const depth = (key: string): number => {\n const seen = new Set<string>()\n let steps = 0\n let current = key\n while (broader.has(current)) {\n if (seen.has(current)) return -1\n seen.add(current)\n current = broader.get(current) as string\n steps += 1\n }\n return steps\n }\n const ordered = [...broader.keys()]\n .map((key) => ({ key, steps: depth(key) }))\n .filter((entry) => entry.steps > 0)\n .sort((a, b) => a.steps - b.steps)\n for (const { key } of ordered) {\n let stored: boolean | undefined\n for (const layer of [customRole, overrides]) {\n const value = layer?.permissions?.[key]\n if (typeof value === 'boolean') stored = value\n }\n const held = out[broader.get(key) as string] === true\n out[key] = followsOnly.has(key) ? (stored === undefined ? held : stored) : held && (stored === undefined ? true : stored)\n }\n return out\n}\n"],"names":["ORG_ROLE_NAMES","CORE_ORG_PERMISSION_GROUPS","id","label","declarationRoleDefaults","declaration","roleDefaults","owner","admin","editor","viewer","tiers","defaults","CORE_ORG_PERMISSION_ENTRIES","key","group","description","scope","CORE_KEYS","map","entry","CORE_SITE_ROLE_PRESETS","author","EDITOR_SITE_KEYS","Object","keys","filter","CORE_ORG_ROLE_GRANTS","ORG_ROLE_GRANTS","permissions","groups","grants","assembleOrgRoleGrants","core","declarationLists","fromEntries","role","taken","Set","groupIds","flat","has","add","pluginId","push","hostRoleDefaults","refines","follows","narrowsPerSite","narrowable","groupLabel","index","findIndex","rolePermissions","catalog","customRole","overrides","name","held","out","layer","values","broader","Map","followsOnly","set","depth","seen","steps","current","get","ordered","sort","a","b","stored","value","undefined"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;CAkBC,GAED,wBAAwB;AA2FxB,OAAO,MAAMA,iBAAyC;IAAC;IAAS;IAAS;IAAU;CAAS,CAAA;AAE5F;;;;CAIC,GACD,OAAO,MAAMC,6BAA4D;IACvE;QAAEC,IAAI;QAAgBC,OAAO;IAAe;IAC5C;QAAED,IAAI;QA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AMf,SAAS;YAACL;YAAYC;SAAU,CAAE;gBAC7BI;YAAd,MAAMgB,QAAQhB,0BAAAA,qBAAAA,MAAO/B,WAAW,qBAAlB+B,kBAAoB,CAAC9C,IAAI;YACvC,IAAI,OAAO8D,UAAU,WAAWD,SAASC;QAC3C;QACA,MAAMlB,OAAOC,GAAG,CAACG,QAAQQ,GAAG,CAACxD,KAAe,KAAK;QACjD6C,GAAG,CAAC7C,IAAI,GAAGkD,YAAYvB,GAAG,CAAC3B,OAAQ6D,WAAWE,YAAYnB,OAAOiB,SAAUjB,QAASiB,CAAAA,WAAWE,YAAY,OAAOF,MAAK;IACzH;IACA,OAAOhB;AACT"}
@@ -119,6 +119,14 @@ export declare const PERSON_ERASURE_RETAINS: readonly string[];
119
119
  * login of their own.
120
120
  */
121
121
  export declare const PERSON_ERASURE_NOT_REACHED: readonly string[];
122
+ /**
123
+ * The heading over what plugins say they keep whole
124
+ * (`plugin-person-erasure-notes`): unlike {@link PERSON_ERASURE_RETAINS}, these
125
+ * records keep the person on them.
126
+ */
127
+ export declare const PERSON_ERASURE_NOTES_HEADING = "Kept as they are, with the person still on them";
128
+ /** What the card says when a plugin's note could not be read. */
129
+ export declare const PERSON_ERASURE_NOTES_UNAVAILABLE = "Some details of what this keeps could not be checked right now. Try again in a moment before you confirm.";
122
130
  /**
123
131
  * Whether the typed confirmation names the record's address.
124
132
  *
@@ -106,6 +106,12 @@
106
106
  'Form submissions — delete them from the Inbox',
107
107
  'A site member account — close it from the site’s Members page'
108
108
  ];
109
+ /**
110
+ * The heading over what plugins say they keep whole
111
+ * (`plugin-person-erasure-notes`): unlike {@link PERSON_ERASURE_RETAINS}, these
112
+ * records keep the person on them.
113
+ */ export const PERSON_ERASURE_NOTES_HEADING = 'Kept as they are, with the person still on them';
114
+ /** What the card says when a plugin's note could not be read. */ export const PERSON_ERASURE_NOTES_UNAVAILABLE = 'Some details of what this keeps could not be checked right now. Try again in a moment before you confirm.';
109
115
  /**
110
116
  * Whether the typed confirmation names the record's address.
111
117
  *
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/person-erasure.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 * Privacy erasure of one PERSON from one workspace (AGL-2623).\n *\n * The CRM's **Delete contact** is a detach: one site lets go of a shared row\n * and the document dies only when the last holder does. A privacy erasure is\n * the opposite act — the person is removed from every site in the workspace\n * regardless of who holds them, together with everything the workspace keeps\n * beside them — and it is filed as a REQUEST rather than executed on the\n * click, so that the same daily job that executes workspace erasures\n * executes these, with one audit trail and one place to watch the queue.\n *\n * A request lives at `personErasures/{orgId}__{sha256(email)}`: keyed by\n * the workspace AND the person, because the workspace is the controller of\n * this data and a second workspace that also knows the person has a\n * relationship of its own that this request has no claim on. The id is\n * deterministic so a second request for the same person is the same\n * document rather than a second one, and the address itself is carried only\n * while the request is pending — the sweep needs it to find the records,\n * and the completed request keeps the hash alone.\n *\n * Pure data module: names, types and the small helpers the dialog, the\n * route and the job would otherwise each write for themselves. No\n * Firestore, no React, no `node:` import — the client barrel re-exports it.\n */\n\nimport { normalizeContactEmail } from './contacts'\n\n/** Top-level collection holding one document per (workspace, person). */\nexport const PERSON_ERASURES_COLLECTION = 'personErasures'\n\n/**\n * The document id: workspace first, then the person's key, joined by a\n * separator neither can contain. A Firestore id may not hold a `/`, and a\n * person key is hex, so a double underscore is unambiguous.\n */\nexport function personErasureId(orgId: string, personKey: string): string {\n if (!orgId || !personKey) {\n throw new Error('a person erasure names a workspace and a person')\n }\n return `${orgId}__${personKey}`\n}\n\n/**\n * The field a pending request stamps on the records it covers — the contact\n * document and each site's lead — so a record page can show the state off\n * the document it already listens to, with no second read. Epoch millis.\n *\n * A marker, not the request: the job reads the queue, never this field, so\n * a client write that strips it hides the banner and changes nothing else.\n */\nexport const CONTACT_ERASURE_REQUESTED_FIELD = 'erasureRequestedAtMs'\n\n/** When a record's erasure was requested, or null for a record with none. */\nexport function readErasureRequestedAtMs(\n row: Record<string, unknown> | null | undefined,\n): number | null {\n const value = (row ?? {})[CONTACT_ERASURE_REQUESTED_FIELD]\n return typeof value === 'number' && Number.isFinite(value) && value > 0\n ? value\n : null\n}\n\n/**\n * Where a request is in its life.\n *\n * - `pending` — filed, waiting for the next run. `pendingSinceMs` is set,\n * which is what the job orders on.\n * - `erased` — the sweep ran and reported its counts. The address is gone\n * from the document.\n * - `failed` — the sweep threw. The request stays pending (it keeps\n * `pendingSinceMs`, moved to the back of the queue) so the next run tries\n * again, and the failure is on the document for a staff member to read.\n */\nexport type PersonErasureStatus = 'pending' | 'erased' | 'failed'\n\n/** `personErasures/{orgId}__{personKey}` document shape. */\nexport interface PersonErasureRequest {\n orgId: string\n /** `sha256(normalizedEmail)` — the same key `emailDeliveries` files under. */\n personKey: string\n status: PersonErasureStatus\n /**\n * The address, present ONLY while the request is pending: the sweep\n * queries by it, and nothing else may. Deleted by the job on completion.\n */\n email?: string\n requestedAtMs: number\n /** The workspace admin who filed it. */\n requestedByUid: string\n /** The site the request was filed from — for the activity feed's link. */\n hostId?: string\n /** The record it was filed from, when it was a contact. */\n contactId?: string\n /** The record it was filed from, when it was a lead. */\n leadId?: string\n /**\n * Set while pending. Absent once erased, so `orderBy('pendingSinceMs')`\n * lists exactly the queue — a document without the field is not returned.\n */\n pendingSinceMs?: number\n erasedAtMs?: number\n /**\n * Counts only — what the sweep removed or anonymized, for the audit: the\n * platform's own figures, and each plugin's share under `plugins`.\n */\n result?: Readonly<Record<string, unknown>>\n failedAtMs?: number\n failureCount?: number\n /** The last failure's message, for the staff reader. Never the data. */\n lastError?: string\n}\n\n/**\n * The `reason` a per-site suppression row carries when it was written by\n * an erasure. Such a row keeps NO address — the id is the hash — and does\n * two jobs the ordinary suppression already does one of: every campaign\n * gate refuses the address, and the contact capture path refuses to create\n * a record for it, so a later form fill or order does not quietly rebuild\n * the person the workspace just erased.\n */\nexport const PERSON_ERASURE_SUPPRESSION_REASON = 'erasure'\n\n/**\n * What a door says when it refuses to create a record for an erased address\n * — the contact create route and both lead-convert doors alike. The person\n * asked to be removed and a workspace admin filed it; a record cannot be\n * re-created by hand any more than by a form, and the sentence says where\n * the decision lives rather than implying the address is malformed.\n */\nexport const CONTACT_ERASED_MESSAGE =\n 'This person was erased from your workspace at their request, so a ' +\n 'record cannot be created for this address.'\n\n/**\n * What one request removes across the workspace — the dialog's list and the\n * docs' list, from one source so the two cannot drift. Each line names a\n * thing a reader recognizes from the console, not a collection.\n */\nexport const PERSON_ERASURE_REMOVES: readonly string[] = [\n 'The contact record on every site in this workspace — profile, notes, tags, timeline and custom fields',\n 'Every lead for this address, on every site',\n 'The tasks and logged activities filed against the person',\n 'The person on any email audience list',\n 'The campaign delivery log — every message sent to the address, with its opens and clicks',\n]\n\n/**\n * What survives, and how. Orders and bookings are the workspace's financial\n * and appointment records, and tax law keeps them; the person is taken off\n * them rather than the record destroyed. A deal is the team's own pipeline\n * record and is unlinked, not deleted.\n */\nexport const PERSON_ERASURE_RETAINS: readonly string[] = [\n 'Orders and bookings stay as financial records with the name, email, phone and addresses removed',\n 'Deals stay on the pipeline, unlinked from the person',\n 'Companies stay, with their contact count reduced',\n]\n\n/**\n * What the request does not reach, so the admin can finish the job by hand\n * where the person asked for everything. A form submission keeps the\n * address inside the answers it recorded, under whatever the form called\n * the field, so there is no key to find them by; a site member holds a\n * login of their own.\n */\nexport const PERSON_ERASURE_NOT_REACHED: readonly string[] = [\n 'Form submissions — delete them from the Inbox',\n 'A site member account — close it from the site’s Members page',\n]\n\n/**\n * Whether the typed confirmation names the record's address.\n *\n * Normalized on both sides, so `Jane@Example.com` confirms `jane@example.com`\n * — the confirmation is there to make the admin read the address, not to\n * test their capitalization.\n */\nexport function personErasureConfirmationMatches(\n typed: unknown,\n email: unknown,\n): boolean {\n const wanted = normalizeContactEmail(email)\n if (!wanted) return false\n return normalizeContactEmail(typed) === wanted\n}\n"],"names":["normalizeContactEmail","PERSON_ERASURES_COLLECTION","personErasureId","orgId","personKey","Error","CONTACT_ERASURE_REQUESTED_FIELD","readErasureRequestedAtMs","row","value","Number","isFinite","PERSON_ERASURE_SUPPRESSION_REASON","CONTACT_ERASED_MESSAGE","PERSON_ERASURE_REMOVES","PERSON_ERASURE_RETAINS","PERSON_ERASURE_NOT_REACHED","personErasureConfirmationMatches","typed","email","wanted"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GAED,SAASA,qBAAqB,QAAQ,gBAAY;AAElD,uEAAuE,GACvE,OAAO,MAAMC,6BAA6B,iBAAgB;AAE1D;;;;CAIC,GACD,OAAO,SAASC,gBAAgBC,KAAa,EAAEC,SAAiB;IAC9D,IAAI,CAACD,SAAS,CAACC,WAAW;QACxB,MAAM,IAAIC,MAAM;IAClB;IACA,OAAO,GAAGF,MAAM,EAAE,EAAEC,WAAW;AACjC;AAEA;;;;;;;CAOC,GACD,OAAO,MAAME,kCAAkC,uBAAsB;AAErE,2EAA2E,GAC3E,OAAO,SAASC,yBACdC,GAA+C;IAE/C,MAAMC,QAAQ,CAACD,cAAAA,MAAO,CAAC,EAAE,CAACF,gCAAgC;IAC1D,OAAO,OAAOG,UAAU,YAAYC,OAAOC,QAAQ,CAACF,UAAUA,QAAQ,IAClEA,QACA;AACN;AAoDA;;;;;;;CAOC,GACD,OAAO,MAAMG,oCAAoC,UAAS;AAE1D;;;;;;CAMC,GACD,OAAO,MAAMC,yBACX,uEACA,6CAA4C;AAE9C;;;;CAIC,GACD,OAAO,MAAMC,yBAA4C;IACvD;IACA;IACA;IACA;IACA;CACD,CAAA;AAED;;;;;CAKC,GACD,OAAO,MAAMC,yBAA4C;IACvD;IACA;IACA;CACD,CAAA;AAED;;;;;;CAMC,GACD,OAAO,MAAMC,6BAAgD;IAC3D;IACA;CACD,CAAA;AAED;;;;;;CAMC,GACD,OAAO,SAASC,iCACdC,KAAc,EACdC,KAAc;IAEd,MAAMC,SAASpB,sBAAsBmB;IACrC,IAAI,CAACC,QAAQ,OAAO;IACpB,OAAOpB,sBAAsBkB,WAAWE;AAC1C"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/person-erasure.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 * Privacy erasure of one PERSON from one workspace (AGL-2623).\n *\n * The CRM's **Delete contact** is a detach: one site lets go of a shared row\n * and the document dies only when the last holder does. A privacy erasure is\n * the opposite act — the person is removed from every site in the workspace\n * regardless of who holds them, together with everything the workspace keeps\n * beside them — and it is filed as a REQUEST rather than executed on the\n * click, so that the same daily job that executes workspace erasures\n * executes these, with one audit trail and one place to watch the queue.\n *\n * A request lives at `personErasures/{orgId}__{sha256(email)}`: keyed by\n * the workspace AND the person, because the workspace is the controller of\n * this data and a second workspace that also knows the person has a\n * relationship of its own that this request has no claim on. The id is\n * deterministic so a second request for the same person is the same\n * document rather than a second one, and the address itself is carried only\n * while the request is pending — the sweep needs it to find the records,\n * and the completed request keeps the hash alone.\n *\n * Pure data module: names, types and the small helpers the dialog, the\n * route and the job would otherwise each write for themselves. No\n * Firestore, no React, no `node:` import — the client barrel re-exports it.\n */\n\nimport { normalizeContactEmail } from './contacts'\n\n/** Top-level collection holding one document per (workspace, person). */\nexport const PERSON_ERASURES_COLLECTION = 'personErasures'\n\n/**\n * The document id: workspace first, then the person's key, joined by a\n * separator neither can contain. A Firestore id may not hold a `/`, and a\n * person key is hex, so a double underscore is unambiguous.\n */\nexport function personErasureId(orgId: string, personKey: string): string {\n if (!orgId || !personKey) {\n throw new Error('a person erasure names a workspace and a person')\n }\n return `${orgId}__${personKey}`\n}\n\n/**\n * The field a pending request stamps on the records it covers — the contact\n * document and each site's lead — so a record page can show the state off\n * the document it already listens to, with no second read. Epoch millis.\n *\n * A marker, not the request: the job reads the queue, never this field, so\n * a client write that strips it hides the banner and changes nothing else.\n */\nexport const CONTACT_ERASURE_REQUESTED_FIELD = 'erasureRequestedAtMs'\n\n/** When a record's erasure was requested, or null for a record with none. */\nexport function readErasureRequestedAtMs(\n row: Record<string, unknown> | null | undefined,\n): number | null {\n const value = (row ?? {})[CONTACT_ERASURE_REQUESTED_FIELD]\n return typeof value === 'number' && Number.isFinite(value) && value > 0\n ? value\n : null\n}\n\n/**\n * Where a request is in its life.\n *\n * - `pending` — filed, waiting for the next run. `pendingSinceMs` is set,\n * which is what the job orders on.\n * - `erased` — the sweep ran and reported its counts. The address is gone\n * from the document.\n * - `failed` — the sweep threw. The request stays pending (it keeps\n * `pendingSinceMs`, moved to the back of the queue) so the next run tries\n * again, and the failure is on the document for a staff member to read.\n */\nexport type PersonErasureStatus = 'pending' | 'erased' | 'failed'\n\n/** `personErasures/{orgId}__{personKey}` document shape. */\nexport interface PersonErasureRequest {\n orgId: string\n /** `sha256(normalizedEmail)` — the same key `emailDeliveries` files under. */\n personKey: string\n status: PersonErasureStatus\n /**\n * The address, present ONLY while the request is pending: the sweep\n * queries by it, and nothing else may. Deleted by the job on completion.\n */\n email?: string\n requestedAtMs: number\n /** The workspace admin who filed it. */\n requestedByUid: string\n /** The site the request was filed from — for the activity feed's link. */\n hostId?: string\n /** The record it was filed from, when it was a contact. */\n contactId?: string\n /** The record it was filed from, when it was a lead. */\n leadId?: string\n /**\n * Set while pending. Absent once erased, so `orderBy('pendingSinceMs')`\n * lists exactly the queue — a document without the field is not returned.\n */\n pendingSinceMs?: number\n erasedAtMs?: number\n /**\n * Counts only — what the sweep removed or anonymized, for the audit: the\n * platform's own figures, and each plugin's share under `plugins`.\n */\n result?: Readonly<Record<string, unknown>>\n failedAtMs?: number\n failureCount?: number\n /** The last failure's message, for the staff reader. Never the data. */\n lastError?: string\n}\n\n/**\n * The `reason` a per-site suppression row carries when it was written by\n * an erasure. Such a row keeps NO address — the id is the hash — and does\n * two jobs the ordinary suppression already does one of: every campaign\n * gate refuses the address, and the contact capture path refuses to create\n * a record for it, so a later form fill or order does not quietly rebuild\n * the person the workspace just erased.\n */\nexport const PERSON_ERASURE_SUPPRESSION_REASON = 'erasure'\n\n/**\n * What a door says when it refuses to create a record for an erased address\n * — the contact create route and both lead-convert doors alike. The person\n * asked to be removed and a workspace admin filed it; a record cannot be\n * re-created by hand any more than by a form, and the sentence says where\n * the decision lives rather than implying the address is malformed.\n */\nexport const CONTACT_ERASED_MESSAGE =\n 'This person was erased from your workspace at their request, so a ' +\n 'record cannot be created for this address.'\n\n/**\n * What one request removes across the workspace — the dialog's list and the\n * docs' list, from one source so the two cannot drift. Each line names a\n * thing a reader recognizes from the console, not a collection.\n */\nexport const PERSON_ERASURE_REMOVES: readonly string[] = [\n 'The contact record on every site in this workspace — profile, notes, tags, timeline and custom fields',\n 'Every lead for this address, on every site',\n 'The tasks and logged activities filed against the person',\n 'The person on any email audience list',\n 'The campaign delivery log — every message sent to the address, with its opens and clicks',\n]\n\n/**\n * What survives, and how. Orders and bookings are the workspace's financial\n * and appointment records, and tax law keeps them; the person is taken off\n * them rather than the record destroyed. A deal is the team's own pipeline\n * record and is unlinked, not deleted.\n */\nexport const PERSON_ERASURE_RETAINS: readonly string[] = [\n 'Orders and bookings stay as financial records with the name, email, phone and addresses removed',\n 'Deals stay on the pipeline, unlinked from the person',\n 'Companies stay, with their contact count reduced',\n]\n\n/**\n * What the request does not reach, so the admin can finish the job by hand\n * where the person asked for everything. A form submission keeps the\n * address inside the answers it recorded, under whatever the form called\n * the field, so there is no key to find them by; a site member holds a\n * login of their own.\n */\nexport const PERSON_ERASURE_NOT_REACHED: readonly string[] = [\n 'Form submissions — delete them from the Inbox',\n 'A site member account — close it from the site’s Members page',\n]\n\n/**\n * The heading over what plugins say they keep whole\n * (`plugin-person-erasure-notes`): unlike {@link PERSON_ERASURE_RETAINS}, these\n * records keep the person on them.\n */\nexport const PERSON_ERASURE_NOTES_HEADING = 'Kept as they are, with the person still on them'\n\n/** What the card says when a plugin's note could not be read. */\nexport const PERSON_ERASURE_NOTES_UNAVAILABLE =\n 'Some details of what this keeps could not be checked right now. Try again in a moment before you confirm.'\n\n/**\n * Whether the typed confirmation names the record's address.\n *\n * Normalized on both sides, so `Jane@Example.com` confirms `jane@example.com`\n * — the confirmation is there to make the admin read the address, not to\n * test their capitalization.\n */\nexport function personErasureConfirmationMatches(\n typed: unknown,\n email: unknown,\n): boolean {\n const wanted = normalizeContactEmail(email)\n if (!wanted) return false\n return normalizeContactEmail(typed) === wanted\n}\n"],"names":["normalizeContactEmail","PERSON_ERASURES_COLLECTION","personErasureId","orgId","personKey","Error","CONTACT_ERASURE_REQUESTED_FIELD","readErasureRequestedAtMs","row","value","Number","isFinite","PERSON_ERASURE_SUPPRESSION_REASON","CONTACT_ERASED_MESSAGE","PERSON_ERASURE_REMOVES","PERSON_ERASURE_RETAINS","PERSON_ERASURE_NOT_REACHED","PERSON_ERASURE_NOTES_HEADING","PERSON_ERASURE_NOTES_UNAVAILABLE","personErasureConfirmationMatches","typed","email","wanted"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GAED,SAASA,qBAAqB,QAAQ,gBAAY;AAElD,uEAAuE,GACvE,OAAO,MAAMC,6BAA6B,iBAAgB;AAE1D;;;;CAIC,GACD,OAAO,SAASC,gBAAgBC,KAAa,EAAEC,SAAiB;IAC9D,IAAI,CAACD,SAAS,CAACC,WAAW;QACxB,MAAM,IAAIC,MAAM;IAClB;IACA,OAAO,GAAGF,MAAM,EAAE,EAAEC,WAAW;AACjC;AAEA;;;;;;;CAOC,GACD,OAAO,MAAME,kCAAkC,uBAAsB;AAErE,2EAA2E,GAC3E,OAAO,SAASC,yBACdC,GAA+C;IAE/C,MAAMC,QAAQ,CAACD,cAAAA,MAAO,CAAC,EAAE,CAACF,gCAAgC;IAC1D,OAAO,OAAOG,UAAU,YAAYC,OAAOC,QAAQ,CAACF,UAAUA,QAAQ,IAClEA,QACA;AACN;AAoDA;;;;;;;CAOC,GACD,OAAO,MAAMG,oCAAoC,UAAS;AAE1D;;;;;;CAMC,GACD,OAAO,MAAMC,yBACX,uEACA,6CAA4C;AAE9C;;;;CAIC,GACD,OAAO,MAAMC,yBAA4C;IACvD;IACA;IACA;IACA;IACA;CACD,CAAA;AAED;;;;;CAKC,GACD,OAAO,MAAMC,yBAA4C;IACvD;IACA;IACA;CACD,CAAA;AAED;;;;;;CAMC,GACD,OAAO,MAAMC,6BAAgD;IAC3D;IACA;CACD,CAAA;AAED;;;;CAIC,GACD,OAAO,MAAMC,+BAA+B,kDAAiD;AAE7F,+DAA+D,GAC/D,OAAO,MAAMC,mCACX,4GAA2G;AAE7G;;;;;;CAMC,GACD,OAAO,SAASC,iCACdC,KAAc,EACdC,KAAc;IAEd,MAAMC,SAAStB,sBAAsBqB;IACrC,IAAI,CAACC,QAAQ,OAAO;IACpB,OAAOtB,sBAAsBoB,WAAWE;AAC1C"}
@@ -86,11 +86,13 @@ export declare function previewScreenIds(host: Pick<SitePreviewHost, 'previewScr
86
86
  export declare function sitePreviewPaths(host: Pick<SitePreviewHost, 'previewScreens' | 'screens'> | null | undefined): string[];
87
87
  /**
88
88
  * Whether a request path is one the team must be routed around the public
89
- * cache for: every path while the site is in preview, or the address of a
90
- * page in preview. Trailing slashes are ignored, as Next ignores them.
89
+ * cache for: every path while the site is in preview or in maintenance, or the
90
+ * address of a page in preview. Trailing slashes are ignored, as Next ignores
91
+ * them.
91
92
  */
92
93
  export declare function isSitePreviewRequest(verdict: {
93
94
  preview?: boolean;
95
+ maintenance?: boolean;
94
96
  previewPaths?: readonly string[];
95
97
  } | null | undefined, pathname: string): boolean;
96
98
  /**
@@ -149,5 +151,7 @@ export declare function sitePreviewNotice(siteName: string | null | undefined):
149
151
  };
150
152
  /** The fixed line the team reads on every page of a site in preview. */
151
153
  export declare const SITE_PREVIEW_BANNER_TEXT = "Preview \u2014 only your team can see this site. Make it public in Admin \u2192 Error pages.";
154
+ /** The same line for a site in maintenance mode, whatever else it is in. */
155
+ export declare const SITE_MAINTENANCE_BANNER_TEXT = "Maintenance mode \u2014 only your team can see this site. Turn it off in Admin \u2192 Error pages.";
152
156
  /** The same line for one page in preview on a public site. */
153
157
  export declare const PAGE_PREVIEW_BANNER_TEXT = "Preview \u2014 only your team can see this page. Make it public in its Page Access card.";
@@ -93,11 +93,12 @@
93
93
  }
94
94
  /**
95
95
  * Whether a request path is one the team must be routed around the public
96
- * cache for: every path while the site is in preview, or the address of a
97
- * page in preview. Trailing slashes are ignored, as Next ignores them.
96
+ * cache for: every path while the site is in preview or in maintenance, or the
97
+ * address of a page in preview. Trailing slashes are ignored, as Next ignores
98
+ * them.
98
99
  */ export function isSitePreviewRequest(verdict, pathname) {
99
100
  if (!verdict) return false;
100
- if (verdict.preview === true) return true;
101
+ if (verdict.preview === true || verdict.maintenance === true) return true;
101
102
  const paths = verdict.previewPaths;
102
103
  if (!paths || !paths.length) return false;
103
104
  const normalized = routingPathToRequestPath(pathname);
@@ -162,6 +163,7 @@ export function sitePreviewSwitchPlan(host, enabled) {
162
163
  };
163
164
  }
164
165
  /** The fixed line the team reads on every page of a site in preview. */ export const SITE_PREVIEW_BANNER_TEXT = 'Preview — only your team can see this site. Make it public in Admin → Error pages.';
166
+ /** The same line for a site in maintenance mode, whatever else it is in. */ export const SITE_MAINTENANCE_BANNER_TEXT = 'Maintenance mode — only your team can see this site. Turn it off in Admin → Error pages.';
165
167
  /** The same line for one page in preview on a public site. */ export const PAGE_PREVIEW_BANNER_TEXT = 'Preview — only your team can see this page. Make it public in its Page Access card.';
166
168
 
167
169
  //# sourceMappingURL=site-preview.js.map