@aglyn/aglyn 1.0.0-beta.220 → 1.0.0-beta.222

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 (358) hide show
  1. package/package.json +15 -11
  2. package/src/lib/app-utils/agent-openapi.js +1 -1
  3. package/src/lib/app-utils/agent-openapi.js.map +1 -1
  4. package/src/lib/app-utils/analytics-events.d.ts +3 -2
  5. package/src/lib/app-utils/analytics-events.js +3 -2
  6. package/src/lib/app-utils/analytics-events.js.map +1 -1
  7. package/src/lib/app-utils/api-plugins.d.ts +30 -0
  8. package/src/lib/app-utils/api-plugins.js +24 -1
  9. package/src/lib/app-utils/api-plugins.js.map +1 -1
  10. package/src/lib/app-utils/author-html.d.ts +1 -1
  11. package/src/lib/app-utils/author-html.js.map +1 -1
  12. package/src/lib/app-utils/bandwidth-cap.d.ts +12 -1
  13. package/src/lib/app-utils/bandwidth-cap.js +17 -1
  14. package/src/lib/app-utils/bandwidth-cap.js.map +1 -1
  15. package/src/lib/app-utils/compose-reusable-components.d.ts +19 -0
  16. package/src/lib/app-utils/compose-reusable-components.js +116 -26
  17. package/src/lib/app-utils/compose-reusable-components.js.map +1 -1
  18. package/src/lib/app-utils/console-routes.d.ts +4 -0
  19. package/src/lib/app-utils/console-routes.js +3 -0
  20. package/src/lib/app-utils/console-routes.js.map +1 -1
  21. package/src/lib/app-utils/contacts.d.ts +71 -0
  22. package/src/lib/app-utils/contacts.js +55 -0
  23. package/src/lib/app-utils/contacts.js.map +1 -1
  24. package/src/lib/app-utils/contexts.d.ts +1 -0
  25. package/src/lib/app-utils/contexts.js +1 -0
  26. package/src/lib/app-utils/contexts.js.map +1 -1
  27. package/src/lib/app-utils/crm-email-templates.js +21 -4
  28. package/src/lib/app-utils/crm-email-templates.js.map +1 -1
  29. package/src/lib/app-utils/crm-kinds.d.ts +2 -0
  30. package/src/lib/app-utils/crm-kinds.js +1 -0
  31. package/src/lib/app-utils/crm-kinds.js.map +1 -1
  32. package/src/lib/app-utils/crm.d.ts +1199 -67
  33. package/src/lib/app-utils/crm.js +1951 -310
  34. package/src/lib/app-utils/crm.js.map +1 -1
  35. package/src/lib/app-utils/csv-import.d.ts +10 -38
  36. package/src/lib/app-utils/csv-import.js +17 -42
  37. package/src/lib/app-utils/csv-import.js.map +1 -1
  38. package/src/lib/app-utils/csv.d.ts +32 -11
  39. package/src/lib/app-utils/csv.js +43 -5
  40. package/src/lib/app-utils/csv.js.map +1 -1
  41. package/src/lib/app-utils/default-site.d.ts +116 -0
  42. package/src/lib/app-utils/default-site.js +1024 -0
  43. package/src/lib/app-utils/default-site.js.map +1 -0
  44. package/src/lib/app-utils/docs-help.generated.d.ts +23 -23
  45. package/src/lib/app-utils/docs-help.generated.js +47 -10
  46. package/src/lib/app-utils/docs-help.generated.js.map +1 -1
  47. package/src/lib/app-utils/docs-index.generated.js +746 -151
  48. package/src/lib/app-utils/docs-index.generated.js.map +1 -1
  49. package/src/lib/app-utils/draft-placeholders.d.ts +76 -0
  50. package/src/lib/app-utils/draft-placeholders.js +115 -0
  51. package/src/lib/app-utils/draft-placeholders.js.map +1 -0
  52. package/src/lib/app-utils/entity-picker-context.d.ts +19 -15
  53. package/src/lib/app-utils/entity-picker-context.js +4 -4
  54. package/src/lib/app-utils/entity-picker-context.js.map +1 -1
  55. package/src/lib/app-utils/expand-repeatables.d.ts +66 -10
  56. package/src/lib/app-utils/expand-repeatables.js +88 -14
  57. package/src/lib/app-utils/expand-repeatables.js.map +1 -1
  58. package/src/lib/app-utils/forms.d.ts +33 -22
  59. package/src/lib/app-utils/forms.js +47 -28
  60. package/src/lib/app-utils/forms.js.map +1 -1
  61. package/src/lib/app-utils/full-use-cost.d.ts +277 -0
  62. package/src/lib/app-utils/full-use-cost.js +421 -0
  63. package/src/lib/app-utils/full-use-cost.js.map +1 -0
  64. package/src/lib/app-utils/health-report.js +33 -0
  65. package/src/lib/app-utils/health-report.js.map +1 -1
  66. package/src/lib/app-utils/leaving-notice.d.ts +96 -0
  67. package/src/lib/app-utils/leaving-notice.js +157 -0
  68. package/src/lib/app-utils/leaving-notice.js.map +1 -0
  69. package/src/lib/app-utils/llms-txt.d.ts +20 -0
  70. package/src/lib/app-utils/llms-txt.js +7 -1
  71. package/src/lib/app-utils/llms-txt.js.map +1 -1
  72. package/src/lib/app-utils/media-asset-facts.d.ts +16 -1
  73. package/src/lib/app-utils/media-asset-facts.js +40 -13
  74. package/src/lib/app-utils/media-asset-facts.js.map +1 -1
  75. package/src/lib/app-utils/media-bandwidth.d.ts +52 -0
  76. package/src/lib/app-utils/media-bandwidth.js +94 -0
  77. package/src/lib/app-utils/media-bandwidth.js.map +1 -0
  78. package/src/lib/app-utils/media-ref.d.ts +241 -33
  79. package/src/lib/app-utils/media-ref.js +324 -43
  80. package/src/lib/app-utils/media-ref.js.map +1 -1
  81. package/src/lib/app-utils/media-src.d.ts +8 -8
  82. package/src/lib/app-utils/media-src.js +27 -11
  83. package/src/lib/app-utils/media-src.js.map +1 -1
  84. package/src/lib/app-utils/media-takedown-reach.d.ts +4 -1
  85. package/src/lib/app-utils/media-takedown-reach.js +6 -3
  86. package/src/lib/app-utils/media-takedown-reach.js.map +1 -1
  87. package/src/lib/app-utils/notifications.d.ts +1 -1
  88. package/src/lib/app-utils/notifications.js +2 -0
  89. package/src/lib/app-utils/notifications.js.map +1 -1
  90. package/src/lib/app-utils/operator-alerts.js +17 -0
  91. package/src/lib/app-utils/operator-alerts.js.map +1 -1
  92. package/src/lib/app-utils/organizations.d.ts +51 -2
  93. package/src/lib/app-utils/organizations.js +56 -3
  94. package/src/lib/app-utils/organizations.js.map +1 -1
  95. package/src/lib/app-utils/page-record-sources.d.ts +87 -0
  96. package/src/lib/app-utils/page-record-sources.js +53 -0
  97. package/src/lib/app-utils/page-record-sources.js.map +1 -0
  98. package/src/lib/app-utils/paid-media-source.d.ts +3 -7
  99. package/src/lib/app-utils/paid-media-source.js +5 -19
  100. package/src/lib/app-utils/paid-media-source.js.map +1 -1
  101. package/src/lib/app-utils/person-erasure.d.ts +5 -2
  102. package/src/lib/app-utils/person-erasure.js.map +1 -1
  103. package/src/lib/app-utils/picklists.d.ts +187 -0
  104. package/src/lib/app-utils/picklists.js +320 -0
  105. package/src/lib/app-utils/picklists.js.map +1 -0
  106. package/src/lib/app-utils/plan-entitlements.d.ts +220 -50
  107. package/src/lib/app-utils/plan-entitlements.js +309 -115
  108. package/src/lib/app-utils/plan-entitlements.js.map +1 -1
  109. package/src/lib/app-utils/realm-host-surface.generated.js +2 -0
  110. package/src/lib/app-utils/realm-host-surface.generated.js.map +1 -1
  111. package/src/lib/app-utils/release-flags.d.ts +1 -1
  112. package/src/lib/app-utils/release-flags.js +11 -0
  113. package/src/lib/app-utils/release-flags.js.map +1 -1
  114. package/src/lib/app-utils/rendered-widths.d.ts +121 -0
  115. package/src/lib/app-utils/rendered-widths.js +211 -0
  116. package/src/lib/app-utils/rendered-widths.js.map +1 -0
  117. package/src/lib/app-utils/repeat-sources.d.ts +2 -1
  118. package/src/lib/app-utils/repeat-sources.js.map +1 -1
  119. package/src/lib/app-utils/screen-link-context-value.d.ts +7 -0
  120. package/src/lib/app-utils/screen-link-context-value.js.map +1 -1
  121. package/src/lib/app-utils/screen-link-context.js +14 -2
  122. package/src/lib/app-utils/screen-link-context.js.map +1 -1
  123. package/src/lib/app-utils/screen-route.d.ts +157 -36
  124. package/src/lib/app-utils/screen-route.js +191 -41
  125. package/src/lib/app-utils/screen-route.js.map +1 -1
  126. package/src/lib/app-utils/seo-audit.d.ts +11 -1
  127. package/src/lib/app-utils/seo-audit.js +33 -13
  128. package/src/lib/app-utils/seo-audit.js.map +1 -1
  129. package/src/lib/app-utils/seo-keywords.d.ts +11 -0
  130. package/src/lib/app-utils/seo-keywords.js +19 -5
  131. package/src/lib/app-utils/seo-keywords.js.map +1 -1
  132. package/src/lib/app-utils/seo-page-facts.d.ts +47 -4
  133. package/src/lib/app-utils/seo-page-facts.js +136 -31
  134. package/src/lib/app-utils/seo-page-facts.js.map +1 -1
  135. package/src/lib/app-utils/seo-site-scan.d.ts +42 -4
  136. package/src/lib/app-utils/seo-site-scan.js +113 -12
  137. package/src/lib/app-utils/seo-site-scan.js.map +1 -1
  138. package/src/lib/app-utils/server.d.ts +5 -4
  139. package/src/lib/app-utils/server.js +14 -5
  140. package/src/lib/app-utils/server.js.map +1 -1
  141. package/src/lib/app-utils/site-icon-set.d.ts +195 -0
  142. package/src/lib/app-utils/site-icon-set.js +351 -0
  143. package/src/lib/app-utils/site-icon-set.js.map +1 -0
  144. package/src/lib/app-utils/site-interactions.d.ts +101 -4
  145. package/src/lib/app-utils/site-interactions.js +120 -4
  146. package/src/lib/app-utils/site-interactions.js.map +1 -1
  147. package/src/lib/app-utils/starter-template-nodes.d.ts +7 -0
  148. package/src/lib/app-utils/starter-template-nodes.js +3 -0
  149. package/src/lib/app-utils/starter-template-nodes.js.map +1 -1
  150. package/src/lib/app-utils/starter-templates.d.ts +5 -19
  151. package/src/lib/app-utils/starter-templates.js +5 -49
  152. package/src/lib/app-utils/starter-templates.js.map +1 -1
  153. package/src/lib/app-utils/transfer-launcher-context.d.ts +136 -0
  154. package/src/lib/app-utils/transfer-launcher-context.js +23 -0
  155. package/src/lib/app-utils/transfer-launcher-context.js.map +1 -0
  156. package/src/lib/app-utils/transfer-resume-import.d.ts +39 -0
  157. package/src/lib/app-utils/transfer-resume-import.js +128 -0
  158. package/src/lib/app-utils/transfer-resume-import.js.map +1 -0
  159. package/src/lib/app-utils/upgrade-proposal.d.ts +66 -0
  160. package/src/lib/app-utils/upgrade-proposal.js +95 -0
  161. package/src/lib/app-utils/upgrade-proposal.js.map +1 -0
  162. package/src/lib/app-utils/utc-month.d.ts +33 -0
  163. package/src/lib/app-utils/utc-month.js +35 -0
  164. package/src/lib/app-utils/utc-month.js.map +1 -0
  165. package/src/lib/app-utils/visitor-record-ceiling.d.ts +4 -4
  166. package/src/lib/app-utils/visitor-record-ceiling.js +4 -4
  167. package/src/lib/app-utils/visitor-record-ceiling.js.map +1 -1
  168. package/src/lib/app-utils/wire-nodes.d.ts +39 -19
  169. package/src/lib/app-utils/wire-nodes.js +120 -34
  170. package/src/lib/app-utils/wire-nodes.js.map +1 -1
  171. package/src/lib/data-transfer/access.d.ts +74 -0
  172. package/src/lib/data-transfer/access.js +93 -0
  173. package/src/lib/data-transfer/access.js.map +1 -0
  174. package/src/lib/data-transfer/derive.d.ts +246 -0
  175. package/src/lib/data-transfer/derive.js +1007 -0
  176. package/src/lib/data-transfer/derive.js.map +1 -0
  177. package/src/lib/data-transfer/export-file.d.ts +46 -0
  178. package/src/lib/data-transfer/export-file.js +146 -0
  179. package/src/lib/data-transfer/export-file.js.map +1 -0
  180. package/src/lib/data-transfer/field-catalog.d.ts +134 -0
  181. package/src/lib/data-transfer/field-catalog.js +278 -0
  182. package/src/lib/data-transfer/field-catalog.js.map +1 -0
  183. package/src/lib/data-transfer/header-match.d.ts +129 -0
  184. package/src/lib/data-transfer/header-match.js +367 -0
  185. package/src/lib/data-transfer/header-match.js.map +1 -0
  186. package/src/lib/data-transfer/index.d.ts +34 -0
  187. package/src/lib/data-transfer/index.js +40 -0
  188. package/src/lib/data-transfer/index.js.map +1 -0
  189. package/src/lib/data-transfer/job.d.ts +190 -0
  190. package/src/lib/data-transfer/job.js +229 -0
  191. package/src/lib/data-transfer/job.js.map +1 -0
  192. package/src/lib/data-transfer/lookup.d.ts +45 -0
  193. package/src/lib/data-transfer/lookup.js +71 -0
  194. package/src/lib/data-transfer/lookup.js.map +1 -0
  195. package/src/lib/data-transfer/match.d.ts +99 -0
  196. package/src/lib/data-transfer/match.js +244 -0
  197. package/src/lib/data-transfer/match.js.map +1 -0
  198. package/src/lib/data-transfer/package-plan.d.ts +205 -0
  199. package/src/lib/data-transfer/package-plan.js +475 -0
  200. package/src/lib/data-transfer/package-plan.js.map +1 -0
  201. package/src/lib/data-transfer/package.d.ts +181 -0
  202. package/src/lib/data-transfer/package.js +426 -0
  203. package/src/lib/data-transfer/package.js.map +1 -0
  204. package/src/lib/data-transfer/picklist-map.d.ts +139 -0
  205. package/src/lib/data-transfer/picklist-map.js +271 -0
  206. package/src/lib/data-transfer/picklist-map.js.map +1 -0
  207. package/src/lib/data-transfer/plan.d.ts +176 -0
  208. package/src/lib/data-transfer/plan.js +451 -0
  209. package/src/lib/data-transfer/plan.js.map +1 -0
  210. package/src/lib/data-transfer/policy.d.ts +170 -0
  211. package/src/lib/data-transfer/policy.js +378 -0
  212. package/src/lib/data-transfer/policy.js.map +1 -0
  213. package/src/lib/data-transfer/resource.d.ts +211 -0
  214. package/src/lib/data-transfer/resource.js +241 -0
  215. package/src/lib/data-transfer/resource.js.map +1 -0
  216. package/src/lib/data-transfer/review.d.ts +70 -0
  217. package/src/lib/data-transfer/review.js +233 -0
  218. package/src/lib/data-transfer/review.js.map +1 -0
  219. package/src/lib/data-transfer/similarity.d.ts +40 -0
  220. package/src/lib/data-transfer/similarity.js +106 -0
  221. package/src/lib/data-transfer/similarity.js.map +1 -0
  222. package/src/lib/data-transfer/site-package.d.ts +365 -0
  223. package/src/lib/data-transfer/site-package.js +1077 -0
  224. package/src/lib/data-transfer/site-package.js.map +1 -0
  225. package/src/lib/data-transfer/source.d.ts +74 -0
  226. package/src/lib/data-transfer/source.js +293 -0
  227. package/src/lib/data-transfer/source.js.map +1 -0
  228. package/src/lib/data-transfer/transfer-api.d.ts +898 -0
  229. package/src/lib/data-transfer/transfer-api.js +107 -0
  230. package/src/lib/data-transfer/transfer-api.js.map +1 -0
  231. package/src/lib/foundation/definitions/org-billing.types.d.ts +31 -0
  232. package/src/lib/foundation/definitions/org-billing.types.js.map +1 -1
  233. package/src/lib/foundation/definitions/organization.types.d.ts +42 -1
  234. package/src/lib/foundation/definitions/organization.types.js.map +1 -1
  235. package/src/lib/foundation/definitions/platform.types.d.ts +6 -4
  236. package/src/lib/foundation/definitions/platform.types.js.map +1 -1
  237. package/src/lib/foundation/index.d.ts +1 -1
  238. package/src/lib/foundation/index.js.map +1 -1
  239. package/src/lib/plugin-manager/feature-plugins.d.ts +91 -2
  240. package/src/lib/plugin-manager/feature-plugins.js +48 -3
  241. package/src/lib/plugin-manager/feature-plugins.js.map +1 -1
  242. package/src/lib/plugin-manager/first-party-plugins.generated.d.ts +56 -0
  243. package/src/lib/plugin-manager/first-party-plugins.generated.js +1132 -27
  244. package/src/lib/plugin-manager/first-party-plugins.generated.js.map +1 -1
  245. package/src/lib/plugin-manager/index.d.ts +0 -1
  246. package/src/lib/plugin-manager/index.js +0 -1
  247. package/src/lib/plugin-manager/index.js.map +1 -1
  248. package/src/lib/plugin-manager/interaction-recipes.d.ts +142 -0
  249. package/src/lib/plugin-manager/interaction-recipes.js +104 -0
  250. package/src/lib/plugin-manager/interaction-recipes.js.map +1 -0
  251. package/src/lib/plugin-manager/interaction-step-checks.d.ts +66 -0
  252. package/src/lib/plugin-manager/interaction-step-checks.js +86 -0
  253. package/src/lib/plugin-manager/interaction-step-checks.js.map +1 -0
  254. package/src/lib/plugin-manager/plugin-artifact-types.d.ts +235 -0
  255. package/src/lib/plugin-manager/plugin-artifact-types.js +99 -0
  256. package/src/lib/plugin-manager/plugin-artifact-types.js.map +1 -0
  257. package/src/lib/plugin-manager/plugin-contact-capture.d.ts +8 -0
  258. package/src/lib/plugin-manager/plugin-contact-capture.js.map +1 -1
  259. package/src/lib/plugin-manager/plugin-conversion-credit.d.ts +216 -0
  260. package/src/lib/plugin-manager/plugin-conversion-credit.js +91 -0
  261. package/src/lib/plugin-manager/plugin-conversion-credit.js.map +1 -0
  262. package/src/lib/plugin-manager/plugin-entity-pickers.d.ts +83 -0
  263. package/src/lib/plugin-manager/plugin-entity-pickers.js +87 -0
  264. package/src/lib/plugin-manager/plugin-entity-pickers.js.map +1 -0
  265. package/src/lib/plugin-manager/plugin-host-resources.d.ts +6 -0
  266. package/src/lib/plugin-manager/plugin-host-resources.js +6 -1
  267. package/src/lib/plugin-manager/plugin-host-resources.js.map +1 -1
  268. package/src/lib/plugin-manager/plugin-intake-gates.d.ts +75 -0
  269. package/src/lib/plugin-manager/plugin-intake-gates.js +49 -0
  270. package/src/lib/plugin-manager/plugin-intake-gates.js.map +1 -0
  271. package/src/lib/plugin-manager/plugin-jobs.d.ts +5 -5
  272. package/src/lib/plugin-manager/plugin-jobs.js +7 -7
  273. package/src/lib/plugin-manager/plugin-jobs.js.map +1 -1
  274. package/src/lib/plugin-manager/plugin-live-paths.d.ts +70 -0
  275. package/src/lib/plugin-manager/plugin-live-paths.js +66 -0
  276. package/src/lib/plugin-manager/plugin-live-paths.js.map +1 -0
  277. package/src/lib/plugin-manager/plugin-org-erasure.d.ts +3 -2
  278. package/src/lib/plugin-manager/plugin-org-erasure.js +30 -5
  279. package/src/lib/plugin-manager/plugin-org-erasure.js.map +1 -1
  280. package/src/lib/plugin-manager/plugin-person-erasure.d.ts +68 -9
  281. package/src/lib/plugin-manager/plugin-person-erasure.js +196 -51
  282. package/src/lib/plugin-manager/plugin-person-erasure.js.map +1 -1
  283. package/src/lib/plugin-manager/plugin-person-records.d.ts +275 -0
  284. package/src/lib/plugin-manager/plugin-person-records.js +107 -0
  285. package/src/lib/plugin-manager/plugin-person-records.js.map +1 -0
  286. package/src/lib/plugin-manager/plugin-record-counts.d.ts +76 -0
  287. package/src/lib/plugin-manager/plugin-record-counts.js +49 -0
  288. package/src/lib/plugin-manager/plugin-record-counts.js.map +1 -0
  289. package/src/lib/plugin-manager/plugin-record-email-state.d.ts +26 -0
  290. package/src/lib/plugin-manager/plugin-record-email-state.js +16 -0
  291. package/src/lib/plugin-manager/plugin-record-email-state.js.map +1 -1
  292. package/src/lib/plugin-manager/plugin-record-index.d.ts +10 -0
  293. package/src/lib/plugin-manager/plugin-record-index.js.map +1 -1
  294. package/src/lib/plugin-manager/plugin-record-lists.d.ts +86 -6
  295. package/src/lib/plugin-manager/plugin-record-lists.js +42 -5
  296. package/src/lib/plugin-manager/plugin-record-lists.js.map +1 -1
  297. package/src/lib/plugin-manager/plugin-record-origin.d.ts +79 -0
  298. package/src/lib/plugin-manager/plugin-record-origin.js +46 -0
  299. package/src/lib/plugin-manager/plugin-record-origin.js.map +1 -0
  300. package/src/lib/plugin-manager/plugin-record-pages.d.ts +37 -0
  301. package/src/lib/plugin-manager/plugin-record-pages.js +52 -0
  302. package/src/lib/plugin-manager/plugin-record-pages.js.map +1 -0
  303. package/src/lib/plugin-manager/plugin-record-timeline.d.ts +60 -0
  304. package/src/lib/plugin-manager/plugin-record-timeline.js +16 -0
  305. package/src/lib/plugin-manager/plugin-record-timeline.js.map +1 -1
  306. package/src/lib/plugin-manager/plugin-resource-drafts.d.ts +5 -5
  307. package/src/lib/plugin-manager/plugin-resource-drafts.js.map +1 -1
  308. package/src/lib/plugin-manager/plugin-revocations.d.ts +64 -0
  309. package/src/lib/plugin-manager/plugin-revocations.js +47 -0
  310. package/src/lib/plugin-manager/plugin-revocations.js.map +1 -0
  311. package/src/lib/plugin-manager/plugin-send-tallies.d.ts +69 -0
  312. package/src/lib/plugin-manager/plugin-send-tallies.js +45 -0
  313. package/src/lib/plugin-manager/plugin-send-tallies.js.map +1 -0
  314. package/src/lib/plugin-manager/plugin-server-steps.d.ts +170 -0
  315. package/src/lib/plugin-manager/plugin-server-steps.js +116 -0
  316. package/src/lib/plugin-manager/plugin-server-steps.js.map +1 -0
  317. package/src/lib/plugin-manager/plugin-site-bundle.d.ts +40 -0
  318. package/src/lib/plugin-manager/plugin-site-bundle.js +4 -0
  319. package/src/lib/plugin-manager/plugin-site-bundle.js.map +1 -1
  320. package/src/lib/plugin-manager/plugin-site-export.d.ts +57 -1
  321. package/src/lib/plugin-manager/plugin-site-export.js +23 -10
  322. package/src/lib/plugin-manager/plugin-site-export.js.map +1 -1
  323. package/src/lib/plugin-manager/plugin-sitemap-readers.d.ts +146 -0
  324. package/src/lib/plugin-manager/plugin-sitemap-readers.js +110 -0
  325. package/src/lib/plugin-manager/plugin-sitemap-readers.js.map +1 -0
  326. package/src/lib/plugin-manager/plugin-transfer-resources.d.ts +714 -0
  327. package/src/lib/plugin-manager/plugin-transfer-resources.js +443 -0
  328. package/src/lib/plugin-manager/plugin-transfer-resources.js.map +1 -0
  329. package/src/lib/plugin-manager/plugin-usage-axes.d.ts +54 -5
  330. package/src/lib/plugin-manager/plugin-usage-axes.js +11 -3
  331. package/src/lib/plugin-manager/plugin-usage-axes.js.map +1 -1
  332. package/src/lib/plugin-manager/plugin-user-erasure.js +9 -1
  333. package/src/lib/plugin-manager/plugin-user-erasure.js.map +1 -1
  334. package/src/lib/plugin-manager/plugin-visitor-doors.d.ts +104 -0
  335. package/src/lib/plugin-manager/plugin-visitor-doors.js +108 -0
  336. package/src/lib/plugin-manager/plugin-visitor-doors.js.map +1 -0
  337. package/src/lib/plugin-manager/realm-host-aglyn.generated.js +2 -0
  338. package/src/lib/plugin-manager/realm-host-aglyn.generated.js.map +1 -1
  339. package/src/lib/plugin-manager/repeat-rows.d.ts +5 -6
  340. package/src/lib/plugin-manager/repeat-rows.js.map +1 -1
  341. package/src/lib/app-utils/actions.d.ts +0 -310
  342. package/src/lib/app-utils/actions.js +0 -506
  343. package/src/lib/app-utils/actions.js.map +0 -1
  344. package/src/lib/app-utils/automation-placeholders.d.ts +0 -72
  345. package/src/lib/app-utils/automation-placeholders.js +0 -207
  346. package/src/lib/app-utils/automation-placeholders.js.map +0 -1
  347. package/src/lib/app-utils/dataset-models.d.ts +0 -339
  348. package/src/lib/app-utils/dataset-models.js +0 -722
  349. package/src/lib/app-utils/dataset-models.js.map +0 -1
  350. package/src/lib/app-utils/datasets.d.ts +0 -171
  351. package/src/lib/app-utils/datasets.js +0 -227
  352. package/src/lib/app-utils/datasets.js.map +0 -1
  353. package/src/lib/app-utils/form-abuse-ceiling.d.ts +0 -146
  354. package/src/lib/app-utils/form-abuse-ceiling.js +0 -158
  355. package/src/lib/app-utils/form-abuse-ceiling.js.map +0 -1
  356. package/src/lib/plugin-manager/order-fulfilment.d.ts +0 -142
  357. package/src/lib/plugin-manager/order-fulfilment.js +0 -104
  358. package/src/lib/plugin-manager/order-fulfilment.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/analytics-events.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 * The one GA4 event taxonomy, shared by the marketing site (tenant runtime)\n * and the console (AGL-1561). See `docs/ANALYTICS.md` for the event map and\n * which GTM-plan §6 metric each event serves.\n *\n * ## Why this module exists\n *\n * Before it, every GA event in the repo was an ad-hoc\n * `;(window as any).gtag?.('event', 'name', {...})` — five of them across the\n * marketing and commerce plugins, plus bare string literals passed to Firebase\n * `logEvent` in the console. Nothing checked the names, nothing checked the\n * params, and a typo produced a silently-missing metric rather than an error.\n * That is the failure mode analytics is worst at surfacing: the number simply\n * reads zero, and zero is indistinguishable from \"nobody did it\".\n *\n * So the names and their params are a TYPE here ({@link AnalyticsEventParams}),\n * and `trackEvent` is generic over it: a misspelled event name or a missing\n * required param is a compile error.\n *\n * That sweep missed five (AGL-1591, closed): the commerce plugin's\n * `view_item` / `add_to_cart` / `begin_checkout` and the marketing runtime's\n * `aglyn_overlay` / `aglyn_experiment`. `window.gtag` is now called in exactly\n * two places in the repo — {@link deliver} below, and `readGaClientId` above,\n * which reads rather than sends.\n *\n * ## Reserved names\n *\n * Where GA4 has a recommended event we use its exact name and its exact param\n * spelling — `sign_up`, `login`, `generate_lead`, `begin_checkout`,\n * `purchase`, `select_content` — so the built-in reports, the funnel\n * explorations and the \"key events\" toggles work without custom definitions.\n * Custom snake_case names appear only where GA4 has no standard: the four\n * activation events, which are Aglyn-specific product milestones.\n *\n * ## Consent (AGL-1498) — the gate is that gtag never loads\n *\n * On tenant sites, including aglyn.com itself, `site-analytics.tsx` renders the\n * gtag `<Script>` pair ONLY when the recorded consent state grants analytics.\n * There is therefore no `window.gtag` at all for a visitor who has not granted,\n * and {@link trackEvent} drops the event on the floor.\n *\n * It drops it — it does not QUEUE it. That distinction is the whole point and\n * `analytics-events.spec.ts` asserts it: an event fired before consent is gone\n * for good, and does not reappear when a later grant loads gtag. A queue would\n * quietly convert \"we did not track you\" into \"we tracked you and waited\", and\n * a replayed hit carries the pre-consent timestamp and page into GA, which is\n * exactly the thing the consent gate exists to prevent. Deliberately no retry,\n * no buffer, no flush-on-grant.\n *\n * ## No PII, enforced rather than promised\n *\n * Every payload passes through {@link sanitizeEventParams} before it reaches a\n * transport: an exact-key denylist drops the identity-bearing params someone\n * will eventually add by reflex (`email`, `org_name`, `first_name`, ...), any\n * value that looks like an email address drops its key entirely, URLs are\n * reduced to origin + pathname so query strings can never smuggle a token or\n * an address, and strings are length-capped. The console separately sets a\n * `user_id` — that is an opaque Firebase uid and is the one identifier GA is\n * allowed to hold.\n *\n * Sanitizing here rather than at each call site is the point: a new call site\n * cannot forget.\n *\n * ## Authored events (AGL-1587)\n *\n * One call site cannot use the taxonomy at all: the `trackGaEvent` action step,\n * whose event name and params are typed by a SITE AUTHOR in the interaction\n * builder. A closed union cannot contain a name nobody has written yet, so\n * {@link trackAuthoredEvent} is the escape hatch — and it is deliberately the\n * only one, so that untrusted input still passes {@link sanitizeEventParams}\n * rather than reaching `window.gtag` raw.\n *\n * The test for which door an event uses is WHO NAMED IT, not whether GA4\n * recommends the name. `aglyn_overlay` and `aglyn_experiment` are outside GA4's\n * recommended set and were candidates for the hatch (AGL-1591); they are in the\n * union instead, because a developer wrote their names and their keys, so they\n * can have compile-time checking — and because the hatch guarantees the\n * opposite of what they need. {@link resolveAuthoredEventName} refuses any name\n * we send — the union AND the server-only names beside it — precisely so that\n * \"not one of ours\" means \"authored\"; put our own events through the hatch and\n * that stops being true, authored hits stop being separable from ours in\n * reports, and an authored `aglyn_experiment` step starts voting in the\n * experiment that decides which variant ships.\n */\n\n/**\n * Read the browser's GA `client_id` — the identifier that ties a hit to a GA\n * user and session.\n *\n * Needed because `purchase` is sent SERVER-side, from the Stripe webhook,\n * where the authoritative money is (see `ga4-measurement-protocol.ts`). The\n * Measurement Protocol requires a `client_id` and a server cannot know one,\n * so it is captured here when checkout starts and carried on the Stripe\n * object's metadata. Without it the revenue still lands, but attached to a\n * synthetic user with no acquisition session — which is exactly the campaign\n * attribution the whole exercise is for.\n *\n * Resolves to null rather than hanging when gtag is absent (no consent, an ad\n * blocker, analytics not configured) or slow to answer. The 500ms cap matters:\n * this sits directly in front of a checkout redirect, and analytics must never\n * be able to delay a payment.\n */\nexport function readGaClientId(\n measurementId: string | undefined | null,\n): Promise<string | null> {\n return new Promise((resolve) => {\n if (typeof window === 'undefined' || !measurementId) return resolve(null)\n const gtag = (window as unknown as { gtag?: unknown }).gtag\n if (typeof gtag !== 'function') return resolve(null)\n let settled = false\n const finish = (value: string | null) => {\n if (settled) return\n settled = true\n resolve(value)\n }\n // Never let a missing callback strand the checkout.\n setTimeout(() => finish(null), 500)\n try {\n ;(gtag as (...args: unknown[]) => void)(\n 'get',\n measurementId,\n 'client_id',\n (id: unknown) => finish(typeof id === 'string' && id ? id : null),\n )\n } catch {\n finish(null)\n }\n })\n}\n\n/** Which door an account was created through (AGL-1497 enumerates all four). */\nexport type SignUpMethod =\n | 'password'\n | 'google_popup'\n | 'google_redirect'\n | 'google_signin'\n\n/** How a returning user authenticated. */\nexport type LoginMethod =\n | 'password'\n | 'google_popup'\n | 'google_redirect'\n | 'sso'\n | 'passkey'\n\n/**\n * A GA4 `items` entry. Only the fields we actually populate — GA accepts more,\n * but an unpopulated field is a column of nulls in every report.\n */\nexport interface AnalyticsItem {\n /** Opaque identifier — a price id, plan key or marketplace listing id. */\n item_id: string\n /** Human-readable product name. NEVER a customer or org name. */\n item_name: string\n /** Distinguishes the revenue lines: `subscription` vs `marketplace`. */\n item_category?: string\n price?: number\n quantity?: number\n}\n\n/**\n * The taxonomy. Adding an event means adding a line here first — which is what\n * makes `docs/ANALYTICS.md` checkable against the code rather than aspirational.\n */\nexport interface AnalyticsEventParams {\n // --- Acquisition (GTM §6: signups, cost/lead by channel) -----------------\n /**\n * GA4 recommended. Real account creation only, never a sign-in.\n *\n * The three campaign params are optional and come from\n * `utmEventParams` (AGL-1731) — present when the signup URL named a\n * campaign, absent entirely otherwise. They are what lets a September ad\n * spend be evaluated: without them a paid click, an organic visit and a\n * partner link arrive indistinguishable and the money cannot be traced to\n * an account. Named `campaign_*` rather than `utm_*` because these are our\n * own registered dimensions and the `utm_` spellings belong to GA's\n * automatic campaign collection.\n */\n sign_up: {\n method: SignUpMethod\n campaign_source?: string\n campaign_medium?: string\n campaign_name?: string\n }\n /** GA4 recommended. Returning user only. */\n login: { method: LoginMethod }\n /**\n * GA4 recommended. Fired on a SUCCESSFUL form submission — never on click,\n * never on a validation failure. `form_name` is the author-given form name,\n * which is site content and not personal data.\n */\n generate_lead: { form_name: string; form_location?: string }\n /**\n * GA4 recommended. A CTA click, with the section that produced it.\n *\n * Fired by `analytics-link-clicks.ts` (AGL-1562) from a delegated listener,\n * not per call site: an authored page has no code to add a handler to.\n */\n select_content: {\n content_type: string\n content_id: string\n /** Which product surface — see `click.surface`. */\n surface?: string\n }\n\n // --- Activation (GTM §6: % publish a site, % connect Stripe) -------------\n /** Custom: no GA4 equivalent. A new organization exists. */\n org_created: { plan?: string }\n /** Custom: no GA4 equivalent. A new site/host exists. */\n host_created: Record<string, never>\n /**\n * Custom: no GA4 equivalent, and the GTM plan's headline activation metric.\n * A site actually went live.\n */\n site_published: { first_publish?: boolean }\n /** Custom: no GA4 equivalent. Stripe Connect onboarding completed. */\n stripe_connected: Record<string, never>\n\n // --- Revenue (GTM §6: paid conversions, ARPA, annual mix) ---------------\n /** GA4 recommended. A plan checkout started. */\n begin_checkout: {\n currency: string\n value: number\n items: AnalyticsItem[]\n /** `monthly` | `annual` — feeds the §6 annual-mix metric. */\n billing_interval?: string\n }\n /**\n * GA4 recommended. A payment actually succeeded. `transaction_id` is the\n * Stripe object id and is what makes the event idempotent in GA: GA4\n * de-duplicates purchases by transaction id, so a webhook retry cannot\n * inflate revenue.\n */\n purchase: {\n transaction_id: string\n currency: string\n value: number\n items: AnalyticsItem[]\n billing_interval?: string\n /**\n * GA4's shipping charged on the transaction, in currency units. Optional\n * because only a tenant STOREFRONT purchase ships anything — a plan or a\n * marketplace purchase has no shipping to report and omits it.\n *\n * There is deliberately no sibling `tax` (AGL-1639, AGL-1641). The\n * asymmetry is the point and is not an inconsistency to tidy away:\n * `shipping` is a COMPONENT of the `value` beside it, so reporting it\n * describes that value; `tax` is not, because `value` is already ex-tax,\n * so reporting it would assert a relationship that does not hold and\n * invite the subtraction that removes tax a second time.\n */\n shipping?: number\n }\n\n // --- Commerce (tenant storefronts, AGL-1591) -----------------------------\n /**\n * GA4 recommended. A product detail page was viewed on a tenant storefront.\n *\n * Only `items`, and only `item_id`/`item_name` within it: those are the two\n * fields the storefront actually has at this point, and an unpopulated\n * `price`/`item_category` would be a column of nulls in the merchant's\n * reports. The item id is the PRODUCT id — the same id `add_to_cart` and\n * `begin_checkout` use — which is what lets GA join the three into one\n * per-product funnel.\n */\n view_item: { items: AnalyticsItem[] }\n /**\n * GA4 recommended. A storefront product was added to the cart.\n *\n * `currency`/`value` are optional because GA4 pairs them — a `value` with no\n * `currency` is dropped by GA — so they travel together or not at all, and\n * {@link buildAddToCartParams} is what keeps that true. They are populated\n * wherever the surface holds a server-priced figure: the product detail\n * block knows the resolved variant's price and the chosen quantity, so the\n * merchant's \"value added to cart\" is a real number rather than the empty\n * column an items-only hit produces.\n */\n add_to_cart: { currency?: string; value?: number; items: AnalyticsItem[] }\n /**\n * GA4 recommended. The shopper looked at their cart — the funnel step\n * between {@link AnalyticsEventParams.add_to_cart} and\n * {@link AnalyticsEventParams.begin_checkout}, and the one GA4's own\n * shopping-behavior report reads to tell \"never opened the cart\" apart from\n * \"opened it and did not check out\". Without it those two collapse into one\n * drop, and the merchant cannot tell a discovery problem from a pricing one.\n *\n * Fired when the cart is actually ON SCREEN carrying lines — a drawer that\n * opened, or an inline cart block that resolved — never on the badge render\n * that every page of a storefront performs. An empty cart is not a view of\n * anything and reports nothing.\n */\n view_cart: { currency: string; value: number; items: AnalyticsItem[] }\n\n // --- Engagement ---------------------------------------------------------\n /**\n * Custom: no GA4 equivalent. An announcement bar or popup was shown,\n * dismissed or clicked on a tenant site (AGL-200/271).\n *\n * In the taxonomy rather than {@link trackAuthoredEvent} even though it is\n * not a GA4 recommended name: the name and every key here are written by US,\n * which is exactly what the closed union is for. See the note on\n * {@link trackAuthoredEvent} for why the two must not be mixed.\n */\n aglyn_overlay: { overlay_action: string; overlay_id?: string }\n /**\n * Custom: no GA4 equivalent. An experiment exposure or conversion\n * (AGL-253). `experiment_action` is `exposure` | `conversion`.\n *\n * Being in the union also makes the name RESERVED against authored events,\n * which matters more here than anywhere else in this file: these are the\n * counts that decide which variant wins, and a hand-authored\n * `aglyn_experiment` step would silently vote in that election.\n */\n aglyn_experiment: {\n experiment_id: string\n variant_id: string\n experiment_action: string\n }\n /**\n * GA4 recommended-ish. Outbound click to docs, GitHub, etc. Fired by\n * `analytics-link-clicks.ts` (AGL-1562) rather than at a call site.\n */\n click: {\n link_domain: string\n link_id?: string\n /**\n * Which product surface produced the click. GA's built-in Hostname\n * dimension already separates the DOMAINS; this separates surfaces that\n * could share one, and keeps the shared click listener from having to\n * know anything about either.\n *\n * `site` — a tenant published site — is the only value ever SENT. `docs`\n * was designed for (AGL-1579) and is not emitted: `apps/docs` cannot\n * import `libs/`, so this listener is not installed there\n * (docs/ANALYTICS.md decision 7 has the Vercel setting that would change\n * that). Registering `surface` as a dimension and reading a one-value\n * breakdown is the trap — the absent `docs` row means \"no listener\", not\n * \"no clicks\".\n */\n surface?: string\n }\n /**\n * Custom: no GA4 equivalent. One Aglyn Assist message sent (AGL-1860).\n * `tier` is the capability tier served (`free` | `entitled`);\n * `grounded` says whether docs retrieval found sections to cite —\n * ungrounded questions at volume are the docs-gap signal the data loop\n * mines. No question text: params carry no user content.\n */\n assistant_message_sent: { tier: string; grounded: boolean }\n /**\n * Custom: no GA4 equivalent. Explicit thumbs on an Assist answer\n * (AGL-1860). `feedback` is `up` | `down`.\n */\n assistant_feedback: { feedback: string }\n /**\n * Custom: no GA4 equivalent. Aglyn Assist offered to open a page for the\n * user (AGL-1988, level 2). `action` is the registry action id — a closed\n * set, so it carries no user content.\n *\n * The pair below is the only read on whether the confirm gate is a real\n * choice or a speed bump people click through. A shown-to-confirmed ratio\n * near 1 means the card is not being read, and the copy has to change\n * BEFORE the ladder goes anywhere near a write.\n */\n assistant_proposal_shown: { action: string }\n /** Custom: no GA4 equivalent. The user confirmed and was navigated. */\n assistant_proposal_confirmed: { action: string }\n /**\n * Custom: no GA4 equivalent. An AI generation job reached `done`\n * (AGL-2904), observed from the console's jobs drawer. `kind` is the\n * closed `AiJobKind` set and `credits` the job's spend at the plan's\n * credit rate — no brief, no output: params carry no user content.\n */\n ai_job_completed: { kind: string; credits: number }\n /**\n * Custom: no GA4 equivalent. An AI generation job reached `failed`\n * (AGL-2904). `kind` only; the failure text is a fixed customer-safe\n * sentence and says nothing a rate could use.\n */\n ai_job_failed: { kind: string }\n\n // --- Retention (AGL-1859/AGL-1863: the leave path, measurable) -----------\n /**\n * Custom: no GA4 equivalent. The churn survey was answered — step 1 of the\n * cancellation/deletion funnel, and the DENOMINATOR every step below is a\n * rate against. Fired for both leave paths.\n *\n * `reason` is the closed `ChurnSurveyReason` set, never the free-text\n * detail: the detail is customer-written prose, it belongs in Firestore\n * where the data loop reads it, and shipping it to GA would put user\n * content in analytics params. `surface` separates a subscription cancel\n * from an account delete — counting only one understates churn by exactly\n * the orgs that chose the other.\n */\n churn_survey_submitted: { reason: string; surface: string; plan?: string }\n /**\n * Custom: no GA4 equivalent. The customer took the smaller tier instead of\n * leaving — a SAVE, at reduced ARPA. `from_plan`/`to_plan` are what makes\n * that tradeoff measurable rather than a win recorded without its cost.\n */\n downsell_accepted: { from_plan: string; to_plan: string; surface: string }\n /**\n * Custom: no GA4 equivalent. The time-boxed winback discount was accepted.\n *\n * `percent_off` and `duration_months` are reported because the discount is\n * bounded and the bound is the entire point (AGL-1620/AGL-1863): a retained\n * org and the margin it was retained at are one fact, and a save recorded\n * without its price reads as free.\n */\n winback_discount_accepted: {\n percent_off: number\n duration_months: number\n plan?: string\n surface: string\n }\n /**\n * Custom: no GA4 equivalent. They left anyway — the funnel's terminal step,\n * and the numerator for churn.\n *\n * `funnel_completed` is false when the cancel arrived without a funnelId\n * (support ops, Stripe dashboard). It mirrors the `funnelSkipped` marker\n * the routes write, so the GA funnel and the Firestore record agree instead\n * of quietly disagreeing about how many departures were ever surveyed.\n */\n cancellation_completed: {\n surface: string\n plan?: string\n funnel_completed: boolean\n }\n\n // --- Plan changes taken from the grid (AGL-2235, under AGL-1859 §4) ------\n /**\n * Custom: no GA4 equivalent. A downgrade was confirmed and SCHEDULED from\n * the billing plan grid — the same economic event `downsell_accepted`\n * records, arrived at by the other door.\n *\n * Why this has to exist separately: all four retention events above fire\n * from `retention-funnel.dialog.tsx` and from nowhere else. A customer who\n * moves Pro → Starter through the cancel funnel is counted; a customer who\n * moves Pro → Starter by clicking Downgrade on the plan card was counted by\n * nothing. So \"how many orgs moved down\" was unanswerable, and the number\n * that WAS answerable — `downsell_accepted` — undercounted by exactly the\n * share that took the direct route while reading like a total. A save rate\n * computed against it is wrong in the flattering direction, which is the\n * worst direction for a retention number to be wrong in.\n *\n * `effective_at` is the whole point of the event's name: this is the\n * asymmetric-friction arm of AGL-1859 §2, and a downgrade that has been\n * SCHEDULED is not a downgrade that has HAPPENED. Reported as the server's\n * ISO date so the gap between decision and effect — up to a full cycle, and\n * the window in which \"keep my plan\" can still save the org — is visible in\n * the data instead of being collapsed into the decision day.\n *\n * No amount, price or fee: pricing is locked for Sept 1, money belongs to\n * `purchase`/`refund`, and a tier pair already says what changed.\n */\n plan_downgrade_scheduled: {\n from_plan: string\n to_plan: string\n interval: string\n effective_at?: string\n }\n /**\n * Custom: no GA4 equivalent. An existing subscriber moved UP in place.\n *\n * Not `app_upgrade` — that name is GA4-RESERVED (it means an app binary\n * version bump) and a hit using it is dropped, which is silence rather than\n * pollution and therefore the harder failure to notice.\n *\n * `purchase` covers only the Checkout path, so before this, expansion\n * revenue from customers who ALREADY had a subscription was dark: the\n * in-place switch never opens a Checkout and never mints a new\n * subscription, so nothing in the revenue taxonomy saw it. Upgrades are the\n * half of AGL-1859 §2 that is supposed to be frictionless, and an\n * unmeasured half cannot be shown to be.\n */\n plan_upgraded: {\n from_plan: string\n to_plan: string\n interval: string\n }\n}\n\nexport type AnalyticsEventName = keyof AnalyticsEventParams\n\n/**\n * Where a sanitized event goes. The console registers a Firebase\n * `logEvent` transport; the tenant runtime and the plugin bundles have none\n * and fall through to `window.gtag`, which only exists once consent has been\n * granted.\n */\nexport type AnalyticsTransport = (\n name: AnalyticsEventName,\n params: Record<string, unknown>,\n) => void | Promise<void>\n\nlet configuredTransport: AnalyticsTransport | null = null\n\n/**\n * Register the transport for this surface. The console calls this once, with\n * Firebase's `logEvent`, because the console's GA is Firebase-initialised and\n * its `user_id`/user-property state lives on the Firebase Analytics instance —\n * poking `window.gtag` directly there would emit hits that miss it.\n *\n * The tenant runtime deliberately does NOT call this: the plugin bundles run\n * in their own realm and do not share this module instance with the host app,\n * so a module-scope singleton would be invisible to exactly the call sites\n * that need it (the form and newsletter elements). `window.gtag` is the only\n * thing genuinely shared across that boundary, and it is also the consent\n * gate, which makes the fallback the correct primary path there rather than a\n * degraded one.\n */\nexport function configureAnalyticsTransport(\n transport: AnalyticsTransport | null,\n): void {\n configuredTransport = transport\n}\n\n/** Test seam — drops the registered transport. */\nexport function resetAnalyticsTransport(): void {\n configuredTransport = null\n}\n\n/**\n * Param keys that must never reach GA, matched EXACTLY. Substring matching\n * would be wrong in both directions: it would drop the legitimate\n * `form_name` / `item_name` / `link_domain`, and it would still miss a\n * creatively-named new one. The value scan below is the backstop for those.\n */\nconst DENIED_PARAM_KEYS: ReadonlySet<string> = new Set([\n 'email',\n 'email_address',\n 'user_email',\n 'name',\n 'full_name',\n 'first_name',\n 'last_name',\n 'user_name',\n 'username',\n 'customer_name',\n 'org_name',\n 'organization_name',\n 'company',\n 'company_name',\n 'phone',\n 'phone_number',\n 'address',\n 'street',\n 'postal_code',\n 'zip',\n 'ip',\n 'ip_address',\n])\n\n/** Deliberately loose — this is a \"does it smell like an address\" test. */\nconst EMAIL_SHAPED = /[^\\s@]+@[^\\s@]+\\.[^\\s@]+/\n\n/**\n * GA4 truncates param values at 100 chars anyway; do it ourselves, visibly.\n *\n * Exported because an AUTHOR types some of these (the `trackGaEvent` step's\n * parameters), and the field they type into caps its input at the same number\n * — the truncation point and the affordance that describes it have to be one\n * value, or the editor promises a length the delivery quietly shortens.\n */\nexport const ANALYTICS_PARAM_MAX_LENGTH = 100\n\nfunction scrubValue(value: string): string | null {\n let candidate = value\n if (/^https?:\\/\\//i.test(candidate)) {\n try {\n const url = new URL(candidate)\n // Origin + pathname only: a query string is where a session token, a\n // signup email or a Stripe id ends up, and none of them belong in GA.\n candidate = `${url.origin}${url.pathname}`\n } catch {\n return null\n }\n }\n // AFTER the URL reduction, not before. A page URL routinely carries an\n // address in its query (`?email=…` on a prefilled signup link), and testing\n // the raw string would throw the whole URL away for PII that the reduction\n // was about to remove — losing the legitimate page dimension to protect\n // something already protected. Testing the REDUCED value still catches an\n // address embedded in the path itself, which the reduction keeps.\n if (EMAIL_SHAPED.test(candidate)) return null\n return candidate.slice(0, ANALYTICS_PARAM_MAX_LENGTH)\n}\n\n/**\n * Strip anything identity-bearing from an event payload. Exported so\n * `analytics-events.spec.ts` can assert the guarantee directly rather than\n * only through `trackEvent`.\n */\nexport function sanitizeEventParams(\n params: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n const safe: Record<string, unknown> = {}\n if (!params) return safe\n for (const [key, value] of Object.entries(params)) {\n if (DENIED_PARAM_KEYS.has(key.toLowerCase())) continue\n if (value === undefined || value === null) continue\n if (typeof value === 'string') {\n const scrubbed = scrubValue(value)\n if (scrubbed === null || scrubbed === '') continue\n safe[key] = scrubbed\n continue\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n safe[key] = value\n continue\n }\n if (Array.isArray(value)) {\n // `items` — sanitize each entry with the same rules.\n safe[key] = value.map((entry) =>\n entry && typeof entry === 'object'\n ? sanitizeEventParams(entry as Record<string, unknown>)\n : entry,\n )\n continue\n }\n if (typeof value === 'object') {\n safe[key] = sanitizeEventParams(value as Record<string, unknown>)\n }\n // Anything else (function, symbol) is dropped.\n }\n return safe\n}\n\n/**\n * Fire a GA4 event.\n *\n * Never throws and never queues. If the surface has no transport and no\n * `window.gtag` — which on a tenant site means the visitor has not granted\n * analytics consent — the event is DROPPED, permanently. See the module\n * comment for why a queue would be the wrong answer.\n */\nexport function trackEvent<K extends AnalyticsEventName>(\n name: K,\n params: AnalyticsEventParams[K],\n): void {\n deliver(name, sanitizeEventParams(params as Record<string, unknown>))\n}\n\n/**\n * How long a navigation may be held waiting for a hit to reach gtag. Short\n * enough to be invisible next to a Stripe redirect, long enough to cover a\n * Firebase Analytics init that has not settled yet.\n */\nconst NAVIGATION_FLUSH_TIMEOUT_MS = 300\n\n/**\n * Fire a GA4 event and resolve once it has been HANDED TO gtag — for the call\n * sites that navigate away in the same tick (AGL-1580).\n *\n * ## What was actually losing the event\n *\n * Not the transport, which was the obvious suspect and the wrong one. Measured\n * against real gtag.js with every transport interposed: gtag flushes its queue\n * on pagehide through `fetch(..., { keepalive: true })`, which is precisely the\n * mechanism that survives a document teardown. Once a hit reaches gtag, a\n * navigation does not destroy it — and `transport_type: 'beacon'`, the standard\n * answer, therefore fixes nothing here.\n *\n * What is lost is the hit that never REACHES gtag. Firebase's `logEvent` is\n * `async` and awaits the SDK's initialization promise before calling gtag\n * (`@firebase/analytics/dist/index.cjs.js`, `logEvent$1`). While that promise is\n * already settled the continuation is a microtask, microtasks drain before the\n * queued navigation task, and the hit gets out. While it is still PENDING — the\n * first checkout of a fresh session, exactly the case that has never yet been\n * seen in the property — the continuation is scheduled behind the navigation\n * and never runs at all. Measured both ways: pending init loses the event,\n * awaiting it delivers it, nothing else changed.\n *\n * ## Why a timeout rather than a bare await\n *\n * A bare `await` on `logEvent` hands the user's redirect to the analytics\n * stack. When the analytics host is blocked — an ad blocker, a corporate proxy,\n * a consent tool that never loads — Firebase's initialization promise can stay\n * pending indefinitely, and the checkout would hang on a metric. So the wait is\n * RACED against {@link NAVIGATION_FLUSH_TIMEOUT_MS}: a blocked analytics stack\n * costs the redirect 300ms once and then it proceeds, which is the same outcome\n * the caller had before this existed. Never rejects, for the same reason\n * {@link trackEvent} never throws.\n *\n * On a surface with no registered transport — the tenant runtime and the plugin\n * bundles, which go straight to `window.gtag` — delivery is synchronous, so\n * this resolves immediately and costs the storefront checkout nothing at all.\n */\nexport async function trackEventBeforeNavigation<K extends AnalyticsEventName>(\n name: K,\n params: AnalyticsEventParams[K],\n): Promise<void> {\n const delivered = deliver(\n name,\n sanitizeEventParams(params as Record<string, unknown>),\n )\n // Synchronous transport (or none): already handed over, nothing to wait for.\n if (!delivered || typeof delivered.then !== 'function') return\n await Promise.race([\n // A transport that REJECTS must not become an unhandled rejection, and\n // must not hold the navigation either — it has already failed.\n Promise.resolve(delivered).catch((): void => undefined),\n new Promise<void>((resolve) =>\n setTimeout(resolve, NAVIGATION_FLUSH_TIMEOUT_MS),\n ),\n ])\n}\n\n/**\n * Build the ONE `begin_checkout` payload, for every surface that starts a\n * checkout (AGL-1591).\n *\n * ## Why a constructor and not just the type\n *\n * Two surfaces fire this name: the console, when a plan checkout starts, and a\n * tenant storefront, when a cart checks out. Until AGL-1591 the storefront\n * fired it raw and carried `value`/`currency` only, so ONE event name arrived\n * in two shapes — and a `begin_checkout` breakdown showed two populations that\n * could not be compared, with the storefront half missing the `items` the GA4\n * ecommerce funnel is built on. Routing both through {@link trackEvent} makes\n * the compiler settle the KEYS.\n *\n * It does not settle the NUMBER, which is the other way two call sites of one\n * event diverge, and the more dangerous one because nothing about it looks\n * wrong: the console's annual plans are priced per-month-billed-yearly, so its\n * `value` is twelve of them, and that only stayed right because a comment said\n * so. Here `value` DERIVES from the items unless a caller states a different\n * one — a cart states its subtotal, which is authoritative after discounts —\n * so \"what the customer is about to be charged\" has one definition rather than\n * one per surface.\n *\n * Server-safe: pure, no DOM, so the Measurement Protocol sender can compose\n * the matching `purchase` items from the same shapes.\n */\nexport function buildBeginCheckoutParams(input: {\n items: AnalyticsItem[]\n /**\n * The amount actually being charged. Defaults to the sum of the items'\n * `price * quantity`, which is right whenever nothing has adjusted it.\n */\n value?: number\n /** ISO 4217. Defaults to `USD`, the only currency either surface bills in. */\n currency?: string\n /** `monthly` | `annual`. Subscriptions only — a storefront cart has none. */\n billingInterval?: string\n}): AnalyticsEventParams['begin_checkout'] {\n return {\n ...priceItems(input),\n ...(input.billingInterval ? { billing_interval: input.billingInterval } : {}),\n }\n}\n\n/**\n * The `currency`/`value`/`items` triple every GA4 ecommerce step shares.\n *\n * Private, because a caller should reach for the named builder for the event\n * it is about to send: the names differ in what they mean by `value` even\n * though the arithmetic is identical, and the JSDoc on each is where that is\n * written down.\n */\nfunction priceItems(input: {\n items: AnalyticsItem[]\n value?: number\n currency?: string\n}): { currency: string; value: number; items: AnalyticsItem[] } {\n const items = input.items ?? []\n const summed = items.reduce(\n (total, item) => total + (item.price ?? 0) * (item.quantity ?? 1),\n 0,\n )\n return {\n currency: input.currency ?? 'USD',\n // Money, so two decimals: a float sum of cents-derived prices produces\n // `59.99999999999999`, and GA would report that verbatim.\n value: Math.round((input.value ?? summed) * 100) / 100,\n items,\n }\n}\n\n/**\n * Build `view_cart` — the shopper is looking at the cart's contents.\n *\n * `value` is the cart's subtotal as the SERVER priced it, which is what makes\n * this comparable with the `begin_checkout` the same cart sends moments later:\n * two steps of one funnel that disagreed about the size of the same cart would\n * read as shoppers editing it between screens.\n */\nexport function buildViewCartParams(input: {\n items: AnalyticsItem[]\n value?: number\n currency?: string\n}): AnalyticsEventParams['view_cart'] {\n return priceItems(input)\n}\n\n/**\n * Build `add_to_cart` — one product going in, not the cart's new total.\n *\n * `value` is what was JUST ADDED (`price * quantity`), which is GA4's\n * definition and the only one that makes the metric additive: summing a\n * running cart total over a session would count the first item once per\n * subsequent add.\n *\n * Callers that cannot price the line — a quick-add with no resolved variant —\n * pass items alone and the pair is omitted rather than reported as zero. A\n * zero here would read as a free product in the merchant's report.\n */\nexport function buildAddToCartParams(input: {\n items: AnalyticsItem[]\n value?: number\n currency?: string\n}): AnalyticsEventParams['add_to_cart'] {\n const priced = priceItems(input)\n if (!(priced.value > 0)) return { items: priced.items }\n return priced\n}\n\n/**\n * Decide `site_published`'s `first_publish` from the host's routing map as it\n * stood BEFORE the route being published was registered (AGL-1588).\n *\n * ## What \"first\" means, and why it is defined once\n *\n * Three call sites report `site_published` — `publishScreenRoute`, the\n * besigner's one-click publish, and the scheduled publish executor, the last\n * of which is server-side and sends over the Measurement Protocol. A\n * breakdown is only worth registering if all three mean the same thing by it,\n * and \"first\" has several plausible readings. This is the one they share:\n *\n * **The host had no live route at all before this one.** Not \"first for the\n * org\" — that needs a cross-host query the server path cannot make, and the\n * scheduled sender's client id is derived from the HOST anyway, so an org is\n * not a thing it can see. Not \"first for this screen\" either, which would be\n * true of every second page a site adds and would make the dimension a\n * synonym for the event.\n *\n * So the metric it separates is the GTM §6 activation one: `first_publish:\n * true` counts sites that came alive, where the event alone counts publishes.\n *\n * ## The one dishonesty, and why it does not matter\n *\n * Unpublishing every route and publishing again reports `true` a second time.\n * Detecting that needs publish history the routing map does not keep. It is\n * harmless for the metric it exists for, because activation is read as the\n * share of USERS who ever sent `first_publish: true`, and a user counted twice\n * is still one user.\n *\n * Callers pass what they already hold — the live-subscribed map in the\n * console, a read snapshot on the server — and never a map read back AFTER\n * the write, which is never empty.\n *\n * ## The placeholder home page is not a publish (AGL-3408)\n *\n * Every new site is created with a home page already routed at `/`, so read\n * literally the map is never empty and no site would ever report a first\n * publish. The host's `defaultHomeScreenId` names that placeholder, and its\n * entry is not counted: the site \"came alive\" when its owner put something on\n * it, not when the platform did. Republishing the placeholder itself after\n * editing it counts, which is the same act.\n */\nexport function isFirstPublishedRoute(\n routing: Record<string, unknown> | null | undefined,\n defaultHomeScreenId?: string | null,\n): boolean {\n return !Object.keys(routing ?? {}).some(\n (screenId) => screenId !== defaultHomeScreenId,\n )\n}\n\n/**\n * The one delivery path, shared by {@link trackEvent} and\n * {@link trackAuthoredEvent}. Takes an ALREADY-sanitized payload — every\n * caller sanitizes first, which is what keeps \"a new call site cannot forget\"\n * true of the authored path too.\n */\nfunction deliver(\n name: string,\n safe: Record<string, unknown>,\n): void | Promise<void> {\n try {\n if (configuredTransport) {\n // The transport's name parameter is the taxonomy union, which an\n // authored name is by definition outside. Nominal only: the console is\n // the sole surface that registers one and it has no authored events\n // (the interaction runtime is tenant-side), and Firebase `logEvent`\n // takes an arbitrary string regardless.\n // Returned, not discarded (AGL-1580). A transport may be ASYNC —\n // Firebase's `logEvent` awaits the SDK's initialization promise before it\n // reaches gtag at all — and a caller that is about to navigate has to be\n // able to wait for it. See `trackEventBeforeNavigation`.\n return configuredTransport(name as AnalyticsEventName, safe)\n }\n if (typeof window === 'undefined') return\n const gtag = (window as unknown as { gtag?: unknown }).gtag\n if (typeof gtag !== 'function') return\n // Synchronous, so nothing is returned and nothing needs awaiting: by the\n // time this call has returned, gtag.js already holds the hit.\n ;(gtag as (...args: unknown[]) => void)('event', name, safe)\n } catch {\n // Analytics never breaks the page — the same posture as the error beacon\n // and the pageview beacon.\n }\n}\n\n/**\n * The taxonomy's names at RUN time. A `Record<AnalyticsEventName, true>` rather\n * than a hand-kept array so the compiler enforces both directions: adding an\n * event to {@link AnalyticsEventParams} without adding it here is a missing-key\n * error, and a name here that is not in the taxonomy is an excess-property one.\n *\n * It exists for {@link trackAuthoredEvent}, which has to refuse these names —\n * a drifting copy would silently re-open the collision it is here to close.\n */\nconst TAXONOMY_EVENT_NAMES: Record<AnalyticsEventName, true> = {\n sign_up: true,\n login: true,\n generate_lead: true,\n select_content: true,\n org_created: true,\n host_created: true,\n site_published: true,\n stripe_connected: true,\n begin_checkout: true,\n purchase: true,\n view_item: true,\n add_to_cart: true,\n view_cart: true,\n aglyn_overlay: true,\n aglyn_experiment: true,\n click: true,\n assistant_message_sent: true,\n assistant_feedback: true,\n assistant_proposal_shown: true,\n assistant_proposal_confirmed: true,\n ai_job_completed: true,\n ai_job_failed: true,\n churn_survey_submitted: true,\n downsell_accepted: true,\n winback_discount_accepted: true,\n cancellation_completed: true,\n plan_downgrade_scheduled: true,\n plan_upgraded: true,\n}\n\n/** The taxonomy, enumerable. */\nexport const ANALYTICS_EVENT_NAMES = Object.keys(\n TAXONOMY_EVENT_NAMES,\n) as AnalyticsEventName[]\n\n/**\n * Event names WE send that this module's union cannot hold, because nothing\n * client-side ever fires them: they are emitted only by the Measurement\n * Protocol sender (`ga4-measurement-protocol.ts`), from a Stripe webhook.\n *\n * They still have to be RESERVED against authored names, and the reason is\n * the same one that puts `purchase` in the union — only less obvious, which\n * is why it was missed. `aglyn.com` is itself a tenant site, pointed at the\n * platform measurement id (`site-analytics.tsx`), so an authored\n * `trackGaEvent` step on our own marketing site lands in the SAME property as\n * these server hits. An authored `refund` does not merely add noise: GA4\n * treats `refund` as ecommerce and SUBTRACTS its `value` from reported\n * revenue, so a mistyped step could walk real money out of the report — the\n * `purchase` hazard, running in the direction nobody audits.\n *\n * Kept as a separate list rather than folded into {@link AnalyticsEventParams}\n * on purpose: adding them to the union would give {@link trackEvent} a\n * client-side door to events that must only ever come from the server, where\n * the authoritative money is. A name here is ours, is never sent from a\n * browser, and is never available to an author.\n *\n * This list is the reason \"not in {@link ANALYTICS_EVENT_NAMES}\" is NOT on its\n * own a sound test for \"authored\" — use {@link isReservedAnalyticsEventName}.\n */\nconst SERVER_ONLY_EVENT_NAMES: ReadonlySet<string> = new Set([\n 'refund',\n 'subscription_cancelled',\n])\n\n/**\n * Every event name Aglyn itself sends, from any surface — the union plus the\n * server-only names above. Exported so a caller can ask the question the two\n * separate lists no longer answer alone.\n */\nexport function isReservedAnalyticsEventName(name: string): boolean {\n return (\n TAXONOMY_EVENT_NAMES[name as AnalyticsEventName] === true ||\n SERVER_ONLY_EVENT_NAMES.has(name)\n )\n}\n\n/**\n * GA4's own reserved event names — GA drops a hit that uses one, so sending it\n * is not pollution but silence, which is the worse failure of the two because\n * nothing anywhere says so.\n */\nconst GA4_RESERVED_EVENT_NAMES: ReadonlySet<string> = new Set([\n 'ad_activeview',\n 'ad_click',\n 'ad_exposure',\n 'ad_impression',\n 'ad_query',\n 'ad_reward',\n 'adunit_exposure',\n 'app_background',\n 'app_clear_data',\n 'app_exception',\n 'app_install',\n 'app_remove',\n 'app_store_refund',\n 'app_store_subscription_cancel',\n 'app_store_subscription_convert',\n 'app_store_subscription_renew',\n 'app_update',\n 'app_upgrade',\n 'dynamic_link_app_open',\n 'dynamic_link_app_update',\n 'dynamic_link_first_open',\n 'error',\n 'first_open',\n 'first_visit',\n 'in_app_purchase',\n 'notification_dismiss',\n 'notification_foreground',\n 'notification_open',\n 'notification_receive',\n 'os_update',\n 'screen_view',\n 'session_start',\n 'user_engagement',\n])\n\n/** GA4 reserves these prefixes outright, whatever follows them. */\nconst GA4_RESERVED_PREFIXES = ['firebase_', 'google_', 'ga_'] as const\n\n/** GA4's hard limit on an event name. Over it, GA drops the event. */\nconst MAX_EVENT_NAME_LENGTH = 40\n\n/**\n * The outcome of putting an authored name through GA4's rules, so the\n * interaction builder can say WHY it refused a name and the runtime can drop\n * the event for the same reason.\n */\nexport interface ResolvedAuthoredEventName {\n /** The name to send, or null when the event must not be sent at all. */\n name: string | null\n /**\n * `reserved` — collides with the taxonomy or with GA4's own names.\n * `unusable` — nothing survives normalization (empty, or no leading letter).\n */\n reason?: 'reserved' | 'unusable'\n}\n\n/**\n * Put an authored event name through GA4's naming rules and our own.\n *\n * Normalization is forgiving on purpose: `\"CTA Click!\"` becomes `cta_click`\n * and still reports, where GA would have dropped it. Names already sitting in\n * published sites were never validated, so refusing them outright would delete\n * working metrics from a paying customer's property to fix a formatting nit.\n *\n * Collisions, in contrast, are refused rather than rewritten. On a tenant site\n * the authored events and OUR events (`generate_lead` from the form element,\n * `select_content`/`click` from the link listener) land in the same property,\n * so an authored `purchase` does not merely add noise — it mixes hand-authored\n * hits into a real revenue number. Refusing is also what keeps authored events\n * separable in reports: an event that is not one of {@link ANALYTICS_EVENT_NAMES}\n * is, by construction, authored.\n *\n * Deliberately NOT prefixed (`site_*`) to achieve that separation. A prefix\n * would rename events already flowing into customers' properties and break\n * every report and key-event conversion configured on the old name — a\n * migration cost paid by people who did nothing wrong.\n */\nexport function resolveAuthoredEventName(\n raw: string | undefined | null,\n): ResolvedAuthoredEventName {\n const normalized = String(raw ?? '')\n .trim()\n .toLowerCase()\n // Anything GA4 does not allow in a name becomes an underscore...\n .replace(/[^a-z0-9_]+/g, '_')\n // ...and a name must START with a letter, so drop what precedes one.\n .replace(/^[^a-z]+/, '')\n .replace(/_{2,}/g, '_')\n .slice(0, MAX_EVENT_NAME_LENGTH)\n // Truncation can leave a trailing underscore; so can the substitution.\n .replace(/_+$/, '')\n if (!normalized) return { name: null, reason: 'unusable' }\n if (\n isReservedAnalyticsEventName(normalized) ||\n GA4_RESERVED_EVENT_NAMES.has(normalized) ||\n GA4_RESERVED_PREFIXES.some((prefix) => normalized.startsWith(prefix))\n ) {\n return { name: null, reason: 'reserved' }\n }\n return { name: normalized }\n}\n\n/** One warning per distinct name per page load — an `everyTime` automation\n * would otherwise fill the console with the same line. */\nconst warnedAuthoredNames = new Set<string>()\n\n/**\n * Fire an event whose name and params were written by a SITE AUTHOR, not by a\n * developer — today only the `trackGaEvent` action step (AGL-1587).\n *\n * Same consent gate, same sanitizer, same drop-never-queue posture as\n * {@link trackEvent}; the only difference is that the name is checked at run\n * time instead of by the compiler, because there is no compiler between the\n * interaction builder and here.\n *\n * A refused event is dropped and warned about in the console rather than\n * surfaced in the page. Nothing here can reach the author — the code is\n * running for a VISITOR of their site, and turning the author's configuration\n * mistake into something a visitor sees would be a worse bug than the missing\n * metric. The author-facing half lives in `validateHostAction`, which refuses\n * to save a name this function would refuse to send, so a silent drop should\n * only ever happen to a step authored before AGL-1587.\n */\nexport function trackAuthoredEvent(\n name: string | undefined | null,\n params?: Record<string, unknown> | null,\n): void {\n const resolved = resolveAuthoredEventName(name)\n if (!resolved.name) {\n const key = String(name ?? '')\n if (!warnedAuthoredNames.has(key)) {\n warnedAuthoredNames.add(key)\n try {\n console.warn(\n `[aglyn] analytics: the event \"${key}\" was not sent — ` +\n (resolved.reason === 'reserved'\n ? 'that name is reserved. Rename the step in the interaction builder.'\n : 'an event name must start with a letter.'),\n )\n } catch {\n // A console that throws is still not worth breaking the page for.\n }\n }\n return\n }\n deliver(resolved.name, sanitizeEventParams(params ?? undefined))\n}\n\n/** Test seam — forgets which authored names have already been warned about. */\nexport function resetAuthoredEventWarnings(): void {\n warnedAuthoredNames.clear()\n}\n"],"names":["readGaClientId","measurementId","Promise","resolve","window","gtag","settled","finish","value","setTimeout","id","configuredTransport","configureAnalyticsTransport","transport","resetAnalyticsTransport","DENIED_PARAM_KEYS","Set","EMAIL_SHAPED","ANALYTICS_PARAM_MAX_LENGTH","scrubValue","candidate","test","url","URL","origin","pathname","slice","sanitizeEventParams","params","safe","key","Object","entries","has","toLowerCase","undefined","scrubbed","Array","isArray","map","entry","trackEvent","name","deliver","NAVIGATION_FLUSH_TIMEOUT_MS","trackEventBeforeNavigation","delivered","then","race","catch","buildBeginCheckoutParams","input","priceItems","billingInterval","billing_interval","items","summed","reduce","total","item","price","quantity","currency","Math","round","buildViewCartParams","buildAddToCartParams","priced","isFirstPublishedRoute","routing","defaultHomeScreenId","keys","some","screenId","TAXONOMY_EVENT_NAMES","sign_up","login","generate_lead","select_content","org_created","host_created","site_published","stripe_connected","begin_checkout","purchase","view_item","add_to_cart","view_cart","aglyn_overlay","aglyn_experiment","click","assistant_message_sent","assistant_feedback","assistant_proposal_shown","assistant_proposal_confirmed","ai_job_completed","ai_job_failed","churn_survey_submitted","downsell_accepted","winback_discount_accepted","cancellation_completed","plan_downgrade_scheduled","plan_upgraded","ANALYTICS_EVENT_NAMES","SERVER_ONLY_EVENT_NAMES","isReservedAnalyticsEventName","GA4_RESERVED_EVENT_NAMES","GA4_RESERVED_PREFIXES","MAX_EVENT_NAME_LENGTH","resolveAuthoredEventName","raw","normalized","String","trim","replace","reason","prefix","startsWith","warnedAuthoredNames","trackAuthoredEvent","resolved","add","console","warn","resetAuthoredEventWarnings","clear"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmFC,GAED;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASA,eACdC,aAAwC;IAExC,OAAO,IAAIC,QAAQ,CAACC;QAClB,IAAI,OAAOC,WAAW,eAAe,CAACH,eAAe,OAAOE,QAAQ;QACpE,MAAME,OAAO,AAACD,OAAyCC,IAAI;QAC3D,IAAI,OAAOA,SAAS,YAAY,OAAOF,QAAQ;QAC/C,IAAIG,UAAU;QACd,MAAMC,SAAS,CAACC;YACd,IAAIF,SAAS;YACbA,UAAU;YACVH,QAAQK;QACV;QACA,oDAAoD;QACpDC,WAAW,IAAMF,OAAO,OAAO;QAC/B,IAAI;;YACAF,KACA,OACAJ,eACA,aACA,CAACS,KAAgBH,OAAO,OAAOG,OAAO,YAAYA,KAAKA,KAAK;QAEhE,EAAE,eAAM;YACNH,OAAO;QACT;IACF;AACF;AAgXA,IAAII,sBAAiD;AAErD;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,4BACdC,SAAoC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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 * The one GA4 event taxonomy, shared by the marketing site (tenant runtime)\n * and the console (AGL-1561). See `docs/ANALYTICS.md` for the event map and\n * which GTM-plan §6 metric each event serves.\n *\n * ## Why this module exists\n *\n * Before it, every GA event in the repo was an ad-hoc\n * `;(window as any).gtag?.('event', 'name', {...})` — five of them across the\n * marketing and commerce plugins, plus bare string literals passed to Firebase\n * `logEvent` in the console. Nothing checked the names, nothing checked the\n * params, and a typo produced a silently-missing metric rather than an error.\n * That is the failure mode analytics is worst at surfacing: the number simply\n * reads zero, and zero is indistinguishable from \"nobody did it\".\n *\n * So the names and their params are a TYPE here ({@link AnalyticsEventParams}),\n * and `trackEvent` is generic over it: a misspelled event name or a missing\n * required param is a compile error.\n *\n * That sweep missed five (AGL-1591, closed): the commerce plugin's\n * `view_item` / `add_to_cart` / `begin_checkout` and the marketing runtime's\n * `aglyn_overlay` / `aglyn_experiment`. `window.gtag` is now called in exactly\n * two places in the repo — {@link deliver} below, and `readGaClientId` above,\n * which reads rather than sends.\n *\n * ## Reserved names\n *\n * Where GA4 has a recommended event we use its exact name and its exact param\n * spelling — `sign_up`, `login`, `generate_lead`, `begin_checkout`,\n * `purchase`, `select_content` — so the built-in reports, the funnel\n * explorations and the \"key events\" toggles work without custom definitions.\n * Custom snake_case names appear only where GA4 has no standard: the four\n * activation events, which are Aglyn-specific product milestones.\n *\n * ## Consent (AGL-1498) — the gate is that gtag never loads\n *\n * On tenant sites, including aglyn.com itself, `site-analytics.tsx` renders the\n * gtag `<Script>` pair ONLY when the recorded consent state grants analytics.\n * There is therefore no `window.gtag` at all for a visitor who has not granted,\n * and {@link trackEvent} drops the event on the floor.\n *\n * It drops it — it does not QUEUE it. That distinction is the whole point and\n * `analytics-events.spec.ts` asserts it: an event fired before consent is gone\n * for good, and does not reappear when a later grant loads gtag. A queue would\n * quietly convert \"we did not track you\" into \"we tracked you and waited\", and\n * a replayed hit carries the pre-consent timestamp and page into GA, which is\n * exactly the thing the consent gate exists to prevent. Deliberately no retry,\n * no buffer, no flush-on-grant.\n *\n * ## No PII, enforced rather than promised\n *\n * Every payload passes through {@link sanitizeEventParams} before it reaches a\n * transport: an exact-key denylist drops the identity-bearing params someone\n * will eventually add by reflex (`email`, `org_name`, `first_name`, ...), any\n * value that looks like an email address drops its key entirely, URLs are\n * reduced to origin + pathname so query strings can never smuggle a token or\n * an address, and strings are length-capped. The console separately sets a\n * `user_id` — that is an opaque Firebase uid and is the one identifier GA is\n * allowed to hold.\n *\n * Sanitizing here rather than at each call site is the point: a new call site\n * cannot forget.\n *\n * ## Authored events (AGL-1587)\n *\n * One call site cannot use the taxonomy at all: the `trackGaEvent` action step,\n * whose event name and params are typed by a SITE AUTHOR in the interaction\n * builder. A closed union cannot contain a name nobody has written yet, so\n * {@link trackAuthoredEvent} is the escape hatch — and it is deliberately the\n * only one, so that untrusted input still passes {@link sanitizeEventParams}\n * rather than reaching `window.gtag` raw.\n *\n * The test for which door an event uses is WHO NAMED IT, not whether GA4\n * recommends the name. `aglyn_overlay` and `aglyn_experiment` are outside GA4's\n * recommended set and were candidates for the hatch (AGL-1591); they are in the\n * union instead, because a developer wrote their names and their keys, so they\n * can have compile-time checking — and because the hatch guarantees the\n * opposite of what they need. {@link resolveAuthoredEventName} refuses any name\n * we send — the union AND the server-only names beside it — precisely so that\n * \"not one of ours\" means \"authored\"; put our own events through the hatch and\n * that stops being true, authored hits stop being separable from ours in\n * reports, and an authored `aglyn_experiment` step starts voting in the\n * experiment that decides which variant ships.\n */\n\n/**\n * Read the browser's GA `client_id` — the identifier that ties a hit to a GA\n * user and session.\n *\n * Needed because `purchase` is sent SERVER-side, from the Stripe webhook,\n * where the authoritative money is (see `ga4-measurement-protocol.ts`). The\n * Measurement Protocol requires a `client_id` and a server cannot know one,\n * so it is captured here when checkout starts and carried on the Stripe\n * object's metadata. Without it the revenue still lands, but attached to a\n * synthetic user with no acquisition session — which is exactly the campaign\n * attribution the whole exercise is for.\n *\n * Resolves to null rather than hanging when gtag is absent (no consent, an ad\n * blocker, analytics not configured) or slow to answer. The 500ms cap matters:\n * this sits directly in front of a checkout redirect, and analytics must never\n * be able to delay a payment.\n */\nexport function readGaClientId(\n measurementId: string | undefined | null,\n): Promise<string | null> {\n return new Promise((resolve) => {\n if (typeof window === 'undefined' || !measurementId) return resolve(null)\n const gtag = (window as unknown as { gtag?: unknown }).gtag\n if (typeof gtag !== 'function') return resolve(null)\n let settled = false\n const finish = (value: string | null) => {\n if (settled) return\n settled = true\n resolve(value)\n }\n // Never let a missing callback strand the checkout.\n setTimeout(() => finish(null), 500)\n try {\n ;(gtag as (...args: unknown[]) => void)(\n 'get',\n measurementId,\n 'client_id',\n (id: unknown) => finish(typeof id === 'string' && id ? id : null),\n )\n } catch {\n finish(null)\n }\n })\n}\n\n/** Which door an account was created through (AGL-1497 enumerates all four). */\nexport type SignUpMethod =\n | 'password'\n | 'google_popup'\n | 'google_redirect'\n | 'google_signin'\n\n/** How a returning user authenticated. */\nexport type LoginMethod =\n | 'password'\n | 'google_popup'\n | 'google_redirect'\n | 'sso'\n | 'passkey'\n\n/**\n * A GA4 `items` entry. Only the fields we actually populate — GA accepts more,\n * but an unpopulated field is a column of nulls in every report.\n */\nexport interface AnalyticsItem {\n /** Opaque identifier — a price id, plan key or marketplace listing id. */\n item_id: string\n /** Human-readable product name. NEVER a customer or org name. */\n item_name: string\n /** Distinguishes the revenue lines: `subscription` vs `marketplace`. */\n item_category?: string\n price?: number\n quantity?: number\n}\n\n/**\n * The taxonomy. Adding an event means adding a line here first — which is what\n * makes `docs/ANALYTICS.md` checkable against the code rather than aspirational.\n */\nexport interface AnalyticsEventParams {\n // --- Acquisition (GTM §6: signups, cost/lead by channel) -----------------\n /**\n * GA4 recommended. Real account creation only, never a sign-in.\n *\n * The three campaign params are optional and come from\n * `utmEventParams` (AGL-1731) — present when the signup URL named a\n * campaign, absent entirely otherwise. They are what lets a September ad\n * spend be evaluated: without them a paid click, an organic visit and a\n * partner link arrive indistinguishable and the money cannot be traced to\n * an account. Named `campaign_*` rather than `utm_*` because these are our\n * own registered dimensions and the `utm_` spellings belong to GA's\n * automatic campaign collection.\n */\n sign_up: {\n method: SignUpMethod\n campaign_source?: string\n campaign_medium?: string\n campaign_name?: string\n }\n /** GA4 recommended. Returning user only. */\n login: { method: LoginMethod }\n /**\n * GA4 recommended. Fired on a SUCCESSFUL form submission — never on click,\n * never on a validation failure. `form_name` is the author-given form name,\n * which is site content and not personal data.\n */\n generate_lead: { form_name: string; form_location?: string }\n /**\n * GA4 recommended. A CTA click, with the section that produced it.\n *\n * Fired by `analytics-link-clicks.ts` (AGL-1562) from a delegated listener,\n * not per call site: an authored page has no code to add a handler to.\n */\n select_content: {\n content_type: string\n content_id: string\n /** Which product surface — see `click.surface`. */\n surface?: string\n }\n\n // --- Activation (GTM §6: % publish a site, % connect Stripe) -------------\n /** Custom: no GA4 equivalent. A new organization exists. */\n org_created: { plan?: string }\n /** Custom: no GA4 equivalent. A new site/host exists. */\n host_created: Record<string, never>\n /**\n * Custom: no GA4 equivalent, and the GTM plan's headline activation metric.\n * A site actually went live.\n */\n site_published: { first_publish?: boolean }\n /** Custom: no GA4 equivalent. Stripe Connect onboarding completed. */\n stripe_connected: Record<string, never>\n\n // --- Revenue (GTM §6: paid conversions, ARPA, annual mix) ---------------\n /** GA4 recommended. A plan checkout started. */\n begin_checkout: {\n currency: string\n value: number\n items: AnalyticsItem[]\n /** `monthly` | `annual` — feeds the §6 annual-mix metric. */\n billing_interval?: string\n }\n /**\n * GA4 recommended. A payment actually succeeded. `transaction_id` is the\n * Stripe object id and is what makes the event idempotent in GA: GA4\n * de-duplicates purchases by transaction id, so a webhook retry cannot\n * inflate revenue.\n */\n purchase: {\n transaction_id: string\n currency: string\n value: number\n items: AnalyticsItem[]\n billing_interval?: string\n /**\n * GA4's shipping charged on the transaction, in currency units. Optional\n * because only a tenant STOREFRONT purchase ships anything — a plan or a\n * marketplace purchase has no shipping to report and omits it.\n *\n * There is deliberately no sibling `tax` (AGL-1639, AGL-1641). The\n * asymmetry is the point and is not an inconsistency to tidy away:\n * `shipping` is a COMPONENT of the `value` beside it, so reporting it\n * describes that value; `tax` is not, because `value` is already ex-tax,\n * so reporting it would assert a relationship that does not hold and\n * invite the subtraction that removes tax a second time.\n */\n shipping?: number\n }\n\n // --- Commerce (tenant storefronts, AGL-1591) -----------------------------\n /**\n * GA4 recommended. A product detail page was viewed on a tenant storefront.\n *\n * Only `items`, and only `item_id`/`item_name` within it: those are the two\n * fields the storefront actually has at this point, and an unpopulated\n * `price`/`item_category` would be a column of nulls in the merchant's\n * reports. The item id is the PRODUCT id — the same id `add_to_cart` and\n * `begin_checkout` use — which is what lets GA join the three into one\n * per-product funnel.\n */\n view_item: { items: AnalyticsItem[] }\n /**\n * GA4 recommended. A storefront product was added to the cart.\n *\n * `currency`/`value` are optional because GA4 pairs them — a `value` with no\n * `currency` is dropped by GA — so they travel together or not at all, and\n * {@link buildAddToCartParams} is what keeps that true. They are populated\n * wherever the surface holds a server-priced figure: the product detail\n * block knows the resolved variant's price and the chosen quantity, so the\n * merchant's \"value added to cart\" is a real number rather than the empty\n * column an items-only hit produces.\n */\n add_to_cart: { currency?: string; value?: number; items: AnalyticsItem[] }\n /**\n * GA4 recommended. The shopper looked at their cart — the funnel step\n * between {@link AnalyticsEventParams.add_to_cart} and\n * {@link AnalyticsEventParams.begin_checkout}, and the one GA4's own\n * shopping-behavior report reads to tell \"never opened the cart\" apart from\n * \"opened it and did not check out\". Without it those two collapse into one\n * drop, and the merchant cannot tell a discovery problem from a pricing one.\n *\n * Fired when the cart is actually ON SCREEN carrying lines — a drawer that\n * opened, or an inline cart block that resolved — never on the badge render\n * that every page of a storefront performs. An empty cart is not a view of\n * anything and reports nothing.\n */\n view_cart: { currency: string; value: number; items: AnalyticsItem[] }\n\n // --- Engagement ---------------------------------------------------------\n /**\n * Custom: no GA4 equivalent. An announcement bar or popup was shown,\n * dismissed or clicked on a tenant site (AGL-200/271).\n *\n * In the taxonomy rather than {@link trackAuthoredEvent} even though it is\n * not a GA4 recommended name: the name and every key here are written by US,\n * which is exactly what the closed union is for. See the note on\n * {@link trackAuthoredEvent} for why the two must not be mixed.\n */\n aglyn_overlay: { overlay_action: string; overlay_id?: string }\n /**\n * Custom: no GA4 equivalent. An experiment exposure or conversion\n * (AGL-253). `experiment_action` is `exposure` | `conversion`.\n *\n * Being in the union also makes the name RESERVED against authored events,\n * which matters more here than anywhere else in this file: these are the\n * counts that decide which variant wins, and a hand-authored\n * `aglyn_experiment` step would silently vote in that election.\n */\n aglyn_experiment: {\n experiment_id: string\n variant_id: string\n experiment_action: string\n }\n /**\n * GA4 recommended-ish. Outbound click to docs, GitHub, etc. Fired by\n * `analytics-link-clicks.ts` (AGL-1562) rather than at a call site.\n */\n click: {\n link_domain: string\n link_id?: string\n /**\n * Which product surface produced the click. GA's built-in Hostname\n * dimension already separates the DOMAINS; this separates surfaces that\n * could share one, and keeps the shared click listener from having to\n * know anything about either.\n *\n * `site` — a tenant published site — is the only value ever SENT. `docs`\n * was designed for (AGL-1579) and is not emitted: `apps/docs` cannot\n * import `libs/`, so this listener is not installed there\n * (docs/ANALYTICS.md decision 7 has the Vercel setting that would change\n * that). Registering `surface` as a dimension and reading a one-value\n * breakdown is the trap — the absent `docs` row means \"no listener\", not\n * \"no clicks\".\n */\n surface?: string\n }\n /**\n * Custom: no GA4 equivalent. One Aglyn Assist message sent (AGL-1860).\n * `tier` is the capability tier served (`free` | `entitled`);\n * `grounded` says whether docs retrieval found sections to cite —\n * ungrounded questions at volume are the docs-gap signal the data loop\n * mines. No question text: params carry no user content.\n */\n assistant_message_sent: { tier: string; grounded: boolean }\n /**\n * Custom: no GA4 equivalent. Explicit thumbs on an Assist answer\n * (AGL-1860). `feedback` is `up` | `down`.\n */\n assistant_feedback: { feedback: string }\n /**\n * Custom: no GA4 equivalent. Aglyn Assist offered to open a page for the\n * user (AGL-1988, level 2). `action` is the registry action id — a closed\n * set, so it carries no user content.\n *\n * The pair below is the only read on whether the confirm gate is a real\n * choice or a speed bump people click through. A shown-to-confirmed ratio\n * near 1 means the card is not being read, and the copy has to change\n * BEFORE the ladder goes anywhere near a write.\n */\n assistant_proposal_shown: { action: string }\n /** Custom: no GA4 equivalent. The user confirmed and was navigated. */\n assistant_proposal_confirmed: { action: string }\n /**\n * Custom: no GA4 equivalent. An AI generation job reached `done`\n * (AGL-2904), observed from the console's jobs drawer. `kind` is the\n * closed `AiJobKind` set and `credits` the job's spend at the plan's\n * credit rate — no brief, no output: params carry no user content.\n */\n ai_job_completed: { kind: string; credits: number }\n /**\n * Custom: no GA4 equivalent. An AI generation job reached `failed`\n * (AGL-2904). `kind` only; the failure text is a fixed customer-safe\n * sentence and says nothing a rate could use.\n */\n ai_job_failed: { kind: string }\n\n // --- Retention (AGL-1859/AGL-1863: the leave path, measurable) -----------\n /**\n * Custom: no GA4 equivalent. The churn survey was answered — step 1 of the\n * cancellation/deletion funnel, and the DENOMINATOR every step below is a\n * rate against. Fired for both leave paths.\n *\n * `reason` is the closed `ChurnSurveyReason` set, never the free-text\n * detail: the detail is customer-written prose, it belongs in Firestore\n * where the data loop reads it, and shipping it to GA would put user\n * content in analytics params. `surface` separates a subscription cancel\n * from an account delete — counting only one understates churn by exactly\n * the orgs that chose the other.\n */\n churn_survey_submitted: { reason: string; surface: string; plan?: string }\n /**\n * Custom: no GA4 equivalent. The customer took the smaller tier instead of\n * leaving — a SAVE, at reduced ARPA. `from_plan`/`to_plan` are what makes\n * that tradeoff measurable rather than a win recorded without its cost.\n */\n downsell_accepted: { from_plan: string; to_plan: string; surface: string }\n /**\n * Custom: no GA4 equivalent. The time-boxed winback discount was accepted.\n *\n * `percent_off` and `duration_months` are reported because the discount is\n * bounded and the bound is the entire point (AGL-1620/AGL-1863): a retained\n * org and the margin it was retained at are one fact, and a save recorded\n * without its price reads as free.\n */\n winback_discount_accepted: {\n percent_off: number\n duration_months: number\n plan?: string\n surface: string\n }\n /**\n * Custom: no GA4 equivalent. They left anyway — the funnel's terminal step,\n * and the numerator for churn.\n *\n * `funnel_completed` is false when the cancel arrived without a funnelId\n * (support ops, Stripe dashboard). It mirrors the `funnelSkipped` marker\n * the routes write, so the GA funnel and the Firestore record agree instead\n * of quietly disagreeing about how many departures were ever surveyed.\n */\n cancellation_completed: {\n surface: string\n plan?: string\n funnel_completed: boolean\n }\n\n // --- Plan changes taken from the grid (AGL-2235, under AGL-1859 §4) ------\n /**\n * Custom: no GA4 equivalent. A downgrade was confirmed and SCHEDULED from\n * the billing plan grid — the same economic event `downsell_accepted`\n * records, arrived at by the other door.\n *\n * Why this has to exist separately: all four retention events above fire\n * from `retention-funnel.dialog.tsx` and from nowhere else. A customer who\n * moves Pro → Starter through the cancel funnel is counted; a customer who\n * moves Pro → Starter by clicking Downgrade on the plan card was counted by\n * nothing. So \"how many orgs moved down\" was unanswerable, and the number\n * that WAS answerable — `downsell_accepted` — undercounted by exactly the\n * share that took the direct route while reading like a total. A save rate\n * computed against it is wrong in the flattering direction, which is the\n * worst direction for a retention number to be wrong in.\n *\n * `effective_at` is the whole point of the event's name: this is the\n * asymmetric-friction arm of AGL-1859 §2, and a downgrade that has been\n * SCHEDULED is not a downgrade that has HAPPENED. Reported as the server's\n * ISO date so the gap between decision and effect — up to a full cycle, and\n * the window in which \"keep my plan\" can still save the org — is visible in\n * the data instead of being collapsed into the decision day.\n *\n * No amount, price or fee: pricing is locked for Sept 1, money belongs to\n * `purchase`/`refund`, and a tier pair already says what changed.\n */\n plan_downgrade_scheduled: {\n from_plan: string\n to_plan: string\n interval: string\n effective_at?: string\n }\n /**\n * Custom: no GA4 equivalent. An existing subscriber moved UP in place.\n *\n * Not `app_upgrade` — that name is GA4-RESERVED (it means an app binary\n * version bump) and a hit using it is dropped, which is silence rather than\n * pollution and therefore the harder failure to notice.\n *\n * `purchase` covers only the Checkout path, so before this, expansion\n * revenue from customers who ALREADY had a subscription was dark: the\n * in-place switch never opens a Checkout and never mints a new\n * subscription, so nothing in the revenue taxonomy saw it. Upgrades are the\n * half of AGL-1859 §2 that is supposed to be frictionless, and an\n * unmeasured half cannot be shown to be.\n */\n plan_upgraded: {\n from_plan: string\n to_plan: string\n interval: string\n }\n}\n\nexport type AnalyticsEventName = keyof AnalyticsEventParams\n\n/**\n * Where a sanitized event goes. The console registers a Firebase\n * `logEvent` transport; the tenant runtime and the plugin bundles have none\n * and fall through to `window.gtag`, which only exists once consent has been\n * granted.\n */\nexport type AnalyticsTransport = (\n name: AnalyticsEventName,\n params: Record<string, unknown>,\n) => void | Promise<void>\n\nlet configuredTransport: AnalyticsTransport | null = null\n\n/**\n * Register the transport for this surface. The console calls this once, with\n * Firebase's `logEvent`, because the console's GA is Firebase-initialised and\n * its `user_id`/user-property state lives on the Firebase Analytics instance —\n * poking `window.gtag` directly there would emit hits that miss it.\n *\n * The tenant runtime deliberately does NOT call this: the plugin bundles run\n * in their own realm and do not share this module instance with the host app,\n * so a module-scope singleton would be invisible to exactly the call sites\n * that need it (the form and newsletter elements). `window.gtag` is the only\n * thing genuinely shared across that boundary, and it is also the consent\n * gate, which makes the fallback the correct primary path there rather than a\n * degraded one.\n */\nexport function configureAnalyticsTransport(\n transport: AnalyticsTransport | null,\n): void {\n configuredTransport = transport\n}\n\n/** Test seam — drops the registered transport. */\nexport function resetAnalyticsTransport(): void {\n configuredTransport = null\n}\n\n/**\n * Param keys that must never reach GA, matched EXACTLY. Substring matching\n * would be wrong in both directions: it would drop the legitimate\n * `form_name` / `item_name` / `link_domain`, and it would still miss a\n * creatively-named new one. The value scan below is the backstop for those.\n */\nconst DENIED_PARAM_KEYS: ReadonlySet<string> = new Set([\n 'email',\n 'email_address',\n 'user_email',\n 'name',\n 'full_name',\n 'first_name',\n 'last_name',\n 'user_name',\n 'username',\n 'customer_name',\n 'org_name',\n 'organization_name',\n 'company',\n 'company_name',\n 'phone',\n 'phone_number',\n 'address',\n 'street',\n 'postal_code',\n 'zip',\n 'ip',\n 'ip_address',\n])\n\n/** Deliberately loose — this is a \"does it smell like an address\" test. */\nconst EMAIL_SHAPED = /[^\\s@]+@[^\\s@]+\\.[^\\s@]+/\n\n/**\n * GA4 truncates param values at 100 chars anyway; do it ourselves, visibly.\n *\n * Exported because an AUTHOR types some of these (the `trackGaEvent` step's\n * parameters), and the field they type into caps its input at the same number\n * — the truncation point and the affordance that describes it have to be one\n * value, or the editor promises a length the delivery quietly shortens.\n */\nexport const ANALYTICS_PARAM_MAX_LENGTH = 100\n\nfunction scrubValue(value: string): string | null {\n let candidate = value\n if (/^https?:\\/\\//i.test(candidate)) {\n try {\n const url = new URL(candidate)\n // Origin + pathname only: a query string is where a session token, a\n // signup email or a Stripe id ends up, and none of them belong in GA.\n candidate = `${url.origin}${url.pathname}`\n } catch {\n return null\n }\n }\n // AFTER the URL reduction, not before. A page URL routinely carries an\n // address in its query (`?email=…` on a prefilled signup link), and testing\n // the raw string would throw the whole URL away for PII that the reduction\n // was about to remove — losing the legitimate page dimension to protect\n // something already protected. Testing the REDUCED value still catches an\n // address embedded in the path itself, which the reduction keeps.\n if (EMAIL_SHAPED.test(candidate)) return null\n return candidate.slice(0, ANALYTICS_PARAM_MAX_LENGTH)\n}\n\n/**\n * Strip anything identity-bearing from an event payload. Exported so\n * `analytics-events.spec.ts` can assert the guarantee directly rather than\n * only through `trackEvent`.\n */\nexport function sanitizeEventParams(\n params: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n const safe: Record<string, unknown> = {}\n if (!params) return safe\n for (const [key, value] of Object.entries(params)) {\n if (DENIED_PARAM_KEYS.has(key.toLowerCase())) continue\n if (value === undefined || value === null) continue\n if (typeof value === 'string') {\n const scrubbed = scrubValue(value)\n if (scrubbed === null || scrubbed === '') continue\n safe[key] = scrubbed\n continue\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n safe[key] = value\n continue\n }\n if (Array.isArray(value)) {\n // `items` — sanitize each entry with the same rules.\n safe[key] = value.map((entry) =>\n entry && typeof entry === 'object'\n ? sanitizeEventParams(entry as Record<string, unknown>)\n : entry,\n )\n continue\n }\n if (typeof value === 'object') {\n safe[key] = sanitizeEventParams(value as Record<string, unknown>)\n }\n // Anything else (function, symbol) is dropped.\n }\n return safe\n}\n\n/**\n * Fire a GA4 event.\n *\n * Never throws and never queues. If the surface has no transport and no\n * `window.gtag` — which on a tenant site means the visitor has not granted\n * analytics consent — the event is DROPPED, permanently. See the module\n * comment for why a queue would be the wrong answer.\n */\nexport function trackEvent<K extends AnalyticsEventName>(\n name: K,\n params: AnalyticsEventParams[K],\n): void {\n deliver(name, sanitizeEventParams(params as Record<string, unknown>))\n}\n\n/**\n * How long a navigation may be held waiting for a hit to reach gtag. Short\n * enough to be invisible next to a Stripe redirect, long enough to cover a\n * Firebase Analytics init that has not settled yet.\n */\nconst NAVIGATION_FLUSH_TIMEOUT_MS = 300\n\n/**\n * Fire a GA4 event and resolve once it has been HANDED TO gtag — for the call\n * sites that navigate away in the same tick (AGL-1580).\n *\n * ## What was actually losing the event\n *\n * Not the transport, which was the obvious suspect and the wrong one. Measured\n * against real gtag.js with every transport interposed: gtag flushes its queue\n * on pagehide through `fetch(..., { keepalive: true })`, which is precisely the\n * mechanism that survives a document teardown. Once a hit reaches gtag, a\n * navigation does not destroy it — and `transport_type: 'beacon'`, the standard\n * answer, therefore fixes nothing here.\n *\n * What is lost is the hit that never REACHES gtag. Firebase's `logEvent` is\n * `async` and awaits the SDK's initialization promise before calling gtag\n * (`@firebase/analytics/dist/index.cjs.js`, `logEvent$1`). While that promise is\n * already settled the continuation is a microtask, microtasks drain before the\n * queued navigation task, and the hit gets out. While it is still PENDING — the\n * first checkout of a fresh session, exactly the case that has never yet been\n * seen in the property — the continuation is scheduled behind the navigation\n * and never runs at all. Measured both ways: pending init loses the event,\n * awaiting it delivers it, nothing else changed.\n *\n * ## Why a timeout rather than a bare await\n *\n * A bare `await` on `logEvent` hands the user's redirect to the analytics\n * stack. When the analytics host is blocked — an ad blocker, a corporate proxy,\n * a consent tool that never loads — Firebase's initialization promise can stay\n * pending indefinitely, and the checkout would hang on a metric. So the wait is\n * RACED against {@link NAVIGATION_FLUSH_TIMEOUT_MS}: a blocked analytics stack\n * costs the redirect 300ms once and then it proceeds, which is the same outcome\n * the caller had before this existed. Never rejects, for the same reason\n * {@link trackEvent} never throws.\n *\n * On a surface with no registered transport — the tenant runtime and the plugin\n * bundles, which go straight to `window.gtag` — delivery is synchronous, so\n * this resolves immediately and costs the storefront checkout nothing at all.\n */\nexport async function trackEventBeforeNavigation<K extends AnalyticsEventName>(\n name: K,\n params: AnalyticsEventParams[K],\n): Promise<void> {\n const delivered = deliver(\n name,\n sanitizeEventParams(params as Record<string, unknown>),\n )\n // Synchronous transport (or none): already handed over, nothing to wait for.\n if (!delivered || typeof delivered.then !== 'function') return\n await Promise.race([\n // A transport that REJECTS must not become an unhandled rejection, and\n // must not hold the navigation either — it has already failed.\n Promise.resolve(delivered).catch((): void => undefined),\n new Promise<void>((resolve) =>\n setTimeout(resolve, NAVIGATION_FLUSH_TIMEOUT_MS),\n ),\n ])\n}\n\n/**\n * Build the ONE `begin_checkout` payload, for every surface that starts a\n * checkout (AGL-1591).\n *\n * ## Why a constructor and not just the type\n *\n * Two surfaces fire this name: the console, when a plan checkout starts, and a\n * tenant storefront, when a cart checks out. Until AGL-1591 the storefront\n * fired it raw and carried `value`/`currency` only, so ONE event name arrived\n * in two shapes — and a `begin_checkout` breakdown showed two populations that\n * could not be compared, with the storefront half missing the `items` the GA4\n * ecommerce funnel is built on. Routing both through {@link trackEvent} makes\n * the compiler settle the KEYS.\n *\n * It does not settle the NUMBER, which is the other way two call sites of one\n * event diverge, and the more dangerous one because nothing about it looks\n * wrong: the console's annual plans are priced per-month-billed-yearly, so its\n * `value` is twelve of them, and that only stayed right because a comment said\n * so. Here `value` DERIVES from the items unless a caller states a different\n * one — a cart states its subtotal, which is authoritative after discounts —\n * so \"what the customer is about to be charged\" has one definition rather than\n * one per surface.\n *\n * Server-safe: pure, no DOM, so the Measurement Protocol sender can compose\n * the matching `purchase` items from the same shapes.\n */\nexport function buildBeginCheckoutParams(input: {\n items: AnalyticsItem[]\n /**\n * The amount actually being charged. Defaults to the sum of the items'\n * `price * quantity`, which is right whenever nothing has adjusted it.\n */\n value?: number\n /** ISO 4217. Defaults to `USD`, the only currency either surface bills in. */\n currency?: string\n /** `monthly` | `annual`. Subscriptions only — a storefront cart has none. */\n billingInterval?: string\n}): AnalyticsEventParams['begin_checkout'] {\n return {\n ...priceItems(input),\n ...(input.billingInterval ? { billing_interval: input.billingInterval } : {}),\n }\n}\n\n/**\n * The `currency`/`value`/`items` triple every GA4 ecommerce step shares.\n *\n * Private, because a caller should reach for the named builder for the event\n * it is about to send: the names differ in what they mean by `value` even\n * though the arithmetic is identical, and the JSDoc on each is where that is\n * written down.\n */\nfunction priceItems(input: {\n items: AnalyticsItem[]\n value?: number\n currency?: string\n}): { currency: string; value: number; items: AnalyticsItem[] } {\n const items = input.items ?? []\n const summed = items.reduce(\n (total, item) => total + (item.price ?? 0) * (item.quantity ?? 1),\n 0,\n )\n return {\n currency: input.currency ?? 'USD',\n // Money, so two decimals: a float sum of cents-derived prices produces\n // `59.99999999999999`, and GA would report that verbatim.\n value: Math.round((input.value ?? summed) * 100) / 100,\n items,\n }\n}\n\n/**\n * Build `view_cart` — the shopper is looking at the cart's contents.\n *\n * `value` is the cart's subtotal as the SERVER priced it, which is what makes\n * this comparable with the `begin_checkout` the same cart sends moments later:\n * two steps of one funnel that disagreed about the size of the same cart would\n * read as shoppers editing it between screens.\n */\nexport function buildViewCartParams(input: {\n items: AnalyticsItem[]\n value?: number\n currency?: string\n}): AnalyticsEventParams['view_cart'] {\n return priceItems(input)\n}\n\n/**\n * Build `add_to_cart` — one product going in, not the cart's new total.\n *\n * `value` is what was JUST ADDED (`price * quantity`), which is GA4's\n * definition and the only one that makes the metric additive: summing a\n * running cart total over a session would count the first item once per\n * subsequent add.\n *\n * Callers that cannot price the line — a quick-add with no resolved variant —\n * pass items alone and the pair is omitted rather than reported as zero. A\n * zero here would read as a free product in the merchant's report.\n */\nexport function buildAddToCartParams(input: {\n items: AnalyticsItem[]\n value?: number\n currency?: string\n}): AnalyticsEventParams['add_to_cart'] {\n const priced = priceItems(input)\n if (!(priced.value > 0)) return { items: priced.items }\n return priced\n}\n\n/**\n * Decide `site_published`'s `first_publish` from the host's routing map as it\n * stood BEFORE the route being published was registered (AGL-1588).\n *\n * ## What \"first\" means, and why it is defined once\n *\n * Three call sites report `site_published` — `publishScreenRoute`, the\n * besigner's one-click publish, and the scheduled publish executor, the last\n * of which is server-side and sends over the Measurement Protocol. A\n * breakdown is only worth registering if all three mean the same thing by it,\n * and \"first\" has several plausible readings. This is the one they share:\n *\n * **The host had no live route at all before this one.** Not \"first for the\n * org\" — that needs a cross-host query the server path cannot make, and the\n * scheduled sender's client id is derived from the HOST anyway, so an org is\n * not a thing it can see. Not \"first for this screen\" either, which would be\n * true of every second page a site adds and would make the dimension a\n * synonym for the event.\n *\n * So the metric it separates is the GTM §6 activation one: `first_publish:\n * true` counts sites that came alive, where the event alone counts publishes.\n *\n * ## The one dishonesty, and why it does not matter\n *\n * Unpublishing every route and publishing again reports `true` a second time.\n * Detecting that needs publish history the routing map does not keep. It is\n * harmless for the metric it exists for, because activation is read as the\n * share of USERS who ever sent `first_publish: true`, and a user counted twice\n * is still one user.\n *\n * Callers pass what they already hold — the live-subscribed map in the\n * console, a read snapshot on the server — and never a map read back AFTER\n * the write, which is never empty.\n *\n * ## The placeholder home page is not a publish (AGL-3408)\n *\n * Every new site is created with a home page already routed at `/`, so read\n * literally the map is never empty and no site would ever report a first\n * publish. The host's `defaultHomeScreenId` names that placeholder, and its\n * entry is not counted: the site \"came alive\" when its owner put something on\n * it, not when the platform did. Republishing the placeholder itself after\n * editing it counts, which is the same act: that publish is read against the\n * map with the marker still set, and clears it in the same write (AGL-3478).\n */\nexport function isFirstPublishedRoute(\n routing: Record<string, unknown> | null | undefined,\n defaultHomeScreenId?: string | null,\n): boolean {\n return !Object.keys(routing ?? {}).some(\n (screenId) => screenId !== defaultHomeScreenId,\n )\n}\n\n/**\n * The one delivery path, shared by {@link trackEvent} and\n * {@link trackAuthoredEvent}. Takes an ALREADY-sanitized payload — every\n * caller sanitizes first, which is what keeps \"a new call site cannot forget\"\n * true of the authored path too.\n */\nfunction deliver(\n name: string,\n safe: Record<string, unknown>,\n): void | Promise<void> {\n try {\n if (configuredTransport) {\n // The transport's name parameter is the taxonomy union, which an\n // authored name is by definition outside. Nominal only: the console is\n // the sole surface that registers one and it has no authored events\n // (the interaction runtime is tenant-side), and Firebase `logEvent`\n // takes an arbitrary string regardless.\n // Returned, not discarded (AGL-1580). A transport may be ASYNC —\n // Firebase's `logEvent` awaits the SDK's initialization promise before it\n // reaches gtag at all — and a caller that is about to navigate has to be\n // able to wait for it. See `trackEventBeforeNavigation`.\n return configuredTransport(name as AnalyticsEventName, safe)\n }\n if (typeof window === 'undefined') return\n const gtag = (window as unknown as { gtag?: unknown }).gtag\n if (typeof gtag !== 'function') return\n // Synchronous, so nothing is returned and nothing needs awaiting: by the\n // time this call has returned, gtag.js already holds the hit.\n ;(gtag as (...args: unknown[]) => void)('event', name, safe)\n } catch {\n // Analytics never breaks the page — the same posture as the error beacon\n // and the pageview beacon.\n }\n}\n\n/**\n * The taxonomy's names at RUN time. A `Record<AnalyticsEventName, true>` rather\n * than a hand-kept array so the compiler enforces both directions: adding an\n * event to {@link AnalyticsEventParams} without adding it here is a missing-key\n * error, and a name here that is not in the taxonomy is an excess-property one.\n *\n * It exists for {@link trackAuthoredEvent}, which has to refuse these names —\n * a drifting copy would silently re-open the collision it is here to close.\n */\nconst TAXONOMY_EVENT_NAMES: Record<AnalyticsEventName, true> = {\n sign_up: true,\n login: true,\n generate_lead: true,\n select_content: true,\n org_created: true,\n host_created: true,\n site_published: true,\n stripe_connected: true,\n begin_checkout: true,\n purchase: true,\n view_item: true,\n add_to_cart: true,\n view_cart: true,\n aglyn_overlay: true,\n aglyn_experiment: true,\n click: true,\n assistant_message_sent: true,\n assistant_feedback: true,\n assistant_proposal_shown: true,\n assistant_proposal_confirmed: true,\n ai_job_completed: true,\n ai_job_failed: true,\n churn_survey_submitted: true,\n downsell_accepted: true,\n winback_discount_accepted: true,\n cancellation_completed: true,\n plan_downgrade_scheduled: true,\n plan_upgraded: true,\n}\n\n/** The taxonomy, enumerable. */\nexport const ANALYTICS_EVENT_NAMES = Object.keys(\n TAXONOMY_EVENT_NAMES,\n) as AnalyticsEventName[]\n\n/**\n * Event names WE send that this module's union cannot hold, because nothing\n * client-side ever fires them: they are emitted only by the Measurement\n * Protocol sender (`ga4-measurement-protocol.ts`), from a Stripe webhook.\n *\n * They still have to be RESERVED against authored names, and the reason is\n * the same one that puts `purchase` in the union — only less obvious, which\n * is why it was missed. `aglyn.com` is itself a tenant site, pointed at the\n * platform measurement id (`site-analytics.tsx`), so an authored\n * `trackGaEvent` step on our own marketing site lands in the SAME property as\n * these server hits. An authored `refund` does not merely add noise: GA4\n * treats `refund` as ecommerce and SUBTRACTS its `value` from reported\n * revenue, so a mistyped step could walk real money out of the report — the\n * `purchase` hazard, running in the direction nobody audits.\n *\n * Kept as a separate list rather than folded into {@link AnalyticsEventParams}\n * on purpose: adding them to the union would give {@link trackEvent} a\n * client-side door to events that must only ever come from the server, where\n * the authoritative money is. A name here is ours, is never sent from a\n * browser, and is never available to an author.\n *\n * This list is the reason \"not in {@link ANALYTICS_EVENT_NAMES}\" is NOT on its\n * own a sound test for \"authored\" — use {@link isReservedAnalyticsEventName}.\n */\nconst SERVER_ONLY_EVENT_NAMES: ReadonlySet<string> = new Set([\n 'refund',\n 'subscription_cancelled',\n])\n\n/**\n * Every event name Aglyn itself sends, from any surface — the union plus the\n * server-only names above. Exported so a caller can ask the question the two\n * separate lists no longer answer alone.\n */\nexport function isReservedAnalyticsEventName(name: string): boolean {\n return (\n TAXONOMY_EVENT_NAMES[name as AnalyticsEventName] === true ||\n SERVER_ONLY_EVENT_NAMES.has(name)\n )\n}\n\n/**\n * GA4's own reserved event names — GA drops a hit that uses one, so sending it\n * is not pollution but silence, which is the worse failure of the two because\n * nothing anywhere says so.\n */\nconst GA4_RESERVED_EVENT_NAMES: ReadonlySet<string> = new Set([\n 'ad_activeview',\n 'ad_click',\n 'ad_exposure',\n 'ad_impression',\n 'ad_query',\n 'ad_reward',\n 'adunit_exposure',\n 'app_background',\n 'app_clear_data',\n 'app_exception',\n 'app_install',\n 'app_remove',\n 'app_store_refund',\n 'app_store_subscription_cancel',\n 'app_store_subscription_convert',\n 'app_store_subscription_renew',\n 'app_update',\n 'app_upgrade',\n 'dynamic_link_app_open',\n 'dynamic_link_app_update',\n 'dynamic_link_first_open',\n 'error',\n 'first_open',\n 'first_visit',\n 'in_app_purchase',\n 'notification_dismiss',\n 'notification_foreground',\n 'notification_open',\n 'notification_receive',\n 'os_update',\n 'screen_view',\n 'session_start',\n 'user_engagement',\n])\n\n/** GA4 reserves these prefixes outright, whatever follows them. */\nconst GA4_RESERVED_PREFIXES = ['firebase_', 'google_', 'ga_'] as const\n\n/** GA4's hard limit on an event name. Over it, GA drops the event. */\nconst MAX_EVENT_NAME_LENGTH = 40\n\n/**\n * The outcome of putting an authored name through GA4's rules, so the\n * interaction builder can say WHY it refused a name and the runtime can drop\n * the event for the same reason.\n */\nexport interface ResolvedAuthoredEventName {\n /** The name to send, or null when the event must not be sent at all. */\n name: string | null\n /**\n * `reserved` — collides with the taxonomy or with GA4's own names.\n * `unusable` — nothing survives normalization (empty, or no leading letter).\n */\n reason?: 'reserved' | 'unusable'\n}\n\n/**\n * Put an authored event name through GA4's naming rules and our own.\n *\n * Normalization is forgiving on purpose: `\"CTA Click!\"` becomes `cta_click`\n * and still reports, where GA would have dropped it. Names already sitting in\n * published sites were never validated, so refusing them outright would delete\n * working metrics from a paying customer's property to fix a formatting nit.\n *\n * Collisions, in contrast, are refused rather than rewritten. On a tenant site\n * the authored events and OUR events (`generate_lead` from the form element,\n * `select_content`/`click` from the link listener) land in the same property,\n * so an authored `purchase` does not merely add noise — it mixes hand-authored\n * hits into a real revenue number. Refusing is also what keeps authored events\n * separable in reports: an event that is not one of {@link ANALYTICS_EVENT_NAMES}\n * is, by construction, authored.\n *\n * Deliberately NOT prefixed (`site_*`) to achieve that separation. A prefix\n * would rename events already flowing into customers' properties and break\n * every report and key-event conversion configured on the old name — a\n * migration cost paid by people who did nothing wrong.\n */\nexport function resolveAuthoredEventName(\n raw: string | undefined | null,\n): ResolvedAuthoredEventName {\n const normalized = String(raw ?? '')\n .trim()\n .toLowerCase()\n // Anything GA4 does not allow in a name becomes an underscore...\n .replace(/[^a-z0-9_]+/g, '_')\n // ...and a name must START with a letter, so drop what precedes one.\n .replace(/^[^a-z]+/, '')\n .replace(/_{2,}/g, '_')\n .slice(0, MAX_EVENT_NAME_LENGTH)\n // Truncation can leave a trailing underscore; so can the substitution.\n .replace(/_+$/, '')\n if (!normalized) return { name: null, reason: 'unusable' }\n if (\n isReservedAnalyticsEventName(normalized) ||\n GA4_RESERVED_EVENT_NAMES.has(normalized) ||\n GA4_RESERVED_PREFIXES.some((prefix) => normalized.startsWith(prefix))\n ) {\n return { name: null, reason: 'reserved' }\n }\n return { name: normalized }\n}\n\n/** One warning per distinct name per page load — an `everyTime` automation\n * would otherwise fill the console with the same line. */\nconst warnedAuthoredNames = new Set<string>()\n\n/**\n * Fire an event whose name and params were written by a SITE AUTHOR, not by a\n * developer — today only the `trackGaEvent` action step (AGL-1587).\n *\n * Same consent gate, same sanitizer, same drop-never-queue posture as\n * {@link trackEvent}; the only difference is that the name is checked at run\n * time instead of by the compiler, because there is no compiler between the\n * interaction builder and here.\n *\n * A refused event is dropped and warned about in the console rather than\n * surfaced in the page. Nothing here can reach the author — the code is\n * running for a VISITOR of their site, and turning the author's configuration\n * mistake into something a visitor sees would be a worse bug than the missing\n * metric. The author-facing half lives in `validateInteraction`, which refuses\n * to save a name this function would refuse to send, so a silent drop should\n * only ever happen to a step authored before AGL-1587.\n */\nexport function trackAuthoredEvent(\n name: string | undefined | null,\n params?: Record<string, unknown> | null,\n): void {\n const resolved = resolveAuthoredEventName(name)\n if (!resolved.name) {\n const key = String(name ?? '')\n if (!warnedAuthoredNames.has(key)) {\n warnedAuthoredNames.add(key)\n try {\n console.warn(\n `[aglyn] analytics: the event \"${key}\" was not sent — ` +\n (resolved.reason === 'reserved'\n ? 'that name is reserved. Rename the step in the interaction builder.'\n : 'an event name must start with a letter.'),\n )\n } catch {\n // A console that throws is still not worth breaking the page for.\n }\n }\n return\n }\n deliver(resolved.name, sanitizeEventParams(params ?? undefined))\n}\n\n/** Test seam — forgets which authored names have already been warned about. */\nexport function resetAuthoredEventWarnings(): void {\n warnedAuthoredNames.clear()\n}\n"],"names":["readGaClientId","measurementId","Promise","resolve","window","gtag","settled","finish","value","setTimeout","id","configuredTransport","configureAnalyticsTransport","transport","resetAnalyticsTransport","DENIED_PARAM_KEYS","Set","EMAIL_SHAPED","ANALYTICS_PARAM_MAX_LENGTH","scrubValue","candidate","test","url","URL","origin","pathname","slice","sanitizeEventParams","params","safe","key","Object","entries","has","toLowerCase","undefined","scrubbed","Array","isArray","map","entry","trackEvent","name","deliver","NAVIGATION_FLUSH_TIMEOUT_MS","trackEventBeforeNavigation","delivered","then","race","catch","buildBeginCheckoutParams","input","priceItems","billingInterval","billing_interval","items","summed","reduce","total","item","price","quantity","currency","Math","round","buildViewCartParams","buildAddToCartParams","priced","isFirstPublishedRoute","routing","defaultHomeScreenId","keys","some","screenId","TAXONOMY_EVENT_NAMES","sign_up","login","generate_lead","select_content","org_created","host_created","site_published","stripe_connected","begin_checkout","purchase","view_item","add_to_cart","view_cart","aglyn_overlay","aglyn_experiment","click","assistant_message_sent","assistant_feedback","assistant_proposal_shown","assistant_proposal_confirmed","ai_job_completed","ai_job_failed","churn_survey_submitted","downsell_accepted","winback_discount_accepted","cancellation_completed","plan_downgrade_scheduled","plan_upgraded","ANALYTICS_EVENT_NAMES","SERVER_ONLY_EVENT_NAMES","isReservedAnalyticsEventName","GA4_RESERVED_EVENT_NAMES","GA4_RESERVED_PREFIXES","MAX_EVENT_NAME_LENGTH","resolveAuthoredEventName","raw","normalized","String","trim","replace","reason","prefix","startsWith","warnedAuthoredNames","trackAuthoredEvent","resolved","add","console","warn","resetAuthoredEventWarnings","clear"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmFC,GAED;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASA,eACdC,aAAwC;IAExC,OAAO,IAAIC,QAAQ,CAACC;QAClB,IAAI,OAAOC,WAAW,eAAe,CAACH,eAAe,OAAOE,QAAQ;QACpE,MAAME,OAAO,AAACD,OAAyCC,IAAI;QAC3D,IAAI,OAAOA,SAAS,YAAY,OAAOF,QAAQ;QAC/C,IAAIG,UAAU;QACd,MAAMC,SAAS,CAACC;YACd,IAAIF,SAAS;YACbA,UAAU;YACVH,QAAQK;QACV;QACA,oDAAoD;QACpDC,WAAW,IAAMF,OAAO,OAAO;QAC/B,IAAI;;YACAF,KACA,OACAJ,eACA,aACA,CAACS,KAAgBH,OAAO,OAAOG,OAAO,YAAYA,KAAKA,KAAK;QAEhE,EAAE,eAAM;YACNH,OAAO;QACT;IACF;AACF;AAgXA,IAAII,sBAAiD;AAErD;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,4BACdC,SAAoC;IAEpCF,sBAAsBE;AACxB;AAEA,gDAAgD,GAChD,OAAO,SAASC;IACdH,s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iEAAiE;KAChEgF,OAAO,CAAC,gBAAgB,IACzB,qEAAqE;KACpEA,OAAO,CAAC,YAAY,IACpBA,OAAO,CAAC,UAAU,KAClBxF,KAAK,CAAC,GAAGkF,sBACV,uEAAuE;KACtEM,OAAO,CAAC,OAAO;IAClB,IAAI,CAACH,YAAY,OAAO;QAAErE,MAAM;QAAMyE,QAAQ;IAAW;IACzD,IACEV,6BAA6BM,eAC7BL,yBAAyBzE,GAAG,CAAC8E,eAC7BJ,sBAAsBnC,IAAI,CAAC,CAAC4C,SAAWL,WAAWM,UAAU,CAACD,UAC7D;QACA,OAAO;YAAE1E,MAAM;YAAMyE,QAAQ;QAAW;IAC1C;IACA,OAAO;QAAEzE,MAAMqE;IAAW;AAC5B;AAEA;wDACwD,GACxD,MAAMO,sBAAsB,IAAItG;AAEhC;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASuG,mBACd7E,IAA+B,EAC/Bd,MAAuC;IAEvC,MAAM4F,WAAWX,yBAAyBnE;IAC1C,IAAI,CAAC8E,SAAS9E,IAAI,EAAE;QAClB,MAAMZ,MAAMkF,OAAOtE,eAAAA,OAAQ;QAC3B,IAAI,CAAC4E,oBAAoBrF,GAAG,CAACH,MAAM;YACjCwF,oBAAoBG,GAAG,CAAC3F;YACxB,IAAI;gBACF4F,QAAQC,IAAI,CACV,CAAC,8BAA8B,EAAE7F,IAAI,iBAAiB,CAAC,GACpD0F,CAAAA,SAASL,MAAM,KAAK,aACjB,uEACA,yCAAwC;YAElD,EAAE,eAAM;YACN,kEAAkE;YACpE;QACF;QACA;IACF;IACAxE,QAAQ6E,SAAS9E,IAAI,EAAEf,oBAAoBC,iBAAAA,SAAUO;AACvD;AAEA,6EAA6E,GAC7E,OAAO,SAASyF;IACdN,oBAAoBO,KAAK;AAC3B"}
@@ -184,6 +184,30 @@ export interface PluginApiRouteOptions {
184
184
  * a payment, so a new visitor door cannot skip the declaration.
185
185
  */
186
186
  cardPayment?: boolean;
187
+ /**
188
+ * The route is a public VISITOR door that runs every visitor gate itself,
189
+ * because its answers to them are a published contract the tenant
190
+ * dispatcher's own would change (AGL-3080).
191
+ *
192
+ * The forms plugin's `forms/submit` is the case: one door for every form
193
+ * and for a Marketing popup's capture, judged by the switch of the plugin
194
+ * whose door a submission came through (not the route's owner), answering
195
+ * a site with Forms off with its own "not accepting" notice, limiting per
196
+ * site and address and capping a flood per month with its own bodies and
197
+ * `Retry-After`s, and placing lockdown among those where its comments say
198
+ * why. The dispatcher's enablement 404, its write limit, its cross-origin
199
+ * refusal and its lockdown would each answer first, and differently.
200
+ *
201
+ * So the tenant dispatcher hands such a route the request untouched: no
202
+ * cross-origin check, no site read from the body, no per-site enablement or
203
+ * release gate, no lockdown, no write limit, no card velocity. Declaring it
204
+ * takes ALL of those on — a door that skips lockdown is one a paused site
205
+ * keeps open — so it is honored only for a FIRST-PARTY plugin's
206
+ * registration, made under the loader's marker; anyone else's keeps the
207
+ * dispatcher's gates, and the drop is logged. The console's dispatcher does
208
+ * not read it.
209
+ */
210
+ ownVisitorGates?: boolean;
187
211
  }
188
212
  export { setRegisteringPluginId, getRegisteringPluginId, } from './registering-plugin';
189
213
  /**
@@ -240,6 +264,12 @@ export declare function isPluginMachineRoute(path: string): boolean;
240
264
  * ask before their enablement and release gates (AGL-3080).
241
265
  */
242
266
  export declare function isPluginPortabilityRoute(path: string): boolean;
267
+ /**
268
+ * Whether a request path resolves to a route that keeps its own visitor
269
+ * gates — {@link PluginApiRouteOptions.ownVisitorGates} — what the tenant
270
+ * dispatcher asks before any gate of its own.
271
+ */
272
+ export declare function isPluginOwnVisitorGatesRoute(path: string): boolean;
243
273
  /**
244
274
  * Whether a request path resolves to a route registered with
245
275
  * {@link PluginApiRouteOptions.cardPayment} — what the tenant dispatcher
@@ -40,6 +40,7 @@ const apiRouteOptions = new Map();
40
40
  * plugin-manager barrel formed a cycle (AGL-1289). Re-exported here so the
41
41
  * plugin loader's existing import keeps working unchanged.
42
42
  */ import { getRegisteringPluginId } from "./registering-plugin.js";
43
+ import { isFirstPartyPlugin } from "../plugin-manager/enabled-plugins.js";
43
44
  export { setRegisteringPluginId, getRegisteringPluginId } from "./registering-plugin.js";
44
45
  /**
45
46
  * Registers a plugin API handler at a host-relative path (e.g.
@@ -77,9 +78,22 @@ export { setRegisteringPluginId, getRegisteringPluginId } from "./registering-pl
77
78
  apiRouteOwners.set(key, owner);
78
79
  // Replaced with the handler, never merged: a re-registration that drops its
79
80
  // subject resolver must not keep answering with the previous one.
80
- if (options) apiRouteOptions.set(key, options);
81
+ if (options) apiRouteOptions.set(key, ownGatesAllowed(key, owner, options));
81
82
  else apiRouteOptions.delete(key);
82
83
  }
84
+ /**
85
+ * The options as registered, less `ownVisitorGates` where the registration
86
+ * may not take the visitor gates on itself: only a first-party plugin's,
87
+ * under the loader's marker (AGL-3080).
88
+ */ function ownGatesAllowed(key, owner, options) {
89
+ if (!options.ownVisitorGates || owner !== ANONYMOUS_OWNER && isFirstPartyPlugin(owner)) {
90
+ return options;
91
+ }
92
+ console.error(`[plugins] API route "${key}" keeps the dispatcher's visitor gates: only a ` + `first-party plugin may run its own, and "${owner || 'an anonymous registration'}" is not one`);
93
+ return _extends({}, options, {
94
+ ownVisitorGates: false
95
+ });
96
+ }
83
97
  /** The marker for a registration made outside any loader context. */ const ANONYMOUS_OWNER = '';
84
98
  /** The plugin that registered a path, for per-org enablement gating. */ export function pluginIdForRegisteredApiPath(path) {
85
99
  const owner = apiRouteOwners.get(normalizeApiPath(path));
@@ -176,6 +190,15 @@ export function unregisterPluginApiRoute(path) {
176
190
  const matched = matchRegisteredApiKey(path);
177
191
  return matched ? ((_apiRouteOptions_get = apiRouteOptions.get(matched.key)) == null ? void 0 : _apiRouteOptions_get.portability) === true : false;
178
192
  }
193
+ /**
194
+ * Whether a request path resolves to a route that keeps its own visitor
195
+ * gates — {@link PluginApiRouteOptions.ownVisitorGates} — what the tenant
196
+ * dispatcher asks before any gate of its own.
197
+ */ export function isPluginOwnVisitorGatesRoute(path) {
198
+ var _apiRouteOptions_get;
199
+ const matched = matchRegisteredApiKey(path);
200
+ return matched ? ((_apiRouteOptions_get = apiRouteOptions.get(matched.key)) == null ? void 0 : _apiRouteOptions_get.ownVisitorGates) === true : false;
201
+ }
179
202
  /**
180
203
  * Whether a request path resolves to a route registered with
181
204
  * {@link PluginApiRouteOptions.cardPayment} — what the tenant dispatcher
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/api-plugins.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 * Server half of the plugin pattern (AGL-396): the API-route registry, the\n * server counterpart to the ConsoleExtension registry. A feature plugin\n * registers request handlers here from its `/server` entry point (never its\n * client barrel, so firebase-admin and other server-only deps stay out of\n * the browser bundle). The app ships one catch-all dispatcher route per\n * Next app that resolves a request path to a registered handler — so moving\n * a feature's API into its plugin needs no new app route and keeps the same\n * URL. Reference implementation: events-calendar `events/list` (AGL-396).\n *\n * The request/response shapes are structural (not `next` types) so plugins\n * stay framework-light; `NextApiRequest`/`NextApiResponse` satisfy them, so\n * the dispatcher passes Next's objects straight through.\n */\n\nexport interface PluginApiRequest {\n method?: string\n query: Partial<Record<string, string | string[]>>\n // `any` mirrors NextApiRequest.body (parsed JSON/form/text); handlers\n // validate it themselves, as they did as Next routes.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n body: any\n /**\n * The unparsed request text, for handlers that verify signatures over the\n * exact payload (Stripe/Svix webhooks registered as plugin API paths).\n * UTF-8 re-encoding of the text is byte-identical for valid UTF-8 JSON.\n */\n rawBody?: string\n headers: Partial<Record<string, string | string[]>>\n cookies: Partial<Record<string, string>>\n /**\n * Node socket — the client-address fallback (`remoteAddress`).\n *\n * On the console's Pages Router this is the real transport peer. Behind the\n * App Router adapter there is no socket, and `api-adapter.ts` fills it from\n * the shared client-address reader so a handler falling back to it gets the\n * same trusted hop rather than a caller-supplied one.\n */\n socket: { remoteAddress?: string }\n}\n\nexport interface PluginApiResponse {\n status(code: number): PluginApiResponse\n json(body: unknown): void\n send(body: unknown): void\n setHeader(name: string, value: string | number | readonly string[]): void\n redirect(url: string): void\n redirect(status: number, url: string): void\n end(): void\n}\n\nexport type PluginApiHandler = (\n req: PluginApiRequest,\n res: PluginApiResponse,\n) => void | Promise<void>\n\n/**\n * A handler in the Web shape (AGL-2939): the dispatcher's own `Request`\n * in, a `Response` out — with a streamed body when the door streams, as\n * the assistant's chat and a job's event feed do. `params` carries the\n * dispatcher's path segments and any `:name` segment the registered path\n * declared.\n */\nexport type PluginWebApiHandler = (\n request: Request,\n context: { params: Record<string, string | string[]> },\n) => Response | Promise<Response>\n\n/** What a route registers: the (req, res) shape, or a Web handler. */\nexport type PluginApiRoute = PluginApiHandler | { web: PluginWebApiHandler }\n\n/** A registered route matched to a request path, with its `:name` segments filled. */\nexport interface PluginApiMatch {\n route: PluginApiRoute\n params: Record<string, string>\n}\n\n/**\n * Who a request is FOR, as far as the dispatchers' release gate is concerned\n * (AGL-2978).\n *\n * The gate buckets a rollout and reads per-org overrides on an org id, and a\n * dispatcher learns that id from the site a request names (`hostId`). Two\n * kinds of request name no site and still belong to one organization:\n *\n * - a request to an ORGANIZATION-level surface (`ConsoleExtension.orgNavItems`,\n * AGL-2974), which names its org rather than a site;\n * - a request that arrives with no bearer token by design — a provider's\n * OAuth redirect back to the platform, which carries only what the platform\n * signed into it.\n *\n * Without a subject the gate treats both as anonymous, so a plugin released to\n * one organization by override refused that organization's own requests, and\n * a staff member previewing a dark plugin could not complete a redirect their\n * own session had started.\n */\nexport interface PluginApiRequestSubject {\n /** The organization: the rollout bucket and the override key. */\n orgId: string | null\n /**\n * The account the request acts for, read ONLY when the request carries no\n * bearer token — a token speaks for itself. A route may name one only when\n * it verified a signature binding the uid to the request, because the gate\n * lets a staff account named here preview a released-off plugin.\n */\n uid?: string | null\n}\n\n/** Reads a request's subject; answers `null` when the request names none. */\nexport type PluginApiSubjectResolver = (\n request: Request,\n) => PluginApiRequestSubject | null | Promise<PluginApiRequestSubject | null>\n\n/** What a registration may say about its route beyond the handler. */\nexport interface PluginApiRouteOptions {\n /**\n * How a request to this route names its subject when it names no site.\n * Consulted by both dispatchers before their release gate, and only for a\n * request with no `hostId`: a named site always decides the org.\n */\n subject?: PluginApiSubjectResolver\n /**\n * The route answers a link the platform MAILED to somebody — an\n * unsubscribe in a message's `List-Unsubscribe` header — rather than a door\n * a member uses (AGL-2981).\n *\n * Such a link has to keep working whether or not its plugin is released,\n * or switched on, for the workspace NOW. A recipient's way out does not\n * close when a rollout is paused or a workspace turns the plugin off:\n * CAN-SPAM holds an opt-out open for thirty days after the send, and an\n * unsubscribe that 404s the day a kill switch is flipped is one nobody can\n * use. So both dispatchers skip their per-site enablement and release\n * gates for it — and nothing else: lockdown and the rate limit still\n * apply. The flag says nothing about who may act, so the route\n * authenticates the link itself, by a signature it verifies.\n */\n recipientLink?: boolean\n /**\n * The route is called by a MACHINE that proves itself with a credential\n * the route verifies — a scheduler's shared secret, a provider's signed\n * webhook — and names no site and no member (AGL-3080).\n *\n * Such a request has no subject the dispatcher could gate on before the\n * route has verified it: a sweep spans every organization, and a webhook's\n * workspace is inside a payload only a verified signature makes worth\n * reading. Gated anonymously, a plugin on a partial rollout would refuse\n * every delivery. So both dispatchers skip their per-site enablement and\n * release gates for it, and — because a chunked sweep posts from one\n * address, and a provider retries in bursts — their write limit and their\n * cross-origin check (`isMachinePluginApiPath`); lockdown still applies.\n * The flag grants nothing by itself: the route authenticates its caller,\n * and judges the plugin's release and plan for each organization it\n * resolves from what it verified.\n */\n machine?: boolean\n /**\n * The route hands a workspace the records a plugin keeps for it — a\n * data-portability export — which the workspace is owed whether or not the\n * plugin is switched on or released for it now (AGL-3080).\n *\n * Exporting the people a workspace holds is an obligation, not a feature:\n * a workspace that switched the plugin off, or a plugin paused by its\n * kill switch, still has to be able to take its data away. So both\n * dispatchers skip their per-site enablement and release gates for it —\n * and nothing else: lockdown, the email-verification gate and the rate\n * limit still apply. The flag grants nothing by itself: the route\n * authenticates the member, and asks the plugin's release and plan itself\n * of anything it serves beyond what the workspace is owed.\n */\n portability?: boolean\n /**\n * The route OPENS A CARD PAYMENT for whoever calls it: a Checkout Session,\n * a PaymentIntent or a SetupIntent (AGL-3363).\n *\n * The tenant dispatcher holds such a route to the card-testing counters\n * (`card-payment-velocity.ts`) on top of its ordinary write limit, so a\n * plugin's payment door is covered by declaring itself here rather than by\n * carrying a limiter of its own. A console door (a signed-in merchant's\n * POS or draft order) does not declare it: a register ringing up a queue\n * is not a card tester. The 3-D Secure sweep\n * (`card-payments-request-3ds.spec.ts`) classifies every file that creates\n * a payment, so a new visitor door cannot skip the declaration.\n */\n cardPayment?: boolean\n}\n\n/** Leading/trailing slashes stripped so '/events/list' and 'events/list' key alike. */\nfunction normalizeApiPath(path: string): string {\n return path.replace(/^\\/+|\\/+$/g, '')\n}\n\nconst apiRoutes = new Map<string, PluginApiRoute>()\nconst apiRouteOwners = new Map<string, string>()\nconst apiRouteOptions = new Map<string, PluginApiRouteOptions>()\n\n/**\n * The \"currently registering plugin\" marker moved to a leaf module\n * (`registering-plugin`) so `site-page-hooks` can read it too — this file is\n * only reachable through the `/server` entry, and importing it from the shared\n * plugin-manager barrel formed a cycle (AGL-1289). Re-exported here so the\n * plugin loader's existing import keeps working unchanged.\n */\nimport { getRegisteringPluginId } from './registering-plugin'\n\nexport {\n setRegisteringPluginId,\n getRegisteringPluginId,\n} from './registering-plugin'\n\n/**\n * Registers a plugin API handler at a host-relative path (e.g.\n * 'events/list'), served by the app dispatcher at `/api/events/list`.\n *\n * Idempotent by path FOR ITS OWNER — re-registration by the plugin that\n * holds the path replaces the previous handler, which is what a hot reload,\n * a second surface, and a repeated init all depend on.\n *\n * A different plugin is REFUSED (AGL-2484). This map is process-global and\n * was last-writer-wins on the path alone, while Aglyn's own commission-taking\n * handlers sit at `marketplace/checkout` and `commerce/checkout` — and the\n * tenant dispatcher calls `ensureRemoteServerBundles()` after the first-party\n * loader has run, so a remote bundle registering either path was simply the\n * later writer. Getting there needs `PLUGIN_REMOTE_SERVER=enabled` (off by\n * default), realm trust and a valid signature, so this is the last of several\n * doors rather than the only one; it is also the one the registry could close\n * by itself, because it already recorded who registered what.\n *\n * Anonymous registration — no loader marker — is an IDENTITY here, not a\n * wildcard: it may replace itself and nothing else may take it.\n */\nexport function registerPluginApiRoute(\n path: string,\n handler: PluginApiRoute,\n options?: PluginApiRouteOptions,\n): void {\n const key = normalizeApiPath(path)\n const owner = getRegisteringPluginId() ?? ANONYMOUS_OWNER\n const incumbent = apiRouteOwners.get(key)\n if (incumbent !== undefined && incumbent !== owner) {\n // Loud, because the silent version of this is a payment route quietly\n // answering from someone else's code. Refusing is the safe direction:\n // the incumbent keeps serving.\n console.error(\n `[plugins] refused API route \"${key}\" to \"${owner}\": already ` +\n `registered by \"${incumbent}\"`,\n )\n return\n }\n apiRoutes.set(key, handler)\n apiRouteOwners.set(key, owner)\n // Replaced with the handler, never merged: a re-registration that drops its\n // subject resolver must not keep answering with the previous one.\n if (options) apiRouteOptions.set(key, options)\n else apiRouteOptions.delete(key)\n}\n\n/** The marker for a registration made outside any loader context. */\nconst ANONYMOUS_OWNER = ''\n\n/** The plugin that registered a path, for per-org enablement gating. */\nexport function pluginIdForRegisteredApiPath(path: string): string | undefined {\n const owner = apiRouteOwners.get(normalizeApiPath(path))\n // An anonymous registration has no plugin to gate on, and this has always\n // answered `undefined` for one — the sentinel must not leak out as an id.\n return owner === undefined || owner === ANONYMOUS_OWNER ? undefined : owner\n}\n\nexport function unregisterPluginApiRoute(path: string): void {\n const key = normalizeApiPath(path)\n apiRoutes.delete(key)\n // Release the CLAIM too, or the refusal above outlives the route and the\n // path can never be re-registered for the life of the process.\n apiRouteOwners.delete(key)\n apiRouteOptions.delete(key)\n}\n\n/**\n * The registered key a request path resolves to, with its `:name` segments.\n *\n * An exact registration wins; otherwise a registration whose path carries\n * `:name` segments matches segment for segment. One matcher for the route and\n * for its options, so a request can never be answered by one registration and\n * gated with another's subject.\n */\nfunction matchRegisteredApiKey(\n path: string,\n): { key: string; params: Record<string, string> } | undefined {\n const key = normalizeApiPath(path)\n if (apiRoutes.has(key)) return { key, params: {} }\n const segments = key.split('/')\n for (const registered of apiRoutes.keys()) {\n if (!registered.includes(':')) continue\n const pattern = registered.split('/')\n if (pattern.length !== segments.length) continue\n const params: Record<string, string> = {}\n let matched = true\n for (let index = 0; index < pattern.length; index += 1) {\n const part = pattern[index]\n if (part.startsWith(':') && segments[index]) {\n params[part.slice(1)] = segments[index]\n } else if (part !== segments[index]) {\n matched = false\n break\n }\n }\n if (matched) return { key: registered, params }\n }\n return undefined\n}\n\n/**\n * The route for a request path, or undefined when nothing is registered.\n *\n * An exact registration wins; otherwise a registration whose path carries\n * `:name` segments matches segment for segment (`ai/jobs/:jobId/cancel`\n * answers `ai/jobs/abc/cancel`), and the named segments come back as\n * `params`. Patterns are tried in registration order and a static segment\n * beats a named one only by being registered exactly.\n */\nexport function resolvePluginApiMatch(path: string): PluginApiMatch | undefined {\n const matched = matchRegisteredApiKey(path)\n if (!matched) return undefined\n const route = apiRoutes.get(matched.key)\n return route ? { route, params: matched.params } : undefined\n}\n\n/**\n * Whether a request path resolves to a route registered as a\n * {@link PluginApiRouteOptions.recipientLink} — what both dispatchers ask\n * before their enablement and release gates (AGL-2981).\n */\nexport function isPluginRecipientLinkRoute(path: string): boolean {\n const matched = matchRegisteredApiKey(path)\n return matched ? apiRouteOptions.get(matched.key)?.recipientLink === true : false\n}\n\n/**\n * Whether a request path resolves to a route registered as a\n * {@link PluginApiRouteOptions.machine} caller's — what both dispatchers ask\n * before their enablement and release gates, and the write limits before\n * they count (AGL-3080).\n */\nexport function isPluginMachineRoute(path: string): boolean {\n const matched = matchRegisteredApiKey(path)\n return matched ? apiRouteOptions.get(matched.key)?.machine === true : false\n}\n\n/**\n * Whether a request path resolves to a route registered as a\n * {@link PluginApiRouteOptions.portability} export — what both dispatchers\n * ask before their enablement and release gates (AGL-3080).\n */\nexport function isPluginPortabilityRoute(path: string): boolean {\n const matched = matchRegisteredApiKey(path)\n return matched ? apiRouteOptions.get(matched.key)?.portability === true : false\n}\n\n/**\n * Whether a request path resolves to a route registered with\n * {@link PluginApiRouteOptions.cardPayment} — what the tenant dispatcher\n * asks before its card-testing counters (AGL-3363).\n */\nexport function isPluginCardPaymentRoute(path: string): boolean {\n const matched = matchRegisteredApiKey(path)\n return matched ? apiRouteOptions.get(matched.key)?.cardPayment === true : false\n}\n\n/** An id a subject may carry: a non-empty path segment, not a path. */\nconst SUBJECT_ID = /^[^/\\s]{1,128}$/\n\nconst subjectId = (value: unknown): string | null =>\n typeof value === 'string' && SUBJECT_ID.test(value) ? value : null\n\n/**\n * The subject a request to a registered route names, or `null` (AGL-2978).\n *\n * `null` when the route declared no resolver, when the resolver answered\n * nothing, and when it THREW: a resolver that cannot read its request has\n * named no subject, and the gate then treats the request as anonymous — the\n * conservative direction. The resolver reads a clone, so the handler still\n * receives the untouched body. Ids are held to a plain path segment, so a\n * resolver cannot hand the gate a path to read overrides from.\n */\nexport async function resolvePluginApiRequestSubject(\n path: string,\n request: Request,\n): Promise<PluginApiRequestSubject | null> {\n const matched = matchRegisteredApiKey(path)\n const resolve = matched ? apiRouteOptions.get(matched.key)?.subject : undefined\n if (!resolve) return null\n try {\n const subject = await resolve(request.clone())\n if (!subject) return null\n const orgId = subjectId(subject.orgId)\n const uid = subjectId(subject.uid)\n if (!orgId && !uid) return null\n return { orgId, ...(uid ? { uid } : {}) }\n } catch {\n return null\n }\n}\n\n/**\n * The legacy (node-style) handler at a request path, or undefined when\n * nothing is registered there or the route is a web handler — a web route\n * is reached through `resolvePluginApiMatch` and `runPluginApiMatch`, since\n * it takes the `Request` and the filled `:name` segments, not a `req`/`res`\n * pair.\n */\nexport function resolvePluginApiRoute(path: string): PluginApiHandler | undefined {\n const route = resolvePluginApiMatch(path)?.route\n return typeof route === 'function' ? route : undefined\n}\n\n/**\n * Runs a matched route against the dispatcher's request: a Web handler is\n * called as it is, and a (req, res) handler goes through the adapter the\n * caller supplies — the adapter lives on the `/server` entry, which this\n * module may not import.\n */\nexport async function runPluginApiMatch(\n match: PluginApiMatch,\n request: Request,\n params: Record<string, string | string[]>,\n runLegacy: (\n handler: PluginApiHandler,\n request: Request,\n params: Record<string, string | string[]>,\n ) => Promise<Response>,\n): Promise<Response> {\n const merged = { ...params, ...match.params }\n const route = match.route as { web?: PluginWebApiHandler }\n if (typeof route === 'object' && route !== null && typeof route.web === 'function') {\n return route.web(request, { params: merged })\n }\n return runLegacy(match.route as PluginApiHandler, request, merged)\n}\n\n/** Registered paths, for diagnostics. */\nexport function listPluginApiRoutes(): string[] {\n return Array.from(apiRoutes.keys())\n}\n"],"names":["normalizeApiPath","path","replace","apiRoutes","Map","apiRouteOwners","apiRouteOptions","getRegisteringPluginId","setRegisteringPluginId","registerPluginApiRoute","handler","options","key","owner","ANONYMOUS_OWNER","incumbent","get","undefined","console","error","set","delete","pluginIdForRegisteredApiPath","unregisterPluginApiRoute","matchRegisteredApiKey","has","params","segments","split","registered","keys","includes","pattern","length","matched","index","part","startsWith","slice","resolvePluginApiMatch","route","isPluginRecipientLinkRoute","recipientLink","isPluginMachineRoute","machine","isPluginPortabilityRoute","portability","isPluginCardPaymentRoute","cardPayment","SUBJECT_ID","subjectId","value","test","resolvePluginApiRequestSubject","request","resolve","subject","clone","orgId","uid","resolvePluginApiRoute","runPluginApiMatch","match","runLegacy","merged","web","listPluginApiRoutes","Array","from"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;CAaC;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AK;QAC3C,IAAI,CAACD,SAAS,OAAO;QACrB,MAAME,QAAQR,UAAUM,QAAQE,KAAK;QACrC,MAAMC,MAAMT,UAAUM,QAAQG,GAAG;QACjC,IAAI,CAACD,SAAS,CAACC,KAAK,OAAO;QAC3B,OAAO;YAAED;WAAWC,MAAM;YAAEA;QAAI,IAAI,CAAC;IACvC,EAAE,eAAM;QACN,OAAO;IACT;AACF;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,sBAAsB3D,IAAY;QAClCsC;IAAd,MAAMC,SAAQD,yBAAAA,sBAAsBtC,0BAAtBsC,uBAA6BC,KAAK;IAChD,OAAO,OAAOA,UAAU,aAAaA,QAAQvB;AAC/C;AAEA;;;;;CAKC,GACD,OAAO,eAAe4C,kBACpBC,KAAqB,EACrBR,OAAgB,EAChB5B,MAAyC,EACzCqC,SAIsB;IAEtB,MAAMC,SAAS,aAAKtC,QAAWoC,MAAMpC,MAAM;IAC3C,MAAMc,QAAQsB,MAAMtB,KAAK;IACzB,IAAI,OAAOA,UAAU,YAAYA,UAAU,QAAQ,OAAOA,MAAMyB,GAAG,KAAK,YAAY;QAClF,OAAOzB,MAAMyB,GAAG,CAACX,SAAS;YAAE5B,QAAQsC;QAAO;IAC7C;IACA,OAAOD,UAAUD,MAAMtB,KAAK,EAAsBc,SAASU;AAC7D;AAEA,uCAAuC,GACvC,OAAO,SAASE;IACd,OAAOC,MAAMC,IAAI,CAACjE,UAAU2B,IAAI;AAClC"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/api-plugins.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 * Server half of the plugin pattern (AGL-396): the API-route registry, the\n * server counterpart to the ConsoleExtension registry. A feature plugin\n * registers request handlers here from its `/server` entry point (never its\n * client barrel, so firebase-admin and other server-only deps stay out of\n * the browser bundle). The app ships one catch-all dispatcher route per\n * Next app that resolves a request path to a registered handler — so moving\n * a feature's API into its plugin needs no new app route and keeps the same\n * URL. Reference implementation: events-calendar `events/list` (AGL-396).\n *\n * The request/response shapes are structural (not `next` types) so plugins\n * stay framework-light; `NextApiRequest`/`NextApiResponse` satisfy them, so\n * the dispatcher passes Next's objects straight through.\n */\n\nexport interface PluginApiRequest {\n method?: string\n query: Partial<Record<string, string | string[]>>\n // `any` mirrors NextApiRequest.body (parsed JSON/form/text); handlers\n // validate it themselves, as they did as Next routes.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n body: any\n /**\n * The unparsed request text, for handlers that verify signatures over the\n * exact payload (Stripe/Svix webhooks registered as plugin API paths).\n * UTF-8 re-encoding of the text is byte-identical for valid UTF-8 JSON.\n */\n rawBody?: string\n headers: Partial<Record<string, string | string[]>>\n cookies: Partial<Record<string, string>>\n /**\n * Node socket — the client-address fallback (`remoteAddress`).\n *\n * On the console's Pages Router this is the real transport peer. Behind the\n * App Router adapter there is no socket, and `api-adapter.ts` fills it from\n * the shared client-address reader so a handler falling back to it gets the\n * same trusted hop rather than a caller-supplied one.\n */\n socket: { remoteAddress?: string }\n}\n\nexport interface PluginApiResponse {\n status(code: number): PluginApiResponse\n json(body: unknown): void\n send(body: unknown): void\n setHeader(name: string, value: string | number | readonly string[]): void\n redirect(url: string): void\n redirect(status: number, url: string): void\n end(): void\n}\n\nexport type PluginApiHandler = (\n req: PluginApiRequest,\n res: PluginApiResponse,\n) => void | Promise<void>\n\n/**\n * A handler in the Web shape (AGL-2939): the dispatcher's own `Request`\n * in, a `Response` out — with a streamed body when the door streams, as\n * the assistant's chat and a job's event feed do. `params` carries the\n * dispatcher's path segments and any `:name` segment the registered path\n * declared.\n */\nexport type PluginWebApiHandler = (\n request: Request,\n context: { params: Record<string, string | string[]> },\n) => Response | Promise<Response>\n\n/** What a route registers: the (req, res) shape, or a Web handler. */\nexport type PluginApiRoute = PluginApiHandler | { web: PluginWebApiHandler }\n\n/** A registered route matched to a request path, with its `:name` segments filled. */\nexport interface PluginApiMatch {\n route: PluginApiRoute\n params: Record<string, string>\n}\n\n/**\n * Who a request is FOR, as far as the dispatchers' release gate is concerned\n * (AGL-2978).\n *\n * The gate buckets a rollout and reads per-org overrides on an org id, and a\n * dispatcher learns that id from the site a request names (`hostId`). Two\n * kinds of request name no site and still belong to one organization:\n *\n * - a request to an ORGANIZATION-level surface (`ConsoleExtension.orgNavItems`,\n * AGL-2974), which names its org rather than a site;\n * - a request that arrives with no bearer token by design — a provider's\n * OAuth redirect back to the platform, which carries only what the platform\n * signed into it.\n *\n * Without a subject the gate treats both as anonymous, so a plugin released to\n * one organization by override refused that organization's own requests, and\n * a staff member previewing a dark plugin could not complete a redirect their\n * own session had started.\n */\nexport interface PluginApiRequestSubject {\n /** The organization: the rollout bucket and the override key. */\n orgId: string | null\n /**\n * The account the request acts for, read ONLY when the request carries no\n * bearer token — a token speaks for itself. A route may name one only when\n * it verified a signature binding the uid to the request, because the gate\n * lets a staff account named here preview a released-off plugin.\n */\n uid?: string | null\n}\n\n/** Reads a request's subject; answers `null` when the request names none. */\nexport type PluginApiSubjectResolver = (\n request: Request,\n) => PluginApiRequestSubject | null | Promise<PluginApiRequestSubject | null>\n\n/** What a registration may say about its route beyond the handler. */\nexport interface PluginApiRouteOptions {\n /**\n * How a request to this route names its subject when it names no site.\n * Consulted by both dispatchers before their release gate, and only for a\n * request with no `hostId`: a named site always decides the org.\n */\n subject?: PluginApiSubjectResolver\n /**\n * The route answers a link the platform MAILED to somebody — an\n * unsubscribe in a message's `List-Unsubscribe` header — rather than a door\n * a member uses (AGL-2981).\n *\n * Such a link has to keep working whether or not its plugin is released,\n * or switched on, for the workspace NOW. A recipient's way out does not\n * close when a rollout is paused or a workspace turns the plugin off:\n * CAN-SPAM holds an opt-out open for thirty days after the send, and an\n * unsubscribe that 404s the day a kill switch is flipped is one nobody can\n * use. So both dispatchers skip their per-site enablement and release\n * gates for it — and nothing else: lockdown and the rate limit still\n * apply. The flag says nothing about who may act, so the route\n * authenticates the link itself, by a signature it verifies.\n */\n recipientLink?: boolean\n /**\n * The route is called by a MACHINE that proves itself with a credential\n * the route verifies — a scheduler's shared secret, a provider's signed\n * webhook — and names no site and no member (AGL-3080).\n *\n * Such a request has no subject the dispatcher could gate on before the\n * route has verified it: a sweep spans every organization, and a webhook's\n * workspace is inside a payload only a verified signature makes worth\n * reading. Gated anonymously, a plugin on a partial rollout would refuse\n * every delivery. So both dispatchers skip their per-site enablement and\n * release gates for it, and — because a chunked sweep posts from one\n * address, and a provider retries in bursts — their write limit and their\n * cross-origin check (`isMachinePluginApiPath`); lockdown still applies.\n * The flag grants nothing by itself: the route authenticates its caller,\n * and judges the plugin's release and plan for each organization it\n * resolves from what it verified.\n */\n machine?: boolean\n /**\n * The route hands a workspace the records a plugin keeps for it — a\n * data-portability export — which the workspace is owed whether or not the\n * plugin is switched on or released for it now (AGL-3080).\n *\n * Exporting the people a workspace holds is an obligation, not a feature:\n * a workspace that switched the plugin off, or a plugin paused by its\n * kill switch, still has to be able to take its data away. So both\n * dispatchers skip their per-site enablement and release gates for it —\n * and nothing else: lockdown, the email-verification gate and the rate\n * limit still apply. The flag grants nothing by itself: the route\n * authenticates the member, and asks the plugin's release and plan itself\n * of anything it serves beyond what the workspace is owed.\n */\n portability?: boolean\n /**\n * The route OPENS A CARD PAYMENT for whoever calls it: a Checkout Session,\n * a PaymentIntent or a SetupIntent (AGL-3363).\n *\n * The tenant dispatcher holds such a route to the card-testing counters\n * (`card-payment-velocity.ts`) on top of its ordinary write limit, so a\n * plugin's payment door is covered by declaring itself here rather than by\n * carrying a limiter of its own. A console door (a signed-in merchant's\n * POS or draft order) does not declare it: a register ringing up a queue\n * is not a card tester. The 3-D Secure sweep\n * (`card-payments-request-3ds.spec.ts`) classifies every file that creates\n * a payment, so a new visitor door cannot skip the declaration.\n */\n cardPayment?: boolean\n /**\n * The route is a public VISITOR door that runs every visitor gate itself,\n * because its answers to them are a published contract the tenant\n * dispatcher's own would change (AGL-3080).\n *\n * The forms plugin's `forms/submit` is the case: one door for every form\n * and for a Marketing popup's capture, judged by the switch of the plugin\n * whose door a submission came through (not the route's owner), answering\n * a site with Forms off with its own \"not accepting\" notice, limiting per\n * site and address and capping a flood per month with its own bodies and\n * `Retry-After`s, and placing lockdown among those where its comments say\n * why. The dispatcher's enablement 404, its write limit, its cross-origin\n * refusal and its lockdown would each answer first, and differently.\n *\n * So the tenant dispatcher hands such a route the request untouched: no\n * cross-origin check, no site read from the body, no per-site enablement or\n * release gate, no lockdown, no write limit, no card velocity. Declaring it\n * takes ALL of those on — a door that skips lockdown is one a paused site\n * keeps open — so it is honored only for a FIRST-PARTY plugin's\n * registration, made under the loader's marker; anyone else's keeps the\n * dispatcher's gates, and the drop is logged. The console's dispatcher does\n * not read it.\n */\n ownVisitorGates?: boolean\n}\n\n/** Leading/trailing slashes stripped so '/events/list' and 'events/list' key alike. */\nfunction normalizeApiPath(path: string): string {\n return path.replace(/^\\/+|\\/+$/g, '')\n}\n\nconst apiRoutes = new Map<string, PluginApiRoute>()\nconst apiRouteOwners = new Map<string, string>()\nconst apiRouteOptions = new Map<string, PluginApiRouteOptions>()\n\n/**\n * The \"currently registering plugin\" marker moved to a leaf module\n * (`registering-plugin`) so `site-page-hooks` can read it too — this file is\n * only reachable through the `/server` entry, and importing it from the shared\n * plugin-manager barrel formed a cycle (AGL-1289). Re-exported here so the\n * plugin loader's existing import keeps working unchanged.\n */\nimport { getRegisteringPluginId } from './registering-plugin'\nimport { isFirstPartyPlugin } from '../plugin-manager/enabled-plugins'\n\nexport {\n setRegisteringPluginId,\n getRegisteringPluginId,\n} from './registering-plugin'\n\n/**\n * Registers a plugin API handler at a host-relative path (e.g.\n * 'events/list'), served by the app dispatcher at `/api/events/list`.\n *\n * Idempotent by path FOR ITS OWNER — re-registration by the plugin that\n * holds the path replaces the previous handler, which is what a hot reload,\n * a second surface, and a repeated init all depend on.\n *\n * A different plugin is REFUSED (AGL-2484). This map is process-global and\n * was last-writer-wins on the path alone, while Aglyn's own commission-taking\n * handlers sit at `marketplace/checkout` and `commerce/checkout` — and the\n * tenant dispatcher calls `ensureRemoteServerBundles()` after the first-party\n * loader has run, so a remote bundle registering either path was simply the\n * later writer. Getting there needs `PLUGIN_REMOTE_SERVER=enabled` (off by\n * default), realm trust and a valid signature, so this is the last of several\n * doors rather than the only one; it is also the one the registry could close\n * by itself, because it already recorded who registered what.\n *\n * Anonymous registration — no loader marker — is an IDENTITY here, not a\n * wildcard: it may replace itself and nothing else may take it.\n */\nexport function registerPluginApiRoute(\n path: string,\n handler: PluginApiRoute,\n options?: PluginApiRouteOptions,\n): void {\n const key = normalizeApiPath(path)\n const owner = getRegisteringPluginId() ?? ANONYMOUS_OWNER\n const incumbent = apiRouteOwners.get(key)\n if (incumbent !== undefined && incumbent !== owner) {\n // Loud, because the silent version of this is a payment route quietly\n // answering from someone else's code. Refusing is the safe direction:\n // the incumbent keeps serving.\n console.error(\n `[plugins] refused API route \"${key}\" to \"${owner}\": already ` +\n `registered by \"${incumbent}\"`,\n )\n return\n }\n apiRoutes.set(key, handler)\n apiRouteOwners.set(key, owner)\n // Replaced with the handler, never merged: a re-registration that drops its\n // subject resolver must not keep answering with the previous one.\n if (options) apiRouteOptions.set(key, ownGatesAllowed(key, owner, options))\n else apiRouteOptions.delete(key)\n}\n\n/**\n * The options as registered, less `ownVisitorGates` where the registration\n * may not take the visitor gates on itself: only a first-party plugin's,\n * under the loader's marker (AGL-3080).\n */\nfunction ownGatesAllowed(\n key: string,\n owner: string,\n options: PluginApiRouteOptions,\n): PluginApiRouteOptions {\n if (!options.ownVisitorGates || (owner !== ANONYMOUS_OWNER && isFirstPartyPlugin(owner))) {\n return options\n }\n console.error(\n `[plugins] API route \"${key}\" keeps the dispatcher's visitor gates: only a ` +\n `first-party plugin may run its own, and \"${owner || 'an anonymous registration'}\" is not one`,\n )\n return { ...options, ownVisitorGates: false }\n}\n\n/** The marker for a registration made outside any loader context. */\nconst ANONYMOUS_OWNER = ''\n\n/** The plugin that registered a path, for per-org enablement gating. */\nexport function pluginIdForRegisteredApiPath(path: string): string | undefined {\n const owner = apiRouteOwners.get(normalizeApiPath(path))\n // An anonymous registration has no plugin to gate on, and this has always\n // answered `undefined` for one — the sentinel must not leak out as an id.\n return owner === undefined || owner === ANONYMOUS_OWNER ? undefined : owner\n}\n\nexport function unregisterPluginApiRoute(path: string): void {\n const key = normalizeApiPath(path)\n apiRoutes.delete(key)\n // Release the CLAIM too, or the refusal above outlives the route and the\n // path can never be re-registered for the life of the process.\n apiRouteOwners.delete(key)\n apiRouteOptions.delete(key)\n}\n\n/**\n * The registered key a request path resolves to, with its `:name` segments.\n *\n * An exact registration wins; otherwise a registration whose path carries\n * `:name` segments matches segment for segment. One matcher for the route and\n * for its options, so a request can never be answered by one registration and\n * gated with another's subject.\n */\nfunction matchRegisteredApiKey(\n path: string,\n): { key: string; params: Record<string, string> } | undefined {\n const key = normalizeApiPath(path)\n if (apiRoutes.has(key)) return { key, params: {} }\n const segments = key.split('/')\n for (const registered of apiRoutes.keys()) {\n if (!registered.includes(':')) continue\n const pattern = registered.split('/')\n if (pattern.length !== segments.length) continue\n const params: Record<string, string> = {}\n let matched = true\n for (let index = 0; index < pattern.length; index += 1) {\n const part = pattern[index]\n if (part.startsWith(':') && segments[index]) {\n params[part.slice(1)] = segments[index]\n } else if (part !== segments[index]) {\n matched = false\n break\n }\n }\n if (matched) return { key: registered, params }\n }\n return undefined\n}\n\n/**\n * The route for a request path, or undefined when nothing is registered.\n *\n * An exact registration wins; otherwise a registration whose path carries\n * `:name` segments matches segment for segment (`ai/jobs/:jobId/cancel`\n * answers `ai/jobs/abc/cancel`), and the named segments come back as\n * `params`. Patterns are tried in registration order and a static segment\n * beats a named one only by being registered exactly.\n */\nexport function resolvePluginApiMatch(path: string): PluginApiMatch | undefined {\n const matched = matchRegisteredApiKey(path)\n if (!matched) return undefined\n const route = apiRoutes.get(matched.key)\n return route ? { route, params: matched.params } : undefined\n}\n\n/**\n * Whether a request path resolves to a route registered as a\n * {@link PluginApiRouteOptions.recipientLink} — what both dispatchers ask\n * before their enablement and release gates (AGL-2981).\n */\nexport function isPluginRecipientLinkRoute(path: string): boolean {\n const matched = matchRegisteredApiKey(path)\n return matched ? apiRouteOptions.get(matched.key)?.recipientLink === true : false\n}\n\n/**\n * Whether a request path resolves to a route registered as a\n * {@link PluginApiRouteOptions.machine} caller's — what both dispatchers ask\n * before their enablement and release gates, and the write limits before\n * they count (AGL-3080).\n */\nexport function isPluginMachineRoute(path: string): boolean {\n const matched = matchRegisteredApiKey(path)\n return matched ? apiRouteOptions.get(matched.key)?.machine === true : false\n}\n\n/**\n * Whether a request path resolves to a route registered as a\n * {@link PluginApiRouteOptions.portability} export — what both dispatchers\n * ask before their enablement and release gates (AGL-3080).\n */\nexport function isPluginPortabilityRoute(path: string): boolean {\n const matched = matchRegisteredApiKey(path)\n return matched ? apiRouteOptions.get(matched.key)?.portability === true : false\n}\n\n/**\n * Whether a request path resolves to a route that keeps its own visitor\n * gates — {@link PluginApiRouteOptions.ownVisitorGates} — what the tenant\n * dispatcher asks before any gate of its own.\n */\nexport function isPluginOwnVisitorGatesRoute(path: string): boolean {\n const matched = matchRegisteredApiKey(path)\n return matched ? apiRouteOptions.get(matched.key)?.ownVisitorGates === true : false\n}\n\n/**\n * Whether a request path resolves to a route registered with\n * {@link PluginApiRouteOptions.cardPayment} — what the tenant dispatcher\n * asks before its card-testing counters (AGL-3363).\n */\nexport function isPluginCardPaymentRoute(path: string): boolean {\n const matched = matchRegisteredApiKey(path)\n return matched ? apiRouteOptions.get(matched.key)?.cardPayment === true : false\n}\n\n/** An id a subject may carry: a non-empty path segment, not a path. */\nconst SUBJECT_ID = /^[^/\\s]{1,128}$/\n\nconst subjectId = (value: unknown): string | null =>\n typeof value === 'string' && SUBJECT_ID.test(value) ? value : null\n\n/**\n * The subject a request to a registered route names, or `null` (AGL-2978).\n *\n * `null` when the route declared no resolver, when the resolver answered\n * nothing, and when it THREW: a resolver that cannot read its request has\n * named no subject, and the gate then treats the request as anonymous — the\n * conservative direction. The resolver reads a clone, so the handler still\n * receives the untouched body. Ids are held to a plain path segment, so a\n * resolver cannot hand the gate a path to read overrides from.\n */\nexport async function resolvePluginApiRequestSubject(\n path: string,\n request: Request,\n): Promise<PluginApiRequestSubject | null> {\n const matched = matchRegisteredApiKey(path)\n const resolve = matched ? apiRouteOptions.get(matched.key)?.subject : undefined\n if (!resolve) return null\n try {\n const subject = await resolve(request.clone())\n if (!subject) return null\n const orgId = subjectId(subject.orgId)\n const uid = subjectId(subject.uid)\n if (!orgId && !uid) return null\n return { orgId, ...(uid ? { uid } : {}) }\n } catch {\n return null\n }\n}\n\n/**\n * The legacy (node-style) handler at a request path, or undefined when\n * nothing is registered there or the route is a web handler — a web route\n * is reached through `resolvePluginApiMatch` and `runPluginApiMatch`, since\n * it takes the `Request` and the filled `:name` segments, not a `req`/`res`\n * pair.\n */\nexport function resolvePluginApiRoute(path: string): PluginApiHandler | undefined {\n const route = resolvePluginApiMatch(path)?.route\n return typeof route === 'function' ? route : undefined\n}\n\n/**\n * Runs a matched route against the dispatcher's request: a Web handler is\n * called as it is, and a (req, res) handler goes through the adapter the\n * caller supplies — the adapter lives on the `/server` entry, which this\n * module may not import.\n */\nexport async function runPluginApiMatch(\n match: PluginApiMatch,\n request: Request,\n params: Record<string, string | string[]>,\n runLegacy: (\n handler: PluginApiHandler,\n request: Request,\n params: Record<string, string | string[]>,\n ) => Promise<Response>,\n): Promise<Response> {\n const merged = { ...params, ...match.params }\n const route = match.route as { web?: PluginWebApiHandler }\n if (typeof route === 'object' && route !== null && typeof route.web === 'function') {\n return route.web(request, { params: merged })\n }\n return runLegacy(match.route as PluginApiHandler, request, merged)\n}\n\n/** Registered paths, for diagnostics. */\nexport function listPluginApiRoutes(): string[] {\n return Array.from(apiRoutes.keys())\n}\n"],"names":["normalizeApiPath","path","replace","apiRoutes","Map","apiRouteOwners","apiRouteOptions","getRegisteringPluginId","isFirstPartyPlugin","setRegisteringPluginId","registerPluginApiRoute","handler","options","key","owner","ANONYMOUS_OWNER","incumbent","get","undefined","console","error","set","ownGatesAllowed","delete","ownVisitorGates","pluginIdForRegisteredApiPath","unregisterPluginApiRoute","matchRegisteredApiKey","has","params","segments","split","registered","keys","includes","pattern","length","matched","index","part","startsWith","slice","resolvePluginApiMatch","route","isPluginRecipientLinkRoute","recipientLink","isPluginMachineRoute","machine","isPluginPortabilityRoute","portability","isPluginOwnVisitorGatesRoute","isPluginCardPaymentRoute","cardPayment","SUBJECT_ID","subjectId","value","test","resolvePluginApiRequestSubject","request","resolve","subject","clone","orgId","uid","resolvePluginApiRoute","runPluginApiMatch","match","runLegacy","merged","web","listPluginApiRoutes","Array","from"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;CAaC;AAqMD,qFAAqF,GACrF,SAASA,iBAAiBC,IAAY;IACpC,OAAOA,KAAKC,OAAO,CAAC,cAAc;AACpC;AAEA,MAAMC,YAAY,IAAIC;AACtB,MAAMC,iBAAiB,IAAID;AAC3B,MAAME,kBAAkB,IAAIF;AAE5B;;;;;;CAMC,GACD,SAASG,sBAAsB,QAAQ,0BAAsB;AAC7D,SAASC,kBAAkB,QAAQ,uCAAmC;AAEtE,SACEC,sBAAsB,EACtBF,sBAAsB,QACjB,0BAAsB;AAE7B;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,SAASG,uBACdT,IAAY,EACZU,OAAuB,EACvBC,OAA+B;QAGjBL;IADd,MAAMM,MAAMb,iBAAiBC;IAC7B,MAAMa,SAAQP,0BAAAA,oCAAAA,0BAA4BQ;IAC1C,MAAMC,YAAYX,e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I,CAACyC,SAAS,OAAO;IACrB,IAAI;QACF,MAAMC,UAAU,MAAMD,QAAQD,QAAQG,KAAK;QAC3C,IAAI,CAACD,SAAS,OAAO;QACrB,MAAME,QAAQR,UAAUM,QAAQE,KAAK;QACrC,MAAMC,MAAMT,UAAUM,QAAQG,GAAG;QACjC,IAAI,CAACD,SAAS,CAACC,KAAK,OAAO;QAC3B,OAAO;YAAED;WAAWC,MAAM;YAAEA;QAAI,IAAI,CAAC;IACvC,EAAE,eAAM;QACN,OAAO;IACT;AACF;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,sBAAsB/D,IAAY;QAClCyC;IAAd,MAAMC,SAAQD,yBAAAA,sBAAsBzC,0BAAtByC,uBAA6BC,KAAK;IAChD,OAAO,OAAOA,UAAU,aAAaA,QAAQzB;AAC/C;AAEA;;;;;CAKC,GACD,OAAO,eAAe+C,kBACpBC,KAAqB,EACrBR,OAAgB,EAChB7B,MAAyC,EACzCsC,SAIsB;IAEtB,MAAMC,SAAS,aAAKvC,QAAWqC,MAAMrC,MAAM;IAC3C,MAAMc,QAAQuB,MAAMvB,KAAK;IACzB,IAAI,OAAOA,UAAU,YAAYA,UAAU,QAAQ,OAAOA,MAAM0B,GAAG,KAAK,YAAY;QAClF,OAAO1B,MAAM0B,GAAG,CAACX,SAAS;YAAE7B,QAAQuC;QAAO;IAC7C;IACA,OAAOD,UAAUD,MAAMvB,KAAK,EAAsBe,SAASU;AAC7D;AAEA,uCAAuC,GACvC,OAAO,SAASE;IACd,OAAOC,MAAMC,IAAI,CAACrE,UAAU8B,IAAI;AAClC"}
@@ -102,7 +102,7 @@ export declare function authorHtmlBreaksContainer(sanitized: string, container:
102
102
  * The render path never asks for these. They exist for the AUTHORING side,
103
103
  * which is the only place a person who can fix the markup is standing; the
104
104
  * runtime is executing for a VISITOR and can do nothing but drop the value
105
- * silently. Same reasoning as the reserved-name refusal in `actions.ts`.
105
+ * silently. Same reasoning as the reserved-name refusal in `site-interactions.ts`.
106
106
  */
107
107
  export interface AuthorHtmlRemoval {
108
108
  kind: 'element' | 'attribute' | 'style' | 'url';