@connextar/house 0.23.0 → 0.23.3

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 (187) hide show
  1. package/README.md +27 -3
  2. package/dist/analytics/browser.d.ts +1 -0
  3. package/dist/analytics/browser.d.ts.map +1 -1
  4. package/dist/analytics/browser.js +20 -3
  5. package/dist/analytics/browser.js.map +1 -1
  6. package/dist/analytics/config.d.ts +5 -0
  7. package/dist/analytics/config.d.ts.map +1 -1
  8. package/dist/analytics/config.js +4 -1
  9. package/dist/analytics/config.js.map +1 -1
  10. package/dist/analytics/react.d.ts.map +1 -1
  11. package/dist/analytics/react.js +4 -2
  12. package/dist/analytics/react.js.map +1 -1
  13. package/dist/analytics/redact.d.ts.map +1 -1
  14. package/dist/analytics/redact.js +6 -1
  15. package/dist/analytics/redact.js.map +1 -1
  16. package/dist/rate-limit/prisma-index.d.ts +1 -1
  17. package/dist/rate-limit/prisma-index.d.ts.map +1 -1
  18. package/dist/rate-limit/prisma-index.js.map +1 -1
  19. package/dist/rate-limit/prisma.d.ts +10 -1
  20. package/dist/rate-limit/prisma.d.ts.map +1 -1
  21. package/dist/rate-limit/prisma.js +2 -1
  22. package/dist/rate-limit/prisma.js.map +1 -1
  23. package/package.json +5 -2
  24. package/src/account/data-contract.ts +112 -0
  25. package/src/account/index.ts +11 -0
  26. package/src/admin/access.ts +267 -0
  27. package/src/admin/audit.ts +238 -0
  28. package/src/admin/bootstrap.ts +220 -0
  29. package/src/admin/client-index.ts +19 -0
  30. package/src/admin/client.tsx +187 -0
  31. package/src/admin/index.ts +91 -0
  32. package/src/admin/proof.ts +155 -0
  33. package/src/admin/second-factor-index.ts +16 -0
  34. package/src/admin/second-factor.ts +403 -0
  35. package/src/admin/testing-index.ts +13 -0
  36. package/src/admin/testing.ts +299 -0
  37. package/src/admin/view-as.ts +511 -0
  38. package/src/ai/config-index.ts +40 -0
  39. package/src/ai/config.ts +176 -0
  40. package/src/ai/images.ts +18 -0
  41. package/src/ai/index.ts +21 -0
  42. package/src/ai/pricing.ts +107 -0
  43. package/src/ai/provider.ts +403 -0
  44. package/src/analytics/browser.ts +400 -0
  45. package/src/analytics/client-index.ts +12 -0
  46. package/src/analytics/config.ts +89 -0
  47. package/src/analytics/index.ts +17 -0
  48. package/src/analytics/ingest.ts +81 -0
  49. package/src/analytics/react-index.ts +16 -0
  50. package/src/analytics/react.tsx +241 -0
  51. package/src/analytics/redact.ts +146 -0
  52. package/src/analytics/server-index.ts +17 -0
  53. package/src/analytics/server.ts +277 -0
  54. package/src/auth/index.ts +30 -0
  55. package/src/auth/second-factor-index.ts +16 -0
  56. package/src/auth/second-factor-next.ts +136 -0
  57. package/src/auth/second-factor-routes.ts +40 -0
  58. package/src/auth/second-factor.ts +226 -0
  59. package/src/auth/step-up-client-index.ts +13 -0
  60. package/src/auth/step-up-client.ts +23 -0
  61. package/src/auth/step-up-index.ts +19 -0
  62. package/src/auth/step-up-routes.ts +99 -0
  63. package/src/auth/step-up.ts +432 -0
  64. package/src/auth/two-factor-policy.ts +112 -0
  65. package/src/changelog/changelog.tsx +367 -0
  66. package/src/changelog/index.ts +12 -0
  67. package/src/editor/block-handle.tsx +312 -0
  68. package/src/editor/blocks.ts +169 -0
  69. package/src/editor/bubble-toolbar.tsx +208 -0
  70. package/src/editor/collapsible.ts +159 -0
  71. package/src/editor/content-index.ts +1 -0
  72. package/src/editor/content.tsx +343 -0
  73. package/src/editor/editor.tsx +333 -0
  74. package/src/editor/emoji-index.ts +1 -0
  75. package/src/editor/emoji-picker.tsx +114 -0
  76. package/src/editor/emoji.ts +436 -0
  77. package/src/editor/index.ts +6 -0
  78. package/src/editor/sections.ts +83 -0
  79. package/src/editor/suggestion-popup.tsx +136 -0
  80. package/src/editor/suggestions.ts +309 -0
  81. package/src/editor/ui.tsx +171 -0
  82. package/src/errors/error-shell.tsx +72 -0
  83. package/src/errors/global-error-shell.tsx +116 -0
  84. package/src/errors/index.ts +2 -0
  85. package/src/grid/columns.ts +48 -0
  86. package/src/grid/compare.ts +35 -0
  87. package/src/grid/hidden-columns.ts +95 -0
  88. package/src/grid/index.ts +27 -0
  89. package/src/grid/use-grid.ts +282 -0
  90. package/src/grid/views.ts +70 -0
  91. package/src/guides/guide-article.tsx +92 -0
  92. package/src/guides/guide-figure-zoom.tsx +533 -0
  93. package/src/guides/guide-figure.tsx +68 -0
  94. package/src/guides/guide-toc.tsx +133 -0
  95. package/src/guides/guides-landing.tsx +57 -0
  96. package/src/guides/guides-search.tsx +160 -0
  97. package/src/guides/guides-shell.tsx +60 -0
  98. package/src/guides/guides-sidebar.tsx +93 -0
  99. package/src/guides/index.ts +28 -0
  100. package/src/guides/library.ts +165 -0
  101. package/src/health/health.ts +115 -0
  102. package/src/health/index.ts +11 -0
  103. package/src/internal/cx.ts +4 -0
  104. package/src/internal/next-link.ts +23 -0
  105. package/src/jobs/counts.ts +151 -0
  106. package/src/jobs/cron-auth.ts +60 -0
  107. package/src/jobs/health.ts +315 -0
  108. package/src/jobs/idle.ts +86 -0
  109. package/src/jobs/index.ts +120 -0
  110. package/src/jobs/job-health-list.tsx +316 -0
  111. package/src/jobs/next-index.ts +4 -0
  112. package/src/jobs/next.ts +65 -0
  113. package/src/jobs/prisma-index.ts +12 -0
  114. package/src/jobs/prisma.ts +170 -0
  115. package/src/jobs/prune.ts +79 -0
  116. package/src/jobs/react-index.ts +35 -0
  117. package/src/jobs/registry.ts +189 -0
  118. package/src/jobs/scheduler.ts +437 -0
  119. package/src/jobs/store.ts +212 -0
  120. package/src/jobs/windows.ts +157 -0
  121. package/src/maintenance/core.ts +270 -0
  122. package/src/maintenance/gate.ts +171 -0
  123. package/src/maintenance/index.ts +40 -0
  124. package/src/maintenance/page.ts +76 -0
  125. package/src/maintenance/proxy.ts +88 -0
  126. package/src/maintenance/react-index.ts +7 -0
  127. package/src/maintenance/react.tsx +190 -0
  128. package/src/maintenance/route.ts +82 -0
  129. package/src/maintenance/unavailable.ts +61 -0
  130. package/src/markdown/figure.tsx +132 -0
  131. package/src/markdown/figures.ts +237 -0
  132. package/src/markdown/guide.tsx +536 -0
  133. package/src/markdown/index.ts +53 -0
  134. package/src/markdown/table-view.tsx +74 -0
  135. package/src/markdown/table.ts +90 -0
  136. package/src/password/common.ts +58 -0
  137. package/src/password/estimate-index.ts +18 -0
  138. package/src/password/estimate.ts +715 -0
  139. package/src/password/index.ts +40 -0
  140. package/src/password/password-input.tsx +116 -0
  141. package/src/password/password-strength.tsx +157 -0
  142. package/src/password/reveal.ts +151 -0
  143. package/src/rate-limit/better-auth.ts +94 -0
  144. package/src/rate-limit/index.ts +32 -0
  145. package/src/rate-limit/keys.ts +110 -0
  146. package/src/rate-limit/limiter.ts +276 -0
  147. package/src/rate-limit/prisma-index.ts +12 -0
  148. package/src/rate-limit/prisma.ts +157 -0
  149. package/src/rate-limit/store.ts +47 -0
  150. package/src/release/changelog.ts +364 -0
  151. package/src/release/index.ts +32 -0
  152. package/src/release/version.ts +64 -0
  153. package/src/setup-guide/bits.tsx +420 -0
  154. package/src/setup-guide/card.tsx +358 -0
  155. package/src/setup-guide/class-names.ts +144 -0
  156. package/src/setup-guide/context.tsx +239 -0
  157. package/src/setup-guide/guide.ts +271 -0
  158. package/src/setup-guide/index.ts +76 -0
  159. package/src/setup-guide/launcher.tsx +207 -0
  160. package/src/setup-guide/strip.tsx +127 -0
  161. package/src/styles/house.css +384 -0
  162. package/src/trail/index.ts +12 -0
  163. package/src/trail/rules.ts +84 -0
  164. package/src/trail/trail.tsx +367 -0
  165. package/src/ux/errors.ts +32 -0
  166. package/src/ux/feedback.tsx +41 -0
  167. package/src/ux/index.ts +44 -0
  168. package/src/ux/navigation-index.ts +16 -0
  169. package/src/ux/navigation-progress.tsx +270 -0
  170. package/src/ux/optimistic.ts +415 -0
  171. package/src/ux/use-action.ts +155 -0
  172. package/src/ux/use-optimistic-list.ts +227 -0
  173. package/src/ux/use-optimistic-value.ts +136 -0
  174. package/src/web-search/index.ts +13 -0
  175. package/src/web-search/providers.ts +177 -0
  176. package/src/web-search/types.ts +98 -0
  177. package/src/whats-new/body.tsx +190 -0
  178. package/src/whats-new/index.ts +43 -0
  179. package/src/whats-new/seen.ts +40 -0
  180. package/src/whats-new/select.ts +230 -0
  181. package/src/whats-new/use-whats-new.ts +109 -0
  182. package/src/wizard/index.ts +61 -0
  183. package/src/wizard/invalid.ts +152 -0
  184. package/src/wizard/react-hook-form-index.ts +11 -0
  185. package/src/wizard/rhf-adapter.ts +67 -0
  186. package/src/wizard/rules.ts +137 -0
  187. package/src/wizard/wizard.tsx +442 -0
@@ -0,0 +1,400 @@
1
+ import {
2
+ CONSENT_KNOWN_ATTRIBUTE,
3
+ NOT_MEASURED_ATTRIBUTE,
4
+ RECORDABLE_ATTRIBUTE,
5
+ VIEWING_AS_ATTRIBUTE,
6
+ type Analytics,
7
+ } from "./config.js";
8
+
9
+ /**
10
+ * The browser half: the consent answer, Google Tag Manager, and PostHog's configuration and gate.
11
+ *
12
+ * Imports no browser package — the app's `instrumentation-client.ts` calls `posthog.init(key, browser.posthogConfig())`
13
+ * and hands the same `posthog` to `<SiteAnalytics>` — so this module is safe to import anywhere and the PostHog version
14
+ * stays the app's.
15
+ *
16
+ * The rules, all three copies' strictest:
17
+ *
18
+ * - **Consent first.** GTM loads only after a yes, on a tagged page. PostHog keeps nothing (`persistence: "memory"`)
19
+ * and its gate sends nothing but a redacted error until somebody says yes, on a page that may be measured.
20
+ * - **Global Privacy Control is a no**, and outranks a stored yes.
21
+ * - **Never a private page, never while viewing as somebody**: a page measures only if it is tagged, or the app's
22
+ * `recordablePath` with `<RecordingAllowed />` on it; and never while `ViewingAsBanner` or a `data-analytics-private`
23
+ * marker is on the page.
24
+ * - **One gate, deny by default** (`before_send`): every address cleaned, heatmaps only for this page, replay's
25
+ * addresses cleaned, dead-click text stripped, an exception redacted whole. No feature flags, so no `/flags` request
26
+ * carrying the first page's full address.
27
+ */
28
+
29
+ export type AnalyticsConsent = "granted" | "denied";
30
+
31
+ /** posthog-js's event, as `before_send` receives it — typed structurally, so no posthog-js import. */
32
+ export interface CaptureResult {
33
+ event: string;
34
+ properties: Record<string, unknown>;
35
+ $set?: Record<string, unknown>;
36
+ $set_once?: Record<string, unknown>;
37
+ }
38
+
39
+ /** The parts of posthog-js the browser half calls. */
40
+ export interface PostHogLike {
41
+ __loaded?: boolean;
42
+ sessionRecordingStarted(): boolean;
43
+ startSessionRecording(): void;
44
+ stopSessionRecording(): void;
45
+ captureException(error: unknown, properties?: Record<string, unknown>): unknown;
46
+ heatmaps?: { getAndClearBuffer(): unknown } | null;
47
+ }
48
+
49
+ export interface BrowserAnalyticsOptions {
50
+ /** One more reason this browser is not measured — AltEd's: a learner using the family's browser. */
51
+ optsOut?: () => boolean;
52
+ /** For tests. */
53
+ window?: Window;
54
+ }
55
+
56
+ interface GtmWindow extends Window {
57
+ dataLayer?: unknown[];
58
+ }
59
+
60
+ const SCRIPT_ID = "gtm-script";
61
+ const RRWEB_META = 4;
62
+ const RRWEB_CUSTOM = 5;
63
+ const URL_PROPERTY = /url|pathname|referrer|href/i;
64
+
65
+ export type BrowserAnalytics = ReturnType<typeof createBrowserAnalytics>;
66
+
67
+ export function createBrowserAnalytics(analytics: Analytics, options: BrowserAnalyticsOptions = {}) {
68
+ const win = () => options.window ?? window;
69
+ let unstoredConsent: AnalyticsConsent | null = null;
70
+ const consentListeners = new Set<() => void>();
71
+ const recordableListeners = new Set<() => void>();
72
+ let measuring = false;
73
+
74
+ // ── Consent ──────────────────────────────────────────────────────────────
75
+
76
+ function readConsent(): AnalyticsConsent | null {
77
+ try {
78
+ const value = win().localStorage.getItem(analytics.consentKey);
79
+ return value === "granted" || value === "denied" ? value : null;
80
+ } catch {
81
+ return unstoredConsent;
82
+ }
83
+ }
84
+
85
+ function writeConsent(consent: AnalyticsConsent): void {
86
+ try {
87
+ win().localStorage.setItem(analytics.consentKey, consent);
88
+ } catch {
89
+ // Storage refused (a private window, a blocked site): the answer holds for this page's life.
90
+ unstoredConsent = consent;
91
+ }
92
+ if (consent === "denied") clearAnalyticsCookies();
93
+ for (const listener of consentListeners) listener();
94
+ }
95
+
96
+ function subscribeToConsent(onChange: () => void): () => void {
97
+ consentListeners.add(onChange);
98
+ return () => consentListeners.delete(onChange);
99
+ }
100
+
101
+ /** Global Privacy Control, or the app's own reason. A no that outranks any stored yes. */
102
+ function browserOptsOut(): boolean {
103
+ try {
104
+ if ((win().navigator as Navigator & { globalPrivacyControl?: boolean }).globalPrivacyControl === true)
105
+ return true;
106
+ return options.optsOut?.() === true;
107
+ } catch {
108
+ return true;
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Set before paint, so a returning visitor never sees the card flash: an inline `<script>` in `<head>`. The app's
114
+ * CSS hides `html[data-consent-known] [data-cookie-card]:not([data-reopened])`.
115
+ */
116
+ const consentKnownScript = `(function(){var d=document.documentElement,g=navigator.globalPrivacyControl===true,v=null;try{v=localStorage.getItem(${JSON.stringify(
117
+ analytics.consentKey,
118
+ )})}catch(e){}if(g||v==="granted"||v==="denied")d.setAttribute(${JSON.stringify(CONSENT_KNOWN_ATTRIBUTE)},"")})()`;
119
+
120
+ /**
121
+ * Google's cookies, cleared from this host only — never a shared parent like `.connextar.com`, which another site
122
+ * of ours may own. Pairs with `cookie_domain: none` in the GTM container (Quickie's and PharmaLine's rule).
123
+ */
124
+ function clearAnalyticsCookies(): void {
125
+ const w = win();
126
+ const host = w.location.hostname;
127
+ const domains = ["", host, `.${host}`, ...(host.startsWith("www.") ? [`.${host.slice(4)}`] : [])];
128
+ for (const name of w.document.cookie.split(";").map((cookie) => cookie.split("=")[0]!.trim())) {
129
+ if (name !== "_ga" && !name.startsWith("_ga_") && name !== "_gid") continue;
130
+ for (const domain of domains) {
131
+ w.document.cookie = `${name}=; Max-Age=0; path=/${domain ? `; domain=${domain}` : ""}`;
132
+ }
133
+ }
134
+ }
135
+
136
+ const marked = (attribute: string) => win().document.querySelector(`[${attribute}]`) !== null;
137
+
138
+ /** A view is on the page (`ViewingAsBanner`), or the page says it is never measured (`<NotMeasured />`). */
139
+ function pageIsPrivate(): boolean {
140
+ return marked(VIEWING_AS_ATTRIBUTE) || marked(NOT_MEASURED_ATTRIBUTE);
141
+ }
142
+
143
+ // ── Google Tag Manager ───────────────────────────────────────────────────
144
+
145
+ /** Every parameter `track` has sent, so the next event clears the ones it leaves out. */
146
+ const sentParams = new Set<string>();
147
+
148
+ // GTM reads the `arguments` object itself, so the parameters are only there for the type.
149
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
150
+ function gtag(..._args: unknown[]): void {
151
+ const w = win() as GtmWindow;
152
+ w.dataLayer = w.dataLayer ?? [];
153
+ // GTM reads `arguments` objects from the data layer, not arrays.
154
+ // eslint-disable-next-line prefer-rest-params
155
+ w.dataLayer.push(arguments);
156
+ }
157
+
158
+ const isGtmLoaded = () => win().document.getElementById(SCRIPT_ID) !== null;
159
+
160
+ /** After a yes, on a tagged page: Consent Mode v2 with analytics only, then the container. */
161
+ function loadGtm(containerId: string): void {
162
+ if (!containerId || isGtmLoaded()) return;
163
+ if (readConsent() !== "granted" || browserOptsOut() || !analytics.isTaggedPath(win().location.pathname)) return;
164
+ if (pageIsPrivate()) return;
165
+ gtag("consent", "default", {
166
+ analytics_storage: "granted",
167
+ ad_storage: "denied",
168
+ ad_user_data: "denied",
169
+ ad_personalization: "denied",
170
+ });
171
+ const w = win() as GtmWindow;
172
+ w.dataLayer = w.dataLayer ?? [];
173
+ w.dataLayer.push({ "gtm.start": Date.now(), event: "gtm.js" });
174
+ const script = w.document.createElement("script");
175
+ script.id = SCRIPT_ID;
176
+ script.async = true;
177
+ script.src = `https://www.googletagmanager.com/gtm.js?id=${encodeURIComponent(containerId)}`;
178
+ w.document.head.appendChild(script);
179
+ }
180
+
181
+ /** A declared event, only once GTM is loaded — which it is only after a yes, on a tagged page. */
182
+ /**
183
+ * A declared event, only once GTM is loaded and never on a private page. GTM's data layer keeps a key's last value,
184
+ * so every parameter an earlier event sent and this one leaves out is pushed as `undefined` — otherwise a later
185
+ * `go_to_app` would carry the `cta_text` of an earlier `begin_sign_up` (PharmaLine cleared them by hand).
186
+ */
187
+ function track(event: string, params: Record<string, string | number | boolean | undefined> = {}): void {
188
+ if (!isGtmLoaded() || !analytics.events.includes(event) || pageIsPrivate()) return;
189
+ const clean: Record<string, unknown> = {};
190
+ for (const key of sentParams) clean[key] = undefined;
191
+ for (const [key, value] of Object.entries(params)) {
192
+ if (value === undefined) continue;
193
+ clean[key] = typeof value === "string" ? analytics.redact(value).slice(0, 100) : value;
194
+ sentParams.add(key);
195
+ }
196
+ (win() as GtmWindow).dataLayer?.push({ event, ...clean });
197
+ }
198
+
199
+ function ctaLocation(element: Element): "header" | "footer" | "page" {
200
+ if (element.closest("header")) return "header";
201
+ if (element.closest("footer")) return "footer";
202
+ return "page";
203
+ }
204
+
205
+ /** A no after a yes: tell GTM, clear its cookies. The caller reloads, so nothing loaded stays running. */
206
+ function withdrawConsent(): void {
207
+ gtag("consent", "update", { analytics_storage: "denied" });
208
+ clearAnalyticsCookies();
209
+ }
210
+
211
+ // ── PostHog ──────────────────────────────────────────────────────────────
212
+
213
+ function pageIsRecordable(): boolean {
214
+ return marked(RECORDABLE_ATTRIBUTE);
215
+ }
216
+
217
+ function subscribeToRecordable(onChange: () => void): () => void {
218
+ recordableListeners.add(onChange);
219
+ return () => recordableListeners.delete(onChange);
220
+ }
221
+
222
+ function recordableChanged(): void {
223
+ for (const listener of recordableListeners) listener();
224
+ }
225
+
226
+ /** Whether this page, now, may be measured. Asked at every send, not once. */
227
+ function measuredHere(): boolean {
228
+ if (readConsent() !== "granted" || browserOptsOut()) return false;
229
+ if (pageIsPrivate()) return false;
230
+ const { pathname } = win().location;
231
+ return analytics.isTaggedPath(pathname) || (analytics.recordablePath(pathname) && pageIsRecordable());
232
+ }
233
+
234
+ const origin = () => win().location.origin;
235
+
236
+ function cleanProperties(properties: Record<string, unknown> | undefined): void {
237
+ if (!properties) return;
238
+ for (const [key, value] of Object.entries(properties)) {
239
+ if (typeof value === "string" && URL_PROPERTY.test(key)) properties[key] = analytics.cleanUrl(value, origin());
240
+ }
241
+ }
242
+
243
+ /** A heatmap batch keeps only this page's clicks, its addresses cleaned; with none left, it is dropped. */
244
+ function cleanHeatmap(event: CaptureResult): boolean {
245
+ const data = event.properties?.$heatmap_data;
246
+ if (!data || typeof data !== "object") return false;
247
+ const here = win().location.pathname;
248
+ const kept: Record<string, unknown> = {};
249
+ for (const [href, clicks] of Object.entries(data as Record<string, unknown>)) {
250
+ let pathname: string;
251
+ try {
252
+ pathname = new URL(href, origin()).pathname;
253
+ } catch {
254
+ continue;
255
+ }
256
+ if (pathname === here) kept[analytics.cleanUrl(href, origin())] = clicks;
257
+ }
258
+ if (!Object.keys(kept).length) return false;
259
+ event.properties.$heatmap_data = kept;
260
+ return true;
261
+ }
262
+
263
+ type ReplayEvent = { type?: number; data?: { href?: unknown; payload?: { href?: unknown } } };
264
+
265
+ function cleanSnapshot(event: CaptureResult): void {
266
+ const data = event.properties?.$snapshot_data as ReplayEvent | ReplayEvent[] | undefined;
267
+ for (const item of Array.isArray(data) ? data : data ? [data] : []) {
268
+ if (item?.type === RRWEB_META && typeof item.data?.href === "string") {
269
+ item.data.href = analytics.cleanUrl(item.data.href, origin());
270
+ }
271
+ if (item?.type === RRWEB_CUSTOM && typeof item.data?.payload?.href === "string") {
272
+ item.data.payload.href = analytics.cleanUrl(item.data.payload.href, origin());
273
+ }
274
+ }
275
+ }
276
+
277
+ /** Dead clicks are off; should one arrive anyway, it carries no text and no attribute but its class. */
278
+ function cleanDeadClick(event: CaptureResult): void {
279
+ const props = event.properties;
280
+ if (!props) return;
281
+ delete props.$el_text;
282
+ if (Array.isArray(props.$elements)) {
283
+ props.$elements = (props.$elements as Record<string, unknown>[]).map((element) => ({
284
+ tag_name: element.tag_name,
285
+ ...(typeof element.attr__class === "string" ? { attr__class: element.attr__class } : {}),
286
+ nth_child: element.nth_child,
287
+ nth_of_type: element.nth_of_type,
288
+ }));
289
+ }
290
+ if (typeof props.$elements_chain === "string") {
291
+ props.$elements_chain = props.$elements_chain.replace(
292
+ /(?:text|href|attr_id|attr__(?!class)[\w-]+)="(?:[^"\\]|\\.)*"/g,
293
+ "",
294
+ );
295
+ }
296
+ }
297
+
298
+ /**
299
+ * `before_send`. Deny by default: an exception always goes, redacted whole; anything else only while this page may be
300
+ * measured, and cleaned.
301
+ */
302
+ function gate<T extends CaptureResult>(event: T | null): T | null {
303
+ if (!event) return null;
304
+ if (event.event === "$exception") return analytics.redactDeep(event);
305
+ if (!measuredHere()) return null;
306
+ if (event.event === "$$heatmap" && !cleanHeatmap(event)) return null;
307
+ if (event.event === "$snapshot") cleanSnapshot(event);
308
+ if (event.event === "$dead_click" || event.event === "$dead_swipe") cleanDeadClick(event);
309
+ cleanProperties(event.properties);
310
+ cleanProperties(event.$set);
311
+ cleanProperties(event.$set_once);
312
+ return event;
313
+ }
314
+
315
+ /** `posthog.init(key, browser.posthogConfig())`. Only the hosts can be changed; every rule above stays. */
316
+ function posthogConfig(overrides: { apiHost?: string; uiHost?: string } = {}) {
317
+ return {
318
+ api_host: overrides.apiHost ?? "/ingest",
319
+ ui_host: overrides.uiHost ?? "https://eu.posthog.com",
320
+ persistence: "memory" as const,
321
+ person_profiles: "never" as const,
322
+ capture_exceptions: true,
323
+ capture_pageview: "history_change" as const,
324
+ capture_pageleave: "if_capture_pageview" as const,
325
+ enable_heatmaps: true,
326
+ autocapture: false,
327
+ capture_dead_clicks: false,
328
+ capture_performance: false,
329
+ mask_all_text: true,
330
+ mask_all_element_attributes: true,
331
+ logs: { captureConsoleLogs: false },
332
+ enable_recording_console_log: false,
333
+ disable_session_recording: true,
334
+ session_recording: {
335
+ maskAllInputs: true,
336
+ maskTextSelector: "*",
337
+ blockSelector: "img, picture, video, canvas, iframe, svg image",
338
+ recordHeaders: false,
339
+ recordBody: false,
340
+ },
341
+ disable_surveys: true,
342
+ disable_product_tours: true,
343
+ disable_web_experiments: true,
344
+ advanced_disable_flags: true,
345
+ advanced_disable_feature_flags: true,
346
+ advanced_disable_feature_flags_on_first_load: true,
347
+ before_send: gate,
348
+ };
349
+ }
350
+
351
+ /**
352
+ * Start or stop replay, and clear the heatmap buffer, as consent and the page change. Call after each navigation and
353
+ * each answer; `<SiteAnalytics>` does.
354
+ */
355
+ function syncRecording(posthog: PostHogLike | null | undefined): void {
356
+ if (!posthog?.__loaded) return;
357
+ const recording = posthog.sessionRecordingStarted();
358
+ const measured = measuredHere();
359
+ // Clicks gathered while not measured — or before measuring began — are never sent.
360
+ if (!measured || !measuring) posthog.heatmaps?.getAndClearBuffer();
361
+ measuring = measured;
362
+ if (measured) {
363
+ if (!recording) posthog.startSessionRecording();
364
+ } else if (recording) {
365
+ posthog.stopSessionRecording();
366
+ }
367
+ }
368
+
369
+ /** A handled error from the browser: anonymous and redacted by the gate, consent or not. */
370
+ function reportError(posthog: PostHogLike | null | undefined, error: unknown, properties?: Record<string, unknown>) {
371
+ if (posthog?.__loaded) posthog.captureException(error, properties);
372
+ }
373
+
374
+ return {
375
+ analytics,
376
+ readConsent,
377
+ writeConsent,
378
+ subscribeToConsent,
379
+ browserOptsOut,
380
+ consentKnownScript,
381
+ clearAnalyticsCookies,
382
+ gtag,
383
+ isGtmLoaded,
384
+ loadGtm,
385
+ track,
386
+ ctaLocation,
387
+ withdrawConsent,
388
+ pageIsRecordable,
389
+ pageIsPrivate,
390
+ subscribeToRecordable,
391
+ recordableChanged,
392
+ measuredHere,
393
+ gate,
394
+ posthogConfig,
395
+ syncRecording,
396
+ reportError,
397
+ /** Ask again: what a footer's "Cookie settings" does. */
398
+ reopenConsent: () => win().dispatchEvent(new Event(analytics.cookieSettingsEvent)),
399
+ };
400
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `@connextar/house/analytics/client` — the browser half without React: consent, GTM, and PostHog's configuration,
3
+ * gate and replay switch. Imports no browser package; the app's posthog-js is handed in.
4
+ */
5
+ export {
6
+ createBrowserAnalytics,
7
+ type AnalyticsConsent,
8
+ type BrowserAnalytics,
9
+ type BrowserAnalyticsOptions,
10
+ type CaptureResult,
11
+ type PostHogLike,
12
+ } from "./browser.js";
@@ -0,0 +1,89 @@
1
+ import { createRedactor, type RedactionRules, type Redactor } from "./redact.js";
2
+
3
+ /**
4
+ * One app's analytics, declared once and imported by its browser code and its server code alike: where measuring may
5
+ * happen at all, what the consent answer is stored as, and what is redacted.
6
+ *
7
+ * Paths and allow-lists are the app's. The rules are the house's: nothing is measured until somebody says yes, Global
8
+ * Privacy Control is a no, nothing is measured on a private page or while viewing as somebody, and every address,
9
+ * message and stack is redacted before it leaves.
10
+ */
11
+
12
+ export interface AnalyticsDefinition {
13
+ /** The app's name in keys and events: `quickie` → `quickie.analytics-consent.v1`, `quickie:cookie-settings`. */
14
+ app: string;
15
+ /**
16
+ * The public pages that may be measured, by prefix: `/pricing` covers `/pricing/teams`, never `/pricingx`. `/` means
17
+ * the home page alone. Everything else is private, and measured never.
18
+ */
19
+ taggedPaths: readonly string[];
20
+ /**
21
+ * Public pages that are measured as themselves only, never what is under them: a locale-routed app's home pages
22
+ * (`/en`, `/fr`), where `/en` in `taggedPaths` would also tag `/en/dashboard`. `/` is always exact.
23
+ */
24
+ exactPaths?: readonly string[];
25
+ /**
26
+ * Signed-in pages that may be measured too, for a person who said yes, and only where the page also renders
27
+ * `<RecordingAllowed />` (the app renders it for an ordinary member, never an administrator or a view). Default: none
28
+ * — PharmaLine's rule, the strictest.
29
+ */
30
+ recordablePath?: (pathname: string) => boolean;
31
+ /** The consent key's version: bump it to ask everybody again. Default 1. */
32
+ consentVersion?: number;
33
+ redaction?: RedactionRules;
34
+ /** The event names `track` may send. */
35
+ events?: readonly string[];
36
+ }
37
+
38
+ export interface Analytics extends Redactor {
39
+ readonly app: string;
40
+ readonly consentKey: string;
41
+ /** Dispatched on `window` to ask again — a footer's "Cookie settings". */
42
+ readonly cookieSettingsEvent: string;
43
+ /** The symbol an app's `handleError` finds its server reporter under, set by `register()`. */
44
+ readonly errorReporterSymbol: symbol;
45
+ readonly events: readonly string[];
46
+ isTaggedPath(pathname: string): boolean;
47
+ recordablePath(pathname: string): boolean;
48
+ }
49
+
50
+ /** Rendered on a page that must never be measured, however it was reached. `ViewingAsBanner` carries its own. */
51
+ export const NOT_MEASURED_ATTRIBUTE = "data-analytics-private";
52
+ /** `ViewingAsBanner`'s marker: while it is on the page, nothing is measured. */
53
+ export const VIEWING_AS_ATTRIBUTE = "data-viewing-as";
54
+ /** Rendered by `<RecordingAllowed />` on a signed-in page the app lets be measured. */
55
+ export const RECORDABLE_ATTRIBUTE = "data-analytics-recordable";
56
+ /** Set before paint once an answer is known, so the card is hidden by CSS and never flashes. */
57
+ export const CONSENT_KNOWN_ATTRIBUTE = "data-consent-known";
58
+
59
+ const APP = /^[a-z][a-z0-9-]{1,30}$/;
60
+
61
+ export function defineAnalytics(definition: AnalyticsDefinition): Analytics {
62
+ if (!APP.test(definition.app)) {
63
+ throw new Error(`[analytics] app must be a short lower-case name, got "${definition.app}".`);
64
+ }
65
+ for (const path of [...definition.taggedPaths, ...(definition.exactPaths ?? [])]) {
66
+ if (!path.startsWith("/") || (path !== "/" && path.endsWith("/"))) {
67
+ throw new Error(`[analytics] a tagged path starts with "/" and does not end with one: "${path}".`);
68
+ }
69
+ }
70
+ const tagged = new Set(definition.taggedPaths);
71
+ const exact = new Set(definition.exactPaths ?? []);
72
+ const prefixes = definition.taggedPaths.filter((path) => path !== "/");
73
+ const version = definition.consentVersion ?? 1;
74
+ const redactor = createRedactor(definition.redaction);
75
+ return {
76
+ ...redactor,
77
+ app: definition.app,
78
+ consentKey: `${definition.app}.analytics-consent.v${version}`,
79
+ cookieSettingsEvent: `${definition.app}:cookie-settings`,
80
+ errorReporterSymbol: Symbol.for(`${definition.app}.unhandled-error-reporter`),
81
+ events: definition.events ?? [],
82
+ isTaggedPath(pathname) {
83
+ if (exact.has(pathname)) return true;
84
+ if (pathname === "/") return tagged.has("/");
85
+ return prefixes.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
86
+ },
87
+ recordablePath: (pathname) => definition.recordablePath?.(pathname) === true,
88
+ };
89
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * `@connextar/house/analytics` — one app's analytics declared once (`defineAnalytics`), the redaction every address,
3
+ * message and stack goes through, and the same-origin `/ingest` relay. Imports nothing, so it loads in the browser, on
4
+ * the edge and on the server alike. The browser half is `/analytics/client` and `/analytics/react`; the server half,
5
+ * error reports included, is `/analytics/server`.
6
+ */
7
+ export {
8
+ CONSENT_KNOWN_ATTRIBUTE,
9
+ NOT_MEASURED_ATTRIBUTE,
10
+ RECORDABLE_ATTRIBUTE,
11
+ VIEWING_AS_ATTRIBUTE,
12
+ defineAnalytics,
13
+ type Analytics,
14
+ type AnalyticsDefinition,
15
+ } from "./config.js";
16
+ export { ingestProxy, logsSink, type IngestProxy, type IngestProxyOptions } from "./ingest.js";
17
+ export { REDACTED, TOKEN_PLACEHOLDER, createRedactor, type RedactionRules, type Redactor } from "./redact.js";
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The same-origin `/ingest` relay to PostHog — one route handler, edge-safe, importing nothing.
3
+ *
4
+ * Next's rewrites forwarded everything: the visitor's cookies for this site, the page they came from, their address.
5
+ * This forwards four request headers and two response headers, and only the endpoints posthog-js needs to send what
6
+ * the gate let through. It refuses `/flags` and `/decide`: posthog-js's feature-flag request carries the first page's
7
+ * full address — query and all — in its body, past `before_send`. PharmaLine found it (security round 5, S1); Quickie
8
+ * copied the fix; AltEd still forwarded it. And it refuses `/i/v1/logs`, which the app answers itself (`logsSink`).
9
+ */
10
+
11
+ export interface IngestProxyOptions {
12
+ /** Default PostHog's EU ingestion host. */
13
+ apiHost?: string;
14
+ /** Default PostHog's EU asset host, for `/static/*` and `/array/*`. */
15
+ assetHost?: string;
16
+ /** The project key: `/array/*` is then this project's only, not any project's configuration. */
17
+ projectKey?: string;
18
+ /** The path the relay is mounted on. Default `/ingest`. */
19
+ mount?: string;
20
+ fetch?: typeof fetch;
21
+ }
22
+
23
+ const FORWARD_REQUEST = ["content-type", "content-encoding", "user-agent", "accept"] as const;
24
+ const FORWARD_RESPONSE = ["content-type", "cache-control"] as const;
25
+ const REFUSED = /^\/(?:flags|decide|i\/v1\/logs)(?:\/|$)/;
26
+ const ALLOWED = /^\/(?:e|i\/v0\/e|s|batch|static|array)(?:\/|$)/;
27
+
28
+ export interface IngestProxy {
29
+ /** Where a request would go, or null when it is refused. */
30
+ upstreamFor(url: URL): string | null;
31
+ /** The route handler: `export const GET = proxy.handle, POST = proxy.handle`. */
32
+ handle(request: Request): Promise<Response>;
33
+ }
34
+
35
+ export function ingestProxy(options: IngestProxyOptions = {}): IngestProxy {
36
+ const apiHost = (options.apiHost ?? "https://eu.i.posthog.com").replace(/\/+$/, "");
37
+ const assetHost = (options.assetHost ?? "https://eu-assets.i.posthog.com").replace(/\/+$/, "");
38
+ const mount = (options.mount ?? "/ingest").replace(/\/+$/, "");
39
+ const key = options.projectKey;
40
+
41
+ function upstreamFor(url: URL): string | null {
42
+ if (!url.pathname.startsWith(`${mount}/`)) return null;
43
+ // The raw pathname, so a trailing slash (`/ingest/e/`) survives — PostHog's endpoints end in one.
44
+ const rest = url.pathname.slice(mount.length);
45
+ if (rest.includes("/../") || rest.includes("/./") || REFUSED.test(rest) || !ALLOWED.test(rest)) return null;
46
+ if (key && rest.startsWith("/array/") && !rest.startsWith(`/array/${key}/`)) return null;
47
+ const host = rest.startsWith("/static/") || rest.startsWith("/array/") ? assetHost : apiHost;
48
+ return `${host}${rest}${url.search}`;
49
+ }
50
+
51
+ return {
52
+ upstreamFor,
53
+ async handle(request) {
54
+ const target = upstreamFor(new URL(request.url));
55
+ if (!target) return new Response(null, { status: 404 });
56
+ const headers = new Headers();
57
+ for (const name of FORWARD_REQUEST) {
58
+ const value = request.headers.get(name);
59
+ if (value) headers.set(name, value);
60
+ }
61
+ const hasBody = request.method !== "GET" && request.method !== "HEAD";
62
+ const upstream = await (options.fetch ?? fetch)(target, {
63
+ method: request.method,
64
+ headers,
65
+ body: hasBody ? await request.arrayBuffer() : undefined,
66
+ redirect: "manual",
67
+ });
68
+ const out = new Headers();
69
+ for (const name of FORWARD_RESPONSE) {
70
+ const value = upstream.headers.get(name);
71
+ if (value) out.set(name, value);
72
+ }
73
+ return new Response(upstream.body, { status: upstream.status, headers: out });
74
+ },
75
+ };
76
+ }
77
+
78
+ /** `app/ingest/i/v1/logs/route.ts`: posthog-js's console-log sink, answered here and never forwarded. */
79
+ export function logsSink(): Response {
80
+ return new Response(null, { status: 204 });
81
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * `@connextar/house/analytics/react` — the cookie card and what it drives, the pre-paint script, the markers, and the
3
+ * consent hook. Client components.
4
+ */
5
+ export {
6
+ ConsentKnownScript,
7
+ CookieSettingsButton,
8
+ NotMeasured,
9
+ RecordingAllowed,
10
+ SITE_ANALYTICS_CLASS_NAMES,
11
+ SITE_ANALYTICS_LABELS,
12
+ SiteAnalytics,
13
+ useAnalyticsConsent,
14
+ type CookieCardProps,
15
+ type SiteAnalyticsProps,
16
+ } from "./react.js";