@aglyn/aglyn 1.0.0-beta.219 → 1.0.0-beta.221

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 (188) hide show
  1. package/package.json +12 -12
  2. package/src/lib/app-utils/actions.d.ts +1 -59
  3. package/src/lib/app-utils/actions.js +7 -72
  4. package/src/lib/app-utils/actions.js.map +1 -1
  5. package/src/lib/app-utils/consent-groups.d.ts +1 -1
  6. package/src/lib/app-utils/consent-groups.js.map +1 -1
  7. package/src/lib/app-utils/console-routes.d.ts +0 -36
  8. package/src/lib/app-utils/console-routes.js +2 -37
  9. package/src/lib/app-utils/console-routes.js.map +1 -1
  10. package/src/lib/app-utils/contacts.d.ts +1 -1
  11. package/src/lib/app-utils/contacts.js.map +1 -1
  12. package/src/lib/app-utils/container-membership.d.ts +93 -0
  13. package/src/lib/app-utils/container-membership.js +165 -0
  14. package/src/lib/app-utils/container-membership.js.map +1 -0
  15. package/src/lib/app-utils/crm-task-reminders.d.ts +23 -6
  16. package/src/lib/app-utils/crm-task-reminders.js +32 -11
  17. package/src/lib/app-utils/crm-task-reminders.js.map +1 -1
  18. package/src/lib/app-utils/crm.d.ts +24 -4
  19. package/src/lib/app-utils/crm.js +23 -0
  20. package/src/lib/app-utils/crm.js.map +1 -1
  21. package/src/lib/app-utils/csv-upload.d.ts +1 -1
  22. package/src/lib/app-utils/csv-upload.js +1 -1
  23. package/src/lib/app-utils/csv-upload.js.map +1 -1
  24. package/src/lib/app-utils/{dataset-csv.d.ts → csv.d.ts} +10 -43
  25. package/src/lib/app-utils/{dataset-csv.js → csv.js} +10 -81
  26. package/src/lib/app-utils/csv.js.map +1 -0
  27. package/src/lib/app-utils/datasets.d.ts +0 -19
  28. package/src/lib/app-utils/datasets.js +0 -13
  29. package/src/lib/app-utils/datasets.js.map +1 -1
  30. package/src/lib/app-utils/docs-help.generated.d.ts +4 -4
  31. package/src/lib/app-utils/docs-help.generated.js +5 -0
  32. package/src/lib/app-utils/docs-help.generated.js.map +1 -1
  33. package/src/lib/app-utils/docs-index.generated.js +71 -36
  34. package/src/lib/app-utils/docs-index.generated.js.map +1 -1
  35. package/src/lib/app-utils/dynamic-list-rule.js +3 -3
  36. package/src/lib/app-utils/dynamic-list-rule.js.map +1 -1
  37. package/src/lib/app-utils/email-text.d.ts +80 -0
  38. package/src/lib/app-utils/email-text.js +189 -0
  39. package/src/lib/app-utils/email-text.js.map +1 -0
  40. package/src/lib/app-utils/{list-assignment-policy.d.ts → enrollment-basis.d.ts} +4 -0
  41. package/src/lib/app-utils/{list-assignment-policy.js → enrollment-basis.js} +5 -1
  42. package/src/lib/app-utils/enrollment-basis.js.map +1 -0
  43. package/src/lib/app-utils/expand-repeatables.js +4 -4
  44. package/src/lib/app-utils/expand-repeatables.js.map +1 -1
  45. package/src/lib/app-utils/forms.js +2 -2
  46. package/src/lib/app-utils/forms.js.map +1 -1
  47. package/src/lib/app-utils/health-report.d.ts +2 -3
  48. package/src/lib/app-utils/health-report.js +30 -6
  49. package/src/lib/app-utils/health-report.js.map +1 -1
  50. package/src/lib/app-utils/inbound-mail-domain.d.ts +27 -0
  51. package/src/lib/app-utils/inbound-mail-domain.js +31 -0
  52. package/src/lib/app-utils/inbound-mail-domain.js.map +1 -0
  53. package/src/lib/app-utils/leaving-notice.d.ts +96 -0
  54. package/src/lib/app-utils/leaving-notice.js +157 -0
  55. package/src/lib/app-utils/leaving-notice.js.map +1 -0
  56. package/src/lib/app-utils/lockdown.d.ts +11 -0
  57. package/src/lib/app-utils/lockdown.js +33 -3
  58. package/src/lib/app-utils/lockdown.js.map +1 -1
  59. package/src/lib/app-utils/member-email-aliases.d.ts +25 -0
  60. package/src/lib/app-utils/member-email-aliases.js +29 -0
  61. package/src/lib/app-utils/member-email-aliases.js.map +1 -1
  62. package/src/lib/app-utils/notifications.d.ts +69 -0
  63. package/src/lib/app-utils/notifications.js +119 -0
  64. package/src/lib/app-utils/notifications.js.map +1 -1
  65. package/src/lib/app-utils/operator-alerts.d.ts +15 -1
  66. package/src/lib/app-utils/operator-alerts.js +64 -10
  67. package/src/lib/app-utils/operator-alerts.js.map +1 -1
  68. package/src/lib/app-utils/plan-entitlements.d.ts +164 -178
  69. package/src/lib/app-utils/plan-entitlements.js +200 -224
  70. package/src/lib/app-utils/plan-entitlements.js.map +1 -1
  71. package/src/lib/app-utils/platform-marketing-consent.d.ts +56 -2
  72. package/src/lib/app-utils/platform-marketing-consent.js +6 -5
  73. package/src/lib/app-utils/platform-marketing-consent.js.map +1 -1
  74. package/src/lib/app-utils/plugin-starter-templates.generated.d.ts +12 -0
  75. package/src/lib/app-utils/plugin-starter-templates.generated.js +711 -0
  76. package/src/lib/app-utils/plugin-starter-templates.generated.js.map +1 -0
  77. package/src/lib/app-utils/repeat-query.d.ts +56 -0
  78. package/src/lib/app-utils/{dataset-query.js → repeat-query.js} +16 -16
  79. package/src/lib/app-utils/repeat-query.js.map +1 -0
  80. package/src/lib/app-utils/screen-link-context-value.d.ts +7 -0
  81. package/src/lib/app-utils/screen-link-context-value.js.map +1 -1
  82. package/src/lib/app-utils/screen-link-context.js +14 -2
  83. package/src/lib/app-utils/screen-link-context.js.map +1 -1
  84. package/src/lib/app-utils/screen-route.d.ts +3 -0
  85. package/src/lib/app-utils/screen-route.js +6 -1
  86. package/src/lib/app-utils/screen-route.js.map +1 -1
  87. package/src/lib/app-utils/server.d.ts +7 -9
  88. package/src/lib/app-utils/server.js +18 -26
  89. package/src/lib/app-utils/server.js.map +1 -1
  90. package/src/lib/app-utils/starter-template-nodes.d.ts +137 -0
  91. package/src/lib/app-utils/starter-template-nodes.js +129 -0
  92. package/src/lib/app-utils/starter-template-nodes.js.map +1 -0
  93. package/src/lib/app-utils/starter-templates.d.ts +11 -34
  94. package/src/lib/app-utils/starter-templates.js +19 -230
  95. package/src/lib/app-utils/starter-templates.js.map +1 -1
  96. package/src/lib/app-utils/{email-topics.d.ts → subscription-topics.d.ts} +64 -48
  97. package/src/lib/app-utils/{email-topics.js → subscription-topics.js} +39 -109
  98. package/src/lib/app-utils/subscription-topics.js.map +1 -0
  99. package/src/lib/app-utils/usage-budget.d.ts +73 -188
  100. package/src/lib/app-utils/usage-budget.js +58 -194
  101. package/src/lib/app-utils/usage-budget.js.map +1 -1
  102. package/src/lib/app-utils/utm-attribution.d.ts +1 -1
  103. package/src/lib/app-utils/utm-attribution.js +1 -1
  104. package/src/lib/app-utils/utm-attribution.js.map +1 -1
  105. package/src/lib/app-utils/{campaign-touch.d.ts → utm-touch.d.ts} +21 -13
  106. package/src/lib/app-utils/{campaign-touch.js → utm-touch.js} +30 -22
  107. package/src/lib/app-utils/utm-touch.js.map +1 -0
  108. package/src/lib/app-utils/variables.d.ts +9 -9
  109. package/src/lib/app-utils/variables.js.map +1 -1
  110. package/src/lib/app-utils/visitor-record-ceiling.d.ts +32 -0
  111. package/src/lib/app-utils/visitor-record-ceiling.js +39 -0
  112. package/src/lib/app-utils/visitor-record-ceiling.js.map +1 -1
  113. package/src/lib/foundation/definitions/org-billing.types.d.ts +2 -2
  114. package/src/lib/foundation/definitions/org-billing.types.js.map +1 -1
  115. package/src/lib/plugin-manager/feature-plugins.d.ts +80 -79
  116. package/src/lib/plugin-manager/feature-plugins.js +22 -35
  117. package/src/lib/plugin-manager/feature-plugins.js.map +1 -1
  118. package/src/lib/plugin-manager/first-party-plugins.generated.d.ts +18 -1
  119. package/src/lib/plugin-manager/first-party-plugins.generated.js +62 -2
  120. package/src/lib/plugin-manager/first-party-plugins.generated.js.map +1 -1
  121. package/src/lib/plugin-manager/index.d.ts +0 -1
  122. package/src/lib/plugin-manager/index.js +0 -1
  123. package/src/lib/plugin-manager/index.js.map +1 -1
  124. package/src/lib/plugin-manager/plugin-contact-capture.d.ts +9 -4
  125. package/src/lib/plugin-manager/plugin-contact-capture.js.map +1 -1
  126. package/src/lib/plugin-manager/plugin-containers.d.ts +68 -0
  127. package/src/lib/plugin-manager/plugin-containers.generated.d.ts +10 -0
  128. package/src/lib/plugin-manager/plugin-containers.generated.js +20 -0
  129. package/src/lib/plugin-manager/plugin-containers.generated.js.map +1 -0
  130. package/src/lib/plugin-manager/plugin-containers.js +27 -0
  131. package/src/lib/plugin-manager/plugin-containers.js.map +1 -0
  132. package/src/lib/plugin-manager/plugin-entitlements.d.ts +8 -0
  133. package/src/lib/plugin-manager/plugin-entitlements.js.map +1 -1
  134. package/src/lib/plugin-manager/plugin-membership-detach.js +1 -1
  135. package/src/lib/plugin-manager/plugin-membership-detach.js.map +1 -1
  136. package/src/lib/plugin-manager/plugin-record-email-state.d.ts +69 -0
  137. package/src/lib/plugin-manager/plugin-record-email-state.js +32 -0
  138. package/src/lib/plugin-manager/plugin-record-email-state.js.map +1 -1
  139. package/src/lib/plugin-manager/plugin-record-lists.d.ts +115 -0
  140. package/src/lib/plugin-manager/plugin-record-lists.js +75 -0
  141. package/src/lib/plugin-manager/plugin-record-lists.js.map +1 -0
  142. package/src/lib/plugin-manager/plugin-record-timeline.d.ts +42 -8
  143. package/src/lib/plugin-manager/plugin-record-timeline.js.map +1 -1
  144. package/src/lib/plugin-manager/plugin-server-steps.d.ts +170 -0
  145. package/src/lib/plugin-manager/plugin-server-steps.js +116 -0
  146. package/src/lib/plugin-manager/plugin-server-steps.js.map +1 -0
  147. package/src/lib/plugin-manager/plugin-site-beacons.d.ts +71 -0
  148. package/src/lib/plugin-manager/plugin-site-beacons.js +54 -0
  149. package/src/lib/plugin-manager/plugin-site-beacons.js.map +1 -0
  150. package/src/lib/plugin-manager/plugin-subscription-topics.generated.d.ts +11 -0
  151. package/src/lib/plugin-manager/plugin-subscription-topics.generated.js +41 -0
  152. package/src/lib/plugin-manager/plugin-subscription-topics.generated.js.map +1 -0
  153. package/src/lib/plugin-manager/plugin-usage-axes.d.ts +212 -0
  154. package/src/lib/plugin-manager/plugin-usage-axes.js +82 -3
  155. package/src/lib/plugin-manager/plugin-usage-axes.js.map +1 -1
  156. package/src/lib/plugin-manager/plugin-usage-meters.d.ts +108 -0
  157. package/src/lib/plugin-manager/plugin-usage-meters.js +105 -0
  158. package/src/lib/plugin-manager/plugin-usage-meters.js.map +1 -0
  159. package/src/lib/plugin-manager/usage-alert-contributors.d.ts +76 -6
  160. package/src/lib/plugin-manager/usage-alert-contributors.js +23 -10
  161. package/src/lib/plugin-manager/usage-alert-contributors.js.map +1 -1
  162. package/src/lib/app-utils/assist-credits.d.ts +0 -482
  163. package/src/lib/app-utils/assist-credits.js +0 -510
  164. package/src/lib/app-utils/assist-credits.js.map +0 -1
  165. package/src/lib/app-utils/campaign-membership.d.ts +0 -121
  166. package/src/lib/app-utils/campaign-membership.js +0 -189
  167. package/src/lib/app-utils/campaign-membership.js.map +0 -1
  168. package/src/lib/app-utils/campaign-touch.js.map +0 -1
  169. package/src/lib/app-utils/console-record-links.d.ts +0 -84
  170. package/src/lib/app-utils/console-record-links.js +0 -76
  171. package/src/lib/app-utils/console-record-links.js.map +0 -1
  172. package/src/lib/app-utils/crm-booking.d.ts +0 -75
  173. package/src/lib/app-utils/crm-booking.js +0 -133
  174. package/src/lib/app-utils/crm-booking.js.map +0 -1
  175. package/src/lib/app-utils/crm-inbound.d.ts +0 -245
  176. package/src/lib/app-utils/crm-inbound.js +0 -407
  177. package/src/lib/app-utils/crm-inbound.js.map +0 -1
  178. package/src/lib/app-utils/crm-reports.d.ts +0 -479
  179. package/src/lib/app-utils/crm-reports.js +0 -680
  180. package/src/lib/app-utils/crm-reports.js.map +0 -1
  181. package/src/lib/app-utils/dataset-csv.js.map +0 -1
  182. package/src/lib/app-utils/dataset-query.d.ts +0 -57
  183. package/src/lib/app-utils/dataset-query.js.map +0 -1
  184. package/src/lib/app-utils/email-topics.js.map +0 -1
  185. package/src/lib/app-utils/list-assignment-policy.js.map +0 -1
  186. package/src/lib/plugin-manager/plugin-metered-lines.d.ts +0 -97
  187. package/src/lib/plugin-manager/plugin-metered-lines.js +0 -123
  188. package/src/lib/plugin-manager/plugin-metered-lines.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/contacts.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 * Contacts CRM v1 (AGL-197): one contact per normalized email per host,\n * fed by the four existing capture silos (forms, members, orders,\n * bookings). Pure data module — the admin-SDK upsert lives in\n * `@aglyn/tenant-data-admin` (`upsertHostContact`) and the console reads\n * client-side under the host-admin rules.\n */\n\nimport type { AglynPostalAddress } from '../foundation'\nimport { consentGroupForHost } from './consent-groups'\nimport type { ContactCustomValue, ContactLifecycleStage } from './crm'\nimport type { EmailState } from './email-state'\nimport { heldScopeTokens } from './scope-tokens'\nimport {\n CAPTURED_BY_HOST_FIELD,\n MARKETING_CONSENT_BY_HOST_FIELD,\n MARKETING_CONSENT_FIELD,\n readMarketingBasis,\n type MarketingBasis,\n} from './marketing-consent'\nimport { refusalsOf, type RetainedRefusals } from './retained-refusals'\n\nexport type ContactSource =\n | 'form'\n | 'member'\n | 'order'\n | 'booking'\n | 'newsletter'\n // AGL-2276: `POST /v1/contacts`. A first-class source rather than a blank\n // one, because \"where did this person come from\" is the question the\n // console's source filter exists to answer, and an integration importing a\n // CRM is a different answer from a visitor filling in a form. Adding it to\n // the union is what makes `SOURCE_LABELS` and the filter cover it — a raw\n // string written past the type would render as `api` and match no filter.\n | 'api'\n // CRM v2 (AGL-2595): the two doors that are not a capture at all. A person\n // typed into the console by a member of the team, and a person who arrived\n // in a file. Both are first-class for the reason `api` is — a merchant\n // asking \"who did we add ourselves\" and \"who came from the spreadsheet\" is\n // asking the source filter, and a source the union does not name is one it\n // cannot answer for.\n | 'manual'\n | 'import'\n // AGL-3185: the platform's own console — an account created there, and\n // the product-updates decision that account makes at sign-up, in its\n // preferences or at the one-time prompt. First-class for the reason `api`\n // is: the operator's CRM asks \"who signed up for the product\", and\n // `member` is a SITE's member, which an account holder of the platform\n // is not.\n | 'account'\n\n/**\n * How a capture source reads on screen.\n *\n * Typed `Record<ContactSource, string>` so a source added to the union cannot\n * ship without a label, and kept beside the union rather than in the console\n * that first needed it: the contacts filter, the campaign audience and the\n * dynamic-list rule editor all name the same six sources, and three copies of\n * this map is three places for `order` to stop reading as \"Customer\".\n */\nexport const CONTACT_SOURCE_LABELS: Record<ContactSource, string> = {\n form: 'Form',\n member: 'Member',\n order: 'Customer',\n booking: 'Booking',\n newsletter: 'Newsletter',\n api: 'API',\n manual: 'Added by hand',\n import: 'Import',\n account: 'Account',\n}\n\nexport interface ContactInteraction {\n type: ContactSource\n /** Source doc id (formSubmissions/siteMembers/orders/bookings). */\n refId?: string\n /** Epoch millis — Timestamps don't serialize into arrays cleanly. */\n atMs: number\n summary?: string\n /**\n * WHICH SITE this interaction happened on.\n *\n * A contact document is shared by every site in the org — one human who\n * touched two sites is one person, and splitting them into two rows would\n * bill the org twice for the same address and lose the dedupe that makes a\n * multi-brand account worth having. But the HISTORY on that shared row is\n * not shared: a booking made on one client's site is that client's, and a\n * timeline that cannot be split by site shows an agency's client the other\n * clients' activity.\n *\n * Optional because a row written before this field existed carries none,\n * and an interaction whose site is unknown must read as unattributed rather\n * than be assigned to whoever is looking. Nothing may infer it from the\n * contact's own capture attribution: `capturedByHostIds` says which sites\n * met this person, not which of them produced any particular visit.\n */\n hostId?: string\n /**\n * THE ENTRY POINT: the form this capture came in through.\n *\n * `sources` answers \"what KIND of surface met this person\" and is what the\n * console's capture filter reads; it cannot answer \"which form\", because\n * every form on the site sets the same `form` flag. The id rather than the\n * name, for the reason the submission carries the id: a form's caption is\n * editable and a stored name splits the moment somebody renames it.\n *\n * Beside {@link refId} rather than derived from it. The submission the\n * interaction names does carry the form, but reading it back would be a\n * document read per row of a timeline the console renders straight out of\n * the contact.\n */\n formId?: string\n /**\n * THE ENTRY POINT: the page the person was on when this happened.\n *\n * The same `path` the submission stores. It belongs on the interaction and\n * not on the contact, because a person who came in through the pricing page\n * and returned through a blog post has two entry points and one row —\n * a single field at the top would keep whichever capture wrote last.\n */\n path?: string\n}\n\n/** `orgs/{orgId}/contacts/{contactId}` doc shape. */\nexport interface HostContact {\n /** Normalized (trimmed, lowercased) email — the dedupe key. */\n email: string\n name?: string\n sources: Partial<Record<ContactSource, true>>\n /** Newest-first, capped — the profile timeline. */\n interactions: ContactInteraction[]\n tags?: string[]\n notes?: string\n /**\n * Every site that has captured this person, in no order.\n *\n * An ARRAY and a top-level field, because this is the one attribution that\n * has to survive being a QUERY: \"everyone captured on A, B or C\" is an\n * audience, and `array-contains-any` is what answers it. The per-interaction\n * host says which visit belonged to whom; this says which sites have a\n * relationship at all, and only the second shape can be filtered on in\n * Firestore.\n *\n * Grows by `arrayUnion` on every capture, including the ones that merge\n * onto an existing row — which is exactly what the create-only `hostId`\n * beside it could never do.\n */\n capturedByHostIds?: string[]\n /**\n * Every form this person has come in through, in no order (AGL-2612).\n *\n * The entry point proper is `interactions[].formId` inside the capturing\n * holder's facet, and that stays the record: which form produced which\n * visit is one holder's business. But Firestore cannot select documents\n * by a field of an array ELEMENT, and a facet path is per group, so\n * \"everyone who filled in this form\" — the question the form's own page\n * asks of the Contacts list — has to be a top-level array an\n * `array-contains` can hit, exactly as `capturedByHostIds` is for sites\n * and `companyIds` is for companies. A form id is minted under one site,\n * so a query on it is one site's captures by construction.\n *\n * Grows by `arrayUnion` on every form capture, create or merge, bounded at\n * {@link CONTACT_FORM_IDS_CAP}: a person who has filled in more forms than\n * that keeps the first twenty and the timeline keeps the rest. The facet is\n * the truth and this is its index — a reader answering \"which form\" reads\n * the interaction; only a QUERY reads this.\n */\n formIds?: string[]\n /*\n * SEARCH KEYS (AGL-2596), and nothing more.\n *\n * The console's global search reads a window of contact documents and\n * matches over their top-level fields; it never resolves a holder's facet,\n * because it is one search over a dozen collections and a facet read is a\n * contacts-only idea. So the two profile values a person is looked up BY —\n * their phone number and the company they work for — are mirrored here by\n * every writer that sets them on a facet, as plain values a query can hit.\n *\n * The FACET is the record. These are a last-writer-wins echo of it: two\n * holders who keep different numbers for one person each overwrite the\n * echo and each keep their own facet value, and nothing renders these to a\n * reader — the list, the record page and the export all read through the\n * viewing group's facet. `ORG_CONTACT_FIELDS` below is an allow-list, so\n * neither reaches the org view either.\n */\n /** E.164, mirrored from the last facet write that set one. */\n phone?: string\n /** The company name as typed, mirrored the same way. */\n companyName?: string\n /**\n * The OTHER addresses this person answers to (AGL-2625).\n *\n * A contact is keyed on one email, so one human with a work address and a\n * personal one is two documents until somebody merges them. The merge keeps\n * the survivor's `email` as the identity and records the merged record's\n * address here, so a later capture on it — a form filled in from the\n * personal account — resolves to this row rather than minting the second\n * document again. `emailIndex` (see {@link CONTACT_EMAIL_INDEX_COLLECTION})\n * is the lookup; this array is the record of why an entry there points\n * where it does, and what the record page shows as \"also\".\n *\n * Shared identity like `email`, not a facet field: which addresses are one\n * person is a fact about the person, and a holder that did not perform the\n * merge still needs its capture on the alternate address to land on the\n * shared row. Bounded at {@link CONTACT_ALTERNATE_EMAILS_CAP}.\n */\n alternateEmails?: string[]\n /**\n * When the earliest OPEN task filed against this person is due, epoch\n * ms, or `null` when none is (AGL-2661) — see `CrmDeal.nextTaskAtMs` in\n * `crm.ts` for the rule. On the SHARED row rather than a facet, because a\n * task lives at the organization level and names the contact, not a\n * holder's view of them.\n */\n nextTaskAtMs?: number | null\n /**\n * The last verdict on the address (AGL-3245) — bounced, blocked,\n * unsubscribed, do-not-contact — written by the platform's senders only,\n * on the SHARED row because the address is shared. Absent means nothing\n * is known. See `email-state.ts`.\n */\n emailState?: EmailState\n}\n\n/** Timeline cap: keeps the doc small; older interactions age out. */\nexport const CONTACT_INTERACTIONS_CAP = 50\n\n/** The field holding {@link HostContact.alternateEmails}. */\nexport const CONTACT_ALTERNATE_EMAILS_FIELD = 'alternateEmails'\n\n/**\n * The most alternate addresses one contact carries. Ten is past any real\n * person's mailbox count, and it bounds the index writes one merge fans out.\n */\nexport const CONTACT_ALTERNATE_EMAILS_CAP = 10\n\n/**\n * `orgs/{orgId}/emailIndex/{personKey}` → `{ email, contactId }` (AGL-2625).\n *\n * The address-to-contact lookup the capture door consults BEFORE the\n * per-document `email ==` query, so an address recorded as an alternate on a\n * merged row resolves to the survivor. Keyed by `personKey` — the sha256 of\n * the normalized address — so a document id never carries the address\n * itself, the same derivation a lead and a list membership use.\n *\n * WRITTEN LAZILY, never backfilled: the query on `email` stays as the\n * fallback, and a contact that has no entry gets one on the next write that\n * finds it. A row the index has never seen therefore costs one extra read\n * once, and nothing needs to run over the existing collection.\n *\n * Server-written only; the rules close it to every client.\n */\nexport const CONTACT_EMAIL_INDEX_COLLECTION = 'emailIndex'\n\n/**\n * Every address a contact answers to — the primary first, then the\n * alternates — normalized and deduplicated, so an index writer and a lead\n * lookup walk one list.\n */\nexport function contactEmails(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n const out: string[] = []\n const seen = new Set<string>()\n const push = (value: unknown) => {\n const email = normalizeContactEmail(value)\n if (email && !seen.has(email)) {\n seen.add(email)\n out.push(email)\n }\n }\n push((contact ?? {})['email'])\n const alternates = (contact ?? {})[CONTACT_ALTERNATE_EMAILS_FIELD]\n if (Array.isArray(alternates)) alternates.forEach(push)\n return out\n}\n\n/** The top-level field naming every form a contact came in through — see `HostContact.formIds`. */\nexport const CONTACT_FORM_IDS_FIELD = 'formIds'\n\n/**\n * How many forms the {@link CONTACT_FORM_IDS_FIELD} mirror holds.\n *\n * The same figure as the tag cap: enough that no real person reaches it,\n * small enough that the array never becomes the document. Past it the\n * capture stops adding rather than dropping the oldest, because the mirror\n * is an index of the facet's timeline and an index that silently forgets an\n * entry the timeline still holds would answer a form's contact list wrongly\n * in the one direction nobody would notice.\n */\nexport const CONTACT_FORM_IDS_CAP = 20\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** Normalized dedupe key, or null when the input isn't a usable email. */\nexport function normalizeContactEmail(input: unknown): string | null {\n const email = String(input ?? '')\n .trim()\n .toLowerCase()\n return EMAIL_PATTERN.test(email) && email.length <= 320 ? email : null\n}\n\n/**\n * First usable email in a free-form form-submission fields map — forms\n * don't guarantee a canonical email field, so prefer keys that look like\n * email fields before falling back to any email-shaped value.\n */\nexport function extractEmailFromFields(\n fields: Record<string, unknown> | null | undefined,\n): string | null {\n const entries = Object.entries(fields ?? {})\n const preferred = entries.find(([key]) => /email/i.test(key))\n const fromPreferred = normalizeContactEmail(preferred?.[1])\n if (fromPreferred) return fromPreferred\n for (const [, value] of entries) {\n const email = normalizeContactEmail(value)\n if (email) return email\n }\n return null\n}\n\n/**\n * Merges a new interaction into a contact: source flag set, interaction\n * prepended, timeline capped. Pure — the caller persists the result.\n */\nexport function mergeContactInteraction(\n existing: Pick<HostContact, 'sources' | 'interactions'> & {\n name?: string\n },\n update: { source: ContactSource; interaction: ContactInteraction; name?: string },\n): Pick<HostContact, 'sources' | 'interactions'> & { name?: string } {\n return {\n // Existing names win — a later anonymous form shouldn't blank a name.\n name: existing.name || update.name,\n sources: { ...existing.sources, [update.source]: true as const },\n interactions: [update.interaction, ...(existing.interactions ?? [])].slice(\n 0,\n CONTACT_INTERACTIONS_CAP,\n ),\n }\n}\n\n/**\n * THE PER-HOLDER FACET on a shared contact document.\n *\n * ## What is shared and what is not\n *\n * One human who touched two sites is ONE document. That is not a compromise:\n * it is the dedupe the shared address book exists for, it is what keeps a\n * bounce and a suppression describing one person, and it is what makes a\n * multi-brand account bill once for one human instead of once per site. A\n * document per host would push an agency toward twelve separate accounts and\n * throw the whole advantage away.\n *\n * But almost nothing ON that document is legitimately shared.\n *\n * - **SHARED IDENTITY** — `email`, and the canonical `name`. One human, one\n * identity. This is the only part two unrelated businesses may both see,\n * and it is the minimum that makes them one row.\n * - **PER-HOLDER FACET** — everything in this interface. A note, a tag, a\n * call log and a lifetime value are the HOLDER's own business records.\n * Host A's note about a customer is Host A's; a competitor sharing the\n * platform must not read it, and while these lived at the top of the\n * document every site in the org could.\n * - **CONSENT AND VISIBILITY** — per declared group, decided by\n * `marketing-consent.ts` and by `visibleTo`.\n *\n * ## Keyed by GROUP, not by host\n *\n * A business that declared three sites to be one sender is one CRM: a note\n * written on the shop belongs beside the booking made on the booking page,\n * because one team keeps both. Across groups, never — and an undeclared site\n * is a group of one, so the agency case is isolated with nothing configured.\n *\n * ## Commercial figures are per-facet, and that is not a billing change\n *\n * `ltvCents` and `ordersCount` answer \"what is this person worth to ME\". Two\n * unrelated merchants who both sell to one person have two different answers\n * and neither is entitled to the other's. Billing counts DOCUMENTS, and there\n * is still one document, so a person held by two hosts stays one billable\n * contact.\n */\nexport interface ContactFacet {\n /**\n * This holder's display name for the person, overriding the canonical one.\n *\n * The canonical `name` is shared and mutable, so without this a rename on\n * one site changes what an unrelated business sees in its own CRM — two\n * companies that do not know each other exist editing each other's records.\n * The override is written by whoever edits the name from their own console;\n * the canonical field stays as the identity of last resort, for a holder\n * that has never set one.\n */\n name?: string\n /** Which capture surfaces THIS holder saw the person through. */\n sources: Partial<Record<ContactSource, true>>\n /** THIS holder's timeline, newest-first and capped. */\n interactions: ContactInteraction[]\n /** THIS holder's tags. */\n tags?: string[]\n /** THIS holder's notes. */\n notes?: string\n /**\n * The campaigns THIS holder has filed the person under.\n *\n * A label on the CRM record, not an audience: who a campaign's mail reaches\n * is decided by the campaign's lists and by each send's own picker, and\n * nothing in the send path reads this. It answers \"who did we put in the\n * spring push\", which is a question about the holder's own working set.\n *\n * Per-holder for the reason the notes are: two unrelated businesses sharing\n * one row must not read each other's segmentation of a person they both\n * know. See `campaign-membership.ts` for the field and the path.\n */\n campaignIds?: string[]\n /** Gross of fees and refunds — see `upsertHostContact`. */\n ltvCents?: number\n ordersCount?: number\n lastPurchaseAtMs?: number\n firstPurchaseAtMs?: number\n refundedCents?: number\n refundedOrdersCount?: number\n lastRefundAtMs?: number\n /*\n * CRM v2 (AGL-2595): the profile a sales team keeps on a person.\n *\n * Per-holder like everything above them, and for the same reason: a phone\n * number, a job title, an owner and a lifecycle stage are one business's\n * knowledge of a person, and two unrelated businesses sharing the row must\n * not read each other's. `companyId` points at a company document in the\n * same scope, never at the org's whole company list. `custom` is keyed by\n * `ContactFieldDefinition.key`, so a holder's field definitions and a\n * holder's values live under the same group and cannot be joined across\n * one.\n *\n * ⛔ None of these reach the org view. `ORG_CONTACT_FIELDS` is an\n * allow-list, and the org-view spec seeds every one of these with a\n * sentinel and proves it never surfaces.\n */\n /** E.164 — `normalizePhone` before writing. */\n phone?: string\n jobTitle?: string\n /**\n * Where this holder met the person — Salesforce's Lead Source, carried\n * from the lead on conversion and picked from the org's lead source\n * values after it (AGL-3298). The value's label, as the lead stores it.\n */\n leadSource?: string\n /** `orgs/{orgId}/companies/{companyId}`, in this holder's scope. */\n companyId?: string\n /**\n * The company's name as this holder knows it.\n *\n * Free text, so a person can be filed under a company before one exists\n * as a record; the company picker that later sets `companyId` writes the\n * picked company's name here too, so the row reads the same whether the\n * link was made or the name typed. The top-level `companyName` on the\n * document is the search echo of this value — see `HostContact`.\n */\n companyName?: string\n address?: AglynPostalAddress | null\n /** The team member responsible for the relationship. */\n ownerUid?: string\n lifecycleStage?: ContactLifecycleStage\n /** Custom field values, keyed by `ContactFieldDefinition.key`. */\n custom?: Record<string, ContactCustomValue>\n /**\n * When this person last OPENED or CLICKED a campaign sent by one of this\n * holder's sites, epoch ms (AGL-2616).\n *\n * Stamped by the delivery webhook, forward-only, on the first open and the\n * first click of each message — the same bound the per-person rollup on\n * `emailDeliveries/{key}` keeps, so a reader opening one newsletter six\n * times is one write. Per-holder because it answers \"is this person still\n * reading OUR mail\": the address-level rollup counts every sender's mail\n * and a sibling business's, and a re-engagement audience built on that\n * would mail people who are reading somebody else.\n *\n * Absent until the first engagement after the stamp shipped; a message\n * opened before then advanced the address-level rollup and nothing here.\n */\n lastEmailEngagementAtMs?: number\n /**\n * The org-library files THIS holder has attached to the person\n * (AGL-2662), by media document id.\n *\n * Per-holder for the reason every other field here is: an agency running\n * two client brands has one contact document between them, and a signed\n * contract one client filed is not the other client's to see. Ids rather\n * than URLs so a file moved between folders keeps its attachment, and so\n * a private asset is still served through the signed CDN door.\n */\n mediaIds?: string[]\n}\n\n/** The map field holding the facets: `{ [groupId]: ContactFacet }`. */\nexport const CONTACT_FACETS_FIELD = 'facets'\n\n/**\n * The facet one group holds, or an empty one.\n *\n * `map[groupId]` — a lookup, not a search, for the reason the consent map is\n * shaped the same way: there is no expression of this form that returns\n * another holder's notes.\n *\n * An absent facet reads EMPTY rather than falling back to the top-level\n * fields. A fallback would hand every holder in the org the fields the\n * pre-facet document carried at its top, which is the disclosure this shape\n * exists to end; the migration moves them into the capturing group's facet\n * instead.\n */\nexport function readContactFacet(\n contact: Record<string, unknown> | null | undefined,\n groupId: string,\n): ContactFacet {\n const facets = (contact ?? {})[CONTACT_FACETS_FIELD]\n const facet =\n facets && typeof facets === 'object' && !Array.isArray(facets)\n ? (facets as Record<string, unknown>)[groupId]\n : undefined\n if (!facet || typeof facet !== 'object' || Array.isArray(facet)) {\n return { sources: {}, interactions: [] }\n }\n const value = facet as Record<string, unknown>\n return {\n ...(value as unknown as ContactFacet),\n sources: (value['sources'] ?? {}) as ContactFacet['sources'],\n interactions: Array.isArray(value['interactions'])\n ? (value['interactions'] as ContactInteraction[])\n : [],\n }\n}\n\n/** The dotted Firestore path to one field of one holder's facet. */\nexport function contactFacetPath(groupId: string, field: string): string {\n if (!groupId) throw new Error('a contact facet must name a holder')\n return `${CONTACT_FACETS_FIELD}.${groupId}.${field}`\n}\n\n/**\n * The name a given holder should SEE for this person.\n *\n * Their own override first, the canonical identity second. Nothing falls\n * through to another holder's override: that would be one business's edit\n * showing up in another's CRM, which is the thing the override exists to\n * prevent.\n */\nexport function contactDisplayName(\n contact: Record<string, unknown> | null | undefined,\n groupId: string,\n): string {\n const facet = readContactFacet(contact, groupId)\n if (facet.name) return facet.name\n const canonical = (contact ?? {})['name']\n return typeof canonical === 'string' ? canonical : ''\n}\n\n/**\n * Every group that holds this contact — the reference count behind a detach.\n *\n * Read from `visibleTo` rather than from the facet map, because `visibleTo`\n * is what both enforcement layers actually evaluate: a holder that can still\n * READ the row is still holding it whether or not they ever wrote a note. A\n * count taken from the facets would drop a holder who has one and no facet\n * and leave them able to see a document nothing believes they hold.\n *\n * Less the tokens a share ADDED (AGL-3336): a site the record was shared\n * with sees it and holds nothing, so it must not keep the record alive when\n * its last holder lets go — `heldScopeTokens` is `visibleTo` without them.\n */\nexport function contactHolderTokens(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n return heldScopeTokens(contact)\n}\n\n/** What a holder letting go of a contact should do to the document. */\nexport type ContactDetach =\n | {\n /** Nobody else holds it. Delete the document. */\n action: 'delete'\n /**\n * Every refusal the document holds, every site's and the unscoped one,\n * which the delete keeps in `retainedRefusals` in the same transaction\n * — see `retained-refusals.ts`. `null` when it holds none.\n */\n retained: RetainedRefusals | null\n }\n | {\n /** Other holders remain. Drop this one's half. */\n action: 'detach'\n /**\n * Field-level removals, as a patch. Dotted paths so the OTHER holders'\n * facets and consent entries are untouched — a nested write would\n * replace the whole map and take every other holder's records with it.\n *\n * A consent entry that is a REFUSAL is not among them: it stays on the\n * document for the holders that remain, because a person's \"no\" is not\n * the leaving holder's to take with it.\n */\n remove: string[]\n /** Scope tokens to pull out of `visibleTo`. */\n removeTokens: string[]\n /** Host ids to pull out of the capture attribution. */\n removeHostIds: string[]\n }\n\n/**\n * DELETE IS A DETACH.\n *\n * One holder removing a contact from their own CRM must not destroy another\n * holder's relationship with that person: they have their own notes, their\n * own order history and their own consent, none of which the deleting holder\n * ever had a claim on. So a delete drops the deleting group's facet, its\n * consent grants, its capture attribution and its scope tokens — and the\n * DOCUMENT dies only when the last holder lets go.\n *\n * A REFUSAL IS NOT LET GO (AGL-3338). The list gate reads a stored refusal\n * as the one fact an operator's attestation cannot overrule, so a detach\n * leaves the leaving group's refusal entries on the document, and a delete\n * answers every refusal the document holds for the caller to retain beside\n * the delete. Read off the document's own data: a table row's projection\n * carries neither the consent map nor the unscoped field.\n *\n * ⛔ This is NOT the erasure path. A privacy erasure removes the person\n * everywhere regardless of how many holders remain, and routing it through\n * reference counting would turn a lawful erasure into a partial one — the same\n * absent-versus-invisible defect this area keeps hitting, in the one place\n * where getting it wrong is a legal failure rather than a bug. Erasure calls\n * the document delete directly and must never consult this function.\n *\n * @param group the holder letting go, with every site it covers.\n */\nexport function planContactDetach(\n contact: Record<string, unknown> | null | undefined,\n group: { groupId: string; hostIds: readonly string[] },\n): ContactDetach {\n const held = contactHolderTokens(contact)\n const leaving = new Set(group.hostIds.map((id) => `host:${id}`))\n /*\n * A remaining holder is a token naming somebody else. `'org'` counts as one\n * and blocks the delete on purpose: an org-wide row is held by every site\n * in the account, so one site letting go leaves it held. Narrowing it would\n * be a scope decision, and a delete button is not where that belongs.\n */\n const remaining = held.filter((token) => !leaving.has(token))\n if (!remaining.length) return { action: 'delete', retained: refusalsOf(contact) }\n const refused = refusalsOf(contact)?.byHost ?? {}\n return {\n action: 'detach',\n remove: [\n `${CONTACT_FACETS_FIELD}.${group.groupId}`,\n ...group.hostIds\n .filter((id) => !(id in refused))\n .map((id) => `${MARKETING_CONSENT_BY_HOST_FIELD}.${id}`),\n ],\n removeTokens: [...leaving],\n removeHostIds: [...group.hostIds],\n }\n}\n\n/**\n * The interactions one group of sites may see on a shared contact.\n *\n * An interaction with NO host is shown to everyone: it predates the\n * attribution, so hiding it would empty every existing timeline, and it is\n * already visible to anyone who can read the row. An interaction that names a\n * site is shown only to that site's own group — the agency case, where one\n * client must not read another client's bookings off a person they both know.\n */\nexport function interactionsForGroup(\n interactions: readonly ContactInteraction[] | undefined,\n hostIds: readonly string[],\n): ContactInteraction[] {\n const reach = new Set(hostIds)\n return (interactions ?? []).filter(\n (interaction) => !interaction.hostId || reach.has(interaction.hostId),\n )\n}\n\n/** `orgs/{orgId}/contactSegments/{id}` — a saved audience filter. */\nexport interface ContactSegment {\n name: string\n /** Match contacts sharing at least one tag (empty = any). */\n tags?: string[]\n /** Match contacts with at least one of these sources (empty = any). */\n sources?: ContactSource[]\n}\n\n/** Segment matching (AGL-199): AND across filter kinds, OR within one. */\nexport function contactMatchesSegment(\n contact: Pick<HostContact, 'tags' | 'sources'>,\n segment: Pick<ContactSegment, 'tags' | 'sources'>,\n): boolean {\n if (segment.tags?.length) {\n const contactTags = new Set(\n (contact.tags ?? []).map((tag) => tag.toLowerCase()),\n )\n if (!segment.tags.some((tag) => contactTags.has(tag.toLowerCase()))) {\n return false\n }\n }\n if (segment.sources?.length) {\n if (!segment.sources.some((source) => contact.sources?.[source])) {\n return false\n }\n }\n return true\n}\n\n/*==========================================\n * THE ORG-LEVEL VIEW: the complement of the facet reader above.\n *\n * {@link readContactFacet} answers \"what does THIS holder know about this\n * person\". Everything below answers the question no host page can:\n *\n * who does this ORGANIZATION know, and which of its sites know them.\n *\n * That question is the entire justification for one shared document. Dedupe,\n * suppression and honest billing all rest on one human being one row, and\n * with no surface that shows the deduped person the model's benefit is\n * invisible and the billing unit — unique people per org — looks arbitrary.\n *\n * ## The org view crosses the host boundary, so it carries LESS, not more\n *\n * It is the one place in the product designed to read across holders, which\n * makes it the one place where a careless field re-creates the disclosure the\n * facets exist to end. So the projection is an ALLOW-LIST\n * ({@link ORG_CONTACT_FIELDS}) rather than an omission: identity, capture\n * attribution and consent state. Notes, tags, timelines, call logs and\n * commercial figures are the holder's own business records and are not read\n * here at all — not summarized, not counted, not indicated by their absence.\n *\n * An allow-list rather than a `delete facets` is the load-bearing choice. A\n * subtraction is correct only for as long as somebody remembers to extend it,\n * and a field added to {@link ContactFacet} tomorrow would ride out through a\n * subtraction and be caught by an allow-list.\n *\n * ## The NAME is the canonical one, never a holder's override\n *\n * {@link contactDisplayName} prefers the viewing group's own override, which\n * is right on a host page and wrong here: an override is a name ONE business\n * chose, and rendering it at org level shows an agency the label its client\n * picked. The shared identity is what every holder already sees, so it is the\n * only name that belongs to the org.\n *=========================================*/\n\n/**\n * Every field of a contact document the org view may read.\n *\n * Stated as a value so it can be asserted against — see the org-view spec,\n * which seeds each facet field with a sentinel and proves none of them\n * reaches a row.\n */\nexport const ORG_CONTACT_FIELDS = [\n 'email',\n 'name',\n CAPTURED_BY_HOST_FIELD,\n MARKETING_CONSENT_BY_HOST_FIELD,\n MARKETING_CONSENT_FIELD,\n] as const\n\n/**\n * What one site's relationship with one person amounts to, at org level.\n *\n * Consent is per (contact, host-or-group) and there is no expression that\n * returns another controller's grant, so a row cannot carry one consent\n * verdict. It carries one PER CAPTURING SITE, each naming the controller it\n * was read for — a bare \"consented\" with nobody attached would be exactly the\n * confusion the per-brand model was built to prevent.\n */\nexport interface OrgContactHostConsent {\n /** The site this verdict answers about, and no other. */\n hostId: string\n /** The controller the basis runs to — the declared group, or the site. */\n groupId: string\n /**\n * The group's disclosed name, or `null` for a site that pools with nobody.\n *\n * `null` is not \"unknown\": it is the group of one, where the site's own\n * name is the disclosure and inventing a second would put a label in front\n * of a reader that nothing else uses.\n */\n groupName: string | null\n /** Whether the controller is a DECLARED group rather than the site alone. */\n declared: boolean\n /** `granted` | `declined` | `unrecorded` — never collapsed to a boolean. */\n basis: MarketingBasis\n}\n\n/** One person, as the organization may see them across all of its sites. */\nexport interface OrgContactRow {\n $id: string\n /** The dedupe key, and the reason two captures are one row. */\n email: string\n /** The SHARED identity. Never a holder's own override. */\n name: string\n /** Every site that has captured this person, sorted for a stable render. */\n capturedByHostIds: string[]\n /** One verdict per capturing site, in the same order. */\n consent: OrgContactHostConsent[]\n}\n\n/**\n * Every site that has captured this person.\n *\n * Sorted, because the array is maintained by `arrayUnion` and therefore\n * carries capture order, which is not an order anything should render: two\n * readers of the same row would see the sites in different places on the\n * screen depending on which site met the person first.\n */\nexport function contactCaptureHostIds(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n const raw = (contact ?? {})[CAPTURED_BY_HOST_FIELD]\n if (!Array.isArray(raw)) return []\n return [\n ...new Set(\n raw\n .map((id) => String(id ?? '').trim())\n .filter((id): id is string => id !== ''),\n ),\n ].sort()\n}\n\n/**\n * One contact document, projected to what an ORG may see.\n *\n * @param org - the org document — the only input that can resolve a declared\n * consent group, and required for that reason. Without it every site reads\n * as a group of one, which understates the disclosure a person was given\n * and is the safe direction to be wrong in.\n */\nexport function orgContactRow(\n contact: Record<string, unknown> | null | undefined,\n contactId: string,\n org: Record<string, unknown> | null | undefined,\n): OrgContactRow {\n const record = contact ?? {}\n const capturedByHostIds = contactCaptureHostIds(record)\n return {\n $id: contactId,\n email: typeof record['email'] === 'string' ? record['email'] : '',\n name: typeof record['name'] === 'string' ? record['name'] : '',\n capturedByHostIds,\n consent: capturedByHostIds.map((hostId) => {\n /*\n * READ FOR THE SITE, one call per site. `readMarketingBasis` requires\n * the group it is being read for and has no default, so this cannot\n * accidentally report a grant that belongs to somebody else — the\n * argument is the guarantee, and passing the whole row through one\n * call would have had to invent a controller to ask about.\n */\n const group = consentGroupForHost(org, hostId)\n const { basis } = readMarketingBasis(record, group)\n return {\n hostId,\n groupId: group.groupId,\n groupName: group.name,\n declared: group.declared,\n basis,\n }\n }),\n }\n}\n\n/**\n * How a basis reads on screen.\n *\n * Three labels because there are three states. \"Opted in\" and \"No record\" are\n * not opposites and must never collapse into one negative: absence is the\n * commonest case by far — a record captured before the checkbox existed — and\n * showing it as a refusal would tell a merchant they may not mail somebody\n * who never said so.\n */\nexport const MARKETING_BASIS_LABELS: Record<MarketingBasis, string> = {\n granted: 'Opted in',\n declined: 'Opted out',\n unrecorded: 'No record',\n}\n\n/**\n * One consent verdict, WITH THE CONTROLLER IT RUNS TO, as one string.\n *\n * ⛔ There is no function here that returns a basis on its own, and that is\n * the point. A basis is per (person, controller): the same person can be\n * opted in to one brand in an org and opted out of another, so \"consented\"\n * with nobody attached is not a shortened truth, it is a different and false\n * claim — precisely the confusion the per-brand model was built to prevent.\n * Joining the two into a single value is what stops a caller rendering half\n * of it.\n *\n * The controller is the DECLARED GROUP when there is one, because that is who\n * the person was told they would hear from, and the site otherwise. A group\n * of one is named by the site, which is what the capture surface already\n * showed them.\n *\n * @param siteName - how this site reads — the caller resolves it, since the\n * contact document holds ids and not names. An empty one falls back to the\n * id: a site whose name cannot be resolved must still be NAMED, because\n * dropping it would understate which brands hold a relationship.\n */\nexport function orgContactConsentLabel(\n entry: OrgContactHostConsent,\n siteName?: string,\n): string {\n const controller = entry.declared\n ? (entry.groupName ?? entry.groupId)\n : siteName || entry.hostId\n return `${controller} · ${MARKETING_BASIS_LABELS[entry.basis]}`\n}\n"],"names":["consentGroupForHost","heldScopeTokens","CAPTURED_BY_HOST_FIELD","MARKETING_CONSENT_BY_HOST_FIELD","MARKETING_CONSENT_FIELD","readMarketingBasis","refusalsOf","CONTACT_SOURCE_LABELS","form","member","order","booking","newsletter","api","manual","import","account","CONTACT_INTERACTIONS_CAP","CONTACT_ALTERNATE_EMAILS_FIELD","CONTACT_ALTERNATE_EMAILS_CAP","CONTACT_EMAIL_INDEX_COLLECTION","contactEmails","contact","out","seen","Set","push","value","email","normalizeContactEmail","has","add","alternates","Array","isArray","forEach","CONTACT_FORM_IDS_FIELD","CONTACT_FORM_IDS_CAP","EMAIL_PATTERN","input","String","trim","toLowerCase","test","length","extractEmailFromFields","fields","entries","Object","preferred","find","key","fromPreferred","mergeContactInteraction","existing","update","name","sources","source","interactions","interaction","slice","CONTACT_FACETS_FIELD","readContactFacet","groupId","facets","facet","undefined","contactFacetPath","field","Error","contactDisplayName","canonical","contactHolderTokens","planContactDetach","group","held","leaving","hostIds","map","id","remaining","filter","token","action","retained","refused","byHost","remove","removeTokens","removeHostIds","interactionsForGroup","reach","hostId","contactMatchesSegment","segment","tags","contactTags","tag","some","ORG_CONTACT_FIELDS","contactCaptureHostIds","raw","sort","orgContactRow","contactId","org","record","capturedByHostIds","$id","consent","basis","groupName","declared","MARKETING_BASIS_LABELS","granted","declined","unrecorded","orgContactConsentLabel","entry","siteName","controller"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;CAMC;AAGD,SAASA,mBAAmB,QAAQ,sBAAkB;AAGtD,SAASC,eAAe,QAAQ,oBAAgB;AAChD,SACEC,sBAAsB,EACtBC,+BAA+B,EAC/BC,uBAAuB,EACvBC,kBAAkB,QAEb,yBAAqB;AAC5B,SAASC,UAAU,QAA+B,yBAAqB;AA+BvE;;;;;;;;CAQC,GACD,OAAO,MAAMC,wBAAuD;IAClEC,MAAM;IACNC,QAAQ;IACRC,OAAO;IACPC,SAAS;IACTC,YAAY;IACZC,KAAK;IACLC,QAAQ;IACRC,QAAQ;IACRC,SAAS;AACX,EAAC;AA0JD,mEAAmE,GACnE,OAAO,MAAMC,2BAA2B,GAAE;AAE1C,2DAA2D,GAC3D,OAAO,MAAMC,iCAAiC,kBAAiB;AAE/D;;;CAGC,GACD,OAAO,MAAMC,+BAA+B,GAAE;AAE9C;;;;;;;;;;;;;;;CAeC,GACD,OAAO,MAAMC,iCAAiC,aAAY;AAE1D;;;;CAIC,GACD,OAAO,SAASC,cACdC,OAAmD;IAEnD,MAAMC,MAAgB,EAAE;IACxB,MAAMC,OAAO,IAAIC;IACjB,MAAMC,OAAO,CAACC;QACZ,MAAMC,QAAQC,sBAAsBF;QACpC,IAAIC,SAAS,CAACJ,KAAKM,GAAG,CAACF,QAAQ;YAC7BJ,KAAKO,GAAG,CAACH;YACTL,IAAIG,IAAI,CAACE;QACX;IACF;IACAF,KAAK,CAACJ,kBAAAA,UAAW,CAAC,EAAE,CAAC,QAAQ;IAC7B,MAAMU,aAAa,CAACV,kBAAAA,UAAW,CAAC,EAAE,CAACJ,+BAA+B;IAClE,IAAIe,MAAMC,OAAO,CAACF,aAAaA,WAAWG,OAAO,CAACT;IAClD,OAAOH;AACT;AAEA,iGAAiG,GACjG,OAAO,MAAMa,yBAAyB,UAA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oB0G,KAAKb;YACvC,MAAM,EAAEkB,KAAK,EAAE,GAAG1G,mBAAmBsG,QAAQhC;YAC7C,OAAO;gBACLkB;gBACA7B,SAASW,MAAMX,OAAO;gBACtBgD,WAAWrC,MAAMnB,IAAI;gBACrByD,UAAUtC,MAAMsC,QAAQ;gBACxBF;YACF;QACF;IACF;AACF;AAEA;;;;;;;;CAQC,GACD,OAAO,MAAMG,yBAAyD;IACpEC,SAAS;IACTC,UAAU;IACVC,YAAY;AACd,EAAC;AAED;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,SAASC,uBACdC,KAA4B,EAC5BC,QAAiB;QAGZD;IADL,MAAME,aAAaF,MAAMN,QAAQ,IAC5BM,mBAAAA,MAAMP,SAAS,YAAfO,mBAAmBA,MAAMvD,OAAO,GACjCwD,YAAYD,MAAM1B,MAAM;IAC5B,OAAO,GAAG4B,WAAW,GAAG,EAAEP,sBAAsB,CAACK,MAAMR,KAAK,CAAC,EAAE;AACjE"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/contacts.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 * Contacts CRM v1 (AGL-197): one contact per normalized email per host,\n * fed by the four existing capture silos (forms, members, orders,\n * bookings). Pure data module — the admin-SDK upsert lives in\n * `@aglyn/tenant-data-admin` (`upsertHostContact`) and the console reads\n * client-side under the host-admin rules.\n */\n\nimport type { AglynPostalAddress } from '../foundation'\nimport { consentGroupForHost } from './consent-groups'\nimport type { ContactCustomValue, ContactLifecycleStage } from './crm'\nimport type { EmailState } from './email-state'\nimport { heldScopeTokens } from './scope-tokens'\nimport {\n CAPTURED_BY_HOST_FIELD,\n MARKETING_CONSENT_BY_HOST_FIELD,\n MARKETING_CONSENT_FIELD,\n readMarketingBasis,\n type MarketingBasis,\n} from './marketing-consent'\nimport { refusalsOf, type RetainedRefusals } from './retained-refusals'\n\nexport type ContactSource =\n | 'form'\n | 'member'\n | 'order'\n | 'booking'\n | 'newsletter'\n // AGL-2276: `POST /v1/contacts`. A first-class source rather than a blank\n // one, because \"where did this person come from\" is the question the\n // console's source filter exists to answer, and an integration importing a\n // CRM is a different answer from a visitor filling in a form. Adding it to\n // the union is what makes `SOURCE_LABELS` and the filter cover it — a raw\n // string written past the type would render as `api` and match no filter.\n | 'api'\n // CRM v2 (AGL-2595): the two doors that are not a capture at all. A person\n // typed into the console by a member of the team, and a person who arrived\n // in a file. Both are first-class for the reason `api` is — a merchant\n // asking \"who did we add ourselves\" and \"who came from the spreadsheet\" is\n // asking the source filter, and a source the union does not name is one it\n // cannot answer for.\n | 'manual'\n | 'import'\n // AGL-3185: the platform's own console — an account created there, and\n // the product-updates decision that account makes at sign-up, in its\n // preferences or at the one-time prompt. First-class for the reason `api`\n // is: the operator's CRM asks \"who signed up for the product\", and\n // `member` is a SITE's member, which an account holder of the platform\n // is not.\n | 'account'\n\n/**\n * How a capture source reads on screen.\n *\n * Typed `Record<ContactSource, string>` so a source added to the union cannot\n * ship without a label, and kept beside the union rather than in the console\n * that first needed it: the contacts filter, the campaign audience and the\n * dynamic-list rule editor all name the same six sources, and three copies of\n * this map is three places for `order` to stop reading as \"Customer\".\n */\nexport const CONTACT_SOURCE_LABELS: Record<ContactSource, string> = {\n form: 'Form',\n member: 'Member',\n order: 'Customer',\n booking: 'Booking',\n newsletter: 'Newsletter',\n api: 'API',\n manual: 'Added by hand',\n import: 'Import',\n account: 'Account',\n}\n\nexport interface ContactInteraction {\n type: ContactSource\n /** Source doc id (formSubmissions/siteMembers/orders/bookings). */\n refId?: string\n /** Epoch millis — Timestamps don't serialize into arrays cleanly. */\n atMs: number\n summary?: string\n /**\n * WHICH SITE this interaction happened on.\n *\n * A contact document is shared by every site in the org — one human who\n * touched two sites is one person, and splitting them into two rows would\n * bill the org twice for the same address and lose the dedupe that makes a\n * multi-brand account worth having. But the HISTORY on that shared row is\n * not shared: a booking made on one client's site is that client's, and a\n * timeline that cannot be split by site shows an agency's client the other\n * clients' activity.\n *\n * Optional because a row written before this field existed carries none,\n * and an interaction whose site is unknown must read as unattributed rather\n * than be assigned to whoever is looking. Nothing may infer it from the\n * contact's own capture attribution: `capturedByHostIds` says which sites\n * met this person, not which of them produced any particular visit.\n */\n hostId?: string\n /**\n * THE ENTRY POINT: the form this capture came in through.\n *\n * `sources` answers \"what KIND of surface met this person\" and is what the\n * console's capture filter reads; it cannot answer \"which form\", because\n * every form on the site sets the same `form` flag. The id rather than the\n * name, for the reason the submission carries the id: a form's caption is\n * editable and a stored name splits the moment somebody renames it.\n *\n * Beside {@link refId} rather than derived from it. The submission the\n * interaction names does carry the form, but reading it back would be a\n * document read per row of a timeline the console renders straight out of\n * the contact.\n */\n formId?: string\n /**\n * THE ENTRY POINT: the page the person was on when this happened.\n *\n * The same `path` the submission stores. It belongs on the interaction and\n * not on the contact, because a person who came in through the pricing page\n * and returned through a blog post has two entry points and one row —\n * a single field at the top would keep whichever capture wrote last.\n */\n path?: string\n}\n\n/** `orgs/{orgId}/contacts/{contactId}` doc shape. */\nexport interface HostContact {\n /** Normalized (trimmed, lowercased) email — the dedupe key. */\n email: string\n name?: string\n sources: Partial<Record<ContactSource, true>>\n /** Newest-first, capped — the profile timeline. */\n interactions: ContactInteraction[]\n tags?: string[]\n notes?: string\n /**\n * Every site that has captured this person, in no order.\n *\n * An ARRAY and a top-level field, because this is the one attribution that\n * has to survive being a QUERY: \"everyone captured on A, B or C\" is an\n * audience, and `array-contains-any` is what answers it. The per-interaction\n * host says which visit belonged to whom; this says which sites have a\n * relationship at all, and only the second shape can be filtered on in\n * Firestore.\n *\n * Grows by `arrayUnion` on every capture, including the ones that merge\n * onto an existing row — which is exactly what the create-only `hostId`\n * beside it could never do.\n */\n capturedByHostIds?: string[]\n /**\n * Every form this person has come in through, in no order (AGL-2612).\n *\n * The entry point proper is `interactions[].formId` inside the capturing\n * holder's facet, and that stays the record: which form produced which\n * visit is one holder's business. But Firestore cannot select documents\n * by a field of an array ELEMENT, and a facet path is per group, so\n * \"everyone who filled in this form\" — the question the form's own page\n * asks of the Contacts list — has to be a top-level array an\n * `array-contains` can hit, exactly as `capturedByHostIds` is for sites\n * and `companyIds` is for companies. A form id is minted under one site,\n * so a query on it is one site's captures by construction.\n *\n * Grows by `arrayUnion` on every form capture, create or merge, bounded at\n * {@link CONTACT_FORM_IDS_CAP}: a person who has filled in more forms than\n * that keeps the first twenty and the timeline keeps the rest. The facet is\n * the truth and this is its index — a reader answering \"which form\" reads\n * the interaction; only a QUERY reads this.\n */\n formIds?: string[]\n /*\n * SEARCH KEYS (AGL-2596), and nothing more.\n *\n * The console's global search reads a window of contact documents and\n * matches over their top-level fields; it never resolves a holder's facet,\n * because it is one search over a dozen collections and a facet read is a\n * contacts-only idea. So the two profile values a person is looked up BY —\n * their phone number and the company they work for — are mirrored here by\n * every writer that sets them on a facet, as plain values a query can hit.\n *\n * The FACET is the record. These are a last-writer-wins echo of it: two\n * holders who keep different numbers for one person each overwrite the\n * echo and each keep their own facet value, and nothing renders these to a\n * reader — the list, the record page and the export all read through the\n * viewing group's facet. `ORG_CONTACT_FIELDS` below is an allow-list, so\n * neither reaches the org view either.\n */\n /** E.164, mirrored from the last facet write that set one. */\n phone?: string\n /** The company name as typed, mirrored the same way. */\n companyName?: string\n /**\n * The OTHER addresses this person answers to (AGL-2625).\n *\n * A contact is keyed on one email, so one human with a work address and a\n * personal one is two documents until somebody merges them. The merge keeps\n * the survivor's `email` as the identity and records the merged record's\n * address here, so a later capture on it — a form filled in from the\n * personal account — resolves to this row rather than minting the second\n * document again. `emailIndex` (see {@link CONTACT_EMAIL_INDEX_COLLECTION})\n * is the lookup; this array is the record of why an entry there points\n * where it does, and what the record page shows as \"also\".\n *\n * Shared identity like `email`, not a facet field: which addresses are one\n * person is a fact about the person, and a holder that did not perform the\n * merge still needs its capture on the alternate address to land on the\n * shared row. Bounded at {@link CONTACT_ALTERNATE_EMAILS_CAP}.\n */\n alternateEmails?: string[]\n /**\n * When the earliest OPEN task filed against this person is due, epoch\n * ms, or `null` when none is (AGL-2661) — see `CrmDeal.nextTaskAtMs` in\n * `crm.ts` for the rule. On the SHARED row rather than a facet, because a\n * task lives at the organization level and names the contact, not a\n * holder's view of them.\n */\n nextTaskAtMs?: number | null\n /**\n * The last verdict on the address (AGL-3245) — bounced, blocked,\n * unsubscribed, do-not-contact — written by the platform's senders only,\n * on the SHARED row because the address is shared. Absent means nothing\n * is known. See `email-state.ts`.\n */\n emailState?: EmailState\n}\n\n/** Timeline cap: keeps the doc small; older interactions age out. */\nexport const CONTACT_INTERACTIONS_CAP = 50\n\n/** The field holding {@link HostContact.alternateEmails}. */\nexport const CONTACT_ALTERNATE_EMAILS_FIELD = 'alternateEmails'\n\n/**\n * The most alternate addresses one contact carries. Ten is past any real\n * person's mailbox count, and it bounds the index writes one merge fans out.\n */\nexport const CONTACT_ALTERNATE_EMAILS_CAP = 10\n\n/**\n * `orgs/{orgId}/emailIndex/{personKey}` → `{ email, contactId }` (AGL-2625).\n *\n * The address-to-contact lookup the capture door consults BEFORE the\n * per-document `email ==` query, so an address recorded as an alternate on a\n * merged row resolves to the survivor. Keyed by `personKey` — the sha256 of\n * the normalized address — so a document id never carries the address\n * itself, the same derivation a lead and a list membership use.\n *\n * WRITTEN LAZILY, never backfilled: the query on `email` stays as the\n * fallback, and a contact that has no entry gets one on the next write that\n * finds it. A row the index has never seen therefore costs one extra read\n * once, and nothing needs to run over the existing collection.\n *\n * Server-written only; the rules close it to every client.\n */\nexport const CONTACT_EMAIL_INDEX_COLLECTION = 'emailIndex'\n\n/**\n * Every address a contact answers to — the primary first, then the\n * alternates — normalized and deduplicated, so an index writer and a lead\n * lookup walk one list.\n */\nexport function contactEmails(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n const out: string[] = []\n const seen = new Set<string>()\n const push = (value: unknown) => {\n const email = normalizeContactEmail(value)\n if (email && !seen.has(email)) {\n seen.add(email)\n out.push(email)\n }\n }\n push((contact ?? {})['email'])\n const alternates = (contact ?? {})[CONTACT_ALTERNATE_EMAILS_FIELD]\n if (Array.isArray(alternates)) alternates.forEach(push)\n return out\n}\n\n/** The top-level field naming every form a contact came in through — see `HostContact.formIds`. */\nexport const CONTACT_FORM_IDS_FIELD = 'formIds'\n\n/**\n * How many forms the {@link CONTACT_FORM_IDS_FIELD} mirror holds.\n *\n * The same figure as the tag cap: enough that no real person reaches it,\n * small enough that the array never becomes the document. Past it the\n * capture stops adding rather than dropping the oldest, because the mirror\n * is an index of the facet's timeline and an index that silently forgets an\n * entry the timeline still holds would answer a form's contact list wrongly\n * in the one direction nobody would notice.\n */\nexport const CONTACT_FORM_IDS_CAP = 20\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** Normalized dedupe key, or null when the input isn't a usable email. */\nexport function normalizeContactEmail(input: unknown): string | null {\n const email = String(input ?? '')\n .trim()\n .toLowerCase()\n return EMAIL_PATTERN.test(email) && email.length <= 320 ? email : null\n}\n\n/**\n * First usable email in a free-form form-submission fields map — forms\n * don't guarantee a canonical email field, so prefer keys that look like\n * email fields before falling back to any email-shaped value.\n */\nexport function extractEmailFromFields(\n fields: Record<string, unknown> | null | undefined,\n): string | null {\n const entries = Object.entries(fields ?? {})\n const preferred = entries.find(([key]) => /email/i.test(key))\n const fromPreferred = normalizeContactEmail(preferred?.[1])\n if (fromPreferred) return fromPreferred\n for (const [, value] of entries) {\n const email = normalizeContactEmail(value)\n if (email) return email\n }\n return null\n}\n\n/**\n * Merges a new interaction into a contact: source flag set, interaction\n * prepended, timeline capped. Pure — the caller persists the result.\n */\nexport function mergeContactInteraction(\n existing: Pick<HostContact, 'sources' | 'interactions'> & {\n name?: string\n },\n update: { source: ContactSource; interaction: ContactInteraction; name?: string },\n): Pick<HostContact, 'sources' | 'interactions'> & { name?: string } {\n return {\n // Existing names win — a later anonymous form shouldn't blank a name.\n name: existing.name || update.name,\n sources: { ...existing.sources, [update.source]: true as const },\n interactions: [update.interaction, ...(existing.interactions ?? [])].slice(\n 0,\n CONTACT_INTERACTIONS_CAP,\n ),\n }\n}\n\n/**\n * THE PER-HOLDER FACET on a shared contact document.\n *\n * ## What is shared and what is not\n *\n * One human who touched two sites is ONE document. That is not a compromise:\n * it is the dedupe the shared address book exists for, it is what keeps a\n * bounce and a suppression describing one person, and it is what makes a\n * multi-brand account bill once for one human instead of once per site. A\n * document per host would push an agency toward twelve separate accounts and\n * throw the whole advantage away.\n *\n * But almost nothing ON that document is legitimately shared.\n *\n * - **SHARED IDENTITY** — `email`, and the canonical `name`. One human, one\n * identity. This is the only part two unrelated businesses may both see,\n * and it is the minimum that makes them one row.\n * - **PER-HOLDER FACET** — everything in this interface. A note, a tag, a\n * call log and a lifetime value are the HOLDER's own business records.\n * Host A's note about a customer is Host A's; a competitor sharing the\n * platform must not read it, and while these lived at the top of the\n * document every site in the org could.\n * - **CONSENT AND VISIBILITY** — per declared group, decided by\n * `marketing-consent.ts` and by `visibleTo`.\n *\n * ## Keyed by GROUP, not by host\n *\n * A business that declared three sites to be one sender is one CRM: a note\n * written on the shop belongs beside the booking made on the booking page,\n * because one team keeps both. Across groups, never — and an undeclared site\n * is a group of one, so the agency case is isolated with nothing configured.\n *\n * ## Commercial figures are per-facet, and that is not a billing change\n *\n * `ltvCents` and `ordersCount` answer \"what is this person worth to ME\". Two\n * unrelated merchants who both sell to one person have two different answers\n * and neither is entitled to the other's. Billing counts DOCUMENTS, and there\n * is still one document, so a person held by two hosts stays one billable\n * contact.\n */\nexport interface ContactFacet {\n /**\n * This holder's display name for the person, overriding the canonical one.\n *\n * The canonical `name` is shared and mutable, so without this a rename on\n * one site changes what an unrelated business sees in its own CRM — two\n * companies that do not know each other exist editing each other's records.\n * The override is written by whoever edits the name from their own console;\n * the canonical field stays as the identity of last resort, for a holder\n * that has never set one.\n */\n name?: string\n /** Which capture surfaces THIS holder saw the person through. */\n sources: Partial<Record<ContactSource, true>>\n /** THIS holder's timeline, newest-first and capped. */\n interactions: ContactInteraction[]\n /** THIS holder's tags. */\n tags?: string[]\n /** THIS holder's notes. */\n notes?: string\n /**\n * The campaigns THIS holder has filed the person under.\n *\n * A label on the CRM record, not an audience: who a campaign's mail reaches\n * is decided by the campaign's lists and by each send's own picker, and\n * nothing in the send path reads this. It answers \"who did we put in the\n * spring push\", which is a question about the holder's own working set.\n *\n * Per-holder for the reason the notes are: two unrelated businesses sharing\n * one row must not read each other's segmentation of a person they both\n * know. See `container-membership.ts` for the field and the path.\n */\n campaignIds?: string[]\n /** Gross of fees and refunds — see `upsertHostContact`. */\n ltvCents?: number\n ordersCount?: number\n lastPurchaseAtMs?: number\n firstPurchaseAtMs?: number\n refundedCents?: number\n refundedOrdersCount?: number\n lastRefundAtMs?: number\n /*\n * CRM v2 (AGL-2595): the profile a sales team keeps on a person.\n *\n * Per-holder like everything above them, and for the same reason: a phone\n * number, a job title, an owner and a lifecycle stage are one business's\n * knowledge of a person, and two unrelated businesses sharing the row must\n * not read each other's. `companyId` points at a company document in the\n * same scope, never at the org's whole company list. `custom` is keyed by\n * `ContactFieldDefinition.key`, so a holder's field definitions and a\n * holder's values live under the same group and cannot be joined across\n * one.\n *\n * ⛔ None of these reach the org view. `ORG_CONTACT_FIELDS` is an\n * allow-list, and the org-view spec seeds every one of these with a\n * sentinel and proves it never surfaces.\n */\n /** E.164 — `normalizePhone` before writing. */\n phone?: string\n jobTitle?: string\n /**\n * Where this holder met the person — Salesforce's Lead Source, carried\n * from the lead on conversion and picked from the org's lead source\n * values after it (AGL-3298). The value's label, as the lead stores it.\n */\n leadSource?: string\n /** `orgs/{orgId}/companies/{companyId}`, in this holder's scope. */\n companyId?: string\n /**\n * The company's name as this holder knows it.\n *\n * Free text, so a person can be filed under a company before one exists\n * as a record; the company picker that later sets `companyId` writes the\n * picked company's name here too, so the row reads the same whether the\n * link was made or the name typed. The top-level `companyName` on the\n * document is the search echo of this value — see `HostContact`.\n */\n companyName?: string\n address?: AglynPostalAddress | null\n /** The team member responsible for the relationship. */\n ownerUid?: string\n lifecycleStage?: ContactLifecycleStage\n /** Custom field values, keyed by `ContactFieldDefinition.key`. */\n custom?: Record<string, ContactCustomValue>\n /**\n * When this person last OPENED or CLICKED a campaign sent by one of this\n * holder's sites, epoch ms (AGL-2616).\n *\n * Stamped by the delivery webhook, forward-only, on the first open and the\n * first click of each message — the same bound the per-person rollup on\n * `emailDeliveries/{key}` keeps, so a reader opening one newsletter six\n * times is one write. Per-holder because it answers \"is this person still\n * reading OUR mail\": the address-level rollup counts every sender's mail\n * and a sibling business's, and a re-engagement audience built on that\n * would mail people who are reading somebody else.\n *\n * Absent until the first engagement after the stamp shipped; a message\n * opened before then advanced the address-level rollup and nothing here.\n */\n lastEmailEngagementAtMs?: number\n /**\n * The org-library files THIS holder has attached to the person\n * (AGL-2662), by media document id.\n *\n * Per-holder for the reason every other field here is: an agency running\n * two client brands has one contact document between them, and a signed\n * contract one client filed is not the other client's to see. Ids rather\n * than URLs so a file moved between folders keeps its attachment, and so\n * a private asset is still served through the signed CDN door.\n */\n mediaIds?: string[]\n}\n\n/** The map field holding the facets: `{ [groupId]: ContactFacet }`. */\nexport const CONTACT_FACETS_FIELD = 'facets'\n\n/**\n * The facet one group holds, or an empty one.\n *\n * `map[groupId]` — a lookup, not a search, for the reason the consent map is\n * shaped the same way: there is no expression of this form that returns\n * another holder's notes.\n *\n * An absent facet reads EMPTY rather than falling back to the top-level\n * fields. A fallback would hand every holder in the org the fields the\n * pre-facet document carried at its top, which is the disclosure this shape\n * exists to end; the migration moves them into the capturing group's facet\n * instead.\n */\nexport function readContactFacet(\n contact: Record<string, unknown> | null | undefined,\n groupId: string,\n): ContactFacet {\n const facets = (contact ?? {})[CONTACT_FACETS_FIELD]\n const facet =\n facets && typeof facets === 'object' && !Array.isArray(facets)\n ? (facets as Record<string, unknown>)[groupId]\n : undefined\n if (!facet || typeof facet !== 'object' || Array.isArray(facet)) {\n return { sources: {}, interactions: [] }\n }\n const value = facet as Record<string, unknown>\n return {\n ...(value as unknown as ContactFacet),\n sources: (value['sources'] ?? {}) as ContactFacet['sources'],\n interactions: Array.isArray(value['interactions'])\n ? (value['interactions'] as ContactInteraction[])\n : [],\n }\n}\n\n/** The dotted Firestore path to one field of one holder's facet. */\nexport function contactFacetPath(groupId: string, field: string): string {\n if (!groupId) throw new Error('a contact facet must name a holder')\n return `${CONTACT_FACETS_FIELD}.${groupId}.${field}`\n}\n\n/**\n * The name a given holder should SEE for this person.\n *\n * Their own override first, the canonical identity second. Nothing falls\n * through to another holder's override: that would be one business's edit\n * showing up in another's CRM, which is the thing the override exists to\n * prevent.\n */\nexport function contactDisplayName(\n contact: Record<string, unknown> | null | undefined,\n groupId: string,\n): string {\n const facet = readContactFacet(contact, groupId)\n if (facet.name) return facet.name\n const canonical = (contact ?? {})['name']\n return typeof canonical === 'string' ? canonical : ''\n}\n\n/**\n * Every group that holds this contact — the reference count behind a detach.\n *\n * Read from `visibleTo` rather than from the facet map, because `visibleTo`\n * is what both enforcement layers actually evaluate: a holder that can still\n * READ the row is still holding it whether or not they ever wrote a note. A\n * count taken from the facets would drop a holder who has one and no facet\n * and leave them able to see a document nothing believes they hold.\n *\n * Less the tokens a share ADDED (AGL-3336): a site the record was shared\n * with sees it and holds nothing, so it must not keep the record alive when\n * its last holder lets go — `heldScopeTokens` is `visibleTo` without them.\n */\nexport function contactHolderTokens(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n return heldScopeTokens(contact)\n}\n\n/** What a holder letting go of a contact should do to the document. */\nexport type ContactDetach =\n | {\n /** Nobody else holds it. Delete the document. */\n action: 'delete'\n /**\n * Every refusal the document holds, every site's and the unscoped one,\n * which the delete keeps in `retainedRefusals` in the same transaction\n * — see `retained-refusals.ts`. `null` when it holds none.\n */\n retained: RetainedRefusals | null\n }\n | {\n /** Other holders remain. Drop this one's half. */\n action: 'detach'\n /**\n * Field-level removals, as a patch. Dotted paths so the OTHER holders'\n * facets and consent entries are untouched — a nested write would\n * replace the whole map and take every other holder's records with it.\n *\n * A consent entry that is a REFUSAL is not among them: it stays on the\n * document for the holders that remain, because a person's \"no\" is not\n * the leaving holder's to take with it.\n */\n remove: string[]\n /** Scope tokens to pull out of `visibleTo`. */\n removeTokens: string[]\n /** Host ids to pull out of the capture attribution. */\n removeHostIds: string[]\n }\n\n/**\n * DELETE IS A DETACH.\n *\n * One holder removing a contact from their own CRM must not destroy another\n * holder's relationship with that person: they have their own notes, their\n * own order history and their own consent, none of which the deleting holder\n * ever had a claim on. So a delete drops the deleting group's facet, its\n * consent grants, its capture attribution and its scope tokens — and the\n * DOCUMENT dies only when the last holder lets go.\n *\n * A REFUSAL IS NOT LET GO (AGL-3338). The list gate reads a stored refusal\n * as the one fact an operator's attestation cannot overrule, so a detach\n * leaves the leaving group's refusal entries on the document, and a delete\n * answers every refusal the document holds for the caller to retain beside\n * the delete. Read off the document's own data: a table row's projection\n * carries neither the consent map nor the unscoped field.\n *\n * ⛔ This is NOT the erasure path. A privacy erasure removes the person\n * everywhere regardless of how many holders remain, and routing it through\n * reference counting would turn a lawful erasure into a partial one — the same\n * absent-versus-invisible defect this area keeps hitting, in the one place\n * where getting it wrong is a legal failure rather than a bug. Erasure calls\n * the document delete directly and must never consult this function.\n *\n * @param group the holder letting go, with every site it covers.\n */\nexport function planContactDetach(\n contact: Record<string, unknown> | null | undefined,\n group: { groupId: string; hostIds: readonly string[] },\n): ContactDetach {\n const held = contactHolderTokens(contact)\n const leaving = new Set(group.hostIds.map((id) => `host:${id}`))\n /*\n * A remaining holder is a token naming somebody else. `'org'` counts as one\n * and blocks the delete on purpose: an org-wide row is held by every site\n * in the account, so one site letting go leaves it held. Narrowing it would\n * be a scope decision, and a delete button is not where that belongs.\n */\n const remaining = held.filter((token) => !leaving.has(token))\n if (!remaining.length) return { action: 'delete', retained: refusalsOf(contact) }\n const refused = refusalsOf(contact)?.byHost ?? {}\n return {\n action: 'detach',\n remove: [\n `${CONTACT_FACETS_FIELD}.${group.groupId}`,\n ...group.hostIds\n .filter((id) => !(id in refused))\n .map((id) => `${MARKETING_CONSENT_BY_HOST_FIELD}.${id}`),\n ],\n removeTokens: [...leaving],\n removeHostIds: [...group.hostIds],\n }\n}\n\n/**\n * The interactions one group of sites may see on a shared contact.\n *\n * An interaction with NO host is shown to everyone: it predates the\n * attribution, so hiding it would empty every existing timeline, and it is\n * already visible to anyone who can read the row. An interaction that names a\n * site is shown only to that site's own group — the agency case, where one\n * client must not read another client's bookings off a person they both know.\n */\nexport function interactionsForGroup(\n interactions: readonly ContactInteraction[] | undefined,\n hostIds: readonly string[],\n): ContactInteraction[] {\n const reach = new Set(hostIds)\n return (interactions ?? []).filter(\n (interaction) => !interaction.hostId || reach.has(interaction.hostId),\n )\n}\n\n/** `orgs/{orgId}/contactSegments/{id}` — a saved audience filter. */\nexport interface ContactSegment {\n name: string\n /** Match contacts sharing at least one tag (empty = any). */\n tags?: string[]\n /** Match contacts with at least one of these sources (empty = any). */\n sources?: ContactSource[]\n}\n\n/** Segment matching (AGL-199): AND across filter kinds, OR within one. */\nexport function contactMatchesSegment(\n contact: Pick<HostContact, 'tags' | 'sources'>,\n segment: Pick<ContactSegment, 'tags' | 'sources'>,\n): boolean {\n if (segment.tags?.length) {\n const contactTags = new Set(\n (contact.tags ?? []).map((tag) => tag.toLowerCase()),\n )\n if (!segment.tags.some((tag) => contactTags.has(tag.toLowerCase()))) {\n return false\n }\n }\n if (segment.sources?.length) {\n if (!segment.sources.some((source) => contact.sources?.[source])) {\n return false\n }\n }\n return true\n}\n\n/*==========================================\n * THE ORG-LEVEL VIEW: the complement of the facet reader above.\n *\n * {@link readContactFacet} answers \"what does THIS holder know about this\n * person\". Everything below answers the question no host page can:\n *\n * who does this ORGANIZATION know, and which of its sites know them.\n *\n * That question is the entire justification for one shared document. Dedupe,\n * suppression and honest billing all rest on one human being one row, and\n * with no surface that shows the deduped person the model's benefit is\n * invisible and the billing unit — unique people per org — looks arbitrary.\n *\n * ## The org view crosses the host boundary, so it carries LESS, not more\n *\n * It is the one place in the product designed to read across holders, which\n * makes it the one place where a careless field re-creates the disclosure the\n * facets exist to end. So the projection is an ALLOW-LIST\n * ({@link ORG_CONTACT_FIELDS}) rather than an omission: identity, capture\n * attribution and consent state. Notes, tags, timelines, call logs and\n * commercial figures are the holder's own business records and are not read\n * here at all — not summarized, not counted, not indicated by their absence.\n *\n * An allow-list rather than a `delete facets` is the load-bearing choice. A\n * subtraction is correct only for as long as somebody remembers to extend it,\n * and a field added to {@link ContactFacet} tomorrow would ride out through a\n * subtraction and be caught by an allow-list.\n *\n * ## The NAME is the canonical one, never a holder's override\n *\n * {@link contactDisplayName} prefers the viewing group's own override, which\n * is right on a host page and wrong here: an override is a name ONE business\n * chose, and rendering it at org level shows an agency the label its client\n * picked. The shared identity is what every holder already sees, so it is the\n * only name that belongs to the org.\n *=========================================*/\n\n/**\n * Every field of a contact document the org view may read.\n *\n * Stated as a value so it can be asserted against — see the org-view spec,\n * which seeds each facet field with a sentinel and proves none of them\n * reaches a row.\n */\nexport const ORG_CONTACT_FIELDS = [\n 'email',\n 'name',\n CAPTURED_BY_HOST_FIELD,\n MARKETING_CONSENT_BY_HOST_FIELD,\n MARKETING_CONSENT_FIELD,\n] as const\n\n/**\n * What one site's relationship with one person amounts to, at org level.\n *\n * Consent is per (contact, host-or-group) and there is no expression that\n * returns another controller's grant, so a row cannot carry one consent\n * verdict. It carries one PER CAPTURING SITE, each naming the controller it\n * was read for — a bare \"consented\" with nobody attached would be exactly the\n * confusion the per-brand model was built to prevent.\n */\nexport interface OrgContactHostConsent {\n /** The site this verdict answers about, and no other. */\n hostId: string\n /** The controller the basis runs to — the declared group, or the site. */\n groupId: string\n /**\n * The group's disclosed name, or `null` for a site that pools with nobody.\n *\n * `null` is not \"unknown\": it is the group of one, where the site's own\n * name is the disclosure and inventing a second would put a label in front\n * of a reader that nothing else uses.\n */\n groupName: string | null\n /** Whether the controller is a DECLARED group rather than the site alone. */\n declared: boolean\n /** `granted` | `declined` | `unrecorded` — never collapsed to a boolean. */\n basis: MarketingBasis\n}\n\n/** One person, as the organization may see them across all of its sites. */\nexport interface OrgContactRow {\n $id: string\n /** The dedupe key, and the reason two captures are one row. */\n email: string\n /** The SHARED identity. Never a holder's own override. */\n name: string\n /** Every site that has captured this person, sorted for a stable render. */\n capturedByHostIds: string[]\n /** One verdict per capturing site, in the same order. */\n consent: OrgContactHostConsent[]\n}\n\n/**\n * Every site that has captured this person.\n *\n * Sorted, because the array is maintained by `arrayUnion` and therefore\n * carries capture order, which is not an order anything should render: two\n * readers of the same row would see the sites in different places on the\n * screen depending on which site met the person first.\n */\nexport function contactCaptureHostIds(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n const raw = (contact ?? {})[CAPTURED_BY_HOST_FIELD]\n if (!Array.isArray(raw)) return []\n return [\n ...new Set(\n raw\n .map((id) => String(id ?? '').trim())\n .filter((id): id is string => id !== ''),\n ),\n ].sort()\n}\n\n/**\n * One contact document, projected to what an ORG may see.\n *\n * @param org - the org document — the only input that can resolve a declared\n * consent group, and required for that reason. Without it every site reads\n * as a group of one, which understates the disclosure a person was given\n * and is the safe direction to be wrong in.\n */\nexport function orgContactRow(\n contact: Record<string, unknown> | null | undefined,\n contactId: string,\n org: Record<string, unknown> | null | undefined,\n): OrgContactRow {\n const record = contact ?? {}\n const capturedByHostIds = contactCaptureHostIds(record)\n return {\n $id: contactId,\n email: typeof record['email'] === 'string' ? record['email'] : '',\n name: typeof record['name'] === 'string' ? record['name'] : '',\n capturedByHostIds,\n consent: capturedByHostIds.map((hostId) => {\n /*\n * READ FOR THE SITE, one call per site. `readMarketingBasis` requires\n * the group it is being read for and has no default, so this cannot\n * accidentally report a grant that belongs to somebody else — the\n * argument is the guarantee, and passing the whole row through one\n * call would have had to invent a controller to ask about.\n */\n const group = consentGroupForHost(org, hostId)\n const { basis } = readMarketingBasis(record, group)\n return {\n hostId,\n groupId: group.groupId,\n groupName: group.name,\n declared: group.declared,\n basis,\n }\n }),\n }\n}\n\n/**\n * How a basis reads on screen.\n *\n * Three labels because there are three states. \"Opted in\" and \"No record\" are\n * not opposites and must never collapse into one negative: absence is the\n * commonest case by far — a record captured before the checkbox existed — and\n * showing it as a refusal would tell a merchant they may not mail somebody\n * who never said so.\n */\nexport const MARKETING_BASIS_LABELS: Record<MarketingBasis, string> = {\n granted: 'Opted in',\n declined: 'Opted out',\n unrecorded: 'No record',\n}\n\n/**\n * One consent verdict, WITH THE CONTROLLER IT RUNS TO, as one string.\n *\n * ⛔ There is no function here that returns a basis on its own, and that is\n * the point. A basis is per (person, controller): the same person can be\n * opted in to one brand in an org and opted out of another, so \"consented\"\n * with nobody attached is not a shortened truth, it is a different and false\n * claim — precisely the confusion the per-brand model was built to prevent.\n * Joining the two into a single value is what stops a caller rendering half\n * of it.\n *\n * The controller is the DECLARED GROUP when there is one, because that is who\n * the person was told they would hear from, and the site otherwise. A group\n * of one is named by the site, which is what the capture surface already\n * showed them.\n *\n * @param siteName - how this site reads — the caller resolves it, since the\n * contact document holds ids and not names. An empty one falls back to the\n * id: a site whose name cannot be resolved must still be NAMED, because\n * dropping it would understate which brands hold a relationship.\n */\nexport function orgContactConsentLabel(\n entry: OrgContactHostConsent,\n siteName?: string,\n): string {\n const controller = entry.declared\n ? (entry.groupName ?? entry.groupId)\n : siteName || entry.hostId\n return `${controller} · ${MARKETING_BASIS_LABELS[entry.basis]}`\n}\n"],"names":["consentGroupForHost","heldScopeTokens","CAPTURED_BY_HOST_FIELD","MARKETING_CONSENT_BY_HOST_FIELD","MARKETING_CONSENT_FIELD","readMarketingBasis","refusalsOf","CONTACT_SOURCE_LABELS","form","member","order","booking","newsletter","api","manual","import","account","CONTACT_INTERACTIONS_CAP","CONTACT_ALTERNATE_EMAILS_FIELD","CONTACT_ALTERNATE_EMAILS_CAP","CONTACT_EMAIL_INDEX_COLLECTION","contactEmails","contact","out","seen","Set","push","value","email","normalizeContactEmail","has","add","alternates","Array","isArray","forEach","CONTACT_FORM_IDS_FIELD","CONTACT_FORM_IDS_CAP","EMAIL_PATTERN","input","String","trim","toLowerCase","test","length","extractEmailFromFields","fields","entries","Object","preferred","find","key","fromPreferred","mergeContactInteraction","existing","update","name","sources","source","interactions","interaction","slice","CONTACT_FACETS_FIELD","readContactFacet","groupId","facets","facet","undefined","contactFacetPath","field","Error","contactDisplayName","canonical","contactHolderTokens","planContactDetach","group","held","leaving","hostIds","map","id","remaining","filter","token","action","retained","refused","byHost","remove","removeTokens","removeHostIds","interactionsForGroup","reach","hostId","contactMatchesSegment","segment","tags","contactTags","tag","some","ORG_CONTACT_FIELDS","contactCaptureHostIds","raw","sort","orgContactRow","contactId","org","record","capturedByHostIds","$id","consent","basis","groupName","declared","MARKETING_BASIS_LABELS","granted","declined","unrecorded","orgContactConsentLabel","entry","siteName","controller"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;CAMC;AAGD,SAASA,mBAAmB,QAAQ,sBAAkB;AAGtD,SAASC,eAAe,QAAQ,oBAAgB;AAChD,SACEC,sBAAsB,EACtBC,+BAA+B,EAC/BC,uBAAuB,EACvBC,kBAAkB,QAEb,yBAAqB;AAC5B,SAASC,UAAU,QAA+B,yBAAqB;AA+BvE;;;;;;;;CAQC,GACD,OAAO,MAAMC,wBAAuD;IAClEC,MAAM;IACNC,QAAQ;IACRC,OAAO;IACPC,SAAS;IACTC,YAAY;IACZC,KAAK;IACLC,QAAQ;IACRC,QAAQ;IACRC,SAAS;AACX,EAAC;AA0JD,mEAAmE,GACnE,OAAO,MAAMC,2BAA2B,GAAE;AAE1C,2DAA2D,GAC3D,OAAO,MAAMC,iCAAiC,kBAAiB;AAE/D;;;CAGC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@@ -0,0 +1,93 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * The field a member holds its containers of one kind in: `<kind>Ids`.
19
+ *
20
+ * Derived rather than declared, so a record page in one plugin can file
21
+ * itself under a kind another plugin keeps by the kind's name alone, and so
22
+ * two plugins cannot store one kind's membership under two names. The owner
23
+ * declares the kind; the field follows from it.
24
+ */
25
+ export declare function containerMembershipField(kind: string): string;
26
+ /**
27
+ * How many containers of one kind a record may name.
28
+ *
29
+ * A ceiling on the FIELD, not on the product: an array Firestore has to index
30
+ * on every write is not the place to discover that a script has been adding
31
+ * an id a day for a year. Twenty is far past what a person assigns by hand
32
+ * and far short of anything that costs a write.
33
+ */
34
+ export declare const CONTAINER_MEMBERSHIP_CAP = 20;
35
+ /**
36
+ * A stored membership array as a clean list of ids.
37
+ *
38
+ * Deduped, trimmed, non-strings dropped, capped. Every reader goes through
39
+ * this because the field is written by several consoles and automation
40
+ * steps, and a surface that trusted the raw value would render `undefined` as
41
+ * a chip the first time one of them wrote a blank.
42
+ */
43
+ export declare function normalizeContainerIds(raw: unknown): string[];
44
+ /**
45
+ * The containers of one kind a HOST record — a form, a screen — is filed
46
+ * under.
47
+ *
48
+ * Host records carry the field at the top of the document: they belong to
49
+ * one site, and whoever may read the record may read what it is filed under,
50
+ * so there is no second holder to keep the edge away from.
51
+ */
52
+ export declare function readContainerIds(resource: Record<string, unknown> | null | undefined, kind: string): string[];
53
+ /**
54
+ * The dotted path to a contact's membership of one kind, inside ONE holder's
55
+ * facet.
56
+ *
57
+ * A contact document is shared by every site in the org — one human who
58
+ * touched two sites is one row — and almost nothing on it is legitimately
59
+ * shared. What a merchant has filed a person under is that merchant's
60
+ * business record on exactly the footing their notes and tags are, so it
61
+ * lives at `facets.{groupId}.<kind>Ids` and not at the top of the document,
62
+ * where every other site in an agency's account could read it.
63
+ */
64
+ export declare function contactContainerFieldPath(groupId: string, kind: string): string;
65
+ /** The containers of one kind ONE holder has filed this contact under. */
66
+ export declare function readContactContainerIds(contact: Record<string, unknown> | null | undefined, groupId: string, kind: string): string[];
67
+ /**
68
+ * The membership a save should write, given what is on screen.
69
+ *
70
+ * Pure, and shared by every console that offers a picker, because the
71
+ * decision each of them makes is identical and is not obvious: an EMPTY
72
+ * selection has to be stored as an empty array rather than as a removed
73
+ * field.
74
+ *
75
+ * Removing the field would read the same to every surface here — the readers
76
+ * above answer `[]` either way — and would be wrong for the one reader that
77
+ * is not a surface. A container's owner finds its members with
78
+ * `array-contains`, which matches on the automatic single-field index; that
79
+ * index has an entry only while the array does, so the two shapes are the
80
+ * same to a reader and different to a writer only in cost. Storing `[]` keeps
81
+ * one shape for "filed under nothing" across every writer.
82
+ *
83
+ * @returns the value to store under {@link containerMembershipField}.
84
+ */
85
+ export declare function containerMembershipValue(selected: readonly string[]): string[];
86
+ /**
87
+ * Whether a document's stored membership already says what a save would.
88
+ *
89
+ * Order-insensitive: a picker hands back its options' order and the stored
90
+ * array is in the order it was written, so comparing them literally would
91
+ * report a change on every open and leave Save permanently enabled.
92
+ */
93
+ export declare function containerMembershipUnchanged(stored: readonly string[], selected: readonly string[]): boolean;
@@ -0,0 +1,165 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ /**
17
+ * WHAT A RECORD IS FILED UNDER: the edge between a container and the forms,
18
+ * screens and people it gathers.
19
+ *
20
+ * A container is a document of a kind some plugin keeps and declares
21
+ * (`plugin-manager/plugin-containers.ts`) — a campaign is the first. Records
22
+ * of other kinds, kept by other plugins or by the core, are filed under one.
23
+ *
24
+ * ## The edge is a field on the MEMBER, not a list on the container
25
+ *
26
+ * A container names nothing outside itself. A member joins one by carrying
27
+ * the container's id in {@link containerMembershipField} — `<kind>Ids` — on
28
+ * its own document.
29
+ *
30
+ * Three properties decide it, and all three point the same way:
31
+ *
32
+ * - **Reading is free where it is asked.** A form's own page reads the form
33
+ * document to draw anything at all, so its containers come with it. A
34
+ * membership collection under the container would make "what is this
35
+ * filed under" a query issued on mount by every record page, for a fact
36
+ * one field already carries.
37
+ * - **The removal is one mechanism.** The container's owner clears its id
38
+ * from every member before it removes the container, and a plugin whose
39
+ * members the owner cannot name registers a detacher for them
40
+ * (`plugin-manager/plugin-membership-detach.ts`). A membership collection
41
+ * would be a second, different deletion story beside it.
42
+ * - **Deleting a MEMBER can leave nothing behind.** The container holds no
43
+ * list, so a deleted form takes its own edge with it. This matters most on
44
+ * a contact: an erasure removes the document, and a membership row stored
45
+ * anywhere else would survive it holding the id of a person who asked to
46
+ * be forgotten.
47
+ *
48
+ * ## Plural, because a landing page outlives one push
49
+ *
50
+ * The field is an ARRAY. A signup form built for the spring campaign is the
51
+ * same form the summer one places, and a single-valued field would make the
52
+ * second filing silently erase the first — a container losing a member with
53
+ * nothing on screen to say so.
54
+ *
55
+ * ## Ids, never names
56
+ *
57
+ * A container's name is editable, and every reader resolves the name from the
58
+ * container document at read time. Renaming one therefore moves no
59
+ * membership: the stored value is the container's document id, which nothing
60
+ * rewrites.
61
+ */ import { contactFacetPath, readContactFacet } from "./contacts.js";
62
+ /**
63
+ * The field a member holds its containers of one kind in: `<kind>Ids`.
64
+ *
65
+ * Derived rather than declared, so a record page in one plugin can file
66
+ * itself under a kind another plugin keeps by the kind's name alone, and so
67
+ * two plugins cannot store one kind's membership under two names. The owner
68
+ * declares the kind; the field follows from it.
69
+ */ export function containerMembershipField(kind) {
70
+ const key = String(kind != null ? kind : '').trim();
71
+ if (!key) throw new Error('a container membership needs a kind');
72
+ return `${key}Ids`;
73
+ }
74
+ /**
75
+ * How many containers of one kind a record may name.
76
+ *
77
+ * A ceiling on the FIELD, not on the product: an array Firestore has to index
78
+ * on every write is not the place to discover that a script has been adding
79
+ * an id a day for a year. Twenty is far past what a person assigns by hand
80
+ * and far short of anything that costs a write.
81
+ */ export const CONTAINER_MEMBERSHIP_CAP = 20;
82
+ /**
83
+ * A stored membership array as a clean list of ids.
84
+ *
85
+ * Deduped, trimmed, non-strings dropped, capped. Every reader goes through
86
+ * this because the field is written by several consoles and automation
87
+ * steps, and a surface that trusted the raw value would render `undefined` as
88
+ * a chip the first time one of them wrote a blank.
89
+ */ export function normalizeContainerIds(raw) {
90
+ if (!Array.isArray(raw)) return [];
91
+ const seen = [];
92
+ for (const entry of raw){
93
+ if (typeof entry !== 'string') continue;
94
+ const id = entry.trim();
95
+ if (!id || seen.includes(id)) continue;
96
+ seen.push(id);
97
+ if (seen.length >= CONTAINER_MEMBERSHIP_CAP) break;
98
+ }
99
+ return seen;
100
+ }
101
+ /**
102
+ * The containers of one kind a HOST record — a form, a screen — is filed
103
+ * under.
104
+ *
105
+ * Host records carry the field at the top of the document: they belong to
106
+ * one site, and whoever may read the record may read what it is filed under,
107
+ * so there is no second holder to keep the edge away from.
108
+ */ export function readContainerIds(resource, kind) {
109
+ return normalizeContainerIds((resource != null ? resource : {})[containerMembershipField(kind)]);
110
+ }
111
+ /**
112
+ * The dotted path to a contact's membership of one kind, inside ONE holder's
113
+ * facet.
114
+ *
115
+ * A contact document is shared by every site in the org — one human who
116
+ * touched two sites is one row — and almost nothing on it is legitimately
117
+ * shared. What a merchant has filed a person under is that merchant's
118
+ * business record on exactly the footing their notes and tags are, so it
119
+ * lives at `facets.{groupId}.<kind>Ids` and not at the top of the document,
120
+ * where every other site in an agency's account could read it.
121
+ */ export function contactContainerFieldPath(groupId, kind) {
122
+ return contactFacetPath(groupId, containerMembershipField(kind));
123
+ }
124
+ /** The containers of one kind ONE holder has filed this contact under. */ export function readContactContainerIds(contact, groupId, kind) {
125
+ const facet = readContactFacet(contact, groupId);
126
+ return normalizeContainerIds(facet[containerMembershipField(kind)]);
127
+ }
128
+ /**
129
+ * The membership a save should write, given what is on screen.
130
+ *
131
+ * Pure, and shared by every console that offers a picker, because the
132
+ * decision each of them makes is identical and is not obvious: an EMPTY
133
+ * selection has to be stored as an empty array rather than as a removed
134
+ * field.
135
+ *
136
+ * Removing the field would read the same to every surface here — the readers
137
+ * above answer `[]` either way — and would be wrong for the one reader that
138
+ * is not a surface. A container's owner finds its members with
139
+ * `array-contains`, which matches on the automatic single-field index; that
140
+ * index has an entry only while the array does, so the two shapes are the
141
+ * same to a reader and different to a writer only in cost. Storing `[]` keeps
142
+ * one shape for "filed under nothing" across every writer.
143
+ *
144
+ * @returns the value to store under {@link containerMembershipField}.
145
+ */ export function containerMembershipValue(selected) {
146
+ return normalizeContainerIds(selected);
147
+ }
148
+ /**
149
+ * Whether a document's stored membership already says what a save would.
150
+ *
151
+ * Order-insensitive: a picker hands back its options' order and the stored
152
+ * array is in the order it was written, so comparing them literally would
153
+ * report a change on every open and leave Save permanently enabled.
154
+ */ export function containerMembershipUnchanged(stored, selected) {
155
+ if (stored.length !== selected.length) return false;
156
+ const sortedStored = [
157
+ ...stored
158
+ ].sort();
159
+ const sortedSelected = [
160
+ ...selected
161
+ ].sort();
162
+ return sortedStored.every((id, index)=>id === sortedSelected[index]);
163
+ }
164
+
165
+ //# sourceMappingURL=container-membership.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/container-membership.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * WHAT A RECORD IS FILED UNDER: the edge between a container and the forms,\n * screens and people it gathers.\n *\n * A container is a document of a kind some plugin keeps and declares\n * (`plugin-manager/plugin-containers.ts`) — a campaign is the first. Records\n * of other kinds, kept by other plugins or by the core, are filed under one.\n *\n * ## The edge is a field on the MEMBER, not a list on the container\n *\n * A container names nothing outside itself. A member joins one by carrying\n * the container's id in {@link containerMembershipField} — `<kind>Ids` — on\n * its own document.\n *\n * Three properties decide it, and all three point the same way:\n *\n * - **Reading is free where it is asked.** A form's own page reads the form\n * document to draw anything at all, so its containers come with it. A\n * membership collection under the container would make \"what is this\n * filed under\" a query issued on mount by every record page, for a fact\n * one field already carries.\n * - **The removal is one mechanism.** The container's owner clears its id\n * from every member before it removes the container, and a plugin whose\n * members the owner cannot name registers a detacher for them\n * (`plugin-manager/plugin-membership-detach.ts`). A membership collection\n * would be a second, different deletion story beside it.\n * - **Deleting a MEMBER can leave nothing behind.** The container holds no\n * list, so a deleted form takes its own edge with it. This matters most on\n * a contact: an erasure removes the document, and a membership row stored\n * anywhere else would survive it holding the id of a person who asked to\n * be forgotten.\n *\n * ## Plural, because a landing page outlives one push\n *\n * The field is an ARRAY. A signup form built for the spring campaign is the\n * same form the summer one places, and a single-valued field would make the\n * second filing silently erase the first — a container losing a member with\n * nothing on screen to say so.\n *\n * ## Ids, never names\n *\n * A container's name is editable, and every reader resolves the name from the\n * container document at read time. Renaming one therefore moves no\n * membership: the stored value is the container's document id, which nothing\n * rewrites.\n */\n\nimport { contactFacetPath, readContactFacet } from './contacts'\n\n/**\n * The field a member holds its containers of one kind in: `<kind>Ids`.\n *\n * Derived rather than declared, so a record page in one plugin can file\n * itself under a kind another plugin keeps by the kind's name alone, and so\n * two plugins cannot store one kind's membership under two names. The owner\n * declares the kind; the field follows from it.\n */\nexport function containerMembershipField(kind: string): string {\n const key = String(kind ?? '').trim()\n if (!key) throw new Error('a container membership needs a kind')\n return `${key}Ids`\n}\n\n/**\n * How many containers of one kind a record may name.\n *\n * A ceiling on the FIELD, not on the product: an array Firestore has to index\n * on every write is not the place to discover that a script has been adding\n * an id a day for a year. Twenty is far past what a person assigns by hand\n * and far short of anything that costs a write.\n */\nexport const CONTAINER_MEMBERSHIP_CAP = 20\n\n/**\n * A stored membership array as a clean list of ids.\n *\n * Deduped, trimmed, non-strings dropped, capped. Every reader goes through\n * this because the field is written by several consoles and automation\n * steps, and a surface that trusted the raw value would render `undefined` as\n * a chip the first time one of them wrote a blank.\n */\nexport function normalizeContainerIds(raw: unknown): string[] {\n if (!Array.isArray(raw)) return []\n const seen: string[] = []\n for (const entry of raw) {\n if (typeof entry !== 'string') continue\n const id = entry.trim()\n if (!id || seen.includes(id)) continue\n seen.push(id)\n if (seen.length >= CONTAINER_MEMBERSHIP_CAP) break\n }\n return seen\n}\n\n/**\n * The containers of one kind a HOST record — a form, a screen — is filed\n * under.\n *\n * Host records carry the field at the top of the document: they belong to\n * one site, and whoever may read the record may read what it is filed under,\n * so there is no second holder to keep the edge away from.\n */\nexport function readContainerIds(\n resource: Record<string, unknown> | null | undefined,\n kind: string,\n): string[] {\n return normalizeContainerIds((resource ?? {})[containerMembershipField(kind)])\n}\n\n/**\n * The dotted path to a contact's membership of one kind, inside ONE holder's\n * facet.\n *\n * A contact document is shared by every site in the org — one human who\n * touched two sites is one row — and almost nothing on it is legitimately\n * shared. What a merchant has filed a person under is that merchant's\n * business record on exactly the footing their notes and tags are, so it\n * lives at `facets.{groupId}.<kind>Ids` and not at the top of the document,\n * where every other site in an agency's account could read it.\n */\nexport function contactContainerFieldPath(groupId: string, kind: string): string {\n return contactFacetPath(groupId, containerMembershipField(kind))\n}\n\n/** The containers of one kind ONE holder has filed this contact under. */\nexport function readContactContainerIds(\n contact: Record<string, unknown> | null | undefined,\n groupId: string,\n kind: string,\n): string[] {\n const facet = readContactFacet(contact, groupId) as unknown as Record<string, unknown>\n return normalizeContainerIds(facet[containerMembershipField(kind)])\n}\n\n/**\n * The membership a save should write, given what is on screen.\n *\n * Pure, and shared by every console that offers a picker, because the\n * decision each of them makes is identical and is not obvious: an EMPTY\n * selection has to be stored as an empty array rather than as a removed\n * field.\n *\n * Removing the field would read the same to every surface here — the readers\n * above answer `[]` either way — and would be wrong for the one reader that\n * is not a surface. A container's owner finds its members with\n * `array-contains`, which matches on the automatic single-field index; that\n * index has an entry only while the array does, so the two shapes are the\n * same to a reader and different to a writer only in cost. Storing `[]` keeps\n * one shape for \"filed under nothing\" across every writer.\n *\n * @returns the value to store under {@link containerMembershipField}.\n */\nexport function containerMembershipValue(selected: readonly string[]): string[] {\n return normalizeContainerIds(selected)\n}\n\n/**\n * Whether a document's stored membership already says what a save would.\n *\n * Order-insensitive: a picker hands back its options' order and the stored\n * array is in the order it was written, so comparing them literally would\n * report a change on every open and leave Save permanently enabled.\n */\nexport function containerMembershipUnchanged(\n stored: readonly string[],\n selected: readonly string[],\n): boolean {\n if (stored.length !== selected.length) return false\n const sortedStored = [...stored].sort()\n const sortedSelected = [...selected].sort()\n return sortedStored.every((id, index) => id === sortedSelected[index])\n}\n"],"names":["contactFacetPath","readContactFacet","containerMembershipField","kind","key","String","trim","Error","CONTAINER_MEMBERSHIP_CAP","normalizeContainerIds","raw","Array","isArray","seen","entry","id","includes","push","length","readContainerIds","resource","contactContainerFieldPath","groupId","readContactContainerIds","contact","facet","containerMembershipValue","selected","containerMembershipUnchanged","stored","sortedStored","sort","sortedSelected","every","index"],"mappings":"AAAA;;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AiBC,GACD,OAAO,SAASuB,yBAAyBC,QAA2B;IAClE,OAAOlB,sBAAsBkB;AAC/B;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,6BACdC,MAAyB,EACzBF,QAA2B;IAE3B,IAAIE,OAAOX,MAAM,KAAKS,SAAST,MAAM,EAAE,OAAO;IAC9C,MAAMY,eAAe;WAAID;KAAO,CAACE,IAAI;IACrC,MAAMC,iBAAiB;WAAIL;KAAS,CAACI,IAAI;IACzC,OAAOD,aAAaG,KAAK,CAAC,CAAClB,IAAImB,QAAUnB,OAAOiB,cAAc,CAACE,MAAM;AACvE"}
@@ -94,17 +94,29 @@ export interface CrmReminderTask extends Pick<CrmTask, 'title' | 'kind' | 'conta
94
94
  * rewrites onto the organization's own hub for a task with no site.
95
95
  */
96
96
  export declare function crmTaskReminderLink(hostId: string | null, task: Pick<CrmTask, 'contactId' | 'companyId' | 'dealId'>): string;
97
- /** `Wed, Sep 9, 3:00 PM` in a named zone — the words a reminder says a time with. */
97
+ /**
98
+ * `Wed, Sep 9, 3:00 PM CDT` — the words a reminder says a time with. The zone
99
+ * is the server's choice, not the reader's, so it is printed: a reader an
100
+ * hour away would otherwise take it for their own clock.
101
+ */
98
102
  export declare function crmTaskReminderWhen(ms: number, timeZone: string): string;
99
103
  /**
100
- * The one line the console notification is: the title and when the task is
101
- * due. A reminder set on a task with no due date says only the title —
102
- * the person chose the time; the task itself has none.
104
+ * One task as the reminder email lists it: its title and when it is due, or
105
+ * that it has no due date — a reminder can sit on a task with none, at a time
106
+ * the person chose.
107
+ */
108
+ export declare function crmTaskReminderLine(task: Pick<CrmReminderTask, 'title' | 'dueAtMs'>, timeZone: string): string;
109
+ /**
110
+ * The console notification's body, one per task, which is also what a
111
+ * preview of it shows. It says it is a reminder and names the workspace, so
112
+ * it reads whole without the "Task reminder" title above it.
103
113
  */
104
- export declare function composeCrmTaskReminderBody(task: Pick<CrmReminderTask, 'title' | 'dueAtMs'>, timeZone: string): string;
114
+ export declare function composeCrmTaskReminderBody(task: Pick<CrmReminderTask, 'title' | 'dueAtMs'>, timeZone: string, workspaceName?: string): string;
105
115
  /**
106
116
  * One mail per member per run, so five tasks due at nine o'clock are one
107
- * message and not five. The subject names the task when there is one.
117
+ * message and not five. The subject names the task when there is one, and
118
+ * never says a task is due: a reminder can be set ahead of the due time, or
119
+ * on a task with none.
108
120
  */
109
121
  export declare function composeCrmTaskReminderSubject(tasks: ReadonlyArray<Pick<CrmReminderTask, 'title'>>): string;
110
122
  /** What the reminder email needs from the route besides the tasks. */
@@ -113,6 +125,11 @@ export interface CrmTaskReminderEmailInput {
113
125
  timeZone: string;
114
126
  /** The product name the mail reads as — the org's brand when white-labeled. */
115
127
  productName: string;
128
+ /**
129
+ * The workspace the tasks are in. The system email shows only the body, so
130
+ * the body names it: a member of two workspaces gets reminders from each.
131
+ */
132
+ workspaceName?: string;
116
133
  /** The console page a task opens on, absolute. */
117
134
  taskUrl: (task: CrmReminderTask) => string;
118
135
  /** Account settings → Notifications, where the category can be muted. */