@aglyn/aglyn 1.0.0-beta.230 → 1.0.0-beta.232

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 (150) hide show
  1. package/package.json +11 -11
  2. package/src/lib/app-utils/account-acquisition.d.ts +15 -2
  3. package/src/lib/app-utils/account-acquisition.js +20 -1
  4. package/src/lib/app-utils/account-acquisition.js.map +1 -1
  5. package/src/lib/app-utils/artifact-list-queries.d.ts +35 -0
  6. package/src/lib/app-utils/artifact-list-queries.js +203 -0
  7. package/src/lib/app-utils/artifact-list-queries.js.map +1 -0
  8. package/src/lib/app-utils/business-profile.d.ts +171 -0
  9. package/src/lib/app-utils/business-profile.js +277 -0
  10. package/src/lib/app-utils/business-profile.js.map +1 -0
  11. package/src/lib/app-utils/child-contract.d.ts +4 -1
  12. package/src/lib/app-utils/child-contract.js +5 -2
  13. package/src/lib/app-utils/child-contract.js.map +1 -1
  14. package/src/lib/app-utils/console-routes.d.ts +5 -0
  15. package/src/lib/app-utils/console-routes.js +1 -0
  16. package/src/lib/app-utils/console-routes.js.map +1 -1
  17. package/src/lib/app-utils/content-schema-type.d.ts +9 -0
  18. package/src/lib/app-utils/content-schema-type.js +4 -0
  19. package/src/lib/app-utils/content-schema-type.js.map +1 -1
  20. package/src/lib/app-utils/crm.d.ts +14 -1
  21. package/src/lib/app-utils/crm.js +19 -2
  22. package/src/lib/app-utils/crm.js.map +1 -1
  23. package/src/lib/app-utils/docs-help.generated.d.ts +119 -5
  24. package/src/lib/app-utils/docs-help.generated.js +290 -2
  25. package/src/lib/app-utils/docs-help.generated.js.map +1 -1
  26. package/src/lib/app-utils/docs-index.generated.js +697 -32
  27. package/src/lib/app-utils/docs-index.generated.js.map +1 -1
  28. package/src/lib/app-utils/entry-list-declaration.d.ts +33 -0
  29. package/src/lib/app-utils/entry-list-declaration.js +172 -0
  30. package/src/lib/app-utils/entry-list-declaration.js.map +1 -0
  31. package/src/lib/app-utils/first-version-seed.d.ts +19 -0
  32. package/src/lib/app-utils/first-version-seed.js +53 -0
  33. package/src/lib/app-utils/first-version-seed.js.map +1 -0
  34. package/src/lib/app-utils/host-status.d.ts +85 -0
  35. package/src/lib/app-utils/host-status.js +115 -0
  36. package/src/lib/app-utils/host-status.js.map +1 -0
  37. package/src/lib/app-utils/local-business.d.ts +8 -0
  38. package/src/lib/app-utils/local-business.js +4 -0
  39. package/src/lib/app-utils/local-business.js.map +1 -1
  40. package/src/lib/app-utils/lockdown.js +1 -1
  41. package/src/lib/app-utils/lockdown.js.map +1 -1
  42. package/src/lib/app-utils/media-filter.d.ts +136 -0
  43. package/src/lib/app-utils/media-filter.js +400 -0
  44. package/src/lib/app-utils/media-filter.js.map +1 -0
  45. package/src/lib/app-utils/mobile-push.d.ts +98 -0
  46. package/src/lib/app-utils/mobile-push.js +97 -0
  47. package/src/lib/app-utils/mobile-push.js.map +1 -0
  48. package/src/lib/app-utils/notification-push.d.ts +38 -0
  49. package/src/lib/app-utils/notification-push.js +54 -0
  50. package/src/lib/app-utils/notification-push.js.map +1 -0
  51. package/src/lib/app-utils/notifications.d.ts +7 -0
  52. package/src/lib/app-utils/notifications.js.map +1 -1
  53. package/src/lib/app-utils/organizations.js +5 -2
  54. package/src/lib/app-utils/organizations.js.map +1 -1
  55. package/src/lib/app-utils/page-markdown.js +3 -0
  56. package/src/lib/app-utils/page-markdown.js.map +1 -1
  57. package/src/lib/app-utils/plugin-host-events.generated.d.ts +1 -1
  58. package/src/lib/app-utils/plugin-host-events.generated.js +149 -0
  59. package/src/lib/app-utils/plugin-host-events.generated.js.map +1 -1
  60. package/src/lib/app-utils/plugin-release-flags.generated.d.ts +1 -1
  61. package/src/lib/app-utils/plugin-release-flags.generated.js +7 -0
  62. package/src/lib/app-utils/plugin-release-flags.generated.js.map +1 -1
  63. package/src/lib/app-utils/realm-host-surface.generated.js +3 -0
  64. package/src/lib/app-utils/realm-host-surface.generated.js.map +1 -1
  65. package/src/lib/app-utils/release-flags.js +6 -2
  66. package/src/lib/app-utils/release-flags.js.map +1 -1
  67. package/src/lib/app-utils/scope-tokens.d.ts +16 -1
  68. package/src/lib/app-utils/scope-tokens.js +15 -1
  69. package/src/lib/app-utils/scope-tokens.js.map +1 -1
  70. package/src/lib/app-utils/site-list-query.d.ts +47 -0
  71. package/src/lib/app-utils/site-list-query.js +142 -0
  72. package/src/lib/app-utils/site-list-query.js.map +1 -0
  73. package/src/lib/app-utils/site-wide-outbox.d.ts +95 -0
  74. package/src/lib/app-utils/site-wide-outbox.js +117 -0
  75. package/src/lib/app-utils/site-wide-outbox.js.map +1 -0
  76. package/src/lib/app-utils/transfer-launcher-context.d.ts +6 -0
  77. package/src/lib/app-utils/transfer-launcher-context.js.map +1 -1
  78. package/src/lib/app-utils/upload-inspection.js +7 -0
  79. package/src/lib/app-utils/upload-inspection.js.map +1 -1
  80. package/src/lib/app-utils/webhook-delivery.js +4 -1
  81. package/src/lib/app-utils/webhook-delivery.js.map +1 -1
  82. package/src/lib/foundation/definitions/org-billing.types.d.ts +8 -0
  83. package/src/lib/foundation/definitions/org-billing.types.js.map +1 -1
  84. package/src/lib/foundation/definitions/organization.types.d.ts +18 -7
  85. package/src/lib/foundation/definitions/organization.types.js.map +1 -1
  86. package/src/lib/foundation/definitions/write-deny-coverage.util.d.ts +4 -1
  87. package/src/lib/foundation/definitions/write-deny-coverage.util.js +12 -2
  88. package/src/lib/foundation/definitions/write-deny-coverage.util.js.map +1 -1
  89. package/src/lib/plugin-manager/enabled-plugins.js +4 -2
  90. package/src/lib/plugin-manager/enabled-plugins.js.map +1 -1
  91. package/src/lib/plugin-manager/feature-plugins.d.ts +107 -0
  92. package/src/lib/plugin-manager/feature-plugins.js +52 -0
  93. package/src/lib/plugin-manager/feature-plugins.js.map +1 -1
  94. package/src/lib/plugin-manager/first-party-plugins.generated.js +326 -2
  95. package/src/lib/plugin-manager/first-party-plugins.generated.js.map +1 -1
  96. package/src/lib/plugin-manager/plugin-channel-orders.d.ts +262 -0
  97. package/src/lib/plugin-manager/plugin-channel-orders.js +32 -0
  98. package/src/lib/plugin-manager/plugin-channel-orders.js.map +1 -0
  99. package/src/lib/plugin-manager/plugin-checkout-extras.d.ts +168 -0
  100. package/src/lib/plugin-manager/plugin-checkout-extras.js +172 -0
  101. package/src/lib/plugin-manager/plugin-checkout-extras.js.map +1 -0
  102. package/src/lib/plugin-manager/plugin-contributions.d.ts +7 -0
  103. package/src/lib/plugin-manager/plugin-contributions.js +1 -1
  104. package/src/lib/plugin-manager/plugin-contributions.js.map +1 -1
  105. package/src/lib/plugin-manager/plugin-domain-events.d.ts +138 -0
  106. package/src/lib/plugin-manager/plugin-domain-events.js +148 -0
  107. package/src/lib/plugin-manager/plugin-domain-events.js.map +1 -0
  108. package/src/lib/plugin-manager/plugin-events.d.ts +30 -0
  109. package/src/lib/plugin-manager/plugin-events.js +4 -0
  110. package/src/lib/plugin-manager/plugin-events.js.map +1 -1
  111. package/src/lib/plugin-manager/plugin-fulfillment-providers.d.ts +101 -0
  112. package/src/lib/plugin-manager/plugin-fulfillment-providers.js +83 -0
  113. package/src/lib/plugin-manager/plugin-fulfillment-providers.js.map +1 -0
  114. package/src/lib/plugin-manager/plugin-permissions.js +21 -5
  115. package/src/lib/plugin-manager/plugin-permissions.js.map +1 -1
  116. package/src/lib/plugin-manager/plugin-person-records.d.ts +90 -0
  117. package/src/lib/plugin-manager/plugin-person-records.js +26 -0
  118. package/src/lib/plugin-manager/plugin-person-records.js.map +1 -1
  119. package/src/lib/plugin-manager/plugin-product-catalog.d.ts +209 -0
  120. package/src/lib/plugin-manager/plugin-product-catalog.js +43 -0
  121. package/src/lib/plugin-manager/plugin-product-catalog.js.map +1 -0
  122. package/src/lib/plugin-manager/plugin-product-writer.d.ts +166 -0
  123. package/src/lib/plugin-manager/plugin-product-writer.js +31 -0
  124. package/src/lib/plugin-manager/plugin-product-writer.js.map +1 -0
  125. package/src/lib/plugin-manager/plugin-shipment-records.d.ts +210 -0
  126. package/src/lib/plugin-manager/plugin-shipment-records.js +63 -0
  127. package/src/lib/plugin-manager/plugin-shipment-records.js.map +1 -0
  128. package/src/lib/plugin-manager/plugin-shipping-rates.d.ts +151 -0
  129. package/src/lib/plugin-manager/plugin-shipping-rates.js +62 -0
  130. package/src/lib/plugin-manager/plugin-shipping-rates.js.map +1 -0
  131. package/src/lib/plugin-manager/plugin-sms-messaging.d.ts +103 -0
  132. package/src/lib/plugin-manager/plugin-sms-messaging.js +39 -0
  133. package/src/lib/plugin-manager/plugin-sms-messaging.js.map +1 -0
  134. package/src/lib/plugin-manager/plugin-stock-levels.d.ts +81 -0
  135. package/src/lib/plugin-manager/plugin-stock-levels.js +32 -0
  136. package/src/lib/plugin-manager/plugin-stock-levels.js.map +1 -0
  137. package/src/lib/plugin-manager/plugin-tax-profile.d.ts +154 -0
  138. package/src/lib/plugin-manager/plugin-tax-profile.js +56 -0
  139. package/src/lib/plugin-manager/plugin-tax-profile.js.map +1 -1
  140. package/src/lib/plugin-manager/plugin-theme-font-catalog.d.ts +59 -0
  141. package/src/lib/plugin-manager/plugin-theme-font-catalog.js +40 -0
  142. package/src/lib/plugin-manager/plugin-theme-font-catalog.js.map +1 -0
  143. package/src/lib/plugin-manager/plugin-theme-presets.d.ts +40 -0
  144. package/src/lib/plugin-manager/plugin-theme-presets.js +44 -0
  145. package/src/lib/plugin-manager/plugin-theme-presets.js.map +1 -0
  146. package/src/lib/plugin-manager/plugin-tracking-pages.d.ts +55 -0
  147. package/src/lib/plugin-manager/plugin-tracking-pages.js +76 -0
  148. package/src/lib/plugin-manager/plugin-tracking-pages.js.map +1 -0
  149. package/src/lib/plugin-manager/realm-host-aglyn.generated.js +3 -0
  150. package/src/lib/plugin-manager/realm-host-aglyn.generated.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/organizations.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 * Organization helpers (AGL-233): slug policy for workspace subdomains\n * (`{slug}.aglyn.com`) and role math shared by the org APIs, the console\n * UI, and the Firestore rules' mental model. See\n * docs/MULTI_TENANT_FIRESTORE.md.\n */\n\nimport type {\n AglynOrgMember,\n AglynOrgOwnerHandoff,\n HostAccessRole,\n HostUid,\n OrgRole,\n OwnerHandoffPreviousOwner,\n ScopeToken,\n UserOrgMembership,\n} from '../foundation'\nimport {\n consoleLabelUnder,\n generateSubdomain,\n isBlockedSubdomain,\n SUBDOMAIN_PATTERN,\n} from './host-naming'\nimport {\n hostScopeToken,\n ORG_SCOPE_TOKEN,\n visibleToTokens,\n} from './scope-tokens'\n\n/** Same lexical policy as host subdomains: 3–30 lowercase/digits/dashes. */\nexport const ORG_SLUG_PATTERN = SUBDOMAIN_PATTERN\n\n/**\n * Org workspace slugs ride the host reserved/profanity blocklist plus\n * console-specific labels the workspace router must own.\n */\nconst RESERVED_ORG_ONLY = new Set(['staff', 'org', 'orgs', 'workspace'])\n\n/**\n * The label this deployment serves its own console on, when it has one\n * (AGL-3295).\n *\n * `app` and `console` are reserved above for every install. One whose console\n * lives at, say, `studio.example.com` needs `studio` refused as well, or an\n * organization could claim a workspace address the console itself answers.\n * Read from the same two settings the console's host gate reads; with either\n * unset nothing extra is reserved, because nothing extra is shadowed.\n */\nconst CONSOLE_LABEL = consoleLabelUnder(\n process.env.NEXT_PUBLIC_CONSOLE_URL,\n process.env.NEXT_PUBLIC_WORKSPACE_DOMAIN,\n)\n\nexport function isBlockedOrgSlug(slug: string): boolean {\n const normalized = slug.toLowerCase()\n return (\n RESERVED_ORG_ONLY.has(normalized) ||\n normalized === CONSOLE_LABEL ||\n isBlockedSubdomain(slug)\n )\n}\n\nexport function isValidOrgSlug(slug: string): boolean {\n return ORG_SLUG_PATTERN.test(slug) && !isBlockedOrgSlug(slug)\n}\n\n/** Best-effort slug from an org name; '' when nothing usable remains. */\nexport function generateOrgSlug(name: string): string {\n const slug = generateSubdomain(name)\n return slug && !isBlockedOrgSlug(slug) ? slug : ''\n}\n\nexport const ORG_ROLES: readonly OrgRole[] = [\n 'owner',\n 'admin',\n 'editor',\n 'viewer',\n]\n\nconst ORG_ROLE_WEIGHT: Record<OrgRole, number> = {\n owner: 3,\n admin: 2,\n editor: 1,\n viewer: 0,\n}\n\nexport function isOrgRole(value: unknown): value is OrgRole {\n return typeof value === 'string' && value in ORG_ROLE_WEIGHT\n}\n\nexport function orgRoleAtLeast(\n role: OrgRole | null | undefined,\n minimum: OrgRole,\n): boolean {\n if (!role || !(role in ORG_ROLE_WEIGHT)) return false\n return ORG_ROLE_WEIGHT[role] >= ORG_ROLE_WEIGHT[minimum]\n}\n\n/** Org settings, members, invites, host creation: admin and owner. */\nexport function canManageOrg(role: OrgRole | null | undefined): boolean {\n return orgRoleAtLeast(role, 'admin')\n}\n\n/**\n * The member's effective role on one host, or null for no access.\n * Owner/admin span every host; editor/viewer resolve through `allHosts`\n * (mapped to their org role) or the per-host access map.\n */\nexport function hostRoleFor(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid,\n): HostAccessRole | null {\n const role = member?.role\n if (!isOrgRole(role)) return null\n if (role === 'owner' || role === 'admin') return 'admin'\n const explicit = member?.hostAccess?.[hostId]\n if (explicit) return explicit\n return member?.allHosts ? role : null\n}\n\n/**\n * Host roles that may MUTATE content — the axis `canWriteHostContent()` in\n * the security rules asks (AGL-2334).\n *\n * `author` is here and absent from `HOST_PUBLISH_ROLES` below: that single\n * difference IS the \"edit content but not publish\" role. Kept as two named\n * sets rather than two inline comparisons because they are read in three\n * places that must not drift — this module, the ~20 server gates, and the\n * rules — and because a new host role added to the union has to be a\n * deliberate decision on BOTH lists rather than an omission from one.\n */\nexport const HOST_CONTENT_WRITE_ROLES: readonly HostAccessRole[] = [\n 'admin',\n 'editor',\n 'author',\n]\n\n/**\n * Host roles that may make content LIVE. Everything that registers a route,\n * moves a live-version pointer, schedules either of those for later, or\n * flips a collection entry to `published` asks this and not the set above.\n *\n * The list is short and it is the whole product decision: `author` is not on\n * it. If a role is ever added here, the rules' `canPublishHostContent()` and\n * the publish-surface field freezes below it must be updated in the same\n * change — they are the enforcement, this is the server-side echo of it.\n */\nexport const HOST_PUBLISH_ROLES: readonly HostAccessRole[] = ['admin', 'editor']\n\n/**\n * Whether the member may mutate a host's content — admin, editor **or\n * author** on it.\n *\n * An author is a content editor in every respect this predicate covers; what\n * it deliberately does NOT cover is publication. Any caller that is really\n * asking \"may this person make something live\" must call `canPublishHost`\n * instead — this one answering `true` for an author is the point of the role,\n * not a gap in it.\n */\nexport function canWriteHost(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid,\n): boolean {\n const role = hostRoleFor(member, hostId)\n return !!role && HOST_CONTENT_WRITE_ROLES.includes(role)\n}\n\n/**\n * Whether the member may PUBLISH on a host — register a route, move a live\n * version pointer, schedule either for later, or publish a collection entry.\n *\n * Strictly narrower than `canWriteHost`: `author` edits and does not publish.\n * This is the server-side echo of the rules, not the enforcement — publishing\n * is a set of client-direct Firestore writes across five document shapes, so\n * `cloud/firebase-firestore.rules` is where it is actually refused. Server\n * routes that schedule or trigger a publish ask this so the console can say\n * no with a message instead of surfacing a bare permission-denied.\n */\nexport function canPublishHost(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid,\n): boolean {\n const role = hostRoleFor(member, hostId)\n return !!role && HOST_PUBLISH_ROLES.includes(role)\n}\n\n/**\n * The same question asked of a bare `memberRoles` value rather than a member\n * document — the shape every Admin-SDK route already has in hand after its\n * `hosts/{hostId}` read, so it does not have to re-load the org membership.\n *\n * `String(role)` at the call sites keeps `undefined` out; an unknown value\n * is simply not in the set, which fails CLOSED.\n */\nexport function hostRoleCanWrite(role: unknown): boolean {\n return HOST_CONTENT_WRITE_ROLES.includes(role as HostAccessRole)\n}\n\n/** Publish-axis twin of `hostRoleCanWrite`; `author` is excluded. */\nexport function hostRoleCanPublish(role: unknown): boolean {\n return HOST_PUBLISH_ROLES.includes(role as HostAccessRole)\n}\n\n/**\n * Whether a member's reach is the whole org rather than a list of sites.\n *\n * Owner and admin always are; editor/viewer are only when `allHosts` says\n * so — **or** when the membership predates the flag entirely. A pre-\n * `allHosts` doc carries neither the flag nor a `hostAccess` map, and\n * reading that as \"scoped, with access to nothing\" would lock real members\n * out of their own workspace. A site collaborator ALWAYS has a non-empty\n * `hostAccess` (that is what `grantHostAccess` writes), so the absence of\n * both is the legacy shape, not a scoped one.\n *\n * Single source of truth for `resolveOrgPermissions` (the server gate),\n * `projectMemberScopeTokens` (the rules projection), and the rules'\n * own `isOrgWideMember()` — three copies of this predicate that disagree\n * is a privilege bug, not a style problem (AGL-1026, AGL-1038).\n */\nexport function isOrgWideMember(\n member: Partial<AglynOrgMember> | null | undefined,\n): boolean {\n if (!member) return false\n const role = member.role\n if (role === 'owner' || role === 'admin') return true\n if (member.allHosts === true) return true\n const scoping = member.hostAccess\n return (\n member.allHosts === undefined && !Object.keys(scoping ?? {}).length\n )\n}\n\n/**\n * How many of these roster entries consume a **manager** seat (AGL-1113).\n *\n * `orgs/{orgId}/members` holds BOTH org managers and site-scoped\n * collaborators — adding a collaborator to one site writes an org member doc\n * with `allHosts:false` + `hostAccess`, so a raw `.count()` of the collection\n * billed every collaborator as a manager. Collaborators are metered\n * separately, per host, against `membersPerHost` at\n * `hosts/{hostId}/members` — counting them here charged them twice and\n * tripped the manager gate for orgs nowhere near their manager limit.\n *\n * Reuses `isOrgWideMember` rather than filtering on `allHosts` directly:\n * owner/admin are managers whatever the flag says, and a pre-`allHosts` doc\n * is a manager too. A Firestore `where('allHosts','==',true)` count gets both\n * of those wrong, which is why callers pass entries in and count here.\n *\n * Accepts pending INVITES as well as members — an invite carries the same\n * `role`/`allHosts`/`hostAccess` shape and reserves the seat it will become.\n */\nexport function countManagerSeats(\n entries: ReadonlyArray<\n | (Partial<AglynOrgMember> & { handoff?: unknown })\n | null\n | undefined\n >,\n): number {\n let count = 0\n for (const entry of entries) {\n if (usesCustomerSeat(entry) && isOrgWideMember(entry)) count += 1\n }\n return count\n}\n\n/**\n * Whether a roster row or pending invite takes one of the customer's seats\n * at all (AGL-3466). Every seat counter asks this before it asks which kind\n * of seat, so the two populations below never include either exception.\n *\n * Two kinds of entry hold access without a seat:\n *\n * - **Platform staff.** A row or invite stamped `staffSeat: true` belongs to\n * an account holding the `staff` claim. Staff build workspaces for\n * prospects and join them to help; billing the customer a seat for either\n * is what made a Free workspace (one seat) unable to invite the client it\n * was built for without a hand-written override.\n * - **An owner handoff.** An invite carrying `handoff` moves the owner seat\n * from one person to another rather than adding one. Whether the outgoing\n * owner staying on needs a seat of their own is decided when the handoff is\n * sent and again when it is accepted, never by counting the invite.\n */\nexport function usesCustomerSeat(\n entry:\n | { staffSeat?: unknown; handoff?: unknown }\n | null\n | undefined,\n): boolean {\n if (!entry) return false\n if (entry.staffSeat === true) return false\n return !entry.handoff\n}\n\n/**\n * Whether a roster row belongs to platform staff (AGL-3466) — the Team\n * page's \"no seat\" chip, and the row every seat count leaves out.\n */\nexport function isStaffSeat(\n entry: { staffSeat?: unknown } | null | undefined,\n): boolean {\n return entry?.staffSeat === true\n}\n\n/** The outgoing owner's choices, in the order the picker offers them. */\nexport const OWNER_HANDOFF_PREVIOUS_OWNER: readonly OwnerHandoffPreviousOwner[] = [\n 'stay',\n 'leave',\n]\n\n/** What each choice does, for the picker and the confirmation. */\nexport const OWNER_HANDOFF_PREVIOUS_OWNER_LABELS: Record<\n OwnerHandoffPreviousOwner,\n string\n> = {\n stay: 'Stay on as an admin after the handoff',\n leave: 'Leave after the handoff',\n}\n\n/**\n * The handoff half of an invite request, or null when it is not a usable\n * one (AGL-3466).\n *\n * Read in one place because the same body reaches the server from three\n * surfaces (the Team page, the staff organization page and the staff site\n * page), and an unknown `previousOwner` must be refused rather than guessed:\n * guessing `leave` takes someone off a roster they meant to stay on, and\n * guessing `stay` spends a seat they meant to free.\n */\nexport function parseOwnerHandoff(raw: unknown): AglynOrgOwnerHandoff | null {\n if (!raw || typeof raw !== 'object') return null\n const previousOwner = (raw as { previousOwner?: unknown }).previousOwner\n return previousOwner === 'stay' || previousOwner === 'leave'\n ? { previousOwner }\n : null\n}\n\n/**\n * One roster row or pending invite, as the collaborator counter needs to see\n * it (AGL-2068). Deliberately structural rather than `Partial<AglynOrgMember>`\n * — an INVITE is not a member document, it is keyed by email and has no uid,\n * and the whole point of this counter is that the two populations must be\n * counted together or the cap is enforced against a fraction of itself.\n */\nexport interface CollaboratorSeatEntry {\n /** Member documents are keyed by uid; invites have none. */\n uid?: string | null\n email?: string | null\n role?: unknown\n allHosts?: boolean\n hostAccess?: Record<string, unknown> | null\n /** Platform staff hold no seat (AGL-3466) — see `usesCustomerSeat`. */\n staffSeat?: boolean | null\n /** An owner-handoff invite holds no seat (AGL-3466). */\n handoff?: unknown\n}\n\n/**\n * The identity key one entry occupies, or `''` when it identifies nobody.\n *\n * EMAIL FIRST, uid second, and that order is the join (AGL-2068). A person\n * admitted to a site is one seat whether they arrive as an accepted member or\n * as a still-pending invite, and those two rows live in different collections\n * keyed different ways — `orgs/{id}/members/{uid}` and\n * `orgs/{id}/invites/{inviteId}` — with the address as the only field both\n * carry. Counting by uid would count the invite and the membership it becomes\n * as two seats; counting only invites would miss every member.\n *\n * Legacy roster rows written before `email` was mirrored fall back to the uid,\n * which cannot collide with an address (the `uid:` prefix is not a legal\n * local-part/domain pair) and so is safe to mix into the same set.\n */\nfunction collaboratorSeatKey(entry: CollaboratorSeatEntry): string {\n const email =\n typeof entry.email === 'string' ? entry.email.trim().toLowerCase() : ''\n if (email) return email\n const uid = typeof entry.uid === 'string' ? entry.uid.trim() : ''\n return uid ? `uid:${uid}` : ''\n}\n\n/**\n * Every principal consuming a COLLABORATOR seat on one host (AGL-2068).\n *\n * ## Why this exists at all\n *\n * `membersPerHost` was enforced on one of the four doors that admit a site\n * collaborator, and that one door counted `hosts/{hostId}/members` — a\n * DISPLAY roster only `/api/hosts/members` writes. The other three\n * (`/api/orgs/invites` create, `/api/orgs/invites` accept, and the\n * `hostAccess` branch of `/api/orgs/members`) land in `orgs/{id}/members` and\n * the `hosts/{id}.memberRoles` projection, and were invisible to it. So the\n * cap was both skipped on three paths and under-counted on the fourth, and a\n * free org — `membersPerHost: 1` — could take on unlimited collaborators,\n * each with full site access, on a plan that is never invoiced.\n *\n * verbatim: **\"We need to make sure the free/hobby tier\n * does hard cap so it always actually stays free.\"**\n *\n * ## What counts\n *\n * A SCOPED grant on `hostId`, and nothing else. An org-wide member\n * (owner/admin, or `allHosts`) reaches every host but consumes a MANAGER\n * seat — `countManagerSeats` is that side, and charging them here would bill\n * one person twice and trip a cap they are not on. This is the same split\n * AGL-1113 drew; it is now drawn from one place instead of three.\n *\n * Pending invites count, for the reason the manager gate counts them: an\n * invite reserves the seat it will become, and a cap that only bites on\n * acceptance can be walked past by mailing out N invites first.\n */\nexport function collaboratorSeatKeys(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n hostId: string,\n): Set<string> {\n const keys = new Set<string>()\n if (!hostId) return keys\n for (const entry of entries) {\n if (!usesCustomerSeat(entry)) continue\n // Managers are the other counter's population, whatever host map they\n // happen to carry — a promoted collaborator keeps their old `hostAccess`.\n if (isOrgWideMember(entry as Partial<AglynOrgMember>)) continue\n if (!entry.hostAccess?.[hostId]) continue\n const key = collaboratorSeatKey(entry)\n if (key) keys.add(key)\n }\n return keys\n}\n\n/**\n * How many collaborator seats on `hostId` are spoken for by someone OTHER\n * than `exclude` (AGL-2068).\n *\n * `exclude` is the principal the caller is about to admit, and dropping them\n * is what makes this composable with `checkSeatQuota(…, used)`, whose\n * contract is \"usage BEFORE the resource being created\". Without it the\n * accept path refuses its own invite: at the moment acceptance is decided the\n * invitee holds a pending invite AND is about to hold a membership, so they\n * would be counted once or twice against a cap they are the subject of.\n *\n * Both identities are dropped, not whichever one is present. A person can be\n * on the roster under a uid with no mirrored email and hold an invite under\n * that address, and the seat is still one seat.\n *\n * ## `emails`, not `email` — an account holds several (AGL-2486)\n *\n * Since an invitation may be accepted at any CONFIRMED address on the account,\n * the pending invite the accepter is about to consume can be keyed by an\n * address that is not their primary. `exclude.email` alone is the primary, so\n * that invite survived the exclusion and the person was counted against a cap\n * they are the subject of — the exact double-count the paragraph above says\n * this function exists to prevent, re-opened by widening the accept match.\n *\n * It fails CLOSED (a spurious \"out of seats\" refusal, never a free seat), and\n * only for an org sitting exactly on its cap, which is why it survived review.\n *\n * `emails` takes every address PROVEN to belong to the principal being\n * admitted. Passing an address that is not theirs would hand out a free seat,\n * so callers must pass confirmed addresses for that uid and nothing else.\n */\nexport function countCollaboratorSeats(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n hostId: string,\n exclude?: {\n uid?: string | null\n email?: string | null\n /** Further addresses on the SAME account; see above. */\n emails?: readonly (string | null | undefined)[] | null\n },\n): number {\n const keys = collaboratorSeatKeys(entries, hostId)\n for (const candidate of [exclude?.email, ...(exclude?.emails ?? [])]) {\n const email = typeof candidate === 'string' ? candidate.trim().toLowerCase() : ''\n if (email) keys.delete(email)\n }\n const uid = typeof exclude?.uid === 'string' ? exclude.uid.trim() : ''\n if (uid) keys.delete(`uid:${uid}`)\n return keys.size\n}\n\n/**\n * Every principal consuming a MANAGER seat, as identities rather than rows.\n *\n * The org-wide half of `collaboratorSeatKeys`, drawn from the same entries and\n * split on the same predicate, so the two counters partition one roster\n * instead of overlapping on it.\n *\n * Deduplicating by identity is the difference from {@link countManagerSeats},\n * and it is what makes this composable with an `exclude`: a person holding a\n * pending invite AND the membership it became is one seat, and the row-wise\n * counter reports two because it is handed the two collections separately and\n * sums them.\n */\nexport function managerSeatKeys(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n): Set<string> {\n const keys = new Set<string>()\n for (const entry of entries) {\n if (!usesCustomerSeat(entry)) continue\n if (!isOrgWideMember(entry as Partial<AglynOrgMember>)) continue\n const key = collaboratorSeatKey(entry)\n if (key) keys.add(key)\n }\n return keys\n}\n\n/**\n * How many manager seats are spoken for by someone OTHER than `exclude`.\n *\n * The manager twin of {@link countCollaboratorSeats}, and it exists for the\n * same reason that one takes an `exclude`: `checkSeatQuota`'s contract is\n * \"usage BEFORE the resource being created\", and on the invite-accept path the\n * accepter holds a pending invite and is about to hold a membership at the\n * same instant. Counted plainly they are charged once or twice for a seat they\n * are the subject of, and an org on its last seat refuses its own invitation.\n *\n * Both identities are dropped, and `emails` carries the further addresses\n * proven to belong to that account — an invitation may be accepted at any\n * confirmed address, so the invite being consumed need not be keyed by the\n * primary one. Passing an address that is not theirs would hand out a free\n * seat, so callers must pass confirmed addresses for that uid and nothing\n * else.\n *\n * Kept SEPARATE from {@link countManagerSeats} rather than replacing it: that\n * one is row-wise and is what the billing and console surfaces count with, and\n * quietly making it identity-wise would change every one of those totals.\n */\nexport function countManagerSeatsExcluding(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n exclude?: {\n uid?: string | null\n email?: string | null\n /** Further addresses on the SAME account; see above. */\n emails?: readonly (string | null | undefined)[] | null\n },\n): number {\n const keys = managerSeatKeys(entries)\n for (const candidate of [exclude?.email, ...(exclude?.emails ?? [])]) {\n const email = typeof candidate === 'string' ? candidate.trim().toLowerCase() : ''\n if (email) keys.delete(email)\n }\n const uid = typeof exclude?.uid === 'string' ? exclude.uid.trim() : ''\n if (uid) keys.delete(`uid:${uid}`)\n return keys.size\n}\n\n/**\n * What KIND of user a console row represents (AGL-1114) — the distinction\n * that decides which seat they consume, and the one the Team table could not\n * express because a manager and a collaborator differ only by fields the\n * table never showed.\n *\n * Deliberately NOT the same axis as `role`. A `role: 'editor'` is a manager\n * when their reach is the whole org and a collaborator when it is two sites;\n * reading the role alone is the mistake that let a collaborator look like\n * team staff (see the org-leak and role-gate work).\n *\n * `siteMember` is the third kind and never appears in `orgs/{id}/members` at\n * all: it is an end-user account on a PUBLISHED site (`siteMembers`), not a\n * console user. It has no Firebase Auth record of any kind — a site member is\n * a Firestore document under `hosts/{hostId}/siteMembers` with its own scrypt\n * hash and its own session cookie — so no surface that lists AUTH accounts,\n * the staff user directory included, can contain one. The label is here so the\n * vocabulary is complete, for a surface that lists site accounts and needs a\n * word for them. Free and uncounted on every plan (AGL-889).\n */\nexport type ConsoleUserType = 'manager' | 'collaborator' | 'siteMember'\n\nexport const CONSOLE_USER_TYPE_LABELS: Record<ConsoleUserType, string> = {\n manager: 'Team manager',\n collaborator: 'Site collaborator',\n siteMember: 'Site member',\n}\n\n/** One line on what each kind is and what it costs — tooltip/legend copy. */\nexport const CONSOLE_USER_TYPE_HINTS: Record<ConsoleUserType, string> = {\n manager:\n 'Reaches the whole organization. Uses one of your team (manager) seats.',\n collaborator:\n 'Scoped to specific sites. Uses a collaborator seat on each site they ' +\n 'can reach, not a team seat.',\n siteMember:\n 'An end-user account on a published site, not a console user. Free and ' +\n 'unlimited on every plan.',\n}\n\n/**\n * Classify an `orgs/{orgId}/members` entry (or a pending invite, same shape).\n * Never returns `siteMember` — nothing in that collection is one; the value\n * exists for surfaces that list published-site accounts and must label them —\n * never for one that lists both, since the two populations do not share an\n * identity system.\n */\nexport function consoleUserType(\n member: Partial<AglynOrgMember> | null | undefined,\n): Exclude<ConsoleUserType, 'siteMember'> {\n return isOrgWideMember(member) ? 'manager' : 'collaborator'\n}\n\n/**\n * Whether an account is governed by enterprise SSO (AGL-1128) — it lives in\n * an org's GCIP tenant pool rather than the project pool, so its identity is\n * owned by the customer's IdP.\n *\n * `tenantId` is the whole signal: Firebase sets it on the user whenever the\n * account belongs to a tenant, and only SSO accounts do.\n */\nexport function isSsoGovernedAccount(\n user: { tenantId?: string | null } | null | undefined,\n): boolean {\n return Boolean(user?.tenantId)\n}\n\n/**\n * Whether the account may connect an additional consumer sign-in provider.\n *\n * **No, for any SSO-governed account.** The customer's IdP is the single gate\n * they bought: they revoke there, enforce MFA there, offboard there. A linked\n * personal Google account is a way in their IdP can never see or revoke —\n * exactly what SSO is purchased to prevent.\n *\n * Deliberately NOT gated on `sso.enforced`. That flag exists so we never\n * LOCK OUT an existing sign-in method; it is not a licence to hand out new\n * bypasses meanwhile. Nothing here removes a provider an account already has,\n * so this can never lock anyone out.\n *\n * This is the intent, not the boundary — the boundary is upstream, since a\n * GCIP tenant only accepts providers enabled on that tenant. Both matter: the\n * boundary is remote config that could drift, and a UI that offers a\n * security-regressing action is wrong even when the action would fail.\n */\nexport function canLinkSocialProvider(\n user: { tenantId?: string | null } | null | undefined,\n): boolean {\n return !isSsoGovernedAccount(user)\n}\n\n/**\n * The same question as `isOrgWideMember`, asked of the `users/{uid}/orgs`\n * reverse-index row instead of the member doc (AGL-1032).\n *\n * The console navigates from the index — it is what `useOrgScope` loads —\n * and the index carries a MIRROR of the predicate, not the inputs to it, so\n * this cannot recompute: `role: 'viewer'` on the index means \"viewer\",\n * whether the member reaches every site or one.\n *\n * Reads a missing flag as org-wide, for the same reason `isOrgWideMember`\n * reads a missing `allHosts` that way: rows written before the mirror\n * existed have no flag, and hiding the workspace from a real member is a\n * worse failure than showing org chrome to a collaborator whose reads the\n * rules refuse anyway. Owner/admin are org-wide by role regardless of the\n * mirror, so a stale row can never lock an admin out.\n *\n * Navigation only — never an access decision. AGL-1026 (rules) and the\n * Admin-SDK scope checks are the boundary.\n */\nexport function isOrgWideMembership(\n membership:\n | Pick<UserOrgMembership, 'role' | 'orgWide'>\n | null\n | undefined,\n): boolean {\n if (!membership) return true\n if (membership.role === 'owner' || membership.role === 'admin') return true\n return membership.orgWide !== false\n}\n\n/**\n * The `scopeTokens` projection stamped onto member docs (AGL-1038) so the\n * rules can intersect a caller's reach with a resource's `visibleTo` —\n * rules have no `.map()`, so `hostAccess`'s keys cannot be turned into\n * tokens at evaluation time and have to be denormalized here.\n *\n * Org-wide members get `['org']`; they own the org and read everything in\n * it, scoped or not (the rules short-circuit on them anyway). A scoped\n * collaborator gets `'org'` plus one token per granted host — `'org'`\n * because an org-WIDE resource stays readable by any member, which is\n * today's behavior and not something this project narrows.\n *\n * Not capped at `MAX_SCOPE_HOSTS`: the rules' `hasAny` has no 30-value\n * limit, only the client `array-contains-any` query does, so a member of\n * more than 30 sites is a listing problem for AGL-1044 to chunk, not a\n * reason to under-grant here.\n */\nexport function projectMemberScopeTokens(\n member: Partial<AglynOrgMember> | null | undefined,\n): ScopeToken[] {\n if (isOrgWideMember(member)) return [ORG_SCOPE_TOKEN]\n const hostIds = Object.keys(member?.hostAccess ?? {})\n return [ORG_SCOPE_TOKEN, ...hostIds.map(hostScopeToken)]\n}\n\n/**\n * A member's effective read set: the stored `scopeTokens` projection when it\n * is there, recomputed from the membership when it is not.\n *\n * The fallback is the security-relevant half and it was written out by hand\n * in four places (`use-scope-tokens`, `erase-scope`, the media sign route,\n * and by omission in `resolveMediaScope`, which only ever recomputed). Four\n * copies of \"what may this member see\" is the shape that eventually\n * disagrees, and a copy that reads `member.scopeTokens` WITHOUT the\n * `.length` guard silently grants nothing to a member the AGL-1040 backfill\n * has not reached — or, written the other way round, grants everything.\n *\n * Recomputing is the safe fallback rather than a convenience: it produces\n * exactly what `grantHostAccess` would have stamped, so an unstamped member\n * doc behaves as its `hostAccess` says, never as \"no access\" and never as\n * org-wide.\n */\nexport function memberScopeTokens(\n member: Partial<AglynOrgMember> | null | undefined,\n): ScopeToken[] {\n const stored = member?.scopeTokens\n return stored?.length ? stored : projectMemberScopeTokens(member)\n}\n\n/**\n * May this member see a resource carrying `visibleTo`? (AGL-1037/1038)\n *\n * The whole client-side/server-side authorization question in one place:\n * org-wide members read everything they own; everyone else needs their read\n * set to intersect the resource's scope. Absent/empty `visibleTo` is\n * org-wide by the same rule the Firestore rules use, so an unbackfilled\n * resource does not vanish.\n *\n * Every Admin-SDK path must call this (or `scopeAllows`, which wraps an\n * already-resolved scope) — the Admin SDK bypasses rules entirely, so this\n * IS the enforcement there, not a second opinion about it.\n *\n * NOT a membership check, and never a substitute for one: a `null` member\n * \"can see\" an org-wide resource here, because the question this answers is\n * \"is this resource in scope for that reach\", not \"is this person in the\n * org\". Resolve membership first and refuse the caller if there is none —\n * conflating the two is exactly how AGL-1026 exposed a whole org.\n */\nexport function memberCanSee(\n member: Partial<AglynOrgMember> | null | undefined,\n visibleTo: readonly string[] | null | undefined,\n): boolean {\n if (isOrgWideMember(member)) return true\n return visibleToTokens(visibleTo ?? undefined, memberScopeTokens(member))\n}\n\n/**\n * The `memberRoles` projection stamped onto host docs so Firestore rules\n * authorize host content with the single host-doc read they already do\n * (docs/MULTI_TENANT_FIRESTORE.md §5). Recomputed by the membership API\n * whenever a member changes; owner/admin appear on every host.\n */\nexport function projectHostMemberRoles(\n members: ReadonlyArray<Partial<AglynOrgMember> & { $id: string }>,\n hostId: HostUid,\n): Record<string, HostAccessRole> {\n const projection: Record<string, HostAccessRole> = {}\n for (const member of members) {\n const role = hostRoleFor(member, hostId)\n if (role) projection[member.$id] = role\n }\n return projection\n}\n"],"names":["consoleLabelUnder","generateSubdomain","isBlockedSubdomain","SUBDOMAIN_PATTERN","hostScopeToken","ORG_SCOPE_TOKEN","visibleToTokens","ORG_SLUG_PATTERN","RESERVED_ORG_ONLY","Set","CONSOLE_LABEL","process","env","NEXT_PUBLIC_CONSOLE_URL","NEXT_PUBLIC_WORKSPACE_DOMAIN","isBlockedOrgSlug","slug","normalized","toLowerCase","has","isValidOrgSlug","test","generateOrgSlug","name","ORG_ROLES","ORG_ROLE_WEIGHT","owner","admin","editor","viewer","isOrgRole","value","orgRoleAtLeast","role","minimum","canManageOrg","hostRoleFor","member","hostId","explicit","hostAccess","allHosts","HOST_CONTENT_WRITE_ROLES","HOST_PUBLISH_ROLES","canWriteHost","includes","canPublishHost","hostRoleCanWrite","hostRoleCanPublish","isOrgWideMember","scoping","undefined","Object","keys","length","countManagerSeats","entries","count","entry","usesCustomerSeat","staffSeat","handoff","isStaffSeat","OWNER_HANDOFF_PREVIOUS_OWNER","OWNER_HANDOFF_PREVIOUS_OWNER_LABELS","stay","leave","parseOwnerHandoff","raw","previousOwner","collaboratorSeatKey","email","trim","uid","collaboratorSeatKeys","key","add","countCollaboratorSeats","exclude","candidate","emails","delete","size","managerSeatKeys","countManagerSeatsExcluding","CONSOLE_USER_TYPE_LABELS","manager","collaborator","siteMember","CONSOLE_USER_TYPE_HINTS","consoleUserType","isSsoGovernedAccount","user","Boolean","tenantId","canLinkSocialProvider","isOrgWideMembership","membership","orgWide","projectMemberScopeTokens","hostIds","map","memberScopeTokens","stored","scopeTokens","memberCanSee","visibleTo","projectHostMemberRoles","members","projection","$id"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;CAKC,GAYD,SACEA,iBAAiB,EACjBC,iBAAiB,EACjBC,kBAAkB,EAClBC,iBAAiB,QACZ,mBAAe;AACtB,SACEC,cAAc,EACdC,eAAe,EACfC,eAAe,QACV,oBAAgB;AAEvB,0EAA0E,GAC1E,OAAO,MAAMC,mBAAmBJ,kBAAiB;AAEjD;;;CAGC,GACD,MAAMK,oBAAoB,IAAIC,IAAI;IAAC;IAAS;IAAO;IAAQ;CAAY;AAEvE;;;;;;;;;CASC,GACD,MAAMC,gBAAgBV,kBACpBW,QAAQC,GAAG,CAACC,uBAAuB,EACnCF,QAAQC,GAAG,CAACE,4BAA4B;AAG1C,OAAO,SAASC,iBAAiBC,IAAY;IAC3C,MAAMC,aAAaD,KAAKE,WAAW;IACnC,OACEV,kBAAkBW,GAAG,CAACF,eACtBA,eAAeP,iBACfR,mBAAmBc;AAEvB;AAEA,OAAO,SAASI,eAAeJ,IAAY;IACzC,OAAOT,iBAAiBc,IAAI,CAACL,SAAS,CAACD,iBAAiBC;AAC1D;AAEA,uEAAuE,GACvE,OAAO,SAASM,gBAAgBC,IAAY;IAC1C,MAAMP,OAAOf,kBAAkBsB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BZ,SAAS,OAAO;IACpC,OAAO/B,gBAAgBoG,oBAAAA,YAAavD,WAAWmD,kBAAkBjE;AACnE;AAEA;;;;;CAKC,GACD,OAAO,SAASsE,uBACdC,OAAiE,EACjEtE,MAAe;IAEf,MAAMuE,aAA6C,CAAC;IACpD,KAAK,MAAMxE,UAAUuE,QAAS;QAC5B,MAAM3E,OAAOG,YAAYC,QAAQC;QACjC,IAAIL,MAAM4E,UAAU,CAACxE,OAAOyE,GAAG,CAAC,GAAG7E;IACrC;IACA,OAAO4E;AACT"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/organizations.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 * Organization helpers (AGL-233): slug policy for workspace subdomains\n * (`{slug}.aglyn.com`) and role math shared by the org APIs, the console\n * UI, and the Firestore rules' mental model. See\n * docs/MULTI_TENANT_FIRESTORE.md.\n */\n\nimport type {\n AglynOrgMember,\n AglynOrgOwnerHandoff,\n HostAccessRole,\n HostUid,\n OrgRole,\n OwnerHandoffPreviousOwner,\n ScopeToken,\n UserOrgMembership,\n} from '../foundation'\nimport {\n consoleLabelUnder,\n generateSubdomain,\n isBlockedSubdomain,\n SUBDOMAIN_PATTERN,\n} from './host-naming'\nimport {\n hostScopeToken,\n ORG_SCOPE_TOKEN,\n visibleToTokens,\n} from './scope-tokens'\n\n/** Same lexical policy as host subdomains: 3–30 lowercase/digits/dashes. */\nexport const ORG_SLUG_PATTERN = SUBDOMAIN_PATTERN\n\n/**\n * Org workspace slugs ride the host reserved/profanity blocklist plus\n * console-specific labels the workspace router must own. `kiosk` is the\n * console's public device route (AGL-3608), which a static segment serves\n * ahead of any workspace of that name.\n */\nconst RESERVED_ORG_ONLY = new Set(['staff', 'org', 'orgs', 'workspace', 'kiosk'])\n\n/**\n * The label this deployment serves its own console on, when it has one\n * (AGL-3295).\n *\n * `app` and `console` are reserved above for every install. One whose console\n * lives at, say, `studio.example.com` needs `studio` refused as well, or an\n * organization could claim a workspace address the console itself answers.\n * Read from the same two settings the console's host gate reads; with either\n * unset nothing extra is reserved, because nothing extra is shadowed.\n */\nconst CONSOLE_LABEL = consoleLabelUnder(\n process.env.NEXT_PUBLIC_CONSOLE_URL,\n process.env.NEXT_PUBLIC_WORKSPACE_DOMAIN,\n)\n\nexport function isBlockedOrgSlug(slug: string): boolean {\n const normalized = slug.toLowerCase()\n return (\n RESERVED_ORG_ONLY.has(normalized) ||\n normalized === CONSOLE_LABEL ||\n isBlockedSubdomain(slug)\n )\n}\n\nexport function isValidOrgSlug(slug: string): boolean {\n return ORG_SLUG_PATTERN.test(slug) && !isBlockedOrgSlug(slug)\n}\n\n/** Best-effort slug from an org name; '' when nothing usable remains. */\nexport function generateOrgSlug(name: string): string {\n const slug = generateSubdomain(name)\n return slug && !isBlockedOrgSlug(slug) ? slug : ''\n}\n\nexport const ORG_ROLES: readonly OrgRole[] = [\n 'owner',\n 'admin',\n 'editor',\n 'viewer',\n]\n\nconst ORG_ROLE_WEIGHT: Record<OrgRole, number> = {\n owner: 3,\n admin: 2,\n editor: 1,\n viewer: 0,\n}\n\nexport function isOrgRole(value: unknown): value is OrgRole {\n return typeof value === 'string' && value in ORG_ROLE_WEIGHT\n}\n\nexport function orgRoleAtLeast(\n role: OrgRole | null | undefined,\n minimum: OrgRole,\n): boolean {\n if (!role || !(role in ORG_ROLE_WEIGHT)) return false\n return ORG_ROLE_WEIGHT[role] >= ORG_ROLE_WEIGHT[minimum]\n}\n\n/** Org settings, members, invites, host creation: admin and owner. */\nexport function canManageOrg(role: OrgRole | null | undefined): boolean {\n return orgRoleAtLeast(role, 'admin')\n}\n\n/**\n * The member's effective role on one host, or null for no access.\n * Owner/admin span every host; editor/viewer resolve through `allHosts`\n * (mapped to their org role) or the per-host access map.\n */\nexport function hostRoleFor(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid,\n): HostAccessRole | null {\n const role = member?.role\n if (!isOrgRole(role)) return null\n if (role === 'owner' || role === 'admin') return 'admin'\n const explicit = member?.hostAccess?.[hostId]\n if (explicit) return explicit\n return member?.allHosts ? role : null\n}\n\n/**\n * Host roles that may MUTATE content — the axis `canWriteHostContent()` in\n * the security rules asks (AGL-2334).\n *\n * `author` is here and absent from `HOST_PUBLISH_ROLES` below: that single\n * difference IS the \"edit content but not publish\" role. Kept as two named\n * sets rather than two inline comparisons because they are read in three\n * places that must not drift — this module, the ~20 server gates, and the\n * rules — and because a new host role added to the union has to be a\n * deliberate decision on BOTH lists rather than an omission from one.\n */\nexport const HOST_CONTENT_WRITE_ROLES: readonly HostAccessRole[] = [\n 'admin',\n 'editor',\n 'author',\n]\n\n/**\n * Host roles that may make content LIVE. Everything that registers a route,\n * moves a live-version pointer, schedules either of those for later, or\n * flips a collection entry to `published` asks this and not the set above.\n *\n * The list is short and it is the whole product decision: `author` is not on\n * it. If a role is ever added here, the rules' `canPublishHostContent()` and\n * the publish-surface field freezes below it must be updated in the same\n * change — they are the enforcement, this is the server-side echo of it.\n */\nexport const HOST_PUBLISH_ROLES: readonly HostAccessRole[] = ['admin', 'editor']\n\n/**\n * Whether the member may mutate a host's content — admin, editor **or\n * author** on it.\n *\n * An author is a content editor in every respect this predicate covers; what\n * it deliberately does NOT cover is publication. Any caller that is really\n * asking \"may this person make something live\" must call `canPublishHost`\n * instead — this one answering `true` for an author is the point of the role,\n * not a gap in it.\n */\nexport function canWriteHost(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid,\n): boolean {\n const role = hostRoleFor(member, hostId)\n return !!role && HOST_CONTENT_WRITE_ROLES.includes(role)\n}\n\n/**\n * Whether the member may PUBLISH on a host — register a route, move a live\n * version pointer, schedule either for later, or publish a collection entry.\n *\n * Strictly narrower than `canWriteHost`: `author` edits and does not publish.\n * This is the server-side echo of the rules, not the enforcement — publishing\n * is a set of client-direct Firestore writes across five document shapes, so\n * `cloud/firebase-firestore.rules` is where it is actually refused. Server\n * routes that schedule or trigger a publish ask this so the console can say\n * no with a message instead of surfacing a bare permission-denied.\n */\nexport function canPublishHost(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid,\n): boolean {\n const role = hostRoleFor(member, hostId)\n return !!role && HOST_PUBLISH_ROLES.includes(role)\n}\n\n/**\n * The same question asked of a bare `memberRoles` value rather than a member\n * document — the shape every Admin-SDK route already has in hand after its\n * `hosts/{hostId}` read, so it does not have to re-load the org membership.\n *\n * `String(role)` at the call sites keeps `undefined` out; an unknown value\n * is simply not in the set, which fails CLOSED.\n */\nexport function hostRoleCanWrite(role: unknown): boolean {\n return HOST_CONTENT_WRITE_ROLES.includes(role as HostAccessRole)\n}\n\n/** Publish-axis twin of `hostRoleCanWrite`; `author` is excluded. */\nexport function hostRoleCanPublish(role: unknown): boolean {\n return HOST_PUBLISH_ROLES.includes(role as HostAccessRole)\n}\n\n/**\n * Whether a member's reach is the whole org rather than a list of sites.\n *\n * Owner and admin always are; editor/viewer are only when `allHosts` says\n * so — **or** when the membership predates the flag entirely. A pre-\n * `allHosts` doc carries neither the flag nor a `hostAccess` map, and\n * reading that as \"scoped, with access to nothing\" would lock real members\n * out of their own workspace. A site collaborator ALWAYS has a non-empty\n * `hostAccess` (that is what `grantHostAccess` writes), so the absence of\n * both is the legacy shape, not a scoped one.\n *\n * Single source of truth for `resolveOrgPermissions` (the server gate),\n * `projectMemberScopeTokens` (the rules projection), and the rules'\n * own `isOrgWideMember()` — three copies of this predicate that disagree\n * is a privilege bug, not a style problem (AGL-1026, AGL-1038).\n */\nexport function isOrgWideMember(\n member: Partial<AglynOrgMember> | null | undefined,\n): boolean {\n if (!member) return false\n const role = member.role\n if (role === 'owner' || role === 'admin') return true\n if (member.allHosts === true) return true\n const scoping = member.hostAccess\n return (\n member.allHosts === undefined && !Object.keys(scoping ?? {}).length\n )\n}\n\n/**\n * How many of these roster entries consume a **manager** seat (AGL-1113).\n *\n * `orgs/{orgId}/members` holds BOTH org managers and site-scoped\n * collaborators — adding a collaborator to one site writes an org member doc\n * with `allHosts:false` + `hostAccess`, so a raw `.count()` of the collection\n * billed every collaborator as a manager. Collaborators are metered\n * separately, per host, against `membersPerHost` at\n * `hosts/{hostId}/members` — counting them here charged them twice and\n * tripped the manager gate for orgs nowhere near their manager limit.\n *\n * Reuses `isOrgWideMember` rather than filtering on `allHosts` directly:\n * owner/admin are managers whatever the flag says, and a pre-`allHosts` doc\n * is a manager too. A Firestore `where('allHosts','==',true)` count gets both\n * of those wrong, which is why callers pass entries in and count here.\n *\n * Accepts pending INVITES as well as members — an invite carries the same\n * `role`/`allHosts`/`hostAccess` shape and reserves the seat it will become.\n */\nexport function countManagerSeats(\n entries: ReadonlyArray<\n | (Partial<AglynOrgMember> & { handoff?: unknown })\n | null\n | undefined\n >,\n): number {\n let count = 0\n for (const entry of entries) {\n if (usesCustomerSeat(entry) && isOrgWideMember(entry)) count += 1\n }\n return count\n}\n\n/**\n * Whether a roster row or pending invite takes one of the customer's seats\n * at all (AGL-3466). Every seat counter asks this before it asks which kind\n * of seat, so the two populations below never include either exception.\n *\n * Two kinds of entry hold access without a seat:\n *\n * - **Platform staff.** A row or invite stamped `staffSeat: true` belongs to\n * an account holding the `staff` claim. Staff build workspaces for\n * prospects and join them to help; billing the customer a seat for either\n * is what made a Free workspace (one seat) unable to invite the client it\n * was built for without a hand-written override.\n * - **An owner handoff.** An invite carrying `handoff` moves the owner seat\n * from one person to another rather than adding one. Whether the outgoing\n * owner staying on needs a seat of their own is decided when the handoff is\n * sent and again when it is accepted, never by counting the invite.\n */\nexport function usesCustomerSeat(\n entry:\n | { staffSeat?: unknown; handoff?: unknown }\n | null\n | undefined,\n): boolean {\n if (!entry) return false\n if (entry.staffSeat === true) return false\n return !entry.handoff\n}\n\n/**\n * Whether a roster row belongs to platform staff (AGL-3466) — the Team\n * page's \"no seat\" chip, and the row every seat count leaves out.\n */\nexport function isStaffSeat(\n entry: { staffSeat?: unknown } | null | undefined,\n): boolean {\n return entry?.staffSeat === true\n}\n\n/** The outgoing owner's choices, in the order the picker offers them. */\nexport const OWNER_HANDOFF_PREVIOUS_OWNER: readonly OwnerHandoffPreviousOwner[] = [\n 'stay',\n 'leave',\n]\n\n/** What each choice does, for the picker and the confirmation. */\nexport const OWNER_HANDOFF_PREVIOUS_OWNER_LABELS: Record<\n OwnerHandoffPreviousOwner,\n string\n> = {\n stay: 'Stay on as an admin after the handoff',\n leave: 'Leave after the handoff',\n}\n\n/**\n * The handoff half of an invite request, or null when it is not a usable\n * one (AGL-3466).\n *\n * Read in one place because the same body reaches the server from three\n * surfaces (the Team page, the staff organization page and the staff site\n * page), and an unknown `previousOwner` must be refused rather than guessed:\n * guessing `leave` takes someone off a roster they meant to stay on, and\n * guessing `stay` spends a seat they meant to free.\n */\nexport function parseOwnerHandoff(raw: unknown): AglynOrgOwnerHandoff | null {\n if (!raw || typeof raw !== 'object') return null\n const previousOwner = (raw as { previousOwner?: unknown }).previousOwner\n return previousOwner === 'stay' || previousOwner === 'leave'\n ? { previousOwner }\n : null\n}\n\n/**\n * One roster row or pending invite, as the collaborator counter needs to see\n * it (AGL-2068). Deliberately structural rather than `Partial<AglynOrgMember>`\n * — an INVITE is not a member document, it is keyed by email and has no uid,\n * and the whole point of this counter is that the two populations must be\n * counted together or the cap is enforced against a fraction of itself.\n */\nexport interface CollaboratorSeatEntry {\n /** Member documents are keyed by uid; invites have none. */\n uid?: string | null\n email?: string | null\n role?: unknown\n allHosts?: boolean\n hostAccess?: Record<string, unknown> | null\n /** Platform staff hold no seat (AGL-3466) — see `usesCustomerSeat`. */\n staffSeat?: boolean | null\n /** An owner-handoff invite holds no seat (AGL-3466). */\n handoff?: unknown\n}\n\n/**\n * The identity key one entry occupies, or `''` when it identifies nobody.\n *\n * EMAIL FIRST, uid second, and that order is the join (AGL-2068). A person\n * admitted to a site is one seat whether they arrive as an accepted member or\n * as a still-pending invite, and those two rows live in different collections\n * keyed different ways — `orgs/{id}/members/{uid}` and\n * `orgs/{id}/invites/{inviteId}` — with the address as the only field both\n * carry. Counting by uid would count the invite and the membership it becomes\n * as two seats; counting only invites would miss every member.\n *\n * Legacy roster rows written before `email` was mirrored fall back to the uid,\n * which cannot collide with an address (the `uid:` prefix is not a legal\n * local-part/domain pair) and so is safe to mix into the same set.\n */\nfunction collaboratorSeatKey(entry: CollaboratorSeatEntry): string {\n const email =\n typeof entry.email === 'string' ? entry.email.trim().toLowerCase() : ''\n if (email) return email\n const uid = typeof entry.uid === 'string' ? entry.uid.trim() : ''\n return uid ? `uid:${uid}` : ''\n}\n\n/**\n * Every principal consuming a COLLABORATOR seat on one host (AGL-2068).\n *\n * ## Why this exists at all\n *\n * `membersPerHost` was enforced on one of the four doors that admit a site\n * collaborator, and that one door counted `hosts/{hostId}/members` — a\n * DISPLAY roster only `/api/hosts/members` writes. The other three\n * (`/api/orgs/invites` create, `/api/orgs/invites` accept, and the\n * `hostAccess` branch of `/api/orgs/members`) land in `orgs/{id}/members` and\n * the `hosts/{id}.memberRoles` projection, and were invisible to it. So the\n * cap was both skipped on three paths and under-counted on the fourth, and a\n * free org — `membersPerHost: 1` — could take on unlimited collaborators,\n * each with full site access, on a plan that is never invoiced.\n *\n * verbatim: **\"We need to make sure the free/hobby tier\n * does hard cap so it always actually stays free.\"**\n *\n * ## What counts\n *\n * A SCOPED grant on `hostId`, and nothing else. An org-wide member\n * (owner/admin, or `allHosts`) reaches every host but consumes a MANAGER\n * seat — `countManagerSeats` is that side, and charging them here would bill\n * one person twice and trip a cap they are not on. This is the same split\n * AGL-1113 drew; it is now drawn from one place instead of three.\n *\n * Pending invites count, for the reason the manager gate counts them: an\n * invite reserves the seat it will become, and a cap that only bites on\n * acceptance can be walked past by mailing out N invites first.\n */\nexport function collaboratorSeatKeys(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n hostId: string,\n): Set<string> {\n const keys = new Set<string>()\n if (!hostId) return keys\n for (const entry of entries) {\n if (!usesCustomerSeat(entry)) continue\n // Managers are the other counter's population, whatever host map they\n // happen to carry — a promoted collaborator keeps their old `hostAccess`.\n if (isOrgWideMember(entry as Partial<AglynOrgMember>)) continue\n if (!entry.hostAccess?.[hostId]) continue\n const key = collaboratorSeatKey(entry)\n if (key) keys.add(key)\n }\n return keys\n}\n\n/**\n * How many collaborator seats on `hostId` are spoken for by someone OTHER\n * than `exclude` (AGL-2068).\n *\n * `exclude` is the principal the caller is about to admit, and dropping them\n * is what makes this composable with `checkSeatQuota(…, used)`, whose\n * contract is \"usage BEFORE the resource being created\". Without it the\n * accept path refuses its own invite: at the moment acceptance is decided the\n * invitee holds a pending invite AND is about to hold a membership, so they\n * would be counted once or twice against a cap they are the subject of.\n *\n * Both identities are dropped, not whichever one is present. A person can be\n * on the roster under a uid with no mirrored email and hold an invite under\n * that address, and the seat is still one seat.\n *\n * ## `emails`, not `email` — an account holds several (AGL-2486)\n *\n * Since an invitation may be accepted at any CONFIRMED address on the account,\n * the pending invite the accepter is about to consume can be keyed by an\n * address that is not their primary. `exclude.email` alone is the primary, so\n * that invite survived the exclusion and the person was counted against a cap\n * they are the subject of — the exact double-count the paragraph above says\n * this function exists to prevent, re-opened by widening the accept match.\n *\n * It fails CLOSED (a spurious \"out of seats\" refusal, never a free seat), and\n * only for an org sitting exactly on its cap, which is why it survived review.\n *\n * `emails` takes every address PROVEN to belong to the principal being\n * admitted. Passing an address that is not theirs would hand out a free seat,\n * so callers must pass confirmed addresses for that uid and nothing else.\n */\nexport function countCollaboratorSeats(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n hostId: string,\n exclude?: {\n uid?: string | null\n email?: string | null\n /** Further addresses on the SAME account; see above. */\n emails?: readonly (string | null | undefined)[] | null\n },\n): number {\n const keys = collaboratorSeatKeys(entries, hostId)\n for (const candidate of [exclude?.email, ...(exclude?.emails ?? [])]) {\n const email = typeof candidate === 'string' ? candidate.trim().toLowerCase() : ''\n if (email) keys.delete(email)\n }\n const uid = typeof exclude?.uid === 'string' ? exclude.uid.trim() : ''\n if (uid) keys.delete(`uid:${uid}`)\n return keys.size\n}\n\n/**\n * Every principal consuming a MANAGER seat, as identities rather than rows.\n *\n * The org-wide half of `collaboratorSeatKeys`, drawn from the same entries and\n * split on the same predicate, so the two counters partition one roster\n * instead of overlapping on it.\n *\n * Deduplicating by identity is the difference from {@link countManagerSeats},\n * and it is what makes this composable with an `exclude`: a person holding a\n * pending invite AND the membership it became is one seat, and the row-wise\n * counter reports two because it is handed the two collections separately and\n * sums them.\n */\nexport function managerSeatKeys(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n): Set<string> {\n const keys = new Set<string>()\n for (const entry of entries) {\n if (!usesCustomerSeat(entry)) continue\n if (!isOrgWideMember(entry as Partial<AglynOrgMember>)) continue\n const key = collaboratorSeatKey(entry)\n if (key) keys.add(key)\n }\n return keys\n}\n\n/**\n * How many manager seats are spoken for by someone OTHER than `exclude`.\n *\n * The manager twin of {@link countCollaboratorSeats}, and it exists for the\n * same reason that one takes an `exclude`: `checkSeatQuota`'s contract is\n * \"usage BEFORE the resource being created\", and on the invite-accept path the\n * accepter holds a pending invite and is about to hold a membership at the\n * same instant. Counted plainly they are charged once or twice for a seat they\n * are the subject of, and an org on its last seat refuses its own invitation.\n *\n * Both identities are dropped, and `emails` carries the further addresses\n * proven to belong to that account — an invitation may be accepted at any\n * confirmed address, so the invite being consumed need not be keyed by the\n * primary one. Passing an address that is not theirs would hand out a free\n * seat, so callers must pass confirmed addresses for that uid and nothing\n * else.\n *\n * Kept SEPARATE from {@link countManagerSeats} rather than replacing it: that\n * one is row-wise and is what the billing and console surfaces count with, and\n * quietly making it identity-wise would change every one of those totals.\n */\nexport function countManagerSeatsExcluding(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n exclude?: {\n uid?: string | null\n email?: string | null\n /** Further addresses on the SAME account; see above. */\n emails?: readonly (string | null | undefined)[] | null\n },\n): number {\n const keys = managerSeatKeys(entries)\n for (const candidate of [exclude?.email, ...(exclude?.emails ?? [])]) {\n const email = typeof candidate === 'string' ? candidate.trim().toLowerCase() : ''\n if (email) keys.delete(email)\n }\n const uid = typeof exclude?.uid === 'string' ? exclude.uid.trim() : ''\n if (uid) keys.delete(`uid:${uid}`)\n return keys.size\n}\n\n/**\n * What KIND of user a console row represents (AGL-1114) — the distinction\n * that decides which seat they consume, and the one the Team table could not\n * express because a manager and a collaborator differ only by fields the\n * table never showed.\n *\n * Deliberately NOT the same axis as `role`. A `role: 'editor'` is a manager\n * when their reach is the whole org and a collaborator when it is two sites;\n * reading the role alone is the mistake that let a collaborator look like\n * team staff (see the org-leak and role-gate work).\n *\n * `siteMember` is the third kind and never appears in `orgs/{id}/members` at\n * all: it is an end-user account on a PUBLISHED site (`siteMembers`), not a\n * console user. It has no Firebase Auth record of any kind — a site member is\n * a Firestore document under `hosts/{hostId}/siteMembers` with its own scrypt\n * hash and its own session cookie — so no surface that lists AUTH accounts,\n * the staff user directory included, can contain one. The label is here so the\n * vocabulary is complete, for a surface that lists site accounts and needs a\n * word for them. Free and uncounted on every plan (AGL-889).\n */\nexport type ConsoleUserType = 'manager' | 'collaborator' | 'siteMember'\n\nexport const CONSOLE_USER_TYPE_LABELS: Record<ConsoleUserType, string> = {\n manager: 'Team manager',\n collaborator: 'Site collaborator',\n siteMember: 'Site member',\n}\n\n/** One line on what each kind is and what it costs — tooltip/legend copy. */\nexport const CONSOLE_USER_TYPE_HINTS: Record<ConsoleUserType, string> = {\n manager:\n 'Reaches the whole organization. Uses one of your team (manager) seats.',\n collaborator:\n 'Scoped to specific sites. Uses a collaborator seat on each site they ' +\n 'can reach, not a team seat.',\n siteMember:\n 'An end-user account on a published site, not a console user. Free and ' +\n 'unlimited on every plan.',\n}\n\n/**\n * Classify an `orgs/{orgId}/members` entry (or a pending invite, same shape).\n * Never returns `siteMember` — nothing in that collection is one; the value\n * exists for surfaces that list published-site accounts and must label them —\n * never for one that lists both, since the two populations do not share an\n * identity system.\n */\nexport function consoleUserType(\n member: Partial<AglynOrgMember> | null | undefined,\n): Exclude<ConsoleUserType, 'siteMember'> {\n return isOrgWideMember(member) ? 'manager' : 'collaborator'\n}\n\n/**\n * Whether an account is governed by enterprise SSO (AGL-1128) — it lives in\n * an org's GCIP tenant pool rather than the project pool, so its identity is\n * owned by the customer's IdP.\n *\n * `tenantId` is the whole signal: Firebase sets it on the user whenever the\n * account belongs to a tenant, and only SSO accounts do.\n */\nexport function isSsoGovernedAccount(\n user: { tenantId?: string | null } | null | undefined,\n): boolean {\n return Boolean(user?.tenantId)\n}\n\n/**\n * Whether the account may connect an additional consumer sign-in provider.\n *\n * **No, for any SSO-governed account.** The customer's IdP is the single gate\n * they bought: they revoke there, enforce MFA there, offboard there. A linked\n * personal Google account is a way in their IdP can never see or revoke —\n * exactly what SSO is purchased to prevent.\n *\n * Deliberately NOT gated on `sso.enforced`. That flag exists so we never\n * LOCK OUT an existing sign-in method; it is not a licence to hand out new\n * bypasses meanwhile. Nothing here removes a provider an account already has,\n * so this can never lock anyone out.\n *\n * This is the intent, not the boundary — the boundary is upstream, since a\n * GCIP tenant only accepts providers enabled on that tenant. Both matter: the\n * boundary is remote config that could drift, and a UI that offers a\n * security-regressing action is wrong even when the action would fail.\n */\nexport function canLinkSocialProvider(\n user: { tenantId?: string | null } | null | undefined,\n): boolean {\n return !isSsoGovernedAccount(user)\n}\n\n/**\n * The same question as `isOrgWideMember`, asked of the `users/{uid}/orgs`\n * reverse-index row instead of the member doc (AGL-1032).\n *\n * The console navigates from the index — it is what `useOrgScope` loads —\n * and the index carries a MIRROR of the predicate, not the inputs to it, so\n * this cannot recompute: `role: 'viewer'` on the index means \"viewer\",\n * whether the member reaches every site or one.\n *\n * Reads a missing flag as org-wide, for the same reason `isOrgWideMember`\n * reads a missing `allHosts` that way: rows written before the mirror\n * existed have no flag, and hiding the workspace from a real member is a\n * worse failure than showing org chrome to a collaborator whose reads the\n * rules refuse anyway. Owner/admin are org-wide by role regardless of the\n * mirror, so a stale row can never lock an admin out.\n *\n * Navigation only — never an access decision. AGL-1026 (rules) and the\n * Admin-SDK scope checks are the boundary.\n */\nexport function isOrgWideMembership(\n membership:\n | Pick<UserOrgMembership, 'role' | 'orgWide'>\n | null\n | undefined,\n): boolean {\n if (!membership) return true\n if (membership.role === 'owner' || membership.role === 'admin') return true\n return membership.orgWide !== false\n}\n\n/**\n * The `scopeTokens` projection stamped onto member docs (AGL-1038) so the\n * rules can intersect a caller's reach with a resource's `visibleTo` —\n * rules have no `.map()`, so `hostAccess`'s keys cannot be turned into\n * tokens at evaluation time and have to be denormalized here.\n *\n * Org-wide members get `['org']`; they own the org and read everything in\n * it, scoped or not (the rules short-circuit on them anyway). A scoped\n * collaborator gets `'org'` plus one token per granted host — `'org'`\n * because an org-WIDE resource stays readable by any member, which is\n * today's behavior and not something this project narrows.\n *\n * Not capped at `MAX_SCOPE_HOSTS`: the rules' `hasAny` has no 30-value\n * limit, only the client `array-contains-any` query does, so a member of\n * more than 30 sites is a listing problem for AGL-1044 to chunk, not a\n * reason to under-grant here.\n */\nexport function projectMemberScopeTokens(\n member: Partial<AglynOrgMember> | null | undefined,\n): ScopeToken[] {\n if (isOrgWideMember(member)) return [ORG_SCOPE_TOKEN]\n const hostIds = Object.keys(member?.hostAccess ?? {})\n return [ORG_SCOPE_TOKEN, ...hostIds.map(hostScopeToken)]\n}\n\n/**\n * A member's effective read set: the stored `scopeTokens` projection when it\n * is there, recomputed from the membership when it is not.\n *\n * The fallback is the security-relevant half and it was written out by hand\n * in four places (`use-scope-tokens`, `erase-scope`, the media sign route,\n * and by omission in `resolveMediaScope`, which only ever recomputed). Four\n * copies of \"what may this member see\" is the shape that eventually\n * disagrees, and a copy that reads `member.scopeTokens` WITHOUT the\n * `.length` guard silently grants nothing to a member the AGL-1040 backfill\n * has not reached — or, written the other way round, grants everything.\n *\n * Recomputing is the safe fallback rather than a convenience: it produces\n * exactly what `grantHostAccess` would have stamped, so an unstamped member\n * doc behaves as its `hostAccess` says, never as \"no access\" and never as\n * org-wide.\n */\nexport function memberScopeTokens(\n member: Partial<AglynOrgMember> | null | undefined,\n): ScopeToken[] {\n const stored = member?.scopeTokens\n return stored?.length ? stored : projectMemberScopeTokens(member)\n}\n\n/**\n * May this member see a resource carrying `visibleTo`? (AGL-1037/1038)\n *\n * The whole client-side/server-side authorization question in one place:\n * org-wide members read everything they own; everyone else needs their read\n * set to intersect the resource's scope. Absent/empty `visibleTo` is\n * org-wide by the same rule the Firestore rules use, so an unbackfilled\n * resource does not vanish.\n *\n * Every Admin-SDK path must call this (or `scopeAllows`, which wraps an\n * already-resolved scope) — the Admin SDK bypasses rules entirely, so this\n * IS the enforcement there, not a second opinion about it.\n *\n * NOT a membership check, and never a substitute for one: a `null` member\n * \"can see\" an org-wide resource here, because the question this answers is\n * \"is this resource in scope for that reach\", not \"is this person in the\n * org\". Resolve membership first and refuse the caller if there is none —\n * conflating the two is exactly how AGL-1026 exposed a whole org.\n */\nexport function memberCanSee(\n member: Partial<AglynOrgMember> | null | undefined,\n visibleTo: readonly string[] | null | undefined,\n): boolean {\n if (isOrgWideMember(member)) return true\n return visibleToTokens(visibleTo ?? undefined, memberScopeTokens(member))\n}\n\n/**\n * The `memberRoles` projection stamped onto host docs so Firestore rules\n * authorize host content with the single host-doc read they already do\n * (docs/MULTI_TENANT_FIRESTORE.md §5). Recomputed by the membership API\n * whenever a member changes; owner/admin appear on every host.\n */\nexport function projectHostMemberRoles(\n members: ReadonlyArray<Partial<AglynOrgMember> & { $id: string }>,\n hostId: HostUid,\n): Record<string, HostAccessRole> {\n const projection: Record<string, HostAccessRole> = {}\n for (const member of members) {\n const role = hostRoleFor(member, hostId)\n if (role) projection[member.$id] = role\n }\n return projection\n}\n"],"names":["consoleLabelUnder","generateSubdomain","isBlockedSubdomain","SUBDOMAIN_PATTERN","hostScopeToken","ORG_SCOPE_TOKEN","visibleToTokens","ORG_SLUG_PATTERN","RESERVED_ORG_ONLY","Set","CONSOLE_LABEL","process","env","NEXT_PUBLIC_CONSOLE_URL","NEXT_PUBLIC_WORKSPACE_DOMAIN","isBlockedOrgSlug","slug","normalized","toLowerCase","has","isValidOrgSlug","test","generateOrgSlug","name","ORG_ROLES","ORG_ROLE_WEIGHT","owner","admin","editor","viewer","isOrgRole","value","orgRoleAtLeast","role","minimum","canManageOrg","hostRoleFor","member","hostId","explicit","hostAccess","allHosts","HOST_CONTENT_WRITE_ROLES","HOST_PUBLISH_ROLES","canWriteHost","includes","canPublishHost","hostRoleCanWrite","hostRoleCanPublish","isOrgWideMember","scoping","undefined","Object","keys","length","countManagerSeats","entries","count","entry","usesCustomerSeat","staffSeat","handoff","isStaffSeat","OWNER_HANDOFF_PREVIOUS_OWNER","OWNER_HANDOFF_PREVIOUS_OWNER_LABELS","stay","leave","parseOwnerHandoff","raw","previousOwner","collaboratorSeatKey","email","trim","uid","collaboratorSeatKeys","key","add","countCollaboratorSeats","exclude","candidate","emails","delete","size","managerSeatKeys","countManagerSeatsExcluding","CONSOLE_USER_TYPE_LABELS","manager","collaborator","siteMember","CONSOLE_USER_TYPE_HINTS","consoleUserType","isSsoGovernedAccount","user","Boolean","tenantId","canLinkSocialProvider","isOrgWideMembership","membership","orgWide","projectMemberScopeTokens","hostIds","map","memberScopeTokens","stored","scopeTokens","memberCanSee","visibleTo","projectHostMemberRoles","members","projection","$id"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;CAKC,GAYD,SACEA,iBAAiB,EACjBC,iBAAiB,EACjBC,kBAAkB,EAClBC,iBAAiB,QACZ,mBAAe;AACtB,SACEC,cAAc,EACdC,eAAe,EACfC,eAAe,QACV,oBAAgB;AAEvB,0EAA0E,GAC1E,OAAO,MAA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EA;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASC,yBACd9D,MAAkD;;IAElD,IAAIY,gBAAgBZ,SAAS,OAAO;QAAChC;KAAgB;IACrD,MAAM+F,UAAUhD,OAAOC,IAAI,SAAChB,0BAAAA,OAAQG,UAAU,mBAAI,CAAC;IACnD,OAAO;QAACnC;WAAoB+F,QAAQC,GAAG,CAACjG;KAAgB;AAC1D;AAEA;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASkG,kBACdjE,MAAkD;IAElD,MAAMkE,SAASlE,0BAAAA,OAAQmE,WAAW;IAClC,OAAOD,CAAAA,0BAAAA,OAAQjD,MAAM,IAAGiD,SAASJ,yBAAyB9D;AAC5D;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASoE,aACdpE,MAAkD,EAClDqE,SAA+C;IAE/C,IAAIzD,gBAAgBZ,SAAS,OAAO;IACpC,OAAO/B,gBAAgBoG,oBAAAA,YAAavD,WAAWmD,kBAAkBjE;AACnE;AAEA;;;;;CAKC,GACD,OAAO,SAASsE,uBACdC,OAAiE,EACjEtE,MAAe;IAEf,MAAMuE,aAA6C,CAAC;IACpD,KAAK,MAAMxE,UAAUuE,QAAS;QAC5B,MAAM3E,OAAOG,YAAYC,QAAQC;QACjC,IAAIL,MAAM4E,UAAU,CAACxE,OAAOyE,GAAG,CAAC,GAAG7E;IACrC;IACA,OAAO4E;AACT"}
@@ -193,6 +193,9 @@ import { SAFE_HREF_PATTERN, resolveScreenHref, splitLinkValue } from "./screen-l
193
193
  return;
194
194
  }
195
195
  push(level > 0 ? `${'#'.repeat(level)} ${text}` : text);
196
+ // A Typography renders the elements it holds after its text
197
+ // (AGL-3672), so they read after it here too.
198
+ recurse();
196
199
  return;
197
200
  }
198
201
  case 'markdown':
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/page-markdown.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 * A published page as Markdown — the representation an agent gets when it\n * sends `Accept: text/markdown` (acceptmarkdown.com).\n *\n * ## Why serialize the NODE TREE and not the rendered HTML\n *\n * The obvious implementation is to render the page and run an HTML-to-Markdown\n * converter over it. Every site on this platform is a node document, and the\n * tree carries what the HTML has already thrown away: which text is a heading\n * because the author said so rather than because it is large, which container\n * is the page's content region, and which subtree is navigation. Converting\n * the HTML back would be reconstructing, by heuristic, information we are\n * holding.\n *\n * It is also cheaper by a wide margin — no React render, no plugin registry,\n * no MUI — which is what makes this affordable to serve from a cached route on\n * every site rather than only where somebody enabled it.\n *\n * ## The content region, not the document\n *\n * Serialization starts at the document's `main` landmark, which\n * `stampDocumentLandmark` has already placed on the layout slot (the page\n * content between the chrome) or on the screen root. That is what makes the\n * output nav-free and footer-free without this module knowing anything about\n * how a particular site builds its header — the same property that makes a\n * Markdown variant worth serving at all.\n *\n * A page with no landmark falls back to the whole tree. Some content is always\n * better than an empty document, and a page that shipped no landmark\n * deliberately (see `document-landmark.ts`) has no content region to prefer.\n *\n * ## Chrome that lives INSIDE the content region\n *\n * A handful of components are navigation wherever they sit — an app bar, a nav\n * menu, a language switcher, a pagination strip. They are skipped by id, and\n * the list is deliberately short: everything not named recurses, so a plugin\n * block nobody here has heard of still contributes its text instead of\n * vanishing. Silence is the one failure mode that would be invisible to the\n * author.\n */\n\nimport { NODE_ROOT_ID } from '../canvas-manager/canvas-manager'\nimport { authorHtmlToMarkdown, inlineAuthorHtmlToMarkdown } from './author-html-markdown'\nimport { resolveMarkdownSourceLinks } from './markdown-lite'\nimport { absoluteMediaSrc } from './media-ref'\nimport {\n SAFE_HREF_PATTERN,\n resolveScreenHref,\n splitLinkValue,\n} from './screen-link-value'\n\n/** The node shape this serializer reads; keeps callers free of the full type. */\nexport interface PageMarkdownNode {\n componentId?: string\n props?: Record<string, unknown> | null\n /** Normalized documents carry child IDS; this never reads a denormalized tree. */\n nodes?: unknown\n}\n\n/** A flat node map keyed by node id — exactly what the page route already holds. */\nexport type PageMarkdownNodes = Record<string, PageMarkdownNode>\n\n/** The element name a node was told to render as (`props.component`). */\nconst elementOf = (node: PageMarkdownNode | undefined): string =>\n String(node?.props?.['component'] ?? '').toLowerCase()\n\n/** Components that are navigation wherever they appear. See the module note. */\nconst CHROME_COMPONENTS: ReadonlySet<string> = new Set([\n 'muiAppBar',\n 'muiToolbar',\n 'muiDrawer',\n 'muiBreadcrumbs',\n 'navMenu',\n 'searchBox',\n 'languageSwitcher',\n 'themeModeSwitcher',\n 'muiPagination',\n // An icon is decoration with no accessible text of its own. Its LABEL, where\n // one exists, belongs to the control around it and is emitted there.\n 'icon',\n])\n\n/**\n * Whether a node is navigation rather than content: a chrome component, or\n * an element its author declared `nav`, `header` or `footer`. Exported so a\n * reader of a page's CONTENT — the SEO audit's heading and image scan\n * (AGL-2910) — skips exactly what this serializer skips.\n */\nexport function isPageChromeNode(node: PageMarkdownNode | undefined): boolean {\n if (!node) return false\n if (CHROME_COMPONENTS.has(String(node.componentId ?? ''))) return true\n const element = elementOf(node)\n return element === 'nav' || element === 'header' || element === 'footer'\n}\n\n/** Heading levels, as either `props.component` or `props.variant` spells them. */\nconst HEADING = /^h([1-6])$/\n\n/**\n * The heading level a text node publishes, or 0 for body copy.\n *\n * `component` wins over `variant` because they answer different questions and\n * the platform lets them disagree: `variant` is the type STYLE (what size it is\n * drawn at) and `component` is the ELEMENT (what it means). An author who set a\n * hero line to look like an h1 but render as a `p` said it is not a heading,\n * and the Markdown has to agree with the HTML or the two documents describe\n * different pages.\n */\nexport function headingLevelOf(props: Record<string, unknown> | null | undefined): number {\n const element = String(props?.['component'] ?? '').toLowerCase()\n if (element) {\n const asElement = HEADING.exec(element)\n return asElement ? Number(asElement[1]) : 0\n }\n const variant = String(props?.['variant'] ?? '').toLowerCase()\n const asVariant = HEADING.exec(variant)\n return asVariant ? Number(asVariant[1]) : 0\n}\n\n/**\n * Escape the Markdown control characters that would otherwise re-parse.\n *\n * Only the characters that START a construct at the position they can occur in:\n * a leading `#`, `>`, `-`, `+` or `1.` on its own line, and the emphasis,\n * backtick and bracket characters anywhere. Escaping more than that produces\n * output littered with backslashes, which is worse to read and worse to embed\n * than the rare false heading it prevents.\n */\nexport function escapeMarkdownText(value: string): string {\n return value\n .replace(/([\\\\`*_[\\]<>])/g, '\\\\$1')\n .replace(/^(\\s*)([#>])/gm, '$1\\\\$2')\n .replace(/^(\\s*)([-+])(\\s)/gm, '$1\\\\$2$3')\n .replace(/^(\\s*)(\\d+)\\.(\\s)/gm, '$1$2\\\\.$3')\n}\n\n/** Collapse runs of whitespace to single spaces, as inline text renders. */\nconst collapse = (value: string): string => value.replace(/\\s+/g, ' ').trim()\n\n/** Resolution context for values that are stored as references, not URLs. */\nexport interface PageMarkdownContext {\n /** Site origin, for absolutizing media and site-relative links. */\n origin?: string | null\n /** Host id, so a restricted org asset resolves for the site rendering it. */\n hostId?: string\n /**\n * The routing map screen links resolve against (`screenRoutes`), and the\n * link references in authored markdown with them (AGL-3118).\n */\n screenRoutes?: Record<string, string> | null\n}\n\n/**\n * A link target as Markdown should carry it: absolute where we can make it so.\n *\n * Site-relative is fine in a page — the browser has a document to resolve\n * against. A Markdown body has no such context by the time an agent has copied\n * it into a prompt, so a relative href there is a link to nowhere.\n */\nfunction absoluteHref(href: string, context?: PageMarkdownContext): string {\n const value = href.trim()\n if (!value) return ''\n if (/^[a-z][a-z0-9+.-]*:/i.test(value) || value.startsWith('//')) return value\n const origin = context?.origin?.replace(/\\/+$/, '') ?? ''\n if (!origin) return value\n return value.startsWith('/') ? `${origin}${value}` : `${origin}/${value}`\n}\n\n/** The text a control shows, preferring its rich label over the plain one. */\nfunction labelOf(\n props: Record<string, unknown> | null | undefined,\n context?: PageMarkdownContext,\n): string {\n const html = props?.['html']\n if (typeof html === 'string' && html.trim()) {\n const rich = inlineAuthorHtmlToMarkdown(html, context)\n if (rich.trim()) return collapse(rich)\n }\n const children = props?.['children']\n return typeof children === 'string' ? collapse(escapeMarkdownText(children)) : ''\n}\n\n/** A block emitted by the walk, before the blocks are joined. */\ninterface Block {\n /** Markdown text of the block, already escaped. */\n text: string\n}\n\n/**\n * Serialize the subtree at `rootId` into Markdown blocks.\n *\n * A depth budget and a visited set, because a node map is data: a document\n * restored from a backup, or written through the REST API, can name a child\n * that names it back. Recursing that tree is a stack overflow inside a request\n * handler, i.e. a 500 on a page that renders fine — the renderer tolerates it\n * because React unmounts a cycle, and this has nothing to stop it but itself.\n */\nfunction walk(\n nodes: PageMarkdownNodes,\n rootId: string,\n context: PageMarkdownContext | undefined,\n blocks: Block[],\n seen: Set<string>,\n depth: number,\n): void {\n if (depth > 64 || seen.has(rootId)) return\n const node = nodes[rootId]\n if (!node) return\n seen.add(rootId)\n\n const componentId = String(node.componentId ?? '')\n // Chrome components, and `nav`, `header` and `footer` by their OWN\n // declaration — an author who set the element picker to one of them named\n // it navigation, and that is a stronger signal than any component-id list\n // can be.\n if (isPageChromeNode(node)) return\n\n const props = node.props ?? {}\n const childIds = Array.isArray(node.nodes)\n ? node.nodes.filter((id): id is string => typeof id === 'string')\n : []\n const recurse = (): void => {\n for (const childId of childIds) {\n walk(nodes, childId, context, blocks, seen, depth + 1)\n }\n }\n const push = (text: string): void => {\n if (text.trim()) blocks.push({ text: text.trim() })\n }\n\n switch (componentId) {\n case 'muiTypography':\n case 'muiInlineText':\n case 'muiListItemText': {\n const level = headingLevelOf(props)\n const text = labelOf(props, context)\n if (!text) {\n // A Typography with no text of its own but children beneath it is a\n // wrapper, which is how rich composites are built. Recurse rather than\n // dropping the subtree.\n recurse()\n return\n }\n push(level > 0 ? `${'#'.repeat(level)} ${text}` : text)\n return\n }\n case 'markdown': {\n /*\n Already Markdown. Emitted VERBATIM and never re-escaped: `content` is\n the markdown-lite source an author typed, so escaping it would turn\n their headings into literal `#` characters — the one transformation\n that can only make this output worse. Its link REFERENCES are the one\n exception (AGL-3118), resolved as the page resolves them.\n */\n const content = props['content']\n if (typeof content === 'string') push(authoredMarkdown(content, context))\n return\n }\n case 'custom-html': {\n const html = props['html'] ?? props['children']\n if (typeof html === 'string') push(authorHtmlToMarkdown(html, context))\n return\n }\n case 'image': {\n const src = absoluteMediaSrc(String(props['src'] ?? '').trim(), {\n hostId: context?.hostId,\n origin: context?.origin,\n })\n if (!src) return\n const alt = collapse(String(props['alt'] ?? ''))\n push(`![${escapeMarkdownText(alt)}](${src})`)\n return\n }\n case 'video':\n case 'videoEmbed': {\n const src = String(props['src'] ?? props['url'] ?? '').trim()\n if (!src) return\n push(`[Video](${absoluteHref(src, context)})`)\n return\n }\n case 'muiButton':\n case 'muiScreenLink': {\n const label = labelOf(props, context) || 'Link'\n const href = screenLinkHref(props, context)\n push(href ? `[${label}](${href})` : label)\n return\n }\n case 'muiAccordionSummary': {\n /*\n An accordion's question (AGL-3575). The summary carries its text in\n its own props, not in a child node, so the default recursion below\n emitted NOTHING for it — every FAQ on every site reached an agent as\n a run of orphaned answers. It is a heading because that is what the\n HTML publishes: MUI renders the summary inside its `h3` heading slot,\n and the Markdown has to agree with the page or the two describe\n different documents. A linked header (AGL-1232) keeps its link, as\n the page does.\n */\n const text = labelOf(props, context)\n if (!text) {\n recurse()\n return\n }\n const href =\n typeof props['screenId'] === 'string' && props['screenId']\n ? screenLinkHref(props, context)\n : ''\n push(href ? `### [${text}](${href})` : `### ${text}`)\n return\n }\n case 'muiList': {\n /*\n The items are gathered into ONE block so they join as a list. Walking\n them as siblings would put a blank line between every bullet, which is\n a sequence of paragraphs beginning with a dash rather than a list.\n */\n const items: Block[] = []\n for (const childId of childIds) {\n walk(nodes, childId, context, items, seen, depth + 1)\n }\n const lines = items\n .map((item) => item.text.replace(/\\n/g, '\\n '))\n .filter(Boolean)\n .map((text) => `- ${text}`)\n push(lines.join('\\n'))\n return\n }\n default:\n recurse()\n }\n}\n\n/**\n * Where a Button or Screen Link points.\n *\n * A screen link stores a SCREEN ID, not a path, and the path it resolves to is\n * a per-request question — `screenRoutes` is the routing map the router\n * actually honors, which is not the map publishing wrote (a collection's list\n * template answers at the collection's slug, template screens answer nowhere).\n * Emitting `href` alone would publish, in Markdown, the dead links AGL-1998\n * removed from the HTML.\n *\n * `splitLinkValue` + `resolveScreenHref` rather than a local reading of the\n * two props, because WHICH SLOT a screen reference arrives in is not fixed\n * (AGL-1335): a `Link`-typed component prop is bound to whichever of\n * `screenId`/`href` the author reached for, and a value in the `href` slot\n * carries the stored `screen:<id>` spelling. Reading `screenId` alone published\n * that token verbatim as a link target on every page built from a prop-fed\n * CTA — ten of them on aglyn.com, unfollowable by the agents `/llms.txt` sends\n * here (AGL-2740). These are the same two functions `useLinkTarget` resolves\n * the HTML with, so the two representations of a page cannot drift again.\n *\n * An authored screen id that the map has lost resolves to NO link, exactly as\n * the HTML renders it: falling back to the stored `href` there would re-publish\n * the dead path AGL-1998 removed, which is the failure this function's own\n * contract exists to prevent.\n */\nfunction screenLinkHref(\n props: Record<string, unknown>,\n context?: PageMarkdownContext,\n): string {\n const target = splitLinkValue(\n typeof props['screenId'] === 'string' ? props['screenId'] : undefined,\n typeof props['href'] === 'string' ? props['href'] : undefined,\n )\n if (target.screenId) {\n const path = resolveScreenHref(context?.screenRoutes ?? undefined, target.screenId)\n return path ? absoluteHref(path, context) : ''\n }\n // The same protocol guard the linking elements apply. A `javascript:` href\n // is inert in a Markdown body, but it is still a target an agent may be\n // asked to follow, and a representation that offers one the page refuses to\n // render is describing a different document.\n return target.href && SAFE_HREF_PATTERN.test(target.href)\n ? absoluteHref(target.href, context)\n : ''\n}\n\n/**\n * Authored markdown-lite — a Markdown element's content, an entry's body —\n * as this document carries it: verbatim, except that each link REFERENCE\n * (AGL-3118) points where the page's own link does, through the same routing\n * map and the same `resolveScreenHref` as {@link screenLinkHref}, made\n * absolute for the reason {@link absoluteHref} gives. A reference the map\n * does not have becomes the link's text, as the page renders it: the stored\n * `entry:…` is not a URL any reader can follow.\n */\nfunction authoredMarkdown(\n source: string,\n context?: PageMarkdownContext,\n): string {\n return resolveMarkdownSourceLinks(source, (reference) => {\n const path = resolveScreenHref(context?.screenRoutes ?? undefined, reference)\n return path ? absoluteHref(path, context) : undefined\n })\n}\n\n/**\n * The node the document's content begins at.\n *\n * The `main` landmark first — `stampDocumentLandmark` puts it on the layout\n * slot or the screen root — then the layout slot by component id, then the\n * document root. Each fallback is wider than the last, so a tree that is\n * missing the marker still serializes rather than returning nothing.\n */\nexport function pageContentRootId(\n nodes: PageMarkdownNodes | null | undefined,\n rootId: string = NODE_ROOT_ID,\n): string | null {\n if (!nodes) return null\n for (const id in nodes) {\n if (elementOf(nodes[id]) === 'main') return id\n }\n for (const id in nodes) {\n if (nodes[id]?.componentId === 'layoutSlot') return id\n }\n return nodes[rootId] ? rootId : null\n}\n\n/** What a Markdown page carries above its body. */\nexport interface PageMarkdownFrontMatter {\n /** The `# ` heading. The page's own title, never the site's. */\n title?: string\n /** The meta description, emitted as the summary blockquote. */\n description?: string\n /** Canonical absolute URL, emitted as the source line. */\n canonicalUrl?: string\n /** ISO-8601 publication date, for a content entry. */\n publishedAt?: string\n /** ISO-8601 last-modified date, for a content entry. */\n updatedAt?: string\n /** Byline, for a content entry. */\n author?: string\n}\n\n/**\n * The whole Markdown representation of a page.\n *\n * @param body - already-Markdown body to use INSTEAD of walking nodes; the\n * content-entry case, where the stored body is markdown-lite source and\n * round-tripping it through the node tree could only lose fidelity.\n */\nexport function buildPageMarkdown(options: {\n nodes?: PageMarkdownNodes | null\n rootId?: string\n body?: string | null\n front?: PageMarkdownFrontMatter\n context?: PageMarkdownContext\n}): string {\n const front = options.front ?? {}\n const parts: string[] = []\n\n const title = collapse(String(front.title ?? ''))\n if (title) parts.push(`# ${escapeMarkdownText(title)}`)\n\n const description = collapse(String(front.description ?? ''))\n if (description) parts.push(`> ${escapeMarkdownText(description)}`)\n\n /*\n The dateline is one line rather than YAML front matter. Front matter is\n unparsed text to every Markdown reader that has not opted into it, so it\n arrives in an agent's context as a block of `key: value` noise above the\n content; a sentence is read correctly by all of them.\n */\n const meta: string[] = []\n if (front.author) meta.push(`By ${collapse(front.author)}`)\n if (front.publishedAt) meta.push(`Published ${front.publishedAt}`)\n if (front.updatedAt && front.updatedAt !== front.publishedAt) {\n meta.push(`Updated ${front.updatedAt}`)\n }\n if (meta.length) parts.push(`_${meta.join(' · ')}_`)\n\n if (typeof options.body === 'string' && options.body.trim()) {\n parts.push(authoredMarkdown(options.body.trim(), options.context))\n } else if (options.nodes) {\n const contentRoot = pageContentRootId(options.nodes, options.rootId)\n if (contentRoot) {\n const blocks: Block[] = []\n walk(options.nodes, contentRoot, options.context, blocks, new Set(), 0)\n for (const block of blocks) parts.push(block.text)\n }\n }\n\n if (front.canonicalUrl) {\n // A source line, and the reason it is worth the two lines it costs: an\n // agent that has copied this body into a prompt has no URL bar, so without\n // it the document cannot be cited, re-fetched, or linked to by whatever\n // reads it next.\n parts.push('---', `Source: ${front.canonicalUrl}`)\n }\n\n /*\n Collapse the runs of blank lines a nested walk leaves behind, and end with\n exactly one newline. A Markdown body is compared byte-for-byte by caches\n and by the conformance checkers agents run, so \"tidy\" here is a contract\n rather than an aesthetic.\n */\n return `${parts.join('\\n\\n').replace(/\\n{3,}/g, '\\n\\n').trim()}\\n`\n}\n"],"names":["NODE_ROOT_ID","authorHtmlToMarkdown","inlineAuthorHtmlToMarkdown","resolveMarkdownSourceLinks","absoluteMediaSrc","SAFE_HREF_PATTERN","resolveScreenHref","splitLinkValue","elementOf","node","String","props","toLowerCase","CHROME_COMPONENTS","Set","isPageChromeNode","has","componentId","element","HEADING","headingLevelOf","asElement","exec","Number","variant","asVariant","escapeMarkdownText","value","replace","collapse","trim","absoluteHref","href","context","test","startsWith","origin","labelOf","html","rich","children","walk","nodes","rootId","blocks","seen","depth","add","childIds","Array","isArray","filter","id","recurse","childId","push","text","level","repeat","content","authoredMarkdown","src","hostId","alt","label","screenLinkHref","items","lines","map","item","Boolean","join","target","undefined","screenId","path","screenRoutes","source","reference","pageContentRootId","buildPageMarkdown","options","front","parts","title","description","meta","author","publishedAt","updatedAt","length","body","contentRoot","block","canonicalUrl"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GAED,SAASA,YAAY,QAAQ,sCAAkC;AAC/D,SAASC,oBAAoB,EAAEC,0BAA0B,QAAQ,4BAAwB;AACzF,SAASC,0BAA0B,QAAQ,qBAAiB;AAC5D,SAASC,gBAAgB,QAAQ,iBAAa;AAC9C,SACEC,iBAAiB,EACjBC,iBAAiB,EACjBC,cAAc,QACT,yBAAqB;AAa5B,uEAAuE,GACvE,MAAMC,YAAY,CAACC;;QACVA;WAAPC,eAAOD,yBAAAA,cAAAA,KAAME,KAAK,qBAAXF,WAAa,CAAC,YAAY,mBAAI,IAAIG,WAAW;;AAEtD,8EAA8E,GAC9E,MAAMC,oBAAyC,IAAIC,IAAI;IACrD;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,6EAA6E;IAC7E,qEAAqE;IACrE;CACD;AAED;;;;;CAKC,GACD,OAAO,SAASC,iBAAiBN,IAAkC;QAEhCA;IADjC,IAAI,CAACA,MAAM,OAAO;IAClB,IAAII,kBAAkBG,GAAG,CAACN,QAAOD,oBAAAA,KAAKQ,WAAW,YAAhBR,oBAAoB,MAAM,OAAO;IAClE,MAAMS,UAAUV,UAAUC;IAC1B,OAAOS,YAAY,SAASA,YAAY,YAAYA,YAAY;AAClE;AAEA,gFAAgF,GAChF,MAAMC,UAAU;AAEhB;;;;;;;;;CASC,GACD,OAAO,SAASC,eAAeT,KAAiD;;IAC9E,MAAMO,UAAUR,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EAA2E;QAC3E,wEAAwE;QACxE,iBAAiB;QACjBX,MAAM5B,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE2B,MAAMY,YAAY,EAAE;IACnD;IAEA;;;;;EAKA,GACA,OAAO,GAAGX,MAAMZ,IAAI,CAAC,QAAQ3C,OAAO,CAAC,WAAW,QAAQE,IAAI,GAAG,EAAE,CAAC;AACpE"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/page-markdown.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 * A published page as Markdown — the representation an agent gets when it\n * sends `Accept: text/markdown` (acceptmarkdown.com).\n *\n * ## Why serialize the NODE TREE and not the rendered HTML\n *\n * The obvious implementation is to render the page and run an HTML-to-Markdown\n * converter over it. Every site on this platform is a node document, and the\n * tree carries what the HTML has already thrown away: which text is a heading\n * because the author said so rather than because it is large, which container\n * is the page's content region, and which subtree is navigation. Converting\n * the HTML back would be reconstructing, by heuristic, information we are\n * holding.\n *\n * It is also cheaper by a wide margin — no React render, no plugin registry,\n * no MUI — which is what makes this affordable to serve from a cached route on\n * every site rather than only where somebody enabled it.\n *\n * ## The content region, not the document\n *\n * Serialization starts at the document's `main` landmark, which\n * `stampDocumentLandmark` has already placed on the layout slot (the page\n * content between the chrome) or on the screen root. That is what makes the\n * output nav-free and footer-free without this module knowing anything about\n * how a particular site builds its header — the same property that makes a\n * Markdown variant worth serving at all.\n *\n * A page with no landmark falls back to the whole tree. Some content is always\n * better than an empty document, and a page that shipped no landmark\n * deliberately (see `document-landmark.ts`) has no content region to prefer.\n *\n * ## Chrome that lives INSIDE the content region\n *\n * A handful of components are navigation wherever they sit — an app bar, a nav\n * menu, a language switcher, a pagination strip. They are skipped by id, and\n * the list is deliberately short: everything not named recurses, so a plugin\n * block nobody here has heard of still contributes its text instead of\n * vanishing. Silence is the one failure mode that would be invisible to the\n * author.\n */\n\nimport { NODE_ROOT_ID } from '../canvas-manager/canvas-manager'\nimport { authorHtmlToMarkdown, inlineAuthorHtmlToMarkdown } from './author-html-markdown'\nimport { resolveMarkdownSourceLinks } from './markdown-lite'\nimport { absoluteMediaSrc } from './media-ref'\nimport {\n SAFE_HREF_PATTERN,\n resolveScreenHref,\n splitLinkValue,\n} from './screen-link-value'\n\n/** The node shape this serializer reads; keeps callers free of the full type. */\nexport interface PageMarkdownNode {\n componentId?: string\n props?: Record<string, unknown> | null\n /** Normalized documents carry child IDS; this never reads a denormalized tree. */\n nodes?: unknown\n}\n\n/** A flat node map keyed by node id — exactly what the page route already holds. */\nexport type PageMarkdownNodes = Record<string, PageMarkdownNode>\n\n/** The element name a node was told to render as (`props.component`). */\nconst elementOf = (node: PageMarkdownNode | undefined): string =>\n String(node?.props?.['component'] ?? '').toLowerCase()\n\n/** Components that are navigation wherever they appear. See the module note. */\nconst CHROME_COMPONENTS: ReadonlySet<string> = new Set([\n 'muiAppBar',\n 'muiToolbar',\n 'muiDrawer',\n 'muiBreadcrumbs',\n 'navMenu',\n 'searchBox',\n 'languageSwitcher',\n 'themeModeSwitcher',\n 'muiPagination',\n // An icon is decoration with no accessible text of its own. Its LABEL, where\n // one exists, belongs to the control around it and is emitted there.\n 'icon',\n])\n\n/**\n * Whether a node is navigation rather than content: a chrome component, or\n * an element its author declared `nav`, `header` or `footer`. Exported so a\n * reader of a page's CONTENT — the SEO audit's heading and image scan\n * (AGL-2910) — skips exactly what this serializer skips.\n */\nexport function isPageChromeNode(node: PageMarkdownNode | undefined): boolean {\n if (!node) return false\n if (CHROME_COMPONENTS.has(String(node.componentId ?? ''))) return true\n const element = elementOf(node)\n return element === 'nav' || element === 'header' || element === 'footer'\n}\n\n/** Heading levels, as either `props.component` or `props.variant` spells them. */\nconst HEADING = /^h([1-6])$/\n\n/**\n * The heading level a text node publishes, or 0 for body copy.\n *\n * `component` wins over `variant` because they answer different questions and\n * the platform lets them disagree: `variant` is the type STYLE (what size it is\n * drawn at) and `component` is the ELEMENT (what it means). An author who set a\n * hero line to look like an h1 but render as a `p` said it is not a heading,\n * and the Markdown has to agree with the HTML or the two documents describe\n * different pages.\n */\nexport function headingLevelOf(props: Record<string, unknown> | null | undefined): number {\n const element = String(props?.['component'] ?? '').toLowerCase()\n if (element) {\n const asElement = HEADING.exec(element)\n return asElement ? Number(asElement[1]) : 0\n }\n const variant = String(props?.['variant'] ?? '').toLowerCase()\n const asVariant = HEADING.exec(variant)\n return asVariant ? Number(asVariant[1]) : 0\n}\n\n/**\n * Escape the Markdown control characters that would otherwise re-parse.\n *\n * Only the characters that START a construct at the position they can occur in:\n * a leading `#`, `>`, `-`, `+` or `1.` on its own line, and the emphasis,\n * backtick and bracket characters anywhere. Escaping more than that produces\n * output littered with backslashes, which is worse to read and worse to embed\n * than the rare false heading it prevents.\n */\nexport function escapeMarkdownText(value: string): string {\n return value\n .replace(/([\\\\`*_[\\]<>])/g, '\\\\$1')\n .replace(/^(\\s*)([#>])/gm, '$1\\\\$2')\n .replace(/^(\\s*)([-+])(\\s)/gm, '$1\\\\$2$3')\n .replace(/^(\\s*)(\\d+)\\.(\\s)/gm, '$1$2\\\\.$3')\n}\n\n/** Collapse runs of whitespace to single spaces, as inline text renders. */\nconst collapse = (value: string): string => value.replace(/\\s+/g, ' ').trim()\n\n/** Resolution context for values that are stored as references, not URLs. */\nexport interface PageMarkdownContext {\n /** Site origin, for absolutizing media and site-relative links. */\n origin?: string | null\n /** Host id, so a restricted org asset resolves for the site rendering it. */\n hostId?: string\n /**\n * The routing map screen links resolve against (`screenRoutes`), and the\n * link references in authored markdown with them (AGL-3118).\n */\n screenRoutes?: Record<string, string> | null\n}\n\n/**\n * A link target as Markdown should carry it: absolute where we can make it so.\n *\n * Site-relative is fine in a page — the browser has a document to resolve\n * against. A Markdown body has no such context by the time an agent has copied\n * it into a prompt, so a relative href there is a link to nowhere.\n */\nfunction absoluteHref(href: string, context?: PageMarkdownContext): string {\n const value = href.trim()\n if (!value) return ''\n if (/^[a-z][a-z0-9+.-]*:/i.test(value) || value.startsWith('//')) return value\n const origin = context?.origin?.replace(/\\/+$/, '') ?? ''\n if (!origin) return value\n return value.startsWith('/') ? `${origin}${value}` : `${origin}/${value}`\n}\n\n/** The text a control shows, preferring its rich label over the plain one. */\nfunction labelOf(\n props: Record<string, unknown> | null | undefined,\n context?: PageMarkdownContext,\n): string {\n const html = props?.['html']\n if (typeof html === 'string' && html.trim()) {\n const rich = inlineAuthorHtmlToMarkdown(html, context)\n if (rich.trim()) return collapse(rich)\n }\n const children = props?.['children']\n return typeof children === 'string' ? collapse(escapeMarkdownText(children)) : ''\n}\n\n/** A block emitted by the walk, before the blocks are joined. */\ninterface Block {\n /** Markdown text of the block, already escaped. */\n text: string\n}\n\n/**\n * Serialize the subtree at `rootId` into Markdown blocks.\n *\n * A depth budget and a visited set, because a node map is data: a document\n * restored from a backup, or written through the REST API, can name a child\n * that names it back. Recursing that tree is a stack overflow inside a request\n * handler, i.e. a 500 on a page that renders fine — the renderer tolerates it\n * because React unmounts a cycle, and this has nothing to stop it but itself.\n */\nfunction walk(\n nodes: PageMarkdownNodes,\n rootId: string,\n context: PageMarkdownContext | undefined,\n blocks: Block[],\n seen: Set<string>,\n depth: number,\n): void {\n if (depth > 64 || seen.has(rootId)) return\n const node = nodes[rootId]\n if (!node) return\n seen.add(rootId)\n\n const componentId = String(node.componentId ?? '')\n // Chrome components, and `nav`, `header` and `footer` by their OWN\n // declaration — an author who set the element picker to one of them named\n // it navigation, and that is a stronger signal than any component-id list\n // can be.\n if (isPageChromeNode(node)) return\n\n const props = node.props ?? {}\n const childIds = Array.isArray(node.nodes)\n ? node.nodes.filter((id): id is string => typeof id === 'string')\n : []\n const recurse = (): void => {\n for (const childId of childIds) {\n walk(nodes, childId, context, blocks, seen, depth + 1)\n }\n }\n const push = (text: string): void => {\n if (text.trim()) blocks.push({ text: text.trim() })\n }\n\n switch (componentId) {\n case 'muiTypography':\n case 'muiInlineText':\n case 'muiListItemText': {\n const level = headingLevelOf(props)\n const text = labelOf(props, context)\n if (!text) {\n // A Typography with no text of its own but children beneath it is a\n // wrapper, which is how rich composites are built. Recurse rather than\n // dropping the subtree.\n recurse()\n return\n }\n push(level > 0 ? `${'#'.repeat(level)} ${text}` : text)\n // A Typography renders the elements it holds after its text\n // (AGL-3672), so they read after it here too.\n recurse()\n return\n }\n case 'markdown': {\n /*\n Already Markdown. Emitted VERBATIM and never re-escaped: `content` is\n the markdown-lite source an author typed, so escaping it would turn\n their headings into literal `#` characters — the one transformation\n that can only make this output worse. Its link REFERENCES are the one\n exception (AGL-3118), resolved as the page resolves them.\n */\n const content = props['content']\n if (typeof content === 'string') push(authoredMarkdown(content, context))\n return\n }\n case 'custom-html': {\n const html = props['html'] ?? props['children']\n if (typeof html === 'string') push(authorHtmlToMarkdown(html, context))\n return\n }\n case 'image': {\n const src = absoluteMediaSrc(String(props['src'] ?? '').trim(), {\n hostId: context?.hostId,\n origin: context?.origin,\n })\n if (!src) return\n const alt = collapse(String(props['alt'] ?? ''))\n push(`![${escapeMarkdownText(alt)}](${src})`)\n return\n }\n case 'video':\n case 'videoEmbed': {\n const src = String(props['src'] ?? props['url'] ?? '').trim()\n if (!src) return\n push(`[Video](${absoluteHref(src, context)})`)\n return\n }\n case 'muiButton':\n case 'muiScreenLink': {\n const label = labelOf(props, context) || 'Link'\n const href = screenLinkHref(props, context)\n push(href ? `[${label}](${href})` : label)\n return\n }\n case 'muiAccordionSummary': {\n /*\n An accordion's question (AGL-3575). The summary carries its text in\n its own props, not in a child node, so the default recursion below\n emitted NOTHING for it — every FAQ on every site reached an agent as\n a run of orphaned answers. It is a heading because that is what the\n HTML publishes: MUI renders the summary inside its `h3` heading slot,\n and the Markdown has to agree with the page or the two describe\n different documents. A linked header (AGL-1232) keeps its link, as\n the page does.\n */\n const text = labelOf(props, context)\n if (!text) {\n recurse()\n return\n }\n const href =\n typeof props['screenId'] === 'string' && props['screenId']\n ? screenLinkHref(props, context)\n : ''\n push(href ? `### [${text}](${href})` : `### ${text}`)\n return\n }\n case 'muiList': {\n /*\n The items are gathered into ONE block so they join as a list. Walking\n them as siblings would put a blank line between every bullet, which is\n a sequence of paragraphs beginning with a dash rather than a list.\n */\n const items: Block[] = []\n for (const childId of childIds) {\n walk(nodes, childId, context, items, seen, depth + 1)\n }\n const lines = items\n .map((item) => item.text.replace(/\\n/g, '\\n '))\n .filter(Boolean)\n .map((text) => `- ${text}`)\n push(lines.join('\\n'))\n return\n }\n default:\n recurse()\n }\n}\n\n/**\n * Where a Button or Screen Link points.\n *\n * A screen link stores a SCREEN ID, not a path, and the path it resolves to is\n * a per-request question — `screenRoutes` is the routing map the router\n * actually honors, which is not the map publishing wrote (a collection's list\n * template answers at the collection's slug, template screens answer nowhere).\n * Emitting `href` alone would publish, in Markdown, the dead links AGL-1998\n * removed from the HTML.\n *\n * `splitLinkValue` + `resolveScreenHref` rather than a local reading of the\n * two props, because WHICH SLOT a screen reference arrives in is not fixed\n * (AGL-1335): a `Link`-typed component prop is bound to whichever of\n * `screenId`/`href` the author reached for, and a value in the `href` slot\n * carries the stored `screen:<id>` spelling. Reading `screenId` alone published\n * that token verbatim as a link target on every page built from a prop-fed\n * CTA — ten of them on aglyn.com, unfollowable by the agents `/llms.txt` sends\n * here (AGL-2740). These are the same two functions `useLinkTarget` resolves\n * the HTML with, so the two representations of a page cannot drift again.\n *\n * An authored screen id that the map has lost resolves to NO link, exactly as\n * the HTML renders it: falling back to the stored `href` there would re-publish\n * the dead path AGL-1998 removed, which is the failure this function's own\n * contract exists to prevent.\n */\nfunction screenLinkHref(\n props: Record<string, unknown>,\n context?: PageMarkdownContext,\n): string {\n const target = splitLinkValue(\n typeof props['screenId'] === 'string' ? props['screenId'] : undefined,\n typeof props['href'] === 'string' ? props['href'] : undefined,\n )\n if (target.screenId) {\n const path = resolveScreenHref(context?.screenRoutes ?? undefined, target.screenId)\n return path ? absoluteHref(path, context) : ''\n }\n // The same protocol guard the linking elements apply. A `javascript:` href\n // is inert in a Markdown body, but it is still a target an agent may be\n // asked to follow, and a representation that offers one the page refuses to\n // render is describing a different document.\n return target.href && SAFE_HREF_PATTERN.test(target.href)\n ? absoluteHref(target.href, context)\n : ''\n}\n\n/**\n * Authored markdown-lite — a Markdown element's content, an entry's body —\n * as this document carries it: verbatim, except that each link REFERENCE\n * (AGL-3118) points where the page's own link does, through the same routing\n * map and the same `resolveScreenHref` as {@link screenLinkHref}, made\n * absolute for the reason {@link absoluteHref} gives. A reference the map\n * does not have becomes the link's text, as the page renders it: the stored\n * `entry:…` is not a URL any reader can follow.\n */\nfunction authoredMarkdown(\n source: string,\n context?: PageMarkdownContext,\n): string {\n return resolveMarkdownSourceLinks(source, (reference) => {\n const path = resolveScreenHref(context?.screenRoutes ?? undefined, reference)\n return path ? absoluteHref(path, context) : undefined\n })\n}\n\n/**\n * The node the document's content begins at.\n *\n * The `main` landmark first — `stampDocumentLandmark` puts it on the layout\n * slot or the screen root — then the layout slot by component id, then the\n * document root. Each fallback is wider than the last, so a tree that is\n * missing the marker still serializes rather than returning nothing.\n */\nexport function pageContentRootId(\n nodes: PageMarkdownNodes | null | undefined,\n rootId: string = NODE_ROOT_ID,\n): string | null {\n if (!nodes) return null\n for (const id in nodes) {\n if (elementOf(nodes[id]) === 'main') return id\n }\n for (const id in nodes) {\n if (nodes[id]?.componentId === 'layoutSlot') return id\n }\n return nodes[rootId] ? rootId : null\n}\n\n/** What a Markdown page carries above its body. */\nexport interface PageMarkdownFrontMatter {\n /** The `# ` heading. The page's own title, never the site's. */\n title?: string\n /** The meta description, emitted as the summary blockquote. */\n description?: string\n /** Canonical absolute URL, emitted as the source line. */\n canonicalUrl?: string\n /** ISO-8601 publication date, for a content entry. */\n publishedAt?: string\n /** ISO-8601 last-modified date, for a content entry. */\n updatedAt?: string\n /** Byline, for a content entry. */\n author?: string\n}\n\n/**\n * The whole Markdown representation of a page.\n *\n * @param body - already-Markdown body to use INSTEAD of walking nodes; the\n * content-entry case, where the stored body is markdown-lite source and\n * round-tripping it through the node tree could only lose fidelity.\n */\nexport function buildPageMarkdown(options: {\n nodes?: PageMarkdownNodes | null\n rootId?: string\n body?: string | null\n front?: PageMarkdownFrontMatter\n context?: PageMarkdownContext\n}): string {\n const front = options.front ?? {}\n const parts: string[] = []\n\n const title = collapse(String(front.title ?? ''))\n if (title) parts.push(`# ${escapeMarkdownText(title)}`)\n\n const description = collapse(String(front.description ?? ''))\n if (description) parts.push(`> ${escapeMarkdownText(description)}`)\n\n /*\n The dateline is one line rather than YAML front matter. Front matter is\n unparsed text to every Markdown reader that has not opted into it, so it\n arrives in an agent's context as a block of `key: value` noise above the\n content; a sentence is read correctly by all of them.\n */\n const meta: string[] = []\n if (front.author) meta.push(`By ${collapse(front.author)}`)\n if (front.publishedAt) meta.push(`Published ${front.publishedAt}`)\n if (front.updatedAt && front.updatedAt !== front.publishedAt) {\n meta.push(`Updated ${front.updatedAt}`)\n }\n if (meta.length) parts.push(`_${meta.join(' · ')}_`)\n\n if (typeof options.body === 'string' && options.body.trim()) {\n parts.push(authoredMarkdown(options.body.trim(), options.context))\n } else if (options.nodes) {\n const contentRoot = pageContentRootId(options.nodes, options.rootId)\n if (contentRoot) {\n const blocks: Block[] = []\n walk(options.nodes, contentRoot, options.context, blocks, new Set(), 0)\n for (const block of blocks) parts.push(block.text)\n }\n }\n\n if (front.canonicalUrl) {\n // A source line, and the reason it is worth the two lines it costs: an\n // agent that has copied this body into a prompt has no URL bar, so without\n // it the document cannot be cited, re-fetched, or linked to by whatever\n // reads it next.\n parts.push('---', `Source: ${front.canonicalUrl}`)\n }\n\n /*\n Collapse the runs of blank lines a nested walk leaves behind, and end with\n exactly one newline. A Markdown body is compared byte-for-byte by caches\n and by the conformance checkers agents run, so \"tidy\" here is a contract\n rather than an aesthetic.\n */\n return `${parts.join('\\n\\n').replace(/\\n{3,}/g, '\\n\\n').trim()}\\n`\n}\n"],"names":["NODE_ROOT_ID","authorHtmlToMarkdown","inlineAuthorHtmlToMarkdown","resolveMarkdownSourceLinks","absoluteMediaSrc","SAFE_HREF_PATTERN","resolveScreenHref","splitLinkValue","elementOf","node","String","props","toLowerCase","CHROME_COMPONENTS","Set","isPageChromeNode","has","componentId","element","HEADING","headingLevelOf","asElement","exec","Number","variant","asVariant","escapeMarkdownText","value","replace","collapse","trim","absoluteHref","href","context","test","startsWith","origin","labelOf","html","rich","children","walk","nodes","rootId","blocks","seen","depth","add","childIds","Array","isArray","filter","id","recurse","childId","push","text","level","repeat","content","authoredMarkdown","src","hostId","alt","label","screenLinkHref","items","lines","map","item","Boolean","join","target","undefined","screenId","path","screenRoutes","source","reference","pageContentRootId","buildPageMarkdown","options","front","parts","title","description","meta","author","publishedAt","updatedAt","length","body","contentRoot","block","canonicalUrl"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GAED,SAASA,YAAY,QAAQ,sCAAkC;AAC/D,SAASC,oBAAoB,EAAEC,0BAA0B,QAAQ,4BAAwB;AACzF,SAASC,0BAA0B,QAAQ,qBAAiB;AAC5D,SAASC,gBAAgB,QAAQ,iBAAa;AAC9C,SACEC,iBAAiB,EACjBC,iBAAiB,EACjBC,cAAc,QACT,yBAAqB;AAa5B,uEAAuE,GACvE,MAAMC,YAAY,CAACC;;QACVA;WAAPC,eAAOD,yBAAAA,cAAAA,KAAME,KAAK,qBAAXF,WAAa,CAAC,YAAY,mBAAI,IAAIG,WAAW;;AAEtD,8EAA8E,GAC9E,MAAMC,oBAAyC,IAAIC,IAAI;IACrD;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,6E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AAiBqB,QAAQU,IAAI,CAAC7D,IAAI,IAAImD,QAAQhD,OAAO;IAClE,OAAO,IAAIgD,QAAQvC,KAAK,EAAE;QACxB,MAAMkD,cAAcb,kBAAkBE,QAAQvC,KAAK,EAAEuC,QAAQtC,MAAM;QACnE,IAAIiD,aAAa;YACf,MAAMhD,SAAkB,EAAE;YAC1BH,KAAKwC,QAAQvC,KAAK,EAAEkD,aAAaX,QAAQhD,OAAO,EAAEW,QAAQ,IAAI9B,OAAO;YACrE,KAAK,MAAM+E,SAASjD,OAAQuC,MAAM5B,IAAI,CAACsC,MAAMrC,IAAI;QACnD;IACF;IAEA,IAAI0B,MAAMY,YAAY,EAAE;QACtB,uEAAuE;QACvE,2EAA2E;QAC3E,wEAAwE;QACxE,iBAAiB;QACjBX,MAAM5B,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE2B,MAAMY,YAAY,EAAE;IACnD;IAEA;;;;;EAKA,GACA,OAAO,GAAGX,MAAMZ,IAAI,CAAC,QAAQ3C,OAAO,CAAC,WAAW,QAAQE,IAAI,GAAG,EAAE,CAAC;AACpE"}
@@ -8,5 +8,5 @@
8
8
  */
9
9
  import type { HostEventDeclaration } from './host-events';
10
10
  /** Every host event a plugin declares. */
11
- export type PluginHostEventType = 'formSubmission' | 'memberSignUp' | 'memberSignIn' | 'memberSignOut' | 'lead' | 'booking' | 'taskCompleted' | 'contactCreated' | 'contactStageChanged' | 'dealStageChanged' | 'dealWon' | 'dealLost' | 'funnelLeft';
11
+ export type PluginHostEventType = 'formSubmission' | 'memberSignUp' | 'memberSignIn' | 'memberSignOut' | 'lead' | 'booking' | 'taskCompleted' | 'contactCreated' | 'contactStageChanged' | 'dealStageChanged' | 'dealWon' | 'dealLost' | 'orderPaid' | 'orderFulfilled' | 'orderDelivered' | 'orderRefunded' | 'orderCancelled' | 'returnRequested' | 'returnApproved' | 'returnDeclined' | 'returnReceived' | 'returnRefunded' | 'funnelLeft';
12
12
  export declare const PLUGIN_HOST_EVENTS: readonly HostEventDeclaration[];
@@ -173,6 +173,155 @@
173
173
  "lostReason"
174
174
  ]
175
175
  },
176
+ {
177
+ "pluginId": "commerce",
178
+ "type": "orderPaid",
179
+ "order": 140,
180
+ "label": "Order paid",
181
+ "payloadKeys": [
182
+ "orderId",
183
+ "orderNumber",
184
+ "status",
185
+ "channel",
186
+ "email",
187
+ "name",
188
+ "totalCents",
189
+ "currency"
190
+ ]
191
+ },
192
+ {
193
+ "pluginId": "commerce",
194
+ "type": "orderFulfilled",
195
+ "order": 141,
196
+ "label": "Order fulfilled",
197
+ "payloadKeys": [
198
+ "orderId",
199
+ "orderNumber",
200
+ "status",
201
+ "email",
202
+ "name",
203
+ "totalCents",
204
+ "fulfillmentId",
205
+ "carrier",
206
+ "trackingNumber",
207
+ "trackingUrl"
208
+ ]
209
+ },
210
+ {
211
+ "pluginId": "commerce",
212
+ "type": "orderDelivered",
213
+ "order": 142,
214
+ "label": "Order delivered",
215
+ "payloadKeys": [
216
+ "orderId",
217
+ "orderNumber",
218
+ "status",
219
+ "email",
220
+ "name",
221
+ "totalCents"
222
+ ]
223
+ },
224
+ {
225
+ "pluginId": "commerce",
226
+ "type": "orderRefunded",
227
+ "order": 143,
228
+ "label": "Order refunded",
229
+ "payloadKeys": [
230
+ "orderId",
231
+ "orderNumber",
232
+ "status",
233
+ "email",
234
+ "name",
235
+ "totalCents",
236
+ "refundCents",
237
+ "fullRefund"
238
+ ]
239
+ },
240
+ {
241
+ "pluginId": "commerce",
242
+ "type": "orderCancelled",
243
+ "order": 144,
244
+ "label": "Order canceled",
245
+ "payloadKeys": [
246
+ "orderId",
247
+ "orderNumber",
248
+ "status",
249
+ "email",
250
+ "name",
251
+ "totalCents"
252
+ ]
253
+ },
254
+ {
255
+ "pluginId": "commerce",
256
+ "type": "returnRequested",
257
+ "order": 145,
258
+ "label": "Return requested",
259
+ "payloadKeys": [
260
+ "orderId",
261
+ "orderNumber",
262
+ "email",
263
+ "name",
264
+ "returnId",
265
+ "returnStatus"
266
+ ]
267
+ },
268
+ {
269
+ "pluginId": "commerce",
270
+ "type": "returnApproved",
271
+ "order": 146,
272
+ "label": "Return approved",
273
+ "payloadKeys": [
274
+ "orderId",
275
+ "orderNumber",
276
+ "email",
277
+ "name",
278
+ "returnId",
279
+ "returnStatus"
280
+ ]
281
+ },
282
+ {
283
+ "pluginId": "commerce",
284
+ "type": "returnDeclined",
285
+ "order": 147,
286
+ "label": "Return declined",
287
+ "payloadKeys": [
288
+ "orderId",
289
+ "orderNumber",
290
+ "email",
291
+ "name",
292
+ "returnId",
293
+ "returnStatus"
294
+ ]
295
+ },
296
+ {
297
+ "pluginId": "commerce",
298
+ "type": "returnReceived",
299
+ "order": 148,
300
+ "label": "Return received",
301
+ "payloadKeys": [
302
+ "orderId",
303
+ "orderNumber",
304
+ "email",
305
+ "name",
306
+ "returnId",
307
+ "returnStatus"
308
+ ]
309
+ },
310
+ {
311
+ "pluginId": "commerce",
312
+ "type": "returnRefunded",
313
+ "order": 149,
314
+ "label": "Return refunded",
315
+ "payloadKeys": [
316
+ "orderId",
317
+ "orderNumber",
318
+ "email",
319
+ "name",
320
+ "returnId",
321
+ "returnStatus",
322
+ "returnRefundCents"
323
+ ]
324
+ },
176
325
  {
177
326
  "pluginId": "funnels",
178
327
  "type": "funnelLeft",
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/plugin-host-events.generated.ts"],"sourcesContent":["/**\n * GENERATED FILE — do not edit. Regenerate with:\n * node tools/scripts/generate-plugin-manifests.mjs\n *\n * The host events plugins declare (AGL-3080): each plugin's `hostEvents`\n * in plugins.config.json, in `order`. Core's `host-events.ts` folds them\n * in beside the platform's own.\n */\n\nimport type { HostEventDeclaration } from './host-events'\n\n/** Every host event a plugin declares. */\nexport type PluginHostEventType =\n | 'formSubmission'\n | 'memberSignUp'\n | 'memberSignIn'\n | 'memberSignOut'\n | 'lead'\n | 'booking'\n | 'taskCompleted'\n | 'contactCreated'\n | 'contactStageChanged'\n | 'dealStageChanged'\n | 'dealWon'\n | 'dealLost'\n | 'funnelLeft'\n\nexport const PLUGIN_HOST_EVENTS: readonly HostEventDeclaration[] = [\n {\n \"pluginId\": \"forms\",\n \"type\": \"formSubmission\",\n \"order\": 10,\n \"label\": \"Form submitted\",\n \"payloadKeys\": [\n \"formId\",\n \"formName\",\n \"path\",\n \"and every submitted field by name\"\n ],\n \"recipientActed\": true\n },\n {\n \"pluginId\": \"commerce\",\n \"type\": \"memberSignUp\",\n \"order\": 30,\n \"label\": \"Member signed up\",\n \"payloadKeys\": [\n \"email\"\n ],\n \"recipientActed\": true\n },\n {\n \"pluginId\": \"commerce\",\n \"type\": \"memberSignIn\",\n \"order\": 40,\n \"label\": \"Member signed in\",\n \"payloadKeys\": [\n \"email\"\n ]\n },\n {\n \"pluginId\": \"commerce\",\n \"type\": \"memberSignOut\",\n \"order\": 50,\n \"label\": \"Member signed out\"\n },\n {\n \"pluginId\": \"crm\",\n \"type\": \"lead\",\n \"order\": 60,\n \"label\": \"New lead\",\n \"payloadKeys\": [\n \"leadId\",\n \"email\",\n \"name\",\n \"source\",\n \"hostId\",\n \"formId\",\n \"campaignIds\"\n ],\n \"recipientActed\": true\n },\n {\n \"pluginId\": \"bookings\",\n \"type\": \"booking\",\n \"order\": 70,\n \"label\": \"New booking\",\n \"payloadKeys\": [\n \"serviceName\",\n \"email\",\n \"startsAtMs\"\n ],\n \"recipientActed\": true\n },\n {\n \"pluginId\": \"crm\",\n \"type\": \"taskCompleted\",\n \"order\": 80,\n \"label\": \"CRM task completed\",\n \"payloadKeys\": [\n \"taskId\",\n \"title\",\n \"kind\",\n \"priority\",\n \"dueAtMs\",\n \"completedAtMs\",\n \"completedByUid\",\n \"assigneeUid\",\n \"createdByUid\",\n \"contactId\",\n \"companyId\",\n \"dealId\",\n \"taskHostId\"\n ]\n },\n {\n \"pluginId\": \"crm\",\n \"type\": \"contactCreated\",\n \"order\": 90,\n \"label\": \"Contact created\",\n \"payloadKeys\": [\n \"contactId\",\n \"email\",\n \"name\",\n \"source\",\n \"hostId\",\n \"lifecycleStage\",\n \"campaignIds\",\n \"formId\"\n ]\n },\n {\n \"pluginId\": \"crm\",\n \"type\": \"contactStageChanged\",\n \"order\": 100,\n \"label\": \"Contact changed stage\",\n \"payloadKeys\": [\n \"contactId\",\n \"email\",\n \"lifecycleStage\",\n \"previousStage\"\n ]\n },\n {\n \"pluginId\": \"crm\",\n \"type\": \"dealStageChanged\",\n \"order\": 110,\n \"label\": \"Deal moved\",\n \"payloadKeys\": [\n \"dealId\",\n \"title\",\n \"amountCents\",\n \"currency\",\n \"stageId\",\n \"previousStageId\",\n \"ownerUid\",\n \"contactId\",\n \"companyId\"\n ]\n },\n {\n \"pluginId\": \"crm\",\n \"type\": \"dealWon\",\n \"order\": 120,\n \"label\": \"Deal won\",\n \"payloadKeys\": [\n \"dealId\",\n \"title\",\n \"amountCents\",\n \"currency\",\n \"stageId\",\n \"previousStageId\",\n \"ownerUid\",\n \"contactId\",\n \"companyId\"\n ]\n },\n {\n \"pluginId\": \"crm\",\n \"type\": \"dealLost\",\n \"order\": 130,\n \"label\": \"Deal lost\",\n \"payloadKeys\": [\n \"dealId\",\n \"title\",\n \"amountCents\",\n \"currency\",\n \"stageId\",\n \"previousStageId\",\n \"ownerUid\",\n \"contactId\",\n \"companyId\",\n \"lostReason\"\n ]\n },\n {\n \"pluginId\": \"funnels\",\n \"type\": \"funnelLeft\",\n \"order\": 150,\n \"label\": \"Left a funnel\",\n \"payloadKeys\": [\n \"funnelId\",\n \"funnelName\",\n \"step\",\n \"stepLabel\",\n \"nextStepLabel\",\n \"afterHours\",\n \"email\"\n ]\n }\n]\n"],"names":["PLUGIN_HOST_EVENTS"],"mappings":"AAAA;;;;;;;CAOC,GAoBD,OAAO,MAAMA,qBAAsD;IACjE;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;SACD;QACD,kBAAkB;IACpB;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;SACD;QACD,kBAAkB;IACpB;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;IACX;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACD,kBAAkB;IACpB;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;SACD;QACD,kBAAkB;IACpB;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;CACD,CAAA"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/plugin-host-events.generated.ts"],"sourcesContent":["/**\n * GENERATED FILE — do not edit. Regenerate with:\n * node tools/scripts/generate-plugin-manifests.mjs\n *\n * The host events plugins declare (AGL-3080): each plugin's `hostEvents`\n * in plugins.config.json, in `order`. Core's `host-events.ts` folds them\n * in beside the platform's own.\n */\n\nimport type { HostEventDeclaration } from './host-events'\n\n/** Every host event a plugin declares. */\nexport type PluginHostEventType =\n | 'formSubmission'\n | 'memberSignUp'\n | 'memberSignIn'\n | 'memberSignOut'\n | 'lead'\n | 'booking'\n | 'taskCompleted'\n | 'contactCreated'\n | 'contactStageChanged'\n | 'dealStageChanged'\n | 'dealWon'\n | 'dealLost'\n | 'orderPaid'\n | 'orderFulfilled'\n | 'orderDelivered'\n | 'orderRefunded'\n | 'orderCancelled'\n | 'returnRequested'\n | 'returnApproved'\n | 'returnDeclined'\n | 'returnReceived'\n | 'returnRefunded'\n | 'funnelLeft'\n\nexport const PLUGIN_HOST_EVENTS: readonly HostEventDeclaration[] = [\n {\n \"pluginId\": \"forms\",\n \"type\": \"formSubmission\",\n \"order\": 10,\n \"label\": \"Form submitted\",\n \"payloadKeys\": [\n \"formId\",\n \"formName\",\n \"path\",\n \"and every submitted field by name\"\n ],\n \"recipientActed\": true\n },\n {\n \"pluginId\": \"commerce\",\n \"type\": \"memberSignUp\",\n \"order\": 30,\n \"label\": \"Member signed up\",\n \"payloadKeys\": [\n \"email\"\n ],\n \"recipientActed\": true\n },\n {\n \"pluginId\": \"commerce\",\n \"type\": \"memberSignIn\",\n \"order\": 40,\n \"label\": \"Member signed in\",\n \"payloadKeys\": [\n \"email\"\n ]\n },\n {\n \"pluginId\": \"commerce\",\n \"type\": \"memberSignOut\",\n \"order\": 50,\n \"label\": \"Member signed out\"\n },\n {\n \"pluginId\": \"crm\",\n \"type\": \"lead\",\n \"order\": 60,\n \"label\": \"New lead\",\n \"payloadKeys\": [\n \"leadId\",\n \"email\",\n \"name\",\n \"source\",\n \"hostId\",\n \"formId\",\n \"campaignIds\"\n ],\n \"recipientActed\": true\n },\n {\n \"pluginId\": \"bookings\",\n \"type\": \"booking\",\n \"order\": 70,\n \"label\": \"New booking\",\n \"payloadKeys\": [\n \"serviceName\",\n \"email\",\n \"startsAtMs\"\n ],\n \"recipientActed\": true\n },\n {\n \"pluginId\": \"crm\",\n \"type\": \"taskCompleted\",\n \"order\": 80,\n \"label\": \"CRM task completed\",\n \"payloadKeys\": [\n \"taskId\",\n \"title\",\n \"kind\",\n \"priority\",\n \"dueAtMs\",\n \"completedAtMs\",\n \"completedByUid\",\n \"assigneeUid\",\n \"createdByUid\",\n \"contactId\",\n \"companyId\",\n \"dealId\",\n \"taskHostId\"\n ]\n },\n {\n \"pluginId\": \"crm\",\n \"type\": \"contactCreated\",\n \"order\": 90,\n \"label\": \"Contact created\",\n \"payloadKeys\": [\n \"contactId\",\n \"email\",\n \"name\",\n \"source\",\n \"hostId\",\n \"lifecycleStage\",\n \"campaignIds\",\n \"formId\"\n ]\n },\n {\n \"pluginId\": \"crm\",\n \"type\": \"contactStageChanged\",\n \"order\": 100,\n \"label\": \"Contact changed stage\",\n \"payloadKeys\": [\n \"contactId\",\n \"email\",\n \"lifecycleStage\",\n \"previousStage\"\n ]\n },\n {\n \"pluginId\": \"crm\",\n \"type\": \"dealStageChanged\",\n \"order\": 110,\n \"label\": \"Deal moved\",\n \"payloadKeys\": [\n \"dealId\",\n \"title\",\n \"amountCents\",\n \"currency\",\n \"stageId\",\n \"previousStageId\",\n \"ownerUid\",\n \"contactId\",\n \"companyId\"\n ]\n },\n {\n \"pluginId\": \"crm\",\n \"type\": \"dealWon\",\n \"order\": 120,\n \"label\": \"Deal won\",\n \"payloadKeys\": [\n \"dealId\",\n \"title\",\n \"amountCents\",\n \"currency\",\n \"stageId\",\n \"previousStageId\",\n \"ownerUid\",\n \"contactId\",\n \"companyId\"\n ]\n },\n {\n \"pluginId\": \"crm\",\n \"type\": \"dealLost\",\n \"order\": 130,\n \"label\": \"Deal lost\",\n \"payloadKeys\": [\n \"dealId\",\n \"title\",\n \"amountCents\",\n \"currency\",\n \"stageId\",\n \"previousStageId\",\n \"ownerUid\",\n \"contactId\",\n \"companyId\",\n \"lostReason\"\n ]\n },\n {\n \"pluginId\": \"commerce\",\n \"type\": \"orderPaid\",\n \"order\": 140,\n \"label\": \"Order paid\",\n \"payloadKeys\": [\n \"orderId\",\n \"orderNumber\",\n \"status\",\n \"channel\",\n \"email\",\n \"name\",\n \"totalCents\",\n \"currency\"\n ]\n },\n {\n \"pluginId\": \"commerce\",\n \"type\": \"orderFulfilled\",\n \"order\": 141,\n \"label\": \"Order fulfilled\",\n \"payloadKeys\": [\n \"orderId\",\n \"orderNumber\",\n \"status\",\n \"email\",\n \"name\",\n \"totalCents\",\n \"fulfillmentId\",\n \"carrier\",\n \"trackingNumber\",\n \"trackingUrl\"\n ]\n },\n {\n \"pluginId\": \"commerce\",\n \"type\": \"orderDelivered\",\n \"order\": 142,\n \"label\": \"Order delivered\",\n \"payloadKeys\": [\n \"orderId\",\n \"orderNumber\",\n \"status\",\n \"email\",\n \"name\",\n \"totalCents\"\n ]\n },\n {\n \"pluginId\": \"commerce\",\n \"type\": \"orderRefunded\",\n \"order\": 143,\n \"label\": \"Order refunded\",\n \"payloadKeys\": [\n \"orderId\",\n \"orderNumber\",\n \"status\",\n \"email\",\n \"name\",\n \"totalCents\",\n \"refundCents\",\n \"fullRefund\"\n ]\n },\n {\n \"pluginId\": \"commerce\",\n \"type\": \"orderCancelled\",\n \"order\": 144,\n \"label\": \"Order canceled\",\n \"payloadKeys\": [\n \"orderId\",\n \"orderNumber\",\n \"status\",\n \"email\",\n \"name\",\n \"totalCents\"\n ]\n },\n {\n \"pluginId\": \"commerce\",\n \"type\": \"returnRequested\",\n \"order\": 145,\n \"label\": \"Return requested\",\n \"payloadKeys\": [\n \"orderId\",\n \"orderNumber\",\n \"email\",\n \"name\",\n \"returnId\",\n \"returnStatus\"\n ]\n },\n {\n \"pluginId\": \"commerce\",\n \"type\": \"returnApproved\",\n \"order\": 146,\n \"label\": \"Return approved\",\n \"payloadKeys\": [\n \"orderId\",\n \"orderNumber\",\n \"email\",\n \"name\",\n \"returnId\",\n \"returnStatus\"\n ]\n },\n {\n \"pluginId\": \"commerce\",\n \"type\": \"returnDeclined\",\n \"order\": 147,\n \"label\": \"Return declined\",\n \"payloadKeys\": [\n \"orderId\",\n \"orderNumber\",\n \"email\",\n \"name\",\n \"returnId\",\n \"returnStatus\"\n ]\n },\n {\n \"pluginId\": \"commerce\",\n \"type\": \"returnReceived\",\n \"order\": 148,\n \"label\": \"Return received\",\n \"payloadKeys\": [\n \"orderId\",\n \"orderNumber\",\n \"email\",\n \"name\",\n \"returnId\",\n \"returnStatus\"\n ]\n },\n {\n \"pluginId\": \"commerce\",\n \"type\": \"returnRefunded\",\n \"order\": 149,\n \"label\": \"Return refunded\",\n \"payloadKeys\": [\n \"orderId\",\n \"orderNumber\",\n \"email\",\n \"name\",\n \"returnId\",\n \"returnStatus\",\n \"returnRefundCents\"\n ]\n },\n {\n \"pluginId\": \"funnels\",\n \"type\": \"funnelLeft\",\n \"order\": 150,\n \"label\": \"Left a funnel\",\n \"payloadKeys\": [\n \"funnelId\",\n \"funnelName\",\n \"step\",\n \"stepLabel\",\n \"nextStepLabel\",\n \"afterHours\",\n \"email\"\n ]\n }\n]\n"],"names":["PLUGIN_HOST_EVENTS"],"mappings":"AAAA;;;;;;;CAOC,GA8BD,OAAO,MAAMA,qBAAsD;IACjE;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;SACD;QACD,kBAAkB;IACpB;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;SACD;QACD,kBAAkB;IACpB;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;IACX;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACD,kBAAkB;IACpB;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;SACD;QACD,kBAAkB;IACpB;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,SAAS;QACT,eAAe;YACb;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;CACD,CAAA"}
@@ -8,5 +8,5 @@
8
8
  */
9
9
  import type { PluginReleaseFlagDefinition } from './release-flags';
10
10
  /** Every release flag a plugin declares. */
11
- export type PluginReleaseFlagKey = 'release_member_accounts' | 'release_bookings' | 'release_commerce_v2' | 'release_marketplace' | 'release_crm' | 'release_outreach' | 'release_data_store' | 'release_email' | 'release_events' | 'release_inbox' | 'release_logic' | 'release_marketing' | 'release_redirects' | 'release_workflows';
11
+ export type PluginReleaseFlagKey = 'release_member_accounts' | 'release_bookings' | 'release_commerce_v2' | 'release_marketplace' | 'release_crm' | 'release_outreach' | 'release_data_store' | 'release_email' | 'release_events' | 'release_inbox' | 'release_logic' | 'release_marketing' | 'release_redirects' | 'release_workflows' | 'release_accounting';
12
12
  export declare const PLUGIN_RELEASE_FLAGS: readonly PluginReleaseFlagDefinition[];
@@ -100,6 +100,13 @@
100
100
  "description": "Workflows, actions, webhooks and their run history.",
101
101
  "defaultEnabled": true,
102
102
  "navTabId": "nav-tab-workflows"
103
+ },
104
+ {
105
+ "key": "release_accounting",
106
+ "label": "Accounting",
107
+ "description": "QuickBooks Online and Xero sync for commerce: sales receipts or a daily summary journal, refunds, platform fees and Stripe payouts, with a mapping page and a sync log (AGL-3614). OFF by default; needs the deployment's Intuit or Xero app credentials and the accounting token key on the console.",
108
+ "defaultEnabled": false,
109
+ "navTabId": "nav-tab-org-accounting"
103
110
  }
104
111
  ];
105
112